From f66154db37495a300edb7f6684158715f2b64a44 Mon Sep 17 00:00:00 2001 From: wgqqqqq Date: Tue, 17 Nov 2026 21:09:00 +0800 Subject: [PATCH 1/2] refactor: move native mobile ownership to OpenBitFun-Mobile --- .gitattributes | 5 - .github/workflows/ci.yml | 2 +- .github/workflows/desktop-package.yml | 11 +- .github/workflows/mobile-package.yml | 133 - .gitignore | 19 +- AGENTS-CN.md | 6 + AGENTS.md | 6 + README.md | 6 + README.zh-CN.md | 6 + docs/architecture/i18n.md | 2 +- .../platform-portability-design.md | 2 +- docs/architecture/product-architecture.md | 2 +- docs/architecture/theme-token-optimization.md | 2 +- package.json | 7 - release-please-config.json | 4 - scripts/audit-theme-colors.test.mjs | 1 - scripts/build-mobile-terminal.mjs | 16 - scripts/check-github-config.test.mjs | 21 +- scripts/check-harmonyos-architecture.mjs | 479 - scripts/check-mobile-architecture.mjs | 462 - scripts/frontend-color-surface-registry.json | 101 +- scripts/generate-brand-assets.mjs | 77 +- scripts/generate-brand-assets.test.mjs | 31 - scripts/generate-i18n-contract.mjs | 8 - scripts/mobile-client-build.contract.test.mjs | 45 +- scripts/mobile-ui-design-system.mjs | 299 - scripts/mobile-ui-preview.mjs | 110 - scripts/theme-css-var-contract.mjs | 5 - scripts/verify-release-version-sync.mjs | 18 +- src/apps/mobile/AGENTS.md | 143 - src/apps/mobile/README.md | 169 - src/apps/mobile/android/AGENTS.md | 83 - src/apps/mobile/android/README.md | 30 - src/apps/mobile/android/app/build.gradle.kts | 107 - .../mobile/android/app/proguard-rules.pro | 16 - .../mobile/app/AccountLoginPageTest.kt | 68 - .../mobile/app/AccountRemoteScreenTest.kt | 172 - .../mobile/app/ChatMessageBubbleTest.kt | 421 - .../mobile/app/ComposerMediaInputTest.kt | 239 - .../mobile/app/ComposerModelSelectorTest.kt | 130 - .../mobile/app/ConnectionSheetChromeTest.kt | 84 - .../mobile/app/ConversationHeaderTest.kt | 205 - .../mobile/app/ConversationViewTest.kt | 615 -- .../mobile/app/CreateSessionScreenTest.kt | 227 - .../mobile/app/FileReferenceCardsTest.kt | 129 - .../mobile/app/HarnessProfileMenuTest.kt | 61 - .../mobile/app/MessageQueuePanelTest.kt | 68 - .../app/MobileDesignPreviewVisualTest.kt | 180 - .../openbitfun/mobile/app/MobileParityTest.kt | 169 - .../app/MobilePreviewStatesVisualTest.kt | 142 - .../openbitfun/mobile/app/MobileScreenTest.kt | 294 - .../mobile/app/NotificationOnboardingTest.kt | 72 - .../mobile/app/PermissionModeCardTest.kt | 155 - .../mobile/app/QuestionDraftTest.kt | 92 - .../mobile/app/RemoteSessionListViewTest.kt | 144 - .../mobile/app/RemoteSettingsSheetTest.kt | 99 - .../mobile/app/RuntimeFileBrowserTest.kt | 84 - .../mobile/app/RuntimeFileEditorTest.kt | 45 - .../mobile/app/RuntimeTerminalViewTest.kt | 123 - .../mobile/app/RuntimeWorkspacePickerTest.kt | 45 - .../mobile/app/SymbolDrawableTest.kt | 57 - .../com/openbitfun/mobile/app/TestStrings.kt | 7 - .../mobile/app/ToolConfirmationPanelTest.kt | 60 - .../mobile/app/ToolStatusRowTest.kt | 271 - .../android/app/src/debug/AndroidManifest.xml | 14 - .../android/app/src/main/AndroidManifest.xml | 35 - .../app/src/main/assets/miniapps/.gitignore | 2 - .../android/app/src/main/kotlin/.gitkeep | 1 - .../com/openbitfun/mobile/app/MainActivity.kt | 180 - .../app/platform/AccountAvatarLoader.kt | 37 - .../platform/AndroidRuntimeUploadSource.kt | 21 - .../app/platform/AppLocaleController.kt | 78 - .../app/platform/ComposerActivityLauncher.kt | 25 - .../app/platform/ComposerImageEncoder.kt | 81 - .../mobile/app/platform/DeviceInstall.kt | 34 - .../app/platform/GeneratedLocaleContract.kt | 4 - .../mobile/app/platform/LogcatCoreLog.kt | 60 - .../app/platform/NotificationOnboarding.kt | 27 - .../app/platform/StartupRevealPreference.kt | 15 - .../app/platform/TaskCompletionNotifier.kt | 35 - .../mobile/app/platform/WindowMetrics.kt | 206 - .../mobile/app/state/AppShellState.kt | 276 - .../mobile/app/state/SessionViewSettings.kt | 74 - .../app/ui/account/AccountLoginScreen.kt | 144 - .../app/ui/account/AccountProfileCards.kt | 342 - .../mobile/app/ui/chat/ChatMessageBubble.kt | 187 - .../mobile/app/ui/chat/ChatStatusBar.kt | 121 - .../mobile/app/ui/chat/ComposerBar.kt | 870 -- .../mobile/app/ui/chat/ComposerVoiceInput.kt | 43 - .../mobile/app/ui/chat/ConversationHeader.kt | 307 - .../app/ui/chat/ConversationTimelineView.kt | 286 - .../mobile/app/ui/chat/ConversationView.kt | 629 -- .../mobile/app/ui/chat/FileReferenceCards.kt | 222 - .../mobile/app/ui/chat/GeneralChatScreen.kt | 480 - .../mobile/app/ui/chat/InlineImage.kt | 47 - .../mobile/app/ui/chat/MarkdownContent.kt | 358 - .../mobile/app/ui/chat/MessageQueuePanel.kt | 141 - .../app/ui/chat/OpenBitFunHeaderActionMenu.kt | 231 - .../app/ui/chat/message/ChatMessageChrome.kt | 239 - .../app/ui/chat/message/MessageBlockList.kt | 314 - .../ui/chat/message/ProcessPresentation.kt | 57 - .../mobile/app/ui/chat/tool/ToolGlyph.kt | 140 - .../app/ui/chat/tool/ToolInteractionPanels.kt | 295 - .../mobile/app/ui/chat/tool/ToolStatusList.kt | 520 - .../app/ui/common/AdaptiveModalSurface.kt | 161 - .../mobile/app/ui/common/CircleControl.kt | 64 - .../mobile/app/ui/common/ConnectionLabels.kt | 40 - .../app/ui/common/ConnectionSheetChrome.kt | 68 - .../mobile/app/ui/miniapps/MiniApps.kt | 255 - .../app/ui/preview/MessageQueuePreview.kt | 54 - .../app/ui/preview/MobileDesignGallery.kt | 157 - .../app/ui/preview/MobilePreviewStates.kt | 189 - .../generated/MobilePreviewScenarios.kt | 118 - .../ui/remote/ConnectAccountDeviceScreen.kt | 254 - .../app/ui/remote/CreateSessionScreen.kt | 585 -- .../mobile/app/ui/remote/DeviceToolsDialog.kt | 87 - .../app/ui/remote/DocumentExportPolicy.kt | 6 - .../app/ui/remote/FilePreviewSurface.kt | 722 -- .../app/ui/remote/HarnessProfileLabel.kt | 30 - .../mobile/app/ui/remote/PairingScreen.kt | 456 - .../app/ui/remote/RemoteDownloadSaver.kt | 82 - .../app/ui/remote/RemoteSessionListView.kt | 881 -- .../app/ui/remote/RuntimeTerminalView.kt | 99 - .../app/ui/remote/RuntimeWorkspaceDialogs.kt | 324 - .../ui/remote/RuntimeWorkspacePickerDialog.kt | 113 - .../app/ui/remote/SessionActionSheet.kt | 639 -- .../app/ui/settings/CurrentControlCard.kt | 137 - .../app/ui/settings/ModelServiceScreen.kt | 865 -- .../app/ui/settings/PermissionModeCard.kt | 330 - .../app/ui/settings/RemoteSettingsSheet.kt | 204 - .../ui/settings/SessionViewSettingsSheet.kt | 257 - .../mobile/app/ui/settings/SettingsChrome.kt | 149 - .../mobile/app/ui/settings/SettingsScreen.kt | 425 - .../app/ui/shell/ColdStartHomeTransition.kt | 72 - .../mobile/app/ui/shell/MobileScreen.kt | 709 -- .../app/ui/shell/NotificationOnboarding.kt | 45 - .../app/ui/shell/OpenBitFunCompactDrawer.kt | 303 - .../mobile/app/ui/shell/StartupBrandReveal.kt | 118 - .../mobile/app/ui/shell/WelcomeBrandFlow.kt | 88 - .../mobile/app/ui/shell/WelcomeHome.kt | 117 - .../mobile/app/ui/shell/sidebar/AppSidebar.kt | 242 - .../sidebar/RemoteWorkspacePathPolicy.kt | 14 - .../app/ui/shell/sidebar/SidebarChrome.kt | 85 - .../shell/sidebar/SidebarDeviceSelectorRow.kt | 87 - .../app/ui/shell/sidebar/SidebarFooter.kt | 112 - .../app/ui/shell/sidebar/SidebarHeader.kt | 154 - .../sidebar/SidebarRemoteWorkspaceSection.kt | 689 -- .../ui/shell/sidebar/SidebarSessionList.kt | 305 - .../mobile/app/ui/theme/OpenBitFunMotion.kt | 31 - .../openbitfun/mobile/app/ui/theme/Theme.kt | 328 - .../ui/theme/generated/MobileDesignTokens.kt | 277 - .../mobile/app/viewmodel/AccountViewModel.kt | 193 - .../app/viewmodel/AppSettingsViewModel.kt | 41 - .../viewmodel/ComposerAttachmentsViewModel.kt | 110 - .../app/viewmodel/GeneralChatViewModel.kt | 50 - .../mobile/android/app/src/main/res/.gitkeep | 1 - .../res/drawable-nodpi/approval_shield.png | Bin 1324 -> 0 bytes .../res/drawable/ic_symbol_archivebox.xml | 31 - .../drawable/ic_symbol_arrow_clockwise.xml | 20 - .../drawable/ic_symbol_arrow_down_to_line.xml | 31 - .../ic_symbol_arrow_right_and_square.xml | 32 - .../ic_symbol_arrow_triangle_merge.xml | 38 - .../main/res/drawable/ic_symbol_arrow_up.xml | 24 - .../drawable/ic_symbol_checkmark_circle.xml | 24 - .../ic_symbol_checkmark_circle_fill.xml | 24 - .../res/drawable/ic_symbol_chevron_down.xml | 17 - .../res/drawable/ic_symbol_chevron_left.xml | 23 - .../drawable/ic_symbol_chevron_left_wide.xml | 28 - .../res/drawable/ic_symbol_chevron_right.xml | 20 - .../res/drawable/ic_symbol_chevron_up.xml | 17 - .../main/res/drawable/ic_symbol_circle.xml | 17 - .../src/main/res/drawable/ic_symbol_cloud.xml | 17 - .../res/drawable/ic_symbol_code_square.xml | 31 - .../main/res/drawable/ic_symbol_desktop.xml | 31 - .../src/main/res/drawable/ic_symbol_doc.xml | 24 - .../main/res/drawable/ic_symbol_doc_text.xml | 38 - .../ic_symbol_doc_text_badge_arrow_up.xml | 52 - ..._symbol_doc_text_badge_magnifyingglass.xml | 52 - .../main/res/drawable/ic_symbol_ellipsis.xml | 29 - .../src/main/res/drawable/ic_symbol_eye.xml | 19 - .../main/res/drawable/ic_symbol_eye_slash.xml | 25 - .../main/res/drawable/ic_symbol_folder.xml | 17 - .../main/res/drawable/ic_symbol_gearshape.xml | 24 - .../res/drawable/ic_symbol_info_circle.xml | 27 - .../src/main/res/drawable/ic_symbol_link.xml | 24 - .../res/drawable/ic_symbol_list_checkmark.xml | 52 - .../drawable/ic_symbol_magnifyingglass.xml | 24 - .../res/drawable/ic_symbol_menu_lines.xml | 18 - .../main/res/drawable/ic_symbol_message.xml | 17 - .../src/main/res/drawable/ic_symbol_mic.xml | 31 - .../main/res/drawable/ic_symbol_person.xml | 24 - .../main/res/drawable/ic_symbol_picture.xml | 27 - .../src/main/res/drawable/ic_symbol_plus.xml | 24 - .../ic_symbol_questionmark_circle.xml | 27 - .../drawable/ic_symbol_rectangle_stack.xml | 31 - .../src/main/res/drawable/ic_symbol_robot.xml | 33 - .../drawable/ic_symbol_square_and_pencil.xml | 24 - .../drawable/ic_symbol_square_grid_2x2.xml | 38 - .../src/main/res/drawable/ic_symbol_trash.xml | 45 - .../main/res/drawable/ic_symbol_website.xml | 31 - .../ic_symbol_wrench_and_screwdriver.xml | 54 - .../src/main/res/drawable/ic_symbol_xmark.xml | 24 - .../drawable/miniapp_divination_preview.webp | Bin 79446 -> 0 bytes .../res/drawable/miniapp_gomoku_preview.webp | Bin 62780 -> 0 bytes .../res/drawable/miniapp_regex_preview.webp | Bin 34492 -> 0 bytes .../res/mipmap-anydpi-v26/ic_launcher.xml | 17 - .../mipmap-anydpi-v26/ic_launcher_round.xml | 12 - .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 3542 -> 0 bytes .../mipmap-hdpi/ic_launcher_foreground.png | Bin 5409 -> 0 bytes .../mipmap-hdpi/ic_launcher_monochrome.png | Bin 5409 -> 0 bytes .../res/mipmap-hdpi/ic_launcher_round.png | Bin 3542 -> 0 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 2219 -> 0 bytes .../mipmap-mdpi/ic_launcher_foreground.png | Bin 3286 -> 0 bytes .../mipmap-mdpi/ic_launcher_monochrome.png | Bin 3286 -> 0 bytes .../res/mipmap-mdpi/ic_launcher_round.png | Bin 2219 -> 0 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 4797 -> 0 bytes .../mipmap-xhdpi/ic_launcher_foreground.png | Bin 7041 -> 0 bytes .../mipmap-xhdpi/ic_launcher_monochrome.png | Bin 7041 -> 0 bytes .../res/mipmap-xhdpi/ic_launcher_round.png | Bin 4797 -> 0 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 7654 -> 0 bytes .../mipmap-xxhdpi/ic_launcher_foreground.png | Bin 11530 -> 0 bytes .../mipmap-xxhdpi/ic_launcher_monochrome.png | Bin 11530 -> 0 bytes .../res/mipmap-xxhdpi/ic_launcher_round.png | Bin 7654 -> 0 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 10755 -> 0 bytes .../mipmap-xxxhdpi/ic_launcher_foreground.png | Bin 17403 -> 0 bytes .../mipmap-xxxhdpi/ic_launcher_monochrome.png | Bin 17403 -> 0 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.png | Bin 10755 -> 0 bytes .../app/src/main/res/values-zh/strings.xml | 502 - .../res/values/ic_launcher_background.xml | 5 - .../app/src/main/res/values/strings.xml | 517 - .../app/src/main/res/values/themes.xml | 12 - .../app/platform/AppLocaleResolverTest.kt | 21 - .../mobile/app/platform/FoldFactsTest.kt | 115 - .../mobile/app/state/AppShellStateTest.kt | 175 - .../app/ui/chat/ComposerBreakpointTest.kt | 30 - .../ui/chat/ConversationComposerDraftTest.kt | 34 - .../ui/chat/ConversationScrollPolicyTest.kt | 66 - .../ui/chat/HistoryPageArrivalTrackerTest.kt | 23 - .../app/ui/chat/ProcessPresentationTest.kt | 60 - .../ui/chat/tool/ToolInteractionPanelsTest.kt | 88 - .../app/ui/remote/DocumentExportPolicyTest.kt | 15 - .../ui/shell/ContentCardCoordinatorTest.kt | 100 - .../sidebar/RemoteWorkspacePathPolicyTest.kt | 42 - .../app/ui/theme/MobileTextScaleTest.kt | 33 - src/apps/mobile/android/build.gradle.kts | 4 - src/apps/mobile/android/gradle.properties | 11 - .../android/gradle/wrapper/gradle-wrapper.jar | Bin 47505 -> 0 bytes .../gradle/wrapper/gradle-wrapper.properties | 10 - src/apps/mobile/android/gradlew | 248 - src/apps/mobile/android/gradlew.bat | 82 - src/apps/mobile/android/settings.gradle.kts | 34 - src/apps/mobile/design-system/README.md | 227 - .../design-system/assets/approval-shield.svg | 43 - .../assets/welcome-brand-contours.json | 67 - .../components/mobile-components.json | 300 - .../preview/generated/mobile-design-data.js | 1526 --- .../mobile/design-system/preview/index.html | 55 - .../preview/preview-scenarios.smoke.test.mjs | 66 - .../mobile/design-system/preview/preview.css | 412 - .../mobile/design-system/preview/preview.js | 220 - .../preview/snapshots/.gitignore | 1 - .../design-system/preview/snapshots/README.md | 24 - .../scenarios/mobile-preview-scenarios.json | 181 - .../design-system/tokens/mobile-tokens.json | 440 - .../mobile/docs/remote-session-lifecycle.md | 38 - src/apps/mobile/harmonyos/.gitignore | 37 - src/apps/mobile/harmonyos/AGENTS.md | 221 - src/apps/mobile/harmonyos/AppScope/app.json5 | 14 - .../resources/base/element/string.json | 8 - .../base/media/openbitfun_app_icon.png | Bin 104027 -> 0 bytes .../resources/base/profile/configuration.json | 6 - src/apps/mobile/harmonyos/README.md | 98 - src/apps/mobile/harmonyos/build-profile.json5 | 56 - src/apps/mobile/harmonyos/code-linter.json5 | 32 - .../docs/adaptive-sheet-placement-design.md | 366 - .../harmonyos/docs/harmonyos-i18n-design.md | 52 - .../docs/mobile-control-console-design.md | 329 - .../docs/mobile-detached-dispatch-design.md | 251 - .../model-service-settings-sheet-design.md | 84 - .../docs/mvvm-architecture-refactor-design.md | 575 -- .../wide-conversation-navigation-design.md | 545 -- src/apps/mobile/harmonyos/entry/.gitignore | 6 - .../harmonyos/entry/build-profile.json5 | 52 - src/apps/mobile/harmonyos/entry/hvigorfile.ts | 11 - .../harmonyos/entry/obfuscation-rules.txt | 23 - .../harmonyos/entry/oh-package-lock.json5 | 19 - .../mobile/harmonyos/entry/oh-package.json5 | 13 - .../entry/src/main/cpp/CMakeLists.txt | 38 - .../entry/src/main/cpp/napi_argon2.cpp | 205 - .../src/main/cpp/relay_message_encoding.cpp | 143 - .../cpp/types/libopenbitfun_crypto/index.d.ts | 13 - .../libopenbitfun_crypto/oh-package.json5 | 6 - .../main/ets/entryability/EntryAbility.ets | 202 - .../entrybackupability/EntryBackupAbility.ets | 17 - .../main/ets/generated/MobileDesignTokens.ets | 255 - .../ets/generated/MobilePreviewScenarios.ets | 155 - .../entry/src/main/ets/i18n/AppLocale.ets | 110 - .../entry/src/main/ets/i18n/EnUsMessages.ets | 716 -- .../main/ets/i18n/HostTextRetranslator.ets | 292 - .../src/main/ets/i18n/MessageTemplate.ets | 8 - .../entry/src/main/ets/i18n/RemoteI18n.ets | 152 - .../entry/src/main/ets/i18n/ZhCnMessages.ets | 716 -- .../src/main/ets/model/ChatTimelineModels.ets | 167 - .../src/main/ets/model/ComposerSubmission.ets | 5 - .../src/main/ets/model/FilePreviewTarget.ets | 62 - .../src/main/ets/model/InteractionMailbox.ets | 51 - .../entry/src/main/ets/model/MessageQueue.ets | 19 - .../src/main/ets/model/MiniAppModels.ets | 46 - .../entry/src/main/ets/model/RemoteModels.ets | 870 -- .../entry/src/main/ets/pages/AppRoot.ets | 108 - .../actions/AppRootPresentationActions.ets | 170 - .../ets/pages/actions/ConversationIntent.ets | 293 - .../actions/ConversationIntentDispatcher.ets | 107 - .../pages/components/AccountLoginSheet.ets | 31 - .../pages/components/AccountProfilePanel.ets | 506 - .../pages/components/AdaptiveSheetOptions.ets | 66 - .../ets/pages/components/AppActionButton.ets | 68 - .../components/AppRootOverlaySurfaces.ets | 212 - .../pages/components/AppRootPresentation.ets | 655 -- .../main/ets/pages/components/AppShell.ets | 258 - .../main/ets/pages/components/AppSidebar.ets | 364 - .../main/ets/pages/components/BrandMark.ets | 12 - .../pages/components/ChatMessageBubble.ets | 840 -- .../pages/components/ChatMessageChrome.ets | 367 - .../pages/components/ChatMessageContent.ets | 171 - .../ets/pages/components/ChatStatusBar.ets | 62 - .../ets/pages/components/ChatTimeline.ets | 853 -- .../components/ColdStartHomeTransition.ets | 60 - .../ets/pages/components/CommandChipRow.ets | 318 - .../pages/components/CompactMenuButton.ets | 46 - .../main/ets/pages/components/ComposerBar.ets | 1137 --- .../components/ConnectAccountDevicePage.ets | 209 - .../main/ets/pages/components/ConnectView.ets | 310 - .../pages/components/ConversationHeader.ets | 258 - .../components/ConversationLoadingState.ets | 59 - .../components/ConversationRouteSurface.ets | 97 - .../ets/pages/components/ConversationView.ets | 1170 --- .../components/ConversationViewContract.ets | 72 - .../pages/components/ConversationViewHost.ets | 60 - .../components/ConversationViewSettings.ets | 420 - .../components/CurrentControlSection.ets | 150 - .../pages/components/DefaultAccountAvatar.ets | 28 - .../components/DeviceModelDefaultsPanel.ets | 514 - .../pages/components/FilePreviewSurface.ets | 571 -- .../pages/components/FileReferenceCard.ets | 86 - .../pages/components/HarnessProfileMenu.ets | 94 - .../components/InteractionMailboxPanel.ets | 88 - .../components/LanguageSettingsPanel.ets | 97 - .../ets/pages/components/MarkdownContent.ets | 390 - .../pages/components/MessageQueuePanel.ets | 91 - .../ets/pages/components/MiniAppSurface.ets | 133 - .../ets/pages/components/MiniAppWebView.ets | 61 - .../pages/components/ModelRolePickerPanel.ets | 421 - .../components/ModelServiceSettingsPanel.ets | 703 -- .../pages/components/ModelUnavailableCard.ets | 63 - .../pages/components/NavigationBackButton.ets | 33 - .../components/OpenBitFunAccountLoginPage.ets | 121 - .../ets/pages/components/RecentRemoteHome.ets | 91 - .../components/RemoteConnectionPanel.ets | 62 - .../components/RemotePermissionSection.ets | 261 - .../pages/components/RemoteSessionList.ets | 791 -- .../components/RemoteSessionLoadingView.ets | 40 - .../ets/pages/components/RemoteSessionRow.ets | 108 - .../components/RollbackSelectionMenu.ets | 59 - .../pages/components/RollbackStagingBar.ets | 134 - .../pages/components/SessionActionSurface.ets | 199 - .../pages/components/SessionDetailsView.ets | 168 - .../ets/pages/components/SettingsSheet.ets | 389 - .../pages/components/SheetActionFooter.ets | 44 - .../ets/pages/components/SheetCloseButton.ets | 44 - .../ets/pages/components/SheetCloseHeader.ets | 39 - .../main/ets/pages/components/SheetLayout.ets | 18 - .../pages/components/SidebarDeviceGroup.ets | 631 -- .../ets/pages/components/SidebarGlyphs.ets | 152 - .../components/SidebarNavigationIcons.ets | 85 - .../pages/components/SidebarToggleButton.ets | 56 - .../pages/components/SidebarToolsFooter.ets | 60 - .../components/SidebarWorkspacePicker.ets | 385 - .../components/SidebarWorkspaceSection.ets | 479 - .../ets/pages/components/SkillPickerSheet.ets | 464 - .../pages/components/StartupBrandReveal.ets | 108 - .../components/StreamingMarkdownContent.ets | 179 - .../ets/pages/components/SubagentTaskCard.ets | 279 - .../ets/pages/components/TemplateIcon.ets | 36 - .../src/main/ets/pages/components/Theme.ets | 86 - .../ets/pages/components/ThinkingBlock.ets | 165 - .../main/ets/pages/components/ToolGlyphs.ets | 40 - .../components/ToolInteractionPanels.ets | 336 - .../ets/pages/components/ToolStatusList.ets | 1014 -- .../ets/pages/components/UsageReportSheet.ets | 206 - .../components/UserMessageFullTextSheet.ets | 86 - .../pages/components/WatchProvisionCard.ets | 193 - .../ets/pages/components/WelcomeBrandFlow.ets | 81 - .../main/ets/pages/components/WelcomeHome.ets | 204 - .../pages/components/WideConversationHost.ets | 434 - .../components/WorkspaceFileEditorView.ets | 60 - .../components/WorkspaceTerminalView.ets | 84 - .../pages/components/WorkspaceToolsPanel.ets | 309 - .../components/remote/RemoteSurfaceHost.ets | 474 - .../ets/pages/host/AppRootHostAdapter.ets | 68 - .../ets/pages/layout/WideLayoutGeometry.ets | 30 - .../pages/navigation/AppRootRouteState.ets | 91 - .../ets/pages/navigation/AppRouteContract.ets | 114 - .../policy/AccountDeviceSelectionPolicy.ets | 52 - .../pages/policy/AccountLoginErrorPolicy.ets | 13 - .../ets/pages/policy/ActivityGroupPolicy.ets | 130 - .../ets/pages/policy/AdaptiveLayoutInput.ets | 49 - .../policy/AssistantMessageCopyMenuPolicy.ets | 60 - .../policy/AssistantProcessLayoutPolicy.ets | 53 - .../policy/ChatMessageStructurePolicy.ets | 803 -- .../policy/ConnectSheetLandingPolicy.ets | 59 - .../pages/policy/ConversationHeaderPolicy.ets | 65 - .../pages/policy/ConversationLayoutPolicy.ets | 375 - .../ConversationMessageRenderPolicy.ets | 70 - .../ConversationModelPresentationPolicy.ets | 279 - .../ConversationSessionFilterPolicy.ets | 52 - .../policy/DeviceModelSettingsEntryPolicy.ets | 66 - .../policy/FilePreviewPlacementPolicy.ets | 307 - .../ets/pages/policy/FileTargetResolver.ets | 156 - .../ets/pages/policy/HarnessProfilePolicy.ets | 11 - .../policy/HistoryPageArrivalTracker.ets | 11 - .../policy/MessageFileReferenceProjector.ets | 112 - .../policy/ModelRoleCandidatesPolicy.ets | 324 - .../policy/ModelServiceSettingsPolicy.ets | 169 - .../main/ets/pages/policy/PlanToolPolicy.ets | 83 - .../pages/policy/RemoteCompactHomePolicy.ets | 34 - .../pages/policy/RemoteSurfaceEntryPolicy.ets | 14 - .../policy/RollbackPresentationPolicy.ets | 185 - .../pages/policy/RuntimeLocationPolicy.ets | 17 - .../policy/SelectionCapabilityPolicy.ets | 28 - .../ets/pages/policy/SessionActionPolicy.ets | 31 - .../pages/policy/SessionListProjection.ets | 506 - .../pages/policy/SessionRollbackPolicy.ets | 300 - .../ets/pages/policy/SettingsPagePolicy.ets | 12 - .../pages/policy/SettingsPlacementPolicy.ets | 332 - .../policy/SidebarConnectionActionPolicy.ets | 31 - .../policy/SidebarDeviceProjectionPolicy.ets | 19 - .../policy/SidebarDirectoryPreviewPolicy.ets | 54 - .../policy/ThinkingPresentationPolicy.ets | 86 - .../ets/pages/policy/ToolCollapsePolicy.ets | 117 - .../policy/ToolFileReferenceResolver.ets | 66 - .../policy/ToolStatusPresentationPolicy.ets | 301 - .../policy/UsageReportPresentationPolicy.ets | 305 - .../pages/policy/UserMessageMenuPolicy.ets | 37 - .../policy/UserMessageTruncationPolicy.ets | 101 - .../pages/preview/CatalogRefreshPreview.ets | 82 - .../pages/preview/ColdStartHomePreview.ets | 32 - .../pages/preview/CommandPalettePreview.ets | 500 - .../pages/preview/ComposerOverflowPreview.ets | 122 - .../preview/ComposerSubmissionPreview.ets | 69 - .../pages/preview/CopySelectionPreview.ets | 405 - .../preview/DeviceModelDefaultsPreview.ets | 301 - .../pages/preview/DeviceSelectorPreview.ets | 38 - .../pages/preview/DurableTimelinePreview.ets | 94 - .../pages/preview/FileVisibilityPreview.ets | 453 - .../pages/preview/HistoryScrollPreview.ets | 59 - .../pages/preview/ImmersiveBottomPreview.ets | 505 - .../preview/InteractionMailboxPreview.ets | 36 - .../ets/pages/preview/MobileDesignGallery.ets | 214 - .../preview/ModelRoleSelectorPreview.ets | 98 - .../pages/preview/RollbackPreviewScenario.ets | 345 - .../pages/preview/RollbackStagingPreview.ets | 504 - .../pages/preview/SubagentProcessPreview.ets | 333 - .../pages/preview/SubagentSwarmFixture.ets | 822 -- .../main/ets/pages/runtime/AppRootRuntime.ets | 688 -- .../runtime/AppRootRuntimeComposition.ets | 1171 --- .../main/ets/pages/state/AppShellState.ets | 103 - .../pages/state/ChatComposerCapabilities.ets | 36 - .../src/main/ets/pages/state/ChatSurface.ets | 4 - .../state/ColdStartPresentationState.ets | 16 - .../ets/pages/state/CommandPaletteState.ets | 317 - .../ets/pages/state/ConversationCoreState.ets | 272 - .../ets/pages/state/ConversationUiModels.ets | 293 - .../ets/pages/state/ConversationViewState.ets | 181 - .../ets/pages/state/DeviceDirectoryState.ets | 202 - .../state/DeviceModelDefaultsSheetState.ets | 219 - .../main/ets/pages/state/FilePreviewState.ets | 107 - .../ets/pages/state/GeneralChatPageState.ets | 148 - .../src/main/ets/pages/state/MiniAppState.ets | 13 - .../main/ets/pages/state/RemotePageState.ets | 579 -- .../ets/pages/state/SettingsSheetState.ets | 81 - .../state/SubagentBranchExpansionState.ets | 83 - .../ets/pages/state/WatchProvisionState.ets | 66 - .../ets/pages/state/WorkspaceToolsState.ets | 42 - .../ets/pages/viewmodel/AppShellViewModel.ets | 110 - .../viewmodel/ConversationController.ets | 220 - .../pages/viewmodel/ConversationRuntime.ets | 90 - .../pages/viewmodel/ConversationViewModel.ets | 22 - .../viewmodel/DeviceDirectoryViewModel.ets | 625 -- .../pages/viewmodel/FilePreviewController.ets | 92 - .../GeneralChatConversationViewModel.ets | 366 - .../ets/pages/viewmodel/LocaleController.ets | 43 - .../ets/pages/viewmodel/MiniAppViewModel.ets | 90 - .../viewmodel/RemoteActivityViewModel.ets | 193 - .../viewmodel/RemoteConnectionController.ets | 196 - .../viewmodel/RemoteCreateFlowController.ets | 137 - .../viewmodel/RemoteFilePreviewController.ets | 266 - .../viewmodel/RemoteSessionViewModel.ets | 388 - .../viewmodel/RemoteTranscriptController.ets | 742 -- .../viewmodel/RemoteWorkspaceViewModel.ets | 201 - .../pages/viewmodel/SettingsController.ets | 994 -- .../VisibleConversationController.ets | 87 - .../viewmodel/WorkspaceToolsViewModel.ets | 347 - .../ets/services/AccountDeviceDirectory.ets | 110 - .../main/ets/services/AccountDeviceLink.ets | 104 - .../src/main/ets/services/AccountRealtime.ets | 232 - .../main/ets/services/AsyncLifecycleGate.ets | 20 - .../main/ets/services/BuiltinMiniAppHost.ets | 86 - .../main/ets/services/ChatComposerPolicy.ets | 136 - .../ets/services/ChatSessionController.ets | 249 - .../ets/services/ChatTimelineProjector.ets | 231 - .../main/ets/services/ChatTimelineStore.ets | 1051 -- .../src/main/ets/services/ClientBuild.ets | 55 - .../main/ets/services/ClipboardService.ets | 73 - .../main/ets/services/CloudAccountClient.ets | 649 -- .../main/ets/services/CloudAccountCrypto.ets | 27 - .../ets/services/CloudAccountSessionStore.ets | 235 - .../ets/services/CodeSyntaxHighlighter.ets | 422 - .../ets/services/CommandCatalogProjection.ets | 394 - .../ets/services/CommandPalettePolicy.ets | 565 -- .../services/ConcurrentWorkspaceListing.ets | 47 - .../ets/services/ConnectionErrorPolicy.ets | 125 - .../services/ConnectionStatusPresenter.ets | 58 - .../main/ets/services/ConversationEvent.ets | 71 - .../main/ets/services/DeferredLoadingGate.ets | 112 - .../ets/services/DeviceApiLevelService.ets | 19 - .../services/DeviceDirectoryCoordinator.ets | 86 - .../ets/services/DurableSessionReducer.ets | 211 - .../entry/src/main/ets/services/Encoding.ets | 145 - .../ets/services/FilePreviewErrorPolicy.ets | 42 - .../main/ets/services/FilePreviewPolicy.ets | 13 - .../ets/services/GitHubAccountProfile.ets | 65 - .../HarmonyTaskCompletionNotificationPort.ets | 133 - .../HarmonyUpgradeIdentityContract.ets | 24 - .../main/ets/services/HostCatalogObserver.ets | 114 - .../main/ets/services/HostInvokeRefusal.ets | 44 - .../main/ets/services/HostSessionStream.ets | 335 - .../main/ets/services/ImagePickerService.ets | 268 - .../ets/services/InteractionMailboxStore.ets | 121 - .../ets/services/KeyboardReleaseService.ets | 45 - .../services/LegacyWorkspaceCompatibility.ets | 55 - .../ets/services/LocalePreferenceStore.ets | 104 - .../ets/services/MainThreadStallProbe.ets | 58 - .../ets/services/MarkdownHtmlSerializer.ets | 262 - .../src/main/ets/services/MarkdownParser.ets | 789 -- .../main/ets/services/MessageQueueStore.ets | 87 - .../src/main/ets/services/MiniAppDocument.ets | 39 - .../main/ets/services/MobileIdentityStore.ets | 165 - .../main/ets/services/MotionPreference.ets | 13 - .../entry/src/main/ets/services/OhosError.ets | 24 - .../ets/services/RelayMessageEncoding.ets | 25 - .../RemoteActivityLifecycleController.ets | 29 - .../ets/services/RemoteChatBranchCache.ets | 36 - .../src/main/ets/services/RemoteChatCache.ets | 314 - .../services/RemoteChatCommandController.ets | 316 - .../ets/services/RemoteChatLocalRdbStore.ets | 296 - .../RemoteChatPollingLifecycleController.ets | 72 - .../ets/services/RemoteCommandFactory.ets | 344 - .../RemoteCommandPaletteController.ets | 329 - .../ets/services/RemoteCommandTransport.ets | 56 - .../services/RemoteConnectionCoordinator.ets | 20 - .../src/main/ets/services/RemoteCrypto.ets | 120 - .../services/RemoteFileDownloadController.ets | 189 - .../services/RemoteHeartbeatController.ets | 70 - .../src/main/ets/services/RemoteLogger.ets | 18 - .../ets/services/RemoteModelController.ets | 121 - .../RemoteModelDefaultsController.ets | 388 - .../ets/services/RemoteResponseMapper.ets | 368 - .../ets/services/RemoteSessionController.ets | 291 - .../ets/services/RemoteSessionIdentity.ets | 157 - .../ets/services/RemoteSessionListCache.ets | 182 - .../services/RemoteSessionListRdbStore.ets | 221 - .../ets/services/RemoteSessionManager.ets | 976 -- .../services/RemoteToolActionController.ets | 124 - .../src/main/ets/services/RemoteUiState.ets | 301 - .../services/RemoteWorkspaceCoordinator.ets | 74 - .../services/RemoteWorkspaceFileClient.ets | 14 - .../services/RemoteWorkspaceRepository.ets | 67 - .../ets/services/RollbackOutcomePolicy.ets | 51 - .../src/main/ets/services/RpcPayload.ets | 67 - .../ets/services/StartupRevealPreference.ets | 23 - .../services/SubagentStreamCoordinator.ets | 906 -- .../TaskCompletionNotificationController.ets | 126 - .../src/main/ets/services/TimeFormat.ets | 69 - .../services/TranscriptIntegrityPolicy.ets | 80 - .../VoiceInputLifecycleController.ets | 119 - .../main/ets/services/VoiceInputService.ets | 297 - .../main/ets/services/WatchHandoffStore.ets | 219 - .../ets/services/WatchProvisionController.ets | 307 - .../ets/services/WatchProvisionCrypto.ets | 45 - .../ets/services/WatchProvisionDisplay.ets | 9 - .../ets/services/WatchProvisionProtocol.ets | 170 - .../ets/services/WindowSystemBarService.ets | 371 - .../main/ets/services/WorkspaceCatalog.ets | 64 - .../services/WorkspaceFileUploadClient.ets | 114 - .../entry/src/main/ets/services/X25519.ets | 122 - .../general-chat/GeneralChatApiClient.ets | 148 - .../general-chat/GeneralChatApiModels.ets | 79 - .../GeneralChatBootstrapController.ets | 56 - .../GeneralChatCloudConfigPolicy.ets | 119 - .../GeneralChatCommandController.ets | 267 - .../general-chat/GeneralChatConfigStore.ets | 370 - .../general-chat/GeneralChatController.ets | 87 - .../GeneralChatDraftController.ets | 114 - .../GeneralChatDraftLifecycleController.ets | 61 - .../general-chat/GeneralChatEventMapper.ets | 218 - .../GeneralChatExportFormatter.ets | 50 - .../general-chat/GeneralChatHttpTransport.ets | 79 - .../general-chat/GeneralChatLocalRdbStore.ets | 196 - .../services/general-chat/GeneralChatPort.ets | 65 - .../general-chat/GeneralChatRepository.ets | 370 - .../general-chat/GeneralChatServiceState.ets | 63 - .../GeneralChatStreamCoordinator.ets | 95 - .../GeneralChatStreamLifecycleController.ets | 76 - .../general-chat/MockGeneralChatAdapter.ets | 300 - .../ModelProviderGeneralChatAdapter.ets | 631 -- .../general-chat/ModelProviderSseParser.ets | 110 - .../harmonyos/entry/src/main/module.json5 | 109 - .../main/resources/base/element/color.json | 248 - .../main/resources/base/element/float.json | 8 - .../main/resources/base/element/string.json | 72 - .../resources/base/media/approval_shield.png | Bin 1324 -> 0 bytes .../resources/base/media/gpt_chat_glyph.png | Bin 1014 -> 0 bytes .../resources/base/media/gpt_composer_mic.png | Bin 2502 -> 0 bytes .../base/media/gpt_composer_plus.png | Bin 929 -> 0 bytes .../base/media/gpt_composer_send.png | Bin 3785 -> 0 bytes .../base/media/gpt_composer_send_arrow.svg | 5 - .../base/media/gpt_home_chat_glyph.png | Bin 2809 -> 0 bytes .../base/media/gpt_home_globe_glyph.png | Bin 143826 -> 0 bytes .../base/media/gpt_home_image_glyph.png | Bin 115513 -> 0 bytes .../base/media/gpt_home_menu_glyph.png | Bin 921 -> 0 bytes .../base/media/gpt_home_mic_glyph.png | Bin 5572 -> 0 bytes .../base/media/gpt_home_plus_glyph.png | Bin 1980 -> 0 bytes .../base/media/gpt_home_voice_button.png | Bin 337985 -> 0 bytes .../resources/base/media/gpt_search_logo.png | Bin 17959 -> 0 bytes .../base/media/gpt_settings_logo.png | Bin 21392 -> 0 bytes .../resources/base/media/harness_creative.svg | 5 - .../resources/base/media/harness_minimal.svg | 5 - .../resources/base/media/harness_standard.svg | 5 - .../resources/base/media/harness_ultimate.svg | 5 - .../media/miniapp_divination_preview.webp | Bin 79446 -> 0 bytes .../base/media/miniapp_gomoku_preview.webp | Bin 62780 -> 0 bytes .../base/media/miniapp_regex_preview.webp | Bin 34492 -> 0 bytes .../base/media/openbitfun_app_icon.png | Bin 104027 -> 0 bytes .../base/media/openbitfun_brand_mark.png | Bin 42981 -> 0 bytes .../base/media/openbitfun_start_window.png | Bin 16687 -> 0 bytes .../base/media/remote_actions_chat.png | Bin 1075 -> 0 bytes .../base/media/remote_actions_check.png | Bin 452 -> 0 bytes .../base/media/remote_actions_clock.png | Bin 1094 -> 0 bytes .../base/media/remote_actions_cloud.png | Bin 814 -> 0 bytes .../base/media/remote_actions_folder.png | Bin 619 -> 0 bytes .../base/media/remote_actions_link.png | Bin 743 -> 0 bytes .../base/media/remote_actions_settings.png | Bin 1255 -> 0 bytes .../base/media/remote_create_chat.png | Bin 3727 -> 0 bytes .../base/media/remote_create_device.png | Bin 490 -> 0 bytes .../base/media/remote_create_folder.png | Bin 1971 -> 0 bytes .../base/media/remote_create_switch.png | Bin 3937 -> 0 bytes .../main/resources/base/media/remote_logo.png | Bin 12361 -> 0 bytes .../resources/base/media/remote_ref_back.png | Bin 1136 -> 0 bytes .../base/media/remote_ref_chevron.png | Bin 1942 -> 0 bytes .../media/remote_ref_chevron_centered.png | Bin 2151 -> 0 bytes .../base/media/remote_ref_chevron_right.png | Bin 2207 -> 0 bytes .../base/media/remote_ref_device.png | Bin 679 -> 0 bytes .../resources/base/media/remote_ref_down.png | Bin 916 -> 0 bytes .../resources/base/media/remote_ref_edit.png | Bin 1411 -> 0 bytes .../base/media/remote_ref_folder.png | Bin 4896 -> 0 bytes .../resources/base/media/remote_ref_menu.png | Bin 463 -> 0 bytes .../resources/base/media/remote_ref_mic.png | Bin 1232 -> 0 bytes .../resources/base/media/remote_ref_more.png | Bin 822 -> 0 bytes .../base/media/remote_ref_new_chat.png | Bin 2044 -> 0 bytes .../resources/base/media/remote_ref_plus.png | Bin 584 -> 0 bytes .../base/media/remote_ref_search.png | Bin 909 -> 0 bytes .../base/media/remote_ref_search_padded.png | Bin 923 -> 0 bytes .../media/remote_ref_search_reference.png | Bin 937 -> 0 bytes .../base/media/remote_ref_settings.png | Bin 1737 -> 0 bytes .../media/remote_ref_sidebar_connected.png | Bin 3129 -> 0 bytes .../media/settings_appearance_sun_visible.png | Bin 686 -> 0 bytes ...gs_appearance_up_down_chevrons_visible.png | Bin 398 -> 0 bytes .../base/media/settings_apps_grid.png | Bin 873 -> 0 bytes .../base/media/settings_chevron_right.png | Bin 336 -> 0 bytes .../resources/base/media/settings_close_x.png | Bin 590 -> 0 bytes .../base/media/settings_edit_pencil.png | Bin 554 -> 0 bytes .../base/media/settings_email_envelope.png | Bin 644 -> 0 bytes .../base/media/settings_help_about_info.png | Bin 711 -> 0 bytes .../base/media/settings_help_report_flag.png | Bin 445 -> 0 bytes .../base/media/settings_logout_arrow.png | Bin 520 -> 0 bytes .../base/media/settings_memory_book.png | Bin 662 -> 0 bytes .../media/settings_personalization_smile.png | Bin 838 -> 0 bytes .../resources/base/media/settings_phone.png | Bin 718 -> 0 bytes .../base/media/settings_profile_avatar_gw.png | Bin 18867 -> 0 bytes .../media/settings_restore_purchase_arrow.png | Bin 674 -> 0 bytes .../settings_subscription_plus_square.png | Bin 544 -> 0 bytes .../base/media/settings_upgrade_sparkle.png | Bin 806 -> 0 bytes .../base/media/sidebar_chevron_down.png | Bin 11909 -> 0 bytes .../base/media/sidebar_chevron_right.png | Bin 11752 -> 0 bytes .../base/media/sidebar_device_desktop.png | Bin 20750 -> 0 bytes .../base/media/sidebar_device_laptop.png | Bin 20517 -> 0 bytes .../base/media/sidebar_device_server.png | Bin 17667 -> 0 bytes .../media/sidebar_ref_search_reference.png | Bin 1312 -> 0 bytes .../media/sidebar_ref_settings_reference.png | Bin 1925 -> 0 bytes .../resources/base/profile/backup_config.json | 9 - .../main/resources/base/profile/easy_go.json | 8 - .../resources/base/profile/main_pages.json | 6 - .../main/resources/dark/element/color.json | 248 - .../dark/media/openbitfun_start_window.png | Bin 44411 -> 0 bytes .../main/resources/en_US/element/string.json | 3204 ------- .../main/resources/rawfile/editor/index.html | 10 - .../resources/rawfile/terminal/index.html | 1 - .../resources/rawfile/terminal/terminal.css | 32 - .../resources/rawfile/terminal/terminal.js | 58 - .../main/resources/zh_CN/element/string.json | 3204 ------- .../entry/src/mock/mock-config.json5 | 2 - .../src/ohosTest/ets/test/Ability.test.ets | 35 - .../ohosTest/ets/test/DeviceSmoke.test.ets | 31 - .../entry/src/ohosTest/ets/test/List.test.ets | 9 - .../ets/test/NativeCryptoLoad.test.ets | 54 - .../harmonyos/entry/src/ohosTest/module.json5 | 11 - .../src/test/AppRootLifecycleUnit.test.ets | 224 - .../test/AppRootRuntimeStartupUnit.test.ets | 40 - .../entry/src/test/ArchitectureUnit.test.ets | 553 -- .../ConversationPresentationUnit.test.ets | 1082 --- .../src/test/ConversationStateUnit.test.ets | 1771 ---- .../src/test/DeviceDirectoryUnit.test.ets | 845 -- .../entry/src/test/I18nUnit.test.ets | 172 - .../entry/src/test/LifecycleUnit.test.ets | 1023 -- .../harmonyos/entry/src/test/List.test.ets | 7 - .../entry/src/test/LocalTestFixtures.ets | 1414 --- .../entry/src/test/LocalUnit.test.ets | 29 - .../entry/src/test/MiniAppUnit.test.ets | 81 - .../test/MobilePreviewScenarioUnit.test.ets | 86 - .../src/test/RemoteControllersUnit.test.ets | 3048 ------ .../entry/src/test/TextScaleUnit.test.ets | 44 - .../test/TransportAndGeneralChatUnit.test.ets | 2278 ----- .../src/test/WatchProvisionUnit.test.ets | 139 - .../harmonyos/hvigor/hvigor-config.json5 | 23 - src/apps/mobile/harmonyos/hvigorfile.ts | 70 - src/apps/mobile/harmonyos/i18n/generate.cjs | 71 - .../mobile/harmonyos/miniapps/bundle.test.cjs | 51 - .../mobile/harmonyos/miniapps/generate.cjs | 5 - .../harmonyos/miniapps/storage.test.cjs | 84 - .../mobile/harmonyos/oh-package-lock.json5 | 28 - src/apps/mobile/harmonyos/oh-package.json5 | 10 - src/apps/mobile/harmonyos/scripts/ohos-env.sh | 11 - .../harmonyos/tools/check-catalog-refresh.py | 107 - .../harmonyos/tools/check-history-scroll.py | 97 - .../tools/check-rollback-session-isolation.py | 116 - .../mobile/harmonyos/tools/fake-relay.mjs | 1046 -- .../tools/tests/account-restore.test.cjs | 142 - .../assistant-message-copy-menu.test.cjs | 109 - ...assistant-message-copy-visibility.test.cjs | 33 - .../tests/clipboard-rich-payload.test.cjs | 152 - .../tools/tests/command-catalog.test.cjs | 433 - .../tests/command-palette-composer.test.cjs | 570 -- .../tests/command-palette-controller.test.cjs | 188 - .../tests/command-palette-policy.test.cjs | 422 - .../composer-content-affordance.test.cjs | 118 - .../tools/tests/composer-submit.test.cjs | 114 - .../tools/tests/connection-health.test.cjs | 247 - .../tests/device-directory-lifecycle.test.cjs | 221 - .../tests/device-model-defaults.test.cjs | 466 - .../tools/tests/file-visibility.test.cjs | 537 -- .../tools/tests/history-page-arrival.test.cjs | 29 - .../tools/tests/host-catalog.test.cjs | 99 - .../tools/tests/host-stream.test.cjs | 350 - .../tests/host-text-retranslator.test.cjs | 193 - .../tools/tests/immersive-bottom.test.cjs | 805 -- .../tools/tests/interaction-mailbox.test.cjs | 219 - .../tests/markdown-html-serializer.test.cjs | 285 - .../tools/tests/message-queue.test.cjs | 73 - .../tools/tests/model-role-pages.test.cjs | 727 -- .../tools/tests/model-role-selection.test.cjs | 223 - .../tools/tests/permission-mode.test.cjs | 39 - .../tests/relay-message-generation.test.cjs | 84 - .../tools/tests/rollback-preview.test.cjs | 218 - .../tests/rollback-session-isolation.test.cjs | 177 - .../tools/tests/rollback-wire.test.cjs | 157 - .../tools/tests/selection-capability.test.cjs | 76 - .../tools/tests/session-creation.test.cjs | 80 - .../tests/session-model-hydration.test.cjs | 87 - .../tools/tests/session-record.test.cjs | 526 - .../tests/session-rollback-policy.test.cjs | 271 - .../session-rollback-presentation.test.cjs | 291 - .../tools/tests/startup-reveal.test.cjs | 26 - .../tools/tests/stream-download.test.cjs | 13 - .../tools/tests/streaming-markdown.test.cjs | 49 - .../tests/subagent-branch-lifecycle.test.cjs | 584 -- .../subagent-process-visibility.test.cjs | 927 -- .../tools/tests/terminal-input.test.cjs | 27 - .../tools/tests/terminal-lifecycle.test.cjs | 102 - .../tools/tests/user-message-menu.test.cjs | 122 - .../tests/user-message-truncation.test.cjs | 131 - .../tests/watch-login-lifecycle.test.cjs | 65 - .../tests/watch-provision-recovery.test.cjs | 159 - .../tests/window-insets-lifecycle.test.cjs | 105 - .../tools/tests/workspace-catalog.test.cjs | 124 - .../tools/tests/workspace-editor.test.cjs | 130 - .../tools/tests/workspace-identity.test.cjs | 280 - .../tests/workspace-refresh-race.test.cjs | 79 - .../tools/tests/workspace-upload.test.cjs | 106 - .../ios/OpenBitFun.xcodeproj/project.pbxproj | 195 - src/apps/mobile/ios/OpenBitFun/App/.gitkeep | 1 - .../App/MobileLaunchConfiguration.swift | 411 - .../ios/OpenBitFun/App/OpenBitFunApp.swift | 90 - .../mobile/ios/OpenBitFun/Features/.gitkeep | 1 - .../Account/AccountDevicePickerSheet.swift | 197 - .../Account/AccountSettingsView.swift | 412 - .../Features/Chat/ChatTimelineView.swift | 1810 ---- .../Features/Chat/ComposerBar.swift | 669 -- .../Features/Chat/ConversationHeader.swift | 239 - .../Features/Chat/ConversationHomeViews.swift | 7 - .../Chat/HistoryPageArrivalTracker.swift | 16 - .../Features/Chat/MessageQueuePanel.swift | 123 - .../Chat/TimelineScrollController.swift | 385 - .../AdaptiveModalComponents.swift | 406 - .../GeneratedMobileDesignTokens.swift | 219 - .../GeneratedMobilePreviewScenarios.swift | 121 - .../DesignSystem/MobileDesignGallery.swift | 306 - .../Features/Remote/RemoteHomeViews.swift | 208 - .../Features/Settings/AppSettingsView.swift | 450 - .../Features/Shell/MiniAppsView.swift | 250 - .../Features/Shell/MobileShellView.swift | 504 - .../Features/Shell/OpenBitFunTheme.swift | 94 - .../Shell/RemoteCreateSessionView.swift | 1141 --- .../Shell/RemoteFilePreviewView.swift | 338 - .../Features/Shell/RemoteSettingsViews.swift | 182 - .../Shell/SessionActionComponents.swift | 300 - .../Features/Shell/SidebarDeviceRow.swift | 47 - .../Features/Shell/SidebarToolsFooter.swift | 50 - .../Features/Shell/SidebarView.swift | 1263 --- .../Features/Shell/StartupBrandReveal.swift | 229 - src/apps/mobile/ios/OpenBitFun/Info.plist | 52 - .../ios/OpenBitFun/Infrastructure/.gitkeep | 1 - .../Infrastructure/AccountFailureCopy.swift | 29 - .../Infrastructure/ChatImageThumbnail.swift | 21 - .../ComposerDismissGesture.swift | 23 - .../DictationDraftSession.swift | 25 - .../MobileAppModel+Account.swift | 366 - .../MobileAppModel+FilePreview.swift | 347 - .../MobileAppModel+GeneralChat.swift | 174 - .../MobileAppModel+RemoteSession.swift | 1585 --- .../Infrastructure/MobileAppModel.swift | 434 - .../Infrastructure/MobileCoreAdapter.swift | 773 -- .../Infrastructure/MobileLocalization.swift | 57 - .../Platform/SpeechInputController.swift | 115 - .../Platform/TaskCompletionNotifier.swift | 77 - .../Infrastructure/RemoteAuthorityGate.swift | 279 - .../RemoteHomePresentation.swift | 12 - .../StartupRevealPreference.swift | 13 - .../Infrastructure/StreamingTextState.swift | 59 - .../Models/MobilePresentationModels.swift | 563 -- .../AppIcon.appiconset/Contents.json | 14 - .../openbitfun-app-icon.png | Bin 83054 -> 0 bytes .../ApprovalShield.imageset/Contents.json | 12 - .../approval_shield.png | Bin 1324 -> 0 bytes .../ComposerMicGlyph.png | Bin 2502 -> 0 bytes .../ComposerMicGlyph.imageset/Contents.json | 13 - .../ComposerPlusGlyph.png | Bin 929 -> 0 bytes .../ComposerPlusGlyph.imageset/Contents.json | 13 - .../Resources.xcassets/Contents.json | 6 - .../MenuGlyph.imageset/Contents.json | 10 - .../gpt_home_menu_glyph.png | Bin 921 -> 0 bytes .../MoreGlyph.imageset/Contents.json | 10 - .../MoreGlyph.imageset/remote_ref_more.png | Bin 822 -> 0 bytes .../OpenBitFunMark.imageset/Contents.json | 13 - .../openbitfun-mark-light.png | Bin 125150 -> 0 bytes .../Contents.json | 4 - .../SidebarChevronGlyph.png | Bin 2207 -> 0 bytes .../SidebarDeviceGlyph.imageset/Contents.json | 4 - .../SidebarDeviceGlyph.png | Bin 679 -> 0 bytes .../SidebarDownGlyph.imageset/Contents.json | 4 - .../SidebarDownGlyph.png | Bin 916 -> 0 bytes .../SidebarEditGlyph.imageset/Contents.json | 4 - .../SidebarEditGlyph.png | Bin 1411 -> 0 bytes .../SidebarFolderGlyph.imageset/Contents.json | 4 - .../SidebarFolderGlyph.png | Bin 4896 -> 0 bytes .../SidebarMenuGlyph.imageset/Contents.json | 4 - .../SidebarMenuGlyph.png | Bin 463 -> 0 bytes .../Contents.json | 4 - .../SidebarNewChatGlyph.png | Bin 2044 -> 0 bytes .../SidebarPlusGlyph.imageset/Contents.json | 4 - .../SidebarPlusGlyph.png | Bin 584 -> 0 bytes .../SidebarSearchGlyph.imageset/Contents.json | 4 - .../SidebarSearchGlyph.png | Bin 937 -> 0 bytes .../Contents.json | 4 - .../SidebarSettingsGlyph.png | Bin 1925 -> 0 bytes .../Contents.json | 12 - .../preview.png | Bin 861924 -> 0 bytes .../Contents.json | 12 - .../preview.png | Bin 407608 -> 0 bytes .../Contents.json | 12 - .../preview.png | Bin 344299 -> 0 bytes .../mobile/ios/OpenBitFun/Resources/.gitkeep | 1 - .../Resources/Localizable.xcstrings | 8494 ----------------- .../OpenBitFun/Resources/MiniApps/.gitignore | 2 - .../PromptSuggestionUITests.swift | 27 - .../RemoteCodeSessionSendUITests.swift | 1830 ---- src/apps/mobile/ios/README.md | 134 - .../ios/Testing/AccountFailureCopyTests.swift | 28 - .../ios/Testing/ChatImageThumbnailTests.swift | 40 - .../Testing/ComposerDismissGestureTests.swift | 47 - .../Testing/DictationDraftSessionTests.swift | 25 - .../HistoryPageArrivalTrackerTests.swift | 21 - .../ios/Testing/MobileProcessGroupTests.swift | 97 - .../Testing/RemoteAuthorityGateTests.swift | 685 -- .../Testing/RemoteHomePresentationTests.swift | 33 - .../StartupRevealPreferenceTests.swift | 17 - .../ios/Testing/StreamingTextStateTests.swift | 54 - .../ios/Testing/run-pure-swift-tests.sh | 70 - src/apps/mobile/ios/miniapps.css | 12 - src/apps/mobile/miniapps/bridge.js | 48 - src/apps/mobile/miniapps/document.cjs | 37 - src/apps/mobile/miniapps/document.test.cjs | 41 - src/apps/mobile/miniapps/generate.cjs | 47 - src/apps/mobile/miniapps/mobile.css | 36 - src/apps/mobile/shared/build.gradle.kts | 17 - .../shared/core-crypto/build.gradle.kts | 136 - .../core/crypto/CloudAccountKdf.android.kt | 27 - .../crypto/CryptographyProviders.android.kt | 23 - .../mobile/core/crypto/Base64Codec.kt | 28 - .../mobile/core/crypto/CloudAccountKdf.kt | 24 - .../mobile/core/crypto/ContentHash.kt | 28 - .../core/crypto/CryptographyProviders.kt | 17 - .../mobile/core/crypto/DeviceIdentity.kt | 31 - .../mobile/core/crypto/RemoteCrypto.kt | 115 - .../mobile/core/crypto/RemoteCryptoCipher.kt | 96 - .../core/crypto/RemoteCryptoException.kt | 13 - .../mobile/core/crypto/SessionEventCipher.kt | 14 - .../openbitfun/mobile/core/crypto/X25519.kt | 73 - .../mobile/core/crypto/AesGcmCipherTest.kt | 95 - .../mobile/core/crypto/CloudAccountKdfTest.kt | 31 - .../mobile/core/crypto/DeviceIdentityTest.kt | 19 - .../mobile/core/crypto/HexTestSupport.kt | 19 - .../mobile/core/crypto/RemoteCryptoTest.kt | 107 - .../core/crypto/SessionEventCipherTest.kt | 22 - .../mobile/core/crypto/X25519Test.kt | 66 - .../mobile/core/crypto/CloudAccountKdf.ios.kt | 39 - .../core/crypto/CryptographyProviders.ios.kt | 12 - .../mobile/core/crypto/CloudAccountKdf.jvm.kt | 27 - .../core/crypto/CryptographyProviders.jvm.kt | 17 - .../cinterop/openbitfun_argon2.def | 4 - .../cinterop/openbitfun_argon2.h | 13 - .../cinterop/openbitfun_argon2_simulator.def | 4 - .../cinterop/openbitfun_argon2_wrapper.c | 25 - .../shared/core-domain/build.gradle.kts | 48 - .../core/domain/ChatSessionController.kt | 225 - .../core/domain/ChatTimelineProjector.kt | 202 - .../mobile/core/domain/ChatTimelineStore.kt | 903 -- .../mobile/core/domain/ConversationEvent.kt | 56 - .../mobile/core/domain/ConversationModels.kt | 126 - .../mobile/core/domain/FilePreview.kt | 288 - .../core/domain/GeneralChatEventMapper.kt | 145 - .../core/domain/GeneralChatExportFormatter.kt | 27 - .../domain/LegacyWorkspaceCompatibility.kt | 135 - .../mobile/core/domain/ModelLabelPolicy.kt | 77 - .../core/domain/ModelSelectionPolicy.kt | 20 - .../core/domain/RemoteWorkspaceIdentity.kt | 63 - .../mobile/core/domain/SessionListPolicy.kt | 83 - .../mobile/core/domain/StatusSemantics.kt | 30 - .../mobile/core/domain/ToolInputPolicy.kt | 145 - .../mobile/core/domain/ToolNamePolicy.kt | 107 - .../mobile/core/domain/ToolQuestionPolicy.kt | 69 - .../mobile/core/domain/ToolStatusPolicy.kt | 134 - .../core/domain/TranscriptIntegrityPolicy.kt | 24 - .../mobile/core/domain/WorkspaceModels.kt | 45 - .../core/domain/WorkspaceReferencePolicy.kt | 19 - .../core/domain/ChatSessionControllerTest.kt | 277 - .../core/domain/ChatTimelineProjectorTest.kt | 344 - .../core/domain/ChatTimelineStoreTest.kt | 842 -- .../mobile/core/domain/FilePreviewTest.kt | 111 - .../core/domain/GeneralChatEventMapperTest.kt | 93 - .../LegacyWorkspaceCompatibilityTest.kt | 129 - .../core/domain/ModelLabelPolicyTest.kt | 96 - .../core/domain/ModelSelectionPolicyTest.kt | 22 - .../domain/RemoteWorkspaceIdentityTest.kt | 37 - .../core/domain/SessionListPolicyTest.kt | 122 - .../core/domain/ToolQuestionPolicyTest.kt | 85 - .../core/domain/ToolStatusPolicyTest.kt | 120 - .../core/domain/WorkspaceDisplayNameTest.kt | 15 - .../shared/core-feature/build.gradle.kts | 69 - .../feature/account/AccountStore.android.kt | 30 - .../generalchat/GeneralChatStore.android.kt | 21 - .../core/feature/CloudSettingsSource.kt | 22 - .../openbitfun/mobile/core/feature/CoreLog.kt | 26 - .../core/feature/account/AccountDefaults.kt | 8 - .../core/feature/account/AccountDeviceLink.kt | 24 - .../feature/account/AccountDevicePolicy.kt | 60 - .../core/feature/account/AccountStore.kt | 832 -- .../core/feature/account/AccountUiState.kt | 130 - .../feature/account/MobileDeviceIdentity.kt | 4 - .../feature/account/TransportLogAdapter.kt | 10 - .../feature/connection/ConnectionStatus.kt | 86 - .../connection/RemoteControlPresentation.kt | 66 - .../feature/directory/DeviceDirectoryStore.kt | 544 -- .../directory/DeviceDirectoryUiState.kt | 197 - .../GeneralChatCloudConfigPolicy.kt | 146 - .../feature/generalchat/GeneralChatConfig.kt | 229 - .../feature/generalchat/GeneralChatStore.kt | 777 -- .../feature/generalchat/GeneralChatUiState.kt | 175 - .../layout/ConversationLayoutPolicy.kt | 231 - .../layout/FilePreviewPlacementPolicy.kt | 196 - .../feature/layout/SettingsPlacementPolicy.kt | 197 - .../generated/MobileDesignBreakpoints.kt | 8 - .../core/feature/markdown/MarkdownParser.kt | 361 - .../core/feature/relay/HostCatalogObserver.kt | 94 - .../session/ChatComposerCapabilities.kt | 50 - .../feature/session/ChatComposerPolicy.kt | 105 - .../session/ConversationHeaderPresentation.kt | 29 - .../session/ConversationModelPresentation.kt | 97 - .../session/ConversationPresentation.kt | 354 - .../session/CreateSessionPresentation.kt | 38 - .../feature/session/DurableSessionReducer.kt | 90 - .../feature/session/HarnessProfilePolicy.kt | 24 - .../session/MessageBlockPresentation.kt | 349 - .../feature/session/MessageFileReferences.kt | 123 - .../core/feature/session/MessageQueueStore.kt | 119 - .../feature/session/ModelCatalogContract.kt | 19 - .../feature/session/PermissionMailboxStore.kt | 160 - .../core/feature/session/PlanToolPolicy.kt | 25 - .../session/RecentSessionsPresentation.kt | 21 - .../session/RemoteSessionFailureMapping.kt | 43 - .../feature/session/RemoteSessionStore.kt | 2428 ----- .../feature/session/RemoteSessionUiState.kt | 640 -- .../feature/session/SessionActionPolicy.kt | 44 - .../session/SessionListPresentation.kt | 492 - .../feature/session/SessionRecordReplica.kt | 261 - .../session/SessionTimePresentation.kt | 130 - .../feature/session/TaskCompletionPolicy.kt | 50 - .../session/ToolApprovalEditContract.kt | 14 - .../core/feature/session/ToolQuestion.kt | 29 - .../feature/session/ToolRowPresentation.kt | 157 - .../shell/RemoteSidebarPresentation.kt | 145 - .../core/feature/shell/SidebarPresentation.kt | 61 - .../workspace/CodeSyntaxHighlighter.kt | 389 - .../feature/workspace/RemoteWorkspaceStore.kt | 1115 --- .../workspace/RemoteWorkspaceUiState.kt | 323 - .../feature/workspace/RuntimeFilesStore.kt | 204 - .../feature/workspace/RuntimeTerminalStore.kt | 168 - .../feature/workspace/RuntimeUploadSource.kt | 9 - .../workspace/WorkspaceCatalogUiState.kt | 56 - .../feature/account/AccountDeviceLinkTest.kt | 55 - .../core/feature/account/AccountStoreTest.kt | 941 -- .../ConnectionStatusPresenterTest.kt | 29 - .../connection/RemoteControlPresenterTest.kt | 79 - .../directory/DeviceDirectoryStoreTest.kt | 724 -- .../WorkspaceSessionPersistenceTest.kt | 29 - .../GeneralChatCloudConfigPolicyTest.kt | 156 - .../generalchat/GeneralChatStoreTest.kt | 645 -- .../layout/ConversationLayoutPolicyTest.kt | 197 - .../layout/FilePreviewPlacementPolicyTest.kt | 190 - .../layout/SettingsPlacementPolicyTest.kt | 105 - .../feature/markdown/MarkdownParserTest.kt | 73 - .../feature/relay/HostCatalogObserverTest.kt | 115 - .../feature/session/ChatComposerPolicyTest.kt | 192 - .../ConversationHeaderPresentationTest.kt | 30 - .../ConversationModelPresentationTest.kt | 140 - .../session/ConversationPresentationTest.kt | 296 - .../session/CreateSessionPresentationTest.kt | 39 - .../session/DurableSessionReducerTest.kt | 36 - .../session/MessageBlockPresentationTest.kt | 445 - .../session/MessageFileReferencesTest.kt | 73 - .../feature/session/MessageQueueStoreTest.kt | 122 - .../feature/session/MobileParityPolicyTest.kt | 59 - .../session/PermissionMailboxStoreTest.kt | 221 - .../feature/session/PlanToolPolicyTest.kt | 23 - .../session/RecentSessionsPresentationTest.kt | 23 - .../session/RemoteResponseMapperTest.kt | 223 - .../session/RemoteSessionPersistenceTest.kt | 647 -- .../feature/session/RemoteSessionStoreTest.kt | 2522 ----- .../session/SessionActionPolicyTest.kt | 37 - .../feature/session/SessionAgentFilterTest.kt | 27 - .../session/SessionListPresentationTest.kt | 339 - .../session/SessionRecordReplicaTest.kt | 259 - .../session/SessionTimePresentationTest.kt | 73 - .../session/ToolRowPresentationTest.kt | 65 - .../shell/RemoteSidebarPresentationTest.kt | 213 - .../feature/shell/SidebarPresentationTest.kt | 90 - .../workspace/CodeSyntaxHighlighterTest.kt | 141 - .../workspace/FilePreviewFormatTest.kt | 31 - .../workspace/RemoteWorkspaceStoreTest.kt | 1152 --- .../workspace/RuntimeFilesStoreTest.kt | 248 - .../workspace/RuntimeTerminalStoreTest.kt | 211 - .../feature/workspace/WorkspaceCatalogTest.kt | 91 - .../core/feature/account/AccountStore.ios.kt | 25 - .../generalchat/GeneralChatStore.ios.kt | 16 - .../shared/core-persistence/build.gradle.kts | 65 - .../persistence/AndroidSecureStoreTest.kt | 22 - .../core/persistence/AndroidDraftStore.kt | 8 - .../core/persistence/AndroidSecureStore.kt | 90 - .../core/persistence/TemporaryDownload.kt | 12 - .../mobile/core/persistence/ChatLocalStore.kt | 476 - .../mobile/core/persistence/DraftStore.kt | 31 - .../mobile/core/persistence/SecureStore.kt | 10 - .../core/persistence/TemporaryDownload.kt | 9 - .../mobile/core/persistence/db/1.sqm | 6 - .../mobile/core/persistence/db/2.sqm | 41 - .../mobile/core/persistence/db/3.sqm | 3 - .../mobile/core/persistence/db/4.sqm | 10 - .../mobile/core/persistence/db/5.sqm | 11 - .../mobile/core/persistence/db/6.sqm | 33 - .../mobile/core/persistence/db/7.sqm | 8 - .../mobile/core/persistence/db/Mobile.sq | 193 - .../mobile/core/persistence/IosDraftStore.kt | 7 - .../mobile/core/persistence/IosSecureStore.kt | 150 - .../core/persistence/TemporaryDownload.kt | 19 - .../core/persistence/IosSecureStoreTest.kt | 39 - .../core/persistence/TemporaryDownload.kt | 12 - .../mobile/core/persistence/DraftStoreTest.kt | 61 - .../persistence/RemotePersistenceStoreTest.kt | 360 - .../core/persistence/TemporaryDownloadTest.kt | 19 - .../shared/core-protocol/build.gradle.kts | 75 - .../mobile/core/protocol/CommandStatus.kt | 43 - .../mobile/core/protocol/DialogQueue.kt | 41 - .../mobile/core/protocol/EncryptedPayload.kt | 19 - .../mobile/core/protocol/FileDtos.kt | 31 - .../mobile/core/protocol/GeneralChatDtos.kt | 27 - .../mobile/core/protocol/MessageDtos.kt | 111 - .../mobile/core/protocol/ModelCatalogDtos.kt | 86 - .../mobile/core/protocol/Pairing.kt | 78 - .../protocol/ProvisionPeerDeviceContract.kt | 18 - .../mobile/core/protocol/RelayJson.kt | 23 - .../mobile/core/protocol/RemoteCommand.kt | 110 - .../mobile/core/protocol/SessionDtos.kt | 145 - .../mobile/core/protocol/WireTime.kt | 98 - .../mobile/core/protocol/WorkspaceDtos.kt | 153 - .../core/protocol/EncryptedPayloadTest.kt | 22 - .../core/protocol/ModelCatalogDtoTest.kt | 126 - .../mobile/core/protocol/RemoteCommandTest.kt | 268 - .../core/protocol/SessionItemContractTest.kt | 136 - .../mobile/core/protocol/WorkspaceHostTest.kt | 21 - .../shared/core-testing/build.gradle.kts | 31 - .../shared/core-transport/build.gradle.kts | 123 - .../core/transport/AccountDeviceLink.kt | 48 - .../mobile/core/transport/AccountRealtime.kt | 261 - .../mobile/core/transport/ClientBuild.kt | 37 - .../core/transport/CloudAccountClient.kt | 791 -- .../mobile/core/transport/HostStream.kt | 454 - .../core/transport/ModelProviderStream.kt | 260 - .../mobile/core/transport/RelayFailure.kt | 65 - .../mobile/core/transport/RelayHttpClient.kt | 55 - .../core/transport/RelayMessageEncoding.kt | 45 - .../core/transport/RemoteCommandTransport.kt | 20 - .../mobile/core/transport/RpcPayload.kt | 70 - .../mobile/core/transport/SseFrameDecoder.kt | 30 - .../mobile/core/transport/TransportLog.kt | 27 - .../core/transport/CloudAccountClientTest.kt | 588 -- .../mobile/core/transport/HostStreamTest.kt | 493 - .../core/transport/ModelProviderStreamTest.kt | 83 - .../transport/RelayMessageEncodingTest.kt | 20 - .../core/transport/SseFrameDecoderTest.kt | 36 - .../core/transport/ClientBuildContractTest.kt | 53 - .../core/transport/OkHttpRealtimeTest.kt | 129 - .../transport/RealtimeRelayIntegrationTest.kt | 49 - .../core/transport/RpcProcessingThreadTest.kt | 71 - src/apps/mobile/shared/gradle.properties | 8 - .../mobile/shared/gradle/libs.versions.toml | 92 - .../shared/gradle/wrapper/gradle-wrapper.jar | Bin 47505 -> 0 bytes .../gradle/wrapper/gradle-wrapper.properties | 10 - src/apps/mobile/shared/gradlew | 248 - src/apps/mobile/shared/gradlew.bat | 82 - src/apps/mobile/shared/settings.gradle.kts | 34 - .../shared/swift-smoke/MobileCoreSmoke.swift | 5 - .../harmony-file-editor-browser.test.mjs | 22 - .../native-terminal-renderer-browser.test.mjs | 43 - src/shared/argon2/argon2.c | 452 - src/shared/argon2/argon2.h | 437 - src/shared/argon2/blake2/blake2-impl.h | 156 - src/shared/argon2/blake2/blake2.h | 89 - src/shared/argon2/blake2/blake2b.c | 390 - src/shared/argon2/blake2/blamka-round-opt.h | 471 - src/shared/argon2/blake2/blamka-round-ref.h | 56 - src/shared/argon2/core.c | 648 -- src/shared/argon2/core.h | 228 - src/shared/argon2/encoding.c | 461 - src/shared/argon2/encoding.h | 57 - src/shared/argon2/opt.c | 283 - src/shared/argon2/ref.c | 194 - src/shared/argon2/run.c | 335 - src/shared/argon2/thread.c | 57 - src/shared/argon2/thread.h | 67 - .../README.md | 8 +- src/shared/terminal/webview/README.md | 11 - .../terminal/webview/generated/index.html | 1 - .../terminal/webview/generated/terminal.css | 32 - .../terminal/webview/generated/terminal.js | 58 - src/shared/terminal/webview/index.ts | 68 - 1185 files changed, 55 insertions(+), 208235 deletions(-) delete mode 100644 .github/workflows/mobile-package.yml delete mode 100644 scripts/build-mobile-terminal.mjs delete mode 100644 scripts/check-harmonyos-architecture.mjs delete mode 100644 scripts/check-mobile-architecture.mjs delete mode 100644 scripts/mobile-ui-design-system.mjs delete mode 100644 scripts/mobile-ui-preview.mjs delete mode 100644 src/apps/mobile/AGENTS.md delete mode 100644 src/apps/mobile/README.md delete mode 100644 src/apps/mobile/android/AGENTS.md delete mode 100644 src/apps/mobile/android/README.md delete mode 100644 src/apps/mobile/android/app/build.gradle.kts delete mode 100644 src/apps/mobile/android/app/proguard-rules.pro delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountLoginPageTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountRemoteScreenTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerModelSelectorTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConnectionSheetChromeTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationHeaderTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/CreateSessionScreenTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/FileReferenceCardsTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/HarnessProfileMenuTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileDesignPreviewVisualTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileParityTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobilePreviewStatesVisualTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileScreenTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/NotificationOnboardingTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/PermissionModeCardTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/QuestionDraftTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSessionListViewTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSettingsSheetTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileBrowserTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileEditorTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeTerminalViewTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeWorkspacePickerTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/SymbolDrawableTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/TestStrings.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolConfirmationPanelTest.kt delete mode 100644 src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolStatusRowTest.kt delete mode 100644 src/apps/mobile/android/app/src/debug/AndroidManifest.xml delete mode 100644 src/apps/mobile/android/app/src/main/AndroidManifest.xml delete mode 100644 src/apps/mobile/android/app/src/main/assets/miniapps/.gitignore delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/.gitkeep delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AccountAvatarLoader.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AndroidRuntimeUploadSource.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AppLocaleController.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerImageEncoder.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/DeviceInstall.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/GeneratedLocaleContract.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/LogcatCoreLog.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/NotificationOnboarding.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/StartupRevealPreference.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/TaskCompletionNotifier.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/WindowMetrics.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/SessionViewSettings.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountLoginScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountProfileCards.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatStatusBar.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationHeader.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationTimelineView.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/FileReferenceCards.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/OpenBitFunHeaderActionMenu.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ChatMessageChrome.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/MessageBlockList.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ProcessPresentation.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanels.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/AdaptiveModalSurface.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/CircleControl.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionLabels.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionSheetChrome.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/miniapps/MiniApps.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobileDesignGallery.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobilePreviewStates.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/generated/MobilePreviewScenarios.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/ConnectAccountDeviceScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DeviceToolsDialog.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicy.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/FilePreviewSurface.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/HarnessProfileLabel.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/PairingScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteDownloadSaver.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteSessionListView.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeTerminalView.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspaceDialogs.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspacePickerDialog.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/SessionActionSheet.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/CurrentControlCard.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/ModelServiceScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/PermissionModeCard.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/RemoteSettingsSheet.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SessionViewSettingsSheet.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsChrome.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/ColdStartHomeTransition.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/NotificationOnboarding.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/OpenBitFunCompactDrawer.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/StartupBrandReveal.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeBrandFlow.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeHome.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/AppSidebar.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicy.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarChrome.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarDeviceSelectorRow.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarFooter.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarHeader.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarSessionList.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/OpenBitFunMotion.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/Theme.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/generated/MobileDesignTokens.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AccountViewModel.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AppSettingsViewModel.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/ComposerAttachmentsViewModel.kt delete mode 100644 src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/GeneralChatViewModel.kt delete mode 100644 src/apps/mobile/android/app/src/main/res/.gitkeep delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable-nodpi/approval_shield.png delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_archivebox.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_clockwise.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_down_to_line.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_right_and_square.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_triangle_merge.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_up.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle_fill.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_down.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left_wide.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_right.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_up.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_circle.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_cloud.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_code_square.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_desktop.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_arrow_up.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_magnifyingglass.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_ellipsis.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye_slash.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_folder.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_gearshape.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_info_circle.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_link.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_list_checkmark.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_magnifyingglass.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_menu_lines.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_message.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_mic.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_person.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_picture.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_plus.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_questionmark_circle.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_rectangle_stack.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_robot.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_and_pencil.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_grid_2x2.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_trash.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_website.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_wrench_and_screwdriver.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_xmark.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/miniapp_divination_preview.webp delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/miniapp_gomoku_preview.webp delete mode 100644 src/apps/mobile/android/app/src/main/res/drawable/miniapp_regex_preview.webp delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png delete mode 100644 src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png delete mode 100644 src/apps/mobile/android/app/src/main/res/values-zh/strings.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/values/ic_launcher_background.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/values/strings.xml delete mode 100644 src/apps/mobile/android/app/src/main/res/values/themes.xml delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/AppLocaleResolverTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/FoldFactsTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBreakpointTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationComposerDraftTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationScrollPolicyTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/HistoryPageArrivalTrackerTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ProcessPresentationTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanelsTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicyTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/ContentCardCoordinatorTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicyTest.kt delete mode 100644 src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/theme/MobileTextScaleTest.kt delete mode 100644 src/apps/mobile/android/build.gradle.kts delete mode 100644 src/apps/mobile/android/gradle.properties delete mode 100644 src/apps/mobile/android/gradle/wrapper/gradle-wrapper.jar delete mode 100644 src/apps/mobile/android/gradle/wrapper/gradle-wrapper.properties delete mode 100755 src/apps/mobile/android/gradlew delete mode 100644 src/apps/mobile/android/gradlew.bat delete mode 100644 src/apps/mobile/android/settings.gradle.kts delete mode 100644 src/apps/mobile/design-system/README.md delete mode 100644 src/apps/mobile/design-system/assets/approval-shield.svg delete mode 100644 src/apps/mobile/design-system/assets/welcome-brand-contours.json delete mode 100644 src/apps/mobile/design-system/components/mobile-components.json delete mode 100644 src/apps/mobile/design-system/preview/generated/mobile-design-data.js delete mode 100644 src/apps/mobile/design-system/preview/index.html delete mode 100644 src/apps/mobile/design-system/preview/preview-scenarios.smoke.test.mjs delete mode 100644 src/apps/mobile/design-system/preview/preview.css delete mode 100644 src/apps/mobile/design-system/preview/preview.js delete mode 100644 src/apps/mobile/design-system/preview/snapshots/.gitignore delete mode 100644 src/apps/mobile/design-system/preview/snapshots/README.md delete mode 100644 src/apps/mobile/design-system/scenarios/mobile-preview-scenarios.json delete mode 100644 src/apps/mobile/design-system/tokens/mobile-tokens.json delete mode 100644 src/apps/mobile/docs/remote-session-lifecycle.md delete mode 100644 src/apps/mobile/harmonyos/.gitignore delete mode 100644 src/apps/mobile/harmonyos/AGENTS.md delete mode 100644 src/apps/mobile/harmonyos/AppScope/app.json5 delete mode 100644 src/apps/mobile/harmonyos/AppScope/resources/base/element/string.json delete mode 100644 src/apps/mobile/harmonyos/AppScope/resources/base/media/openbitfun_app_icon.png delete mode 100644 src/apps/mobile/harmonyos/AppScope/resources/base/profile/configuration.json delete mode 100644 src/apps/mobile/harmonyos/README.md delete mode 100644 src/apps/mobile/harmonyos/build-profile.json5 delete mode 100644 src/apps/mobile/harmonyos/code-linter.json5 delete mode 100644 src/apps/mobile/harmonyos/docs/adaptive-sheet-placement-design.md delete mode 100644 src/apps/mobile/harmonyos/docs/harmonyos-i18n-design.md delete mode 100644 src/apps/mobile/harmonyos/docs/mobile-control-console-design.md delete mode 100644 src/apps/mobile/harmonyos/docs/mobile-detached-dispatch-design.md delete mode 100644 src/apps/mobile/harmonyos/docs/model-service-settings-sheet-design.md delete mode 100644 src/apps/mobile/harmonyos/docs/mvvm-architecture-refactor-design.md delete mode 100644 src/apps/mobile/harmonyos/docs/wide-conversation-navigation-design.md delete mode 100644 src/apps/mobile/harmonyos/entry/.gitignore delete mode 100644 src/apps/mobile/harmonyos/entry/build-profile.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/hvigorfile.ts delete mode 100644 src/apps/mobile/harmonyos/entry/obfuscation-rules.txt delete mode 100644 src/apps/mobile/harmonyos/entry/oh-package-lock.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/oh-package.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/cpp/CMakeLists.txt delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/cpp/napi_argon2.cpp delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/cpp/relay_message_encoding.cpp delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/index.d.ts delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/oh-package.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/entryability/EntryAbility.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobileDesignTokens.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobilePreviewScenarios.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/i18n/AppLocale.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/i18n/HostTextRetranslator.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/i18n/MessageTemplate.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/ChatTimelineModels.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/ComposerSubmission.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/FilePreviewTarget.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/InteractionMailbox.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/MiniAppModels.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/AppRootPresentationActions.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountLoginSheet.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountProfilePanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AdaptiveSheetOptions.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppActionButton.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootOverlaySurfaces.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootPresentation.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppShell.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppSidebar.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/BrandMark.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageContent.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatStatusBar.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ColdStartHomeTransition.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CommandChipRow.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CompactMenuButton.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectAccountDevicePage.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationHeader.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationLoadingState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationRouteSurface.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewContract.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewHost.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewSettings.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CurrentControlSection.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DefaultAccountAvatar.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DeviceModelDefaultsPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FilePreviewSurface.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FileReferenceCard.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/HarnessProfileMenu.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/InteractionMailboxPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LanguageSettingsPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MarkdownContent.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppSurface.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppWebView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelRolePickerPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelServiceSettingsPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelUnavailableCard.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/NavigationBackButton.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/OpenBitFunAccountLoginPage.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RecentRemoteHome.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteConnectionPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemotePermissionSection.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionList.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionLoadingView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionRow.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackSelectionMenu.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackStagingBar.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionActionSurface.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionDetailsView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SettingsSheet.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetActionFooter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseButton.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseHeader.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetLayout.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarGlyphs.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarNavigationIcons.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToggleButton.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToolsFooter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspacePicker.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspaceSection.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SkillPickerSheet.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StartupBrandReveal.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StreamingMarkdownContent.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SubagentTaskCard.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/TemplateIcon.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/Theme.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ThinkingBlock.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolGlyphs.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolInteractionPanels.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UsageReportSheet.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UserMessageFullTextSheet.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WatchProvisionCard.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeBrandFlow.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeHome.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WideConversationHost.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceFileEditorView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceTerminalView.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceToolsPanel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/remote/RemoteSurfaceHost.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/host/AppRootHostAdapter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/layout/WideLayoutGeometry.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRootRouteState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRouteContract.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountDeviceSelectionPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountLoginErrorPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ActivityGroupPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AdaptiveLayoutInput.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantMessageCopyMenuPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantProcessLayoutPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConnectSheetLandingPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationHeaderPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationLayoutPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationMessageRenderPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationModelPresentationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationSessionFilterPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/DeviceModelSettingsEntryPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FilePreviewPlacementPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FileTargetResolver.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HarnessProfilePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HistoryPageArrivalTracker.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/MessageFileReferenceProjector.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelRoleCandidatesPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelServiceSettingsPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/PlanToolPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteCompactHomePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteSurfaceEntryPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RollbackPresentationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RuntimeLocationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SelectionCapabilityPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionActionPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionListProjection.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionRollbackPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPagePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPlacementPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarConnectionActionPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDeviceProjectionPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDirectoryPreviewPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ThinkingPresentationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolFileReferenceResolver.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolStatusPresentationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UsageReportPresentationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageMenuPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageTruncationPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CatalogRefreshPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ColdStartHomePreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CommandPalettePreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerOverflowPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerSubmissionPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CopySelectionPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceModelDefaultsPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceSelectorPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DurableTimelinePreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/FileVisibilityPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/HistoryScrollPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ImmersiveBottomPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/InteractionMailboxPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/MobileDesignGallery.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ModelRoleSelectorPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackPreviewScenario.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackStagingPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentProcessPreview.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentSwarmFixture.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/AppShellState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatComposerCapabilities.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatSurface.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ColdStartPresentationState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/CommandPaletteState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationCoreState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationUiModels.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceModelDefaultsSheetState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/FilePreviewState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/GeneralChatPageState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/MiniAppState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SettingsSheetState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SubagentBranchExpansionState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WatchProvisionState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WorkspaceToolsState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/AppShellViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationRuntime.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/DeviceDirectoryViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/FilePreviewController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/GeneralChatConversationViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/LocaleController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/MiniAppViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteActivityViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteConnectionController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteCreateFlowController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteFilePreviewController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteSessionViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteTranscriptController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteWorkspaceViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/VisibleConversationController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/WorkspaceToolsViewModel.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceDirectory.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceLink.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountRealtime.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/AsyncLifecycleGate.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/BuiltinMiniAppHost.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatComposerPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineProjector.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ClipboardService.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountCrypto.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/CodeSyntaxHighlighter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandCatalogProjection.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandPalettePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ConcurrentWorkspaceListing.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionErrorPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionStatusPresenter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ConversationEvent.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/DeferredLoadingGate.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceApiLevelService.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceDirectoryCoordinator.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/Encoding.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewErrorPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/GitHubAccountProfile.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyTaskCompletionNotificationPort.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyUpgradeIdentityContract.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/HostCatalogObserver.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/HostInvokeRefusal.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/ImagePickerService.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/InteractionMailboxStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/KeyboardReleaseService.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/LegacyWorkspaceCompatibility.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/LocalePreferenceStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MainThreadStallProbe.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownHtmlSerializer.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppDocument.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MobileIdentityStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/MotionPreference.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/OhosError.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RelayMessageEncoding.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteActivityLifecycleController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatBranchCache.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCache.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCommandController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatLocalRdbStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandFactory.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandPaletteController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandTransport.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteConnectionCoordinator.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCrypto.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteFileDownloadController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteHeartbeatController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteLogger.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelDefaultsController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteResponseMapper.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionIdentity.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListCache.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListRdbStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteToolActionController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteUiState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceCoordinator.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceFileClient.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceRepository.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RollbackOutcomePolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/RpcPayload.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/StartupRevealPreference.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/TaskCompletionNotificationController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/TranscriptIntegrityPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputLifecycleController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputService.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchHandoffStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionCrypto.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionDisplay.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionProtocol.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WindowSystemBarService.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceFileUploadClient.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/X25519.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiClient.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiModels.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatBootstrapController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCloudConfigPolicy.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCommandController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatConfigStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftLifecycleController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatEventMapper.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatExportFormatter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatHttpTransport.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatLocalRdbStore.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatPort.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatRepository.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatServiceState.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamCoordinator.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamLifecycleController.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/MockGeneralChatAdapter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderGeneralChatAdapter.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderSseParser.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/module.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/element/color.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/element/float.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/approval_shield.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_chat_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_mic.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_plus.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send_arrow.svg delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_chat_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_globe_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_image_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_menu_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_mic_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_plus_glyph.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_voice_button.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_search_logo.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_settings_logo.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/harness_creative.svg delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/harness_minimal.svg delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/harness_standard.svg delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/harness_ultimate.svg delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/miniapp_divination_preview.webp delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/miniapp_gomoku_preview.webp delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/miniapp_regex_preview.webp delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/openbitfun_app_icon.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/openbitfun_brand_mark.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/openbitfun_start_window.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_chat.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_check.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_clock.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_cloud.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_folder.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_link.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_actions_settings.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_create_chat.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_create_device.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_create_folder.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_create_switch.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_logo.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_back.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_chevron.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_chevron_centered.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_chevron_right.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_device.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_down.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_edit.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_folder.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_menu.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_mic.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_more.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_new_chat.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_plus.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_search.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_search_padded.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_search_reference.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_settings.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/remote_ref_sidebar_connected.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_appearance_sun_visible.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_appearance_up_down_chevrons_visible.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_apps_grid.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_chevron_right.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_close_x.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_edit_pencil.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_email_envelope.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_help_about_info.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_help_report_flag.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_logout_arrow.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_memory_book.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_personalization_smile.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_phone.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_profile_avatar_gw.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_restore_purchase_arrow.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_subscription_plus_square.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/settings_upgrade_sparkle.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_chevron_down.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_chevron_right.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_device_desktop.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_device_laptop.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_device_server.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_ref_search_reference.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/media/sidebar_ref_settings_reference.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/profile/backup_config.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/profile/easy_go.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/base/profile/main_pages.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/dark/element/color.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/dark/media/openbitfun_start_window.png delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/editor/index.html delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/terminal/index.html delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/terminal/terminal.css delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/terminal/terminal.js delete mode 100644 src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json delete mode 100644 src/apps/mobile/harmonyos/entry/src/mock/mock-config.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/Ability.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/DeviceSmoke.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/List.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/ohosTest/ets/test/NativeCryptoLoad.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/ohosTest/module.json5 delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/AppRootLifecycleUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/AppRootRuntimeStartupUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/ArchitectureUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/ConversationPresentationUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/ConversationStateUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/DeviceDirectoryUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/I18nUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/LifecycleUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/List.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/LocalTestFixtures.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/LocalUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/MiniAppUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/MobilePreviewScenarioUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/RemoteControllersUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/TextScaleUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/TransportAndGeneralChatUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/entry/src/test/WatchProvisionUnit.test.ets delete mode 100644 src/apps/mobile/harmonyos/hvigor/hvigor-config.json5 delete mode 100644 src/apps/mobile/harmonyos/hvigorfile.ts delete mode 100644 src/apps/mobile/harmonyos/i18n/generate.cjs delete mode 100644 src/apps/mobile/harmonyos/miniapps/bundle.test.cjs delete mode 100644 src/apps/mobile/harmonyos/miniapps/generate.cjs delete mode 100644 src/apps/mobile/harmonyos/miniapps/storage.test.cjs delete mode 100644 src/apps/mobile/harmonyos/oh-package-lock.json5 delete mode 100644 src/apps/mobile/harmonyos/oh-package.json5 delete mode 100644 src/apps/mobile/harmonyos/scripts/ohos-env.sh delete mode 100644 src/apps/mobile/harmonyos/tools/check-catalog-refresh.py delete mode 100644 src/apps/mobile/harmonyos/tools/check-history-scroll.py delete mode 100644 src/apps/mobile/harmonyos/tools/check-rollback-session-isolation.py delete mode 100644 src/apps/mobile/harmonyos/tools/fake-relay.mjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/assistant-message-copy-menu.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/assistant-message-copy-visibility.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/clipboard-rich-payload.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/command-catalog.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/command-palette-composer.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/command-palette-controller.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/command-palette-policy.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/composer-content-affordance.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/composer-submit.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/connection-health.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/device-directory-lifecycle.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/device-model-defaults.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/file-visibility.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/history-page-arrival.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/host-catalog.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/host-stream.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/host-text-retranslator.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/immersive-bottom.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/interaction-mailbox.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/markdown-html-serializer.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/message-queue.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/model-role-pages.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/model-role-selection.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/permission-mode.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/relay-message-generation.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/rollback-preview.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/rollback-session-isolation.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/rollback-wire.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/selection-capability.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/session-creation.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/session-model-hydration.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/session-record.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/session-rollback-policy.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/session-rollback-presentation.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/startup-reveal.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/stream-download.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/streaming-markdown.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/subagent-branch-lifecycle.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/subagent-process-visibility.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/terminal-input.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/terminal-lifecycle.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/user-message-menu.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/user-message-truncation.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/watch-login-lifecycle.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/watch-provision-recovery.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/window-insets-lifecycle.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/workspace-catalog.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/workspace-identity.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/workspace-refresh-race.test.cjs delete mode 100644 src/apps/mobile/harmonyos/tools/tests/workspace-upload.test.cjs delete mode 100644 src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj delete mode 100644 src/apps/mobile/ios/OpenBitFun/App/.gitkeep delete mode 100644 src/apps/mobile/ios/OpenBitFun/App/MobileLaunchConfiguration.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/App/OpenBitFunApp.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/.gitkeep delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Account/AccountDevicePickerSheet.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Account/AccountSettingsView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/ChatTimelineView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/ConversationHeader.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/ConversationHomeViews.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/HistoryPageArrivalTracker.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/MessageQueuePanel.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Chat/TimelineScrollController.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/AdaptiveModalComponents.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/GeneratedMobileDesignTokens.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/GeneratedMobilePreviewScenarios.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/DesignSystem/MobileDesignGallery.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Remote/RemoteHomeViews.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Settings/AppSettingsView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/MiniAppsView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/MobileShellView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/OpenBitFunTheme.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/RemoteCreateSessionView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/RemoteFilePreviewView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/RemoteSettingsViews.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/SessionActionComponents.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarDeviceRow.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarToolsFooter.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/SidebarView.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Features/Shell/StartupBrandReveal.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Info.plist delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/.gitkeep delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/AccountFailureCopy.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/ChatImageThumbnail.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/ComposerDismissGesture.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/DictationDraftSession.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+Account.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+FilePreview.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+GeneralChat.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileCoreAdapter.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileLocalization.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/Platform/SpeechInputController.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/Platform/TaskCompletionNotifier.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/RemoteAuthorityGate.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/RemoteHomePresentation.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/StartupRevealPreference.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Infrastructure/StreamingTextState.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Presentation/Models/MobilePresentationModels.swift delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/AppIcon.appiconset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/AppIcon.appiconset/openbitfun-app-icon.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/ApprovalShield.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/ApprovalShield.imageset/approval_shield.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/ComposerMicGlyph.imageset/ComposerMicGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/ComposerMicGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/ComposerPlusGlyph.imageset/ComposerPlusGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/ComposerPlusGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/MenuGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/MenuGlyph.imageset/gpt_home_menu_glyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/MoreGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/MoreGlyph.imageset/remote_ref_more.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/OpenBitFunMark.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/OpenBitFunMark.imageset/openbitfun-mark-light.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarChevronGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarChevronGlyph.imageset/SidebarChevronGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarDeviceGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarDeviceGlyph.imageset/SidebarDeviceGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarDownGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarDownGlyph.imageset/SidebarDownGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarEditGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarEditGlyph.imageset/SidebarEditGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarFolderGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarFolderGlyph.imageset/SidebarFolderGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarMenuGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarMenuGlyph.imageset/SidebarMenuGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarNewChatGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarNewChatGlyph.imageset/SidebarNewChatGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarPlusGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarPlusGlyph.imageset/SidebarPlusGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarSearchGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarSearchGlyph.imageset/SidebarSearchGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarSettingsGlyph.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/SidebarSettingsGlyph.imageset/SidebarSettingsGlyph.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/miniapp-builtin-daily-divination.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/miniapp-builtin-daily-divination.imageset/preview.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/miniapp-builtin-gomoku.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/miniapp-builtin-gomoku.imageset/preview.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/miniapp-builtin-regex-playground.imageset/Contents.json delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources.xcassets/miniapp-builtin-regex-playground.imageset/preview.png delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources/.gitkeep delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources/Localizable.xcstrings delete mode 100644 src/apps/mobile/ios/OpenBitFun/Resources/MiniApps/.gitignore delete mode 100644 src/apps/mobile/ios/OpenBitFunUITests/PromptSuggestionUITests.swift delete mode 100644 src/apps/mobile/ios/OpenBitFunUITests/RemoteCodeSessionSendUITests.swift delete mode 100644 src/apps/mobile/ios/README.md delete mode 100644 src/apps/mobile/ios/Testing/AccountFailureCopyTests.swift delete mode 100644 src/apps/mobile/ios/Testing/ChatImageThumbnailTests.swift delete mode 100644 src/apps/mobile/ios/Testing/ComposerDismissGestureTests.swift delete mode 100644 src/apps/mobile/ios/Testing/DictationDraftSessionTests.swift delete mode 100644 src/apps/mobile/ios/Testing/HistoryPageArrivalTrackerTests.swift delete mode 100644 src/apps/mobile/ios/Testing/MobileProcessGroupTests.swift delete mode 100644 src/apps/mobile/ios/Testing/RemoteAuthorityGateTests.swift delete mode 100644 src/apps/mobile/ios/Testing/RemoteHomePresentationTests.swift delete mode 100644 src/apps/mobile/ios/Testing/StartupRevealPreferenceTests.swift delete mode 100644 src/apps/mobile/ios/Testing/StreamingTextStateTests.swift delete mode 100755 src/apps/mobile/ios/Testing/run-pure-swift-tests.sh delete mode 100644 src/apps/mobile/ios/miniapps.css delete mode 100644 src/apps/mobile/miniapps/bridge.js delete mode 100644 src/apps/mobile/miniapps/document.cjs delete mode 100644 src/apps/mobile/miniapps/document.test.cjs delete mode 100644 src/apps/mobile/miniapps/generate.cjs delete mode 100644 src/apps/mobile/miniapps/mobile.css delete mode 100644 src/apps/mobile/shared/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-crypto/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-crypto/src/androidMain/kotlin/com/openbitfun/mobile/core/crypto/CloudAccountKdf.android.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/androidMain/kotlin/com/openbitfun/mobile/core/crypto/CryptographyProviders.android.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/Base64Codec.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/CloudAccountKdf.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/ContentHash.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/CryptographyProviders.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/DeviceIdentity.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/RemoteCrypto.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/RemoteCryptoCipher.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/RemoteCryptoException.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/SessionEventCipher.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonMain/kotlin/com/openbitfun/mobile/core/crypto/X25519.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/AesGcmCipherTest.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/CloudAccountKdfTest.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/DeviceIdentityTest.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/HexTestSupport.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/RemoteCryptoTest.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/SessionEventCipherTest.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/commonTest/kotlin/com/openbitfun/mobile/core/crypto/X25519Test.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/iosMain/kotlin/com/openbitfun/mobile/core/crypto/CloudAccountKdf.ios.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/iosMain/kotlin/com/openbitfun/mobile/core/crypto/CryptographyProviders.ios.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/jvmMain/kotlin/com/openbitfun/mobile/core/crypto/CloudAccountKdf.jvm.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/jvmMain/kotlin/com/openbitfun/mobile/core/crypto/CryptographyProviders.jvm.kt delete mode 100644 src/apps/mobile/shared/core-crypto/src/nativeInterop/cinterop/openbitfun_argon2.def delete mode 100644 src/apps/mobile/shared/core-crypto/src/nativeInterop/cinterop/openbitfun_argon2.h delete mode 100644 src/apps/mobile/shared/core-crypto/src/nativeInterop/cinterop/openbitfun_argon2_simulator.def delete mode 100644 src/apps/mobile/shared/core-crypto/src/nativeInterop/cinterop/openbitfun_argon2_wrapper.c delete mode 100644 src/apps/mobile/shared/core-domain/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ChatSessionController.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ChatTimelineProjector.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ChatTimelineStore.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ConversationEvent.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ConversationModels.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/FilePreview.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/GeneralChatEventMapper.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/GeneralChatExportFormatter.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibility.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ModelLabelPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ModelSelectionPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/RemoteWorkspaceIdentity.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/SessionListPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/StatusSemantics.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ToolInputPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ToolNamePolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ToolQuestionPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/ToolStatusPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/TranscriptIntegrityPolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/WorkspaceModels.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/WorkspaceReferencePolicy.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ChatSessionControllerTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ChatTimelineProjectorTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ChatTimelineStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/FilePreviewTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/GeneralChatEventMapperTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ModelLabelPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ModelSelectionPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/RemoteWorkspaceIdentityTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/SessionListPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ToolQuestionPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/ToolStatusPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/WorkspaceDisplayNameTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-feature/src/androidMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.android.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/androidMain/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatStore.android.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/CloudSettingsSource.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/CoreLog.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountDefaults.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountDeviceLink.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountDevicePolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountUiState.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/MobileDeviceIdentity.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/TransportLogAdapter.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/connection/ConnectionStatus.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/connection/RemoteControlPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/directory/DeviceDirectoryStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/directory/DeviceDirectoryUiState.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatCloudConfigPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatConfig.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatUiState.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/layout/ConversationLayoutPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/layout/FilePreviewPlacementPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/layout/SettingsPlacementPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/layout/generated/MobileDesignBreakpoints.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParser.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/relay/HostCatalogObserver.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ChatComposerCapabilities.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ChatComposerPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationHeaderPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationModelPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/CreateSessionPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/DurableSessionReducer.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/HarnessProfilePolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/MessageBlockPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/MessageFileReferences.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ModelCatalogContract.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/PermissionMailboxStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/PlanToolPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RecentSessionsPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionFailureMapping.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionUiState.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionActionPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionListPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplica.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/SessionTimePresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/TaskCompletionPolicy.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ToolApprovalEditContract.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ToolQuestion.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/ToolRowPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/shell/SidebarPresentation.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/CodeSyntaxHighlighter.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/RemoteWorkspaceStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/RemoteWorkspaceUiState.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/RuntimeFilesStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/RuntimeTerminalStore.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/RuntimeUploadSource.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogUiState.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/account/AccountDeviceLinkTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/account/AccountStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/connection/ConnectionStatusPresenterTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/connection/RemoteControlPresenterTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/directory/DeviceDirectoryStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/directory/WorkspaceSessionPersistenceTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatCloudConfigPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/layout/ConversationLayoutPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/layout/FilePreviewPlacementPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/layout/SettingsPlacementPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/markdown/MarkdownParserTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/relay/HostCatalogObserverTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ChatComposerPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationHeaderPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationModelPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ConversationPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/CreateSessionPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/DurableSessionReducerTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MessageBlockPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MessageFileReferencesTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MobileParityPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/PermissionMailboxStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/PlanToolPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RecentSessionsPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteResponseMapperTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionPersistenceTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionActionPolicyTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionAgentFilterTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionListPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionRecordReplicaTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/SessionTimePresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/ToolRowPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/shell/RemoteSidebarPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/shell/SidebarPresentationTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/CodeSyntaxHighlighterTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/FilePreviewFormatTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/RemoteWorkspaceStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/RuntimeFilesStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/RuntimeTerminalStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/workspace/WorkspaceCatalogTest.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/iosMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.ios.kt delete mode 100644 src/apps/mobile/shared/core-feature/src/iosMain/kotlin/com/openbitfun/mobile/core/feature/generalchat/GeneralChatStore.ios.kt delete mode 100644 src/apps/mobile/shared/core-persistence/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-persistence/src/androidDeviceTest/kotlin/com/openbitfun/mobile/core/persistence/AndroidSecureStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/androidMain/kotlin/com/openbitfun/mobile/core/persistence/AndroidDraftStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/androidMain/kotlin/com/openbitfun/mobile/core/persistence/AndroidSecureStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/androidMain/kotlin/com/openbitfun/mobile/core/persistence/TemporaryDownload.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/kotlin/com/openbitfun/mobile/core/persistence/ChatLocalStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/kotlin/com/openbitfun/mobile/core/persistence/DraftStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/kotlin/com/openbitfun/mobile/core/persistence/SecureStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/kotlin/com/openbitfun/mobile/core/persistence/TemporaryDownload.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/1.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/2.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/3.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/4.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/5.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/6.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/7.sqm delete mode 100644 src/apps/mobile/shared/core-persistence/src/commonMain/sqldelight/com/openbitfun/mobile/core/persistence/db/Mobile.sq delete mode 100644 src/apps/mobile/shared/core-persistence/src/iosMain/kotlin/com/openbitfun/mobile/core/persistence/IosDraftStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/iosMain/kotlin/com/openbitfun/mobile/core/persistence/IosSecureStore.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/iosMain/kotlin/com/openbitfun/mobile/core/persistence/TemporaryDownload.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/iosTest/kotlin/com/openbitfun/mobile/core/persistence/IosSecureStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/jvmMain/kotlin/com/openbitfun/mobile/core/persistence/TemporaryDownload.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/jvmTest/kotlin/com/openbitfun/mobile/core/persistence/DraftStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/jvmTest/kotlin/com/openbitfun/mobile/core/persistence/RemotePersistenceStoreTest.kt delete mode 100644 src/apps/mobile/shared/core-persistence/src/jvmTest/kotlin/com/openbitfun/mobile/core/persistence/TemporaryDownloadTest.kt delete mode 100644 src/apps/mobile/shared/core-protocol/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/CommandStatus.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/DialogQueue.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/EncryptedPayload.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/FileDtos.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/GeneralChatDtos.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/MessageDtos.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/ModelCatalogDtos.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/Pairing.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/ProvisionPeerDeviceContract.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RelayJson.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/SessionDtos.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/WireTime.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/WorkspaceDtos.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonTest/kotlin/com/openbitfun/mobile/core/protocol/EncryptedPayloadTest.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonTest/kotlin/com/openbitfun/mobile/core/protocol/ModelCatalogDtoTest.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonTest/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommandTest.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonTest/kotlin/com/openbitfun/mobile/core/protocol/SessionItemContractTest.kt delete mode 100644 src/apps/mobile/shared/core-protocol/src/commonTest/kotlin/com/openbitfun/mobile/core/protocol/WorkspaceHostTest.kt delete mode 100644 src/apps/mobile/shared/core-testing/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-transport/build.gradle.kts delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/AccountDeviceLink.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/AccountRealtime.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/ClientBuild.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/HostStream.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/ModelProviderStream.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/RelayFailure.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/RelayHttpClient.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/RelayMessageEncoding.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/RemoteCommandTransport.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/RpcPayload.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/SseFrameDecoder.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/TransportLog.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/HostStreamTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/ModelProviderStreamTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/RelayMessageEncodingTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/SseFrameDecoderTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/ClientBuildContractTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/OkHttpRealtimeTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/RealtimeRelayIntegrationTest.kt delete mode 100644 src/apps/mobile/shared/core-transport/src/jvmTest/kotlin/com/openbitfun/mobile/core/transport/RpcProcessingThreadTest.kt delete mode 100644 src/apps/mobile/shared/gradle.properties delete mode 100644 src/apps/mobile/shared/gradle/libs.versions.toml delete mode 100644 src/apps/mobile/shared/gradle/wrapper/gradle-wrapper.jar delete mode 100644 src/apps/mobile/shared/gradle/wrapper/gradle-wrapper.properties delete mode 100755 src/apps/mobile/shared/gradlew delete mode 100644 src/apps/mobile/shared/gradlew.bat delete mode 100644 src/apps/mobile/shared/settings.gradle.kts delete mode 100644 src/apps/mobile/shared/swift-smoke/MobileCoreSmoke.swift delete mode 100644 src/mobile-web/tests/harmony-file-editor-browser.test.mjs delete mode 100644 src/mobile-web/tests/native-terminal-renderer-browser.test.mjs delete mode 100644 src/shared/argon2/argon2.c delete mode 100644 src/shared/argon2/argon2.h delete mode 100644 src/shared/argon2/blake2/blake2-impl.h delete mode 100644 src/shared/argon2/blake2/blake2.h delete mode 100644 src/shared/argon2/blake2/blake2b.c delete mode 100644 src/shared/argon2/blake2/blamka-round-opt.h delete mode 100644 src/shared/argon2/blake2/blamka-round-ref.h delete mode 100644 src/shared/argon2/core.c delete mode 100644 src/shared/argon2/core.h delete mode 100644 src/shared/argon2/encoding.c delete mode 100644 src/shared/argon2/encoding.h delete mode 100644 src/shared/argon2/opt.c delete mode 100644 src/shared/argon2/ref.c delete mode 100644 src/shared/argon2/run.c delete mode 100644 src/shared/argon2/thread.c delete mode 100644 src/shared/argon2/thread.h delete mode 100644 src/shared/terminal/webview/README.md delete mode 100644 src/shared/terminal/webview/generated/index.html delete mode 100644 src/shared/terminal/webview/generated/terminal.css delete mode 100644 src/shared/terminal/webview/generated/terminal.js delete mode 100644 src/shared/terminal/webview/index.ts diff --git a/.gitattributes b/.gitattributes index 4aae1f6602..17bcae41ea 100644 --- a/.gitattributes +++ b/.gitattributes @@ -29,11 +29,6 @@ # Windows or hosted runner cannot report newline-only generated drift. MiniApp/Demo/git-graph/source/** text eol=lf src/crates/assembly/core/builtin_skills/miniapp-dev/references/examples/demo-git-graph/source/** text eol=lf -src/apps/mobile/**/*.json text eol=lf -src/apps/mobile/**/*.js text eol=lf -src/apps/mobile/**/*.ets text eol=lf -src/apps/mobile/**/*.kt text eol=lf -src/apps/mobile/**/*.swift text eol=lf # The Product Operation Registry embeds and compares this generated JSON byte for byte. src/crates/contracts/product-domains/src/generated/remote-surface-registry.json text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fe78c0863..ebb4aefc87 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -736,7 +736,7 @@ jobs: - name: Validate mobile-web build cache contract if: needs.build-impact.outputs.frontend_required != 'false' - run: node --test scripts/mobile-web-build.test.mjs + run: node --test scripts/mobile-web-build.test.mjs scripts/mobile-client-build.contract.test.mjs - name: Test mobile web account login and reload if: needs.build-impact.outputs.frontend_required != 'false' diff --git a/.github/workflows/desktop-package.yml b/.github/workflows/desktop-package.yml index 2e2b4ca8a8..3b6cbcb617 100644 --- a/.github/workflows/desktop-package.yml +++ b/.github/workflows/desktop-package.yml @@ -1079,20 +1079,17 @@ jobs: esac gh release upload "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \ --clobber release-upload-assets/* - MOBILE_VERSION="$(sed -nE 's/.*versionName = "([^"]+)".*/\1/p' \ - src/apps/mobile/android/app/build.gradle.kts 2>/dev/null | head -n1 || true)" - MOBILE_VERSION="${MOBILE_VERSION:-$RELEASE_VERSION}" gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \ --json body --jq .body > release-notes.md if ! grep -q '' release-notes.md; then cat >> release-notes.md < - ### Android mobile + ### Native mobile - Android mobile version **${MOBILE_VERSION}** is published separately as a prerelease: - [Download the Android prerelease](https://github.com/${GITHUB_REPOSITORY}/releases/tag/mobile-v${MOBILE_VERSION}). - The current APK uses the runner-generated debug signing key. + Native Android, iOS and HarmonyOS development and releases have moved to + [OpenBitFun-Mobile](https://github.com/openBitFun/OpenBitFun-Mobile). + [Mobile releases](https://github.com/openBitFun/OpenBitFun-Mobile/releases). EOF fi gh release edit "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \ diff --git a/.github/workflows/mobile-package.yml b/.github/workflows/mobile-package.yml deleted file mode 100644 index 57c6bd5dc4..0000000000 --- a/.github/workflows/mobile-package.yml +++ /dev/null @@ -1,133 +0,0 @@ -name: Mobile Package - -on: - push: - tags: - - 'mobile-v*' - workflow_dispatch: - inputs: - tag_name: - description: 'Mobile release tag (for example mobile-v1.0.0).' - required: true - type: string - -permissions: - contents: write - -concurrency: - group: mobile-package-${{ github.event.release.tag_name || inputs.tag_name || github.ref_name }} - cancel-in-progress: false - -jobs: - prepare: - name: Prepare mobile release - runs-on: ubuntu-latest - outputs: - tag_name: ${{ steps.meta.outputs.tag_name }} - version: ${{ steps.meta.outputs.version }} - prerelease: ${{ steps.meta.outputs.prerelease }} - steps: - - uses: actions/checkout@v5 - with: - ref: ${{ inputs.tag_name || github.ref_name }} - fetch-depth: 1 - - - name: Resolve mobile version - id: meta - shell: bash - env: - INPUT_TAG_NAME: ${{ inputs.tag_name }} - REF_NAME: ${{ github.ref_name }} - run: | - set -euo pipefail - TAG="${INPUT_TAG_NAME:-${REF_NAME}}" - case "$TAG" in - mobile-v*) ;; - *) echo "Expected a mobile-v* tag, got $TAG" >&2; exit 1 ;; - esac - VERSION="${TAG#mobile-v}" - node scripts/verify-release-version-sync.mjs --mobile-version "$VERSION" - if [[ "$VERSION" == *-* ]]; then - PRERELEASE=true - else - PRERELEASE=false - fi - printf 'tag_name=%s\nversion=%s\nprerelease=%s\n' \ - "$TAG" "$VERSION" "$PRERELEASE" >> "$GITHUB_OUTPUT" - - android: - name: Android package - needs: prepare - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - with: - ref: ${{ needs.prepare.outputs.tag_name }} - - - uses: actions/setup-java@v5 - with: - distribution: temurin - java-version: '21' - - - uses: gradle/actions/setup-gradle@v4 - - - name: Configure Android release signing - shell: bash - run: | - set -euo pipefail - echo "Using the runner-generated Android debug keystore for this mobile prerelease." - - - name: Build signed Android package - working-directory: src/apps/mobile/android - run: ./gradlew :app:assembleRelease --no-daemon - - - name: Stage Android release assets - shell: bash - env: - VERSION: ${{ needs.prepare.outputs.version }} - run: | - set -euo pipefail - mkdir -p mobile-release-assets - suffix='-debug' - cp src/apps/mobile/android/app/build/outputs/apk/release/app-release.apk \ - "mobile-release-assets/OpenBitFun-Mobile-${VERSION}-android${suffix}.apk" - (cd mobile-release-assets && sha256sum ./*.apk > SHA256SUMS) - - - uses: actions/upload-artifact@v6 - with: - name: openbitfun-mobile-${{ needs.prepare.outputs.tag_name }}-android - path: mobile-release-assets/* - if-no-files-found: error - retention-days: 7 - - publish: - name: Publish mobile release - needs: [prepare, android] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - with: - ref: ${{ needs.prepare.outputs.tag_name }} - - - uses: actions/download-artifact@v7 - with: - name: openbitfun-mobile-${{ needs.prepare.outputs.tag_name }}-android - path: mobile-release-assets - - - name: Create mobile release - env: - GH_TOKEN: ${{ github.token }} - TAG_NAME: ${{ needs.prepare.outputs.tag_name }} - VERSION: ${{ needs.prepare.outputs.version }} - PRERELEASE: true - shell: bash - run: | - set -euo pipefail - VERSION="$VERSION (debug signing)" - gh release create "$TAG_NAME" \ - --repo "$GITHUB_REPOSITORY" \ - --verify-tag \ - --title "OpenBitFun Mobile $VERSION" \ - --generate-notes \ - --prerelease="$PRERELEASE" \ - mobile-release-assets/* diff --git a/.gitignore b/.gitignore index a5fa33ceee..9deef85c31 100644 --- a/.gitignore +++ b/.gitignore @@ -107,22 +107,7 @@ external/ .design/ .pnpm-store/ -# KMP shared mobile core and the platform apps that include it (Gradle). -# Written per-directory rather than as a bare `local.properties` so the pattern -# cannot accidentally hide a checked-in file elsewhere in the repo. local.properties -# holds the machine's SDK path, which is exactly the kind of thing -# src/apps/mobile/AGENTS.md says stays out of the repository. -src/apps/mobile/shared/.gradle/ -src/apps/mobile/shared/build/ -src/apps/mobile/shared/*/build/ -src/apps/mobile/shared/local.properties -src/apps/mobile/shared/.kotlin/ -src/apps/mobile/android/.gradle/ -src/apps/mobile/android/build/ -src/apps/mobile/android/*/build/ -src/apps/mobile/android/local.properties -src/apps/mobile/android/.kotlin/ -/src/apps/mobile/ios/build/ + .openbitfun/ .bitfun/ @@ -147,7 +132,7 @@ src/apps/mobile/android/.kotlin/ /src/apps/ohos/*/libs/ # hvigor writes a BuildProfile.ets next to each module during the build. /src/apps/ohos/*/BuildProfile.ets -# Same policy as src/apps/mobile/harmonyos/.gitignore: signing credentials and +# Signing credentials and # installable artifacts never leave the machine. /src/apps/ohos/signing.local.json* /src/apps/ohos/*.cer diff --git a/AGENTS-CN.md b/AGENTS-CN.md index 728091f1fb..2842f7fbd0 100644 --- a/AGENTS-CN.md +++ b/AGENTS-CN.md @@ -191,3 +191,9 @@ await api.invoke('your_command', { request: { ... } }); - 本文件只保留跨模块规则和稳定的仓库级入口。模块 ownership 细节、surface 或 crate 专属命令和 focused test 清单属于最近的指南;只有真实开发流程需要时才在那里补充命令。 - crate 清单由各层指南维护;不要在这里枚举 crate。 - `AGENTS.md` 与 `AGENTS-CN.md` 在同一次改动中同步更新。 + +## 原生移动端仓库 + +Android、iOS、HarmonyOS 应用及其 Kotlin 共享模块、原生 WebView 资源和移动端设计工具 +已迁至 [OpenBitFun-Mobile](https://github.com/openBitFun/OpenBitFun-Mobile)。 +`src/mobile-web` 和主机侧移动端/Relay 协议契约仍由本仓库维护。 diff --git a/AGENTS.md b/AGENTS.md index 66b20d783f..f84f85acc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,3 +191,9 @@ Read the listed documents before editing in these areas. The sub-bullets are har - Keep this file to cross-cutting rules and stable repository entry points. Module ownership details, surface- or crate-specific commands, and focused test lists belong in the nearest guide; add a command there only when a real workflow needs it. - Layer guides own the crate tables; do not enumerate crates here. - Update `AGENTS.md` and `AGENTS-CN.md` in the same change. + +## Native mobile repository + +Android, iOS and HarmonyOS apps, their Kotlin shared core, native WebView assets +and mobile design tooling are maintained in [OpenBitFun-Mobile](https://github.com/openBitFun/OpenBitFun-Mobile). +`src/mobile-web` and host-side mobile/Relay protocol contracts remain here. diff --git a/README.md b/README.md index f40687f2b8..c7e9ccb8f1 100644 --- a/README.md +++ b/README.md @@ -165,3 +165,9 @@ Core code is licensed under the [MIT License](./LICENSE). Third-party dependenci OpenBitFun Star History Chart + +### Native mobile development + +Android, iOS and HarmonyOS source code and releases have moved to +[OpenBitFun-Mobile](https://github.com/openBitFun/OpenBitFun-Mobile). +The browser mobile-web client and Desktop/CLI/Relay host implementations remain in this repository. diff --git a/README.zh-CN.md b/README.zh-CN.md index 933e34e25a..8e4a7aa6f9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -164,3 +164,9 @@ pnpm run desktop:dev OpenBitFun Star 历史图 + +### 原生移动端开发 + +Android、iOS 和 HarmonyOS 的源码及发布已迁至 +[OpenBitFun-Mobile](https://github.com/openBitFun/OpenBitFun-Mobile)。 +浏览器版 mobile-web 以及 Desktop/CLI/Relay 主机实现仍在本仓库维护。 diff --git a/docs/architecture/i18n.md b/docs/architecture/i18n.md index de36c56d83..4a1bbacffa 100644 --- a/docs/architecture/i18n.md +++ b/docs/architecture/i18n.md @@ -53,7 +53,7 @@ catalogs or making an extra request before first paint. | Shared terms | `src/shared/i18n/resources/shared//terms.json` | Generated into a small `shared.*` contract for each surface | | Web UI | `src/web-ui/src/locales//**/*.json` | Eagerly loads bootstrap namespaces only; route and feature copy loads lazily | | Mobile Web | `src/mobile-web/src/i18n/messages.ts` | Owns mobile-only messages; no Web UI catalog imports | -| HarmonyOS phone | `src/apps/mobile/harmonyos/entry/src/main/ets/i18n` | Owns ArkTS catalogs for `zh-CN` and `en-US`; no Web UI or mobile-web catalog imports | +| HarmonyOS phone | [src/apps/mobile/harmonyos/entry/src/main/ets/i18n](https://github.com/openBitFun/OpenBitFun-Mobile/tree/main/src/apps/mobile/harmonyos/entry/src/main/ets/i18n) | Owns ArkTS catalogs for `zh-CN` and `en-US`; no Web UI or mobile-web catalog imports | | Installer | `OpenBitFun-Installer/src/i18n/locales/*.json` | Owns installer-only messages; no app runtime catalog imports | | Backend | `src/crates/assembly/core/locales/*.ftl` | Uses generated locale helpers and Fluent resources | | Relay static homepage | `src/apps/relay-server/static/homepage` | Self-contained static resources plus generated page-scoped shared terms | diff --git a/docs/architecture/platform-portability-design.md b/docs/architecture/platform-portability-design.md index d859469a6d..56ca0f38bb 100644 --- a/docs/architecture/platform-portability-design.md +++ b/docs/architecture/platform-portability-design.md @@ -20,7 +20,7 @@ HarmonyOS PC 真实系统终端中安装并本地执行的原生 `openbitfun`: - 在 HAP 内绘制终端风格界面; - 只通过 `hdc shell` 推送、启动或操作二进制; -- 把现有 `src/apps/mobile/harmonyos` 手机 Remote App 改称为 PC 本地产品; +- 把现有 [src/apps/mobile/harmonyos](https://github.com/openBitFun/OpenBitFun-Mobile/tree/main/src/apps/mobile/harmonyos) 手机 Remote App 改称为 PC 本地产品; - 在其他设备运行 Runtime,再由 HarmonyOS PC 远程控制。 完整的 HarmonyOS PC 支持同时包含本地 CLI/TUI 与 GUI。GUI 是另一项必需交付形态,但由独立产品专题设计和 diff --git a/docs/architecture/product-architecture.md b/docs/architecture/product-architecture.md index b88538f64a..a07c2751ac 100644 --- a/docs/architecture/product-architecture.md +++ b/docs/architecture/product-architecture.md @@ -193,7 +193,7 @@ block-beta | Development area | Repository scope | Current modules | |---|---|---| | Apps | `src/apps/*` | `desktop`、`cli`、`server`、`relay-server`、`sdk-host`、`miniapp-shell`、`data-tools`、`miniapp-market-server`、`extension-host`(Bun Plugin Host 进程) | -| Web and delivery | product roots | `src/web-ui`、`src/mobile-web`、`src/miniapp-market-web`、`src/apps/mobile`、`OpenBitFun-Installer`、`website`、`tests/e2e` | +| Web and delivery | product roots | `src/web-ui`、`src/mobile-web`、`src/miniapp-market-web`、[OpenBitFun-Mobile](https://github.com/openBitFun/OpenBitFun-Mobile)、`OpenBitFun-Installer`、`website`、`tests/e2e` | | SDK | `sdk/*` | `typescript` | | Shared frontend | `src/shared`、`packages/flow-chat-presentation` | `shared`、`flow-chat-presentation` | | Design system | `design-system/*` | `packages/design-tokens`、`packages/theme-openbitfun`、`packages/ui`、`tooling/package-contract`、`tooling/token-engine`、`apps/design-lab` | diff --git a/docs/architecture/theme-token-optimization.md b/docs/architecture/theme-token-optimization.md index 3663bf1eae..b0487ca646 100644 --- a/docs/architecture/theme-token-optimization.md +++ b/docs/architecture/theme-token-optimization.md @@ -239,7 +239,7 @@ Native Mobile 预览的工具 chrome 消费 canonical `--openbitfun-*`;设备 ### HarmonyOS / Android / iOS 原生移动端不加载 Web CSS,也不复制 `@openbitfun/theme-openbitfun`。它们的唯一跨平台视觉事实 owner 是 -`src/apps/mobile/design-system/tokens/mobile-tokens.json`: +[src/apps/mobile/design-system/tokens/mobile-tokens.json](https://github.com/openBitFun/OpenBitFun-Mobile/tree/main/src/apps/mobile/design-system/tokens/mobile-tokens.json): - 颜色名称按语义登记,例如 content、surface、status、scrim、media control 和 shadow;不得使用 `green`、 `red`、`white` 之类数值或外观名称充当公共 API。 diff --git a/package.json b/package.json index 15805f2482..a1aecbf349 100644 --- a/package.json +++ b/package.json @@ -51,8 +51,6 @@ "theme:color-audit:installer": "node scripts/audit-frontend-colors.mjs --surface installer", "theme:color-audit:cli": "node scripts/audit-frontend-colors.mjs --surface cli", "theme:color-audit:desktop-bootstrap": "node scripts/audit-frontend-colors.mjs --surface desktop-bootstrap", - "theme:color-audit:mobile-preview": "node scripts/audit-frontend-colors.mjs --surface mobile-design-preview", - "theme:color-audit:native-mobile": "node scripts/audit-frontend-colors.mjs --kind native-mobile", "theme:color-audit:miniapps": "node scripts/audit-frontend-colors.mjs --kind miniapp", "theme:color-audit:all": "node scripts/audit-frontend-colors.mjs", "theme:color-audit:test": "node --test scripts/audit-theme-colors.test.mjs scripts/audit-cli-theme-colors.test.mjs scripts/audit-frontend-colors.test.mjs", @@ -68,11 +66,6 @@ "models-dev:check": "node scripts/update-models-dev-snapshot.mjs --check", "models-dev:update": "node scripts/update-models-dev-snapshot.mjs", "check:build-prereqs": "node scripts/check-build-prereqs.mjs", - "harmony:architecture": "node scripts/check-harmonyos-architecture.mjs", - "mobile:architecture": "node scripts/check-mobile-architecture.mjs && node --test scripts/mobile-client-build.contract.test.mjs", - "mobile:ui:generate": "node scripts/mobile-ui-design-system.mjs", - "mobile:ui:check": "node scripts/mobile-ui-design-system.mjs --check && node scripts/mobile-ui-preview.mjs --check", - "mobile:ui:preview": "node scripts/mobile-ui-design-system.mjs && node scripts/mobile-ui-preview.mjs", "check:core-boundaries": "pnpm run agent-harness:check && node scripts/check-core-boundaries.mjs", "check:core-boundaries:test": "node --test scripts/check-core-boundaries.test.mjs", "check:github-config": "pnpm --dir src/web-ui exec node ../../scripts/check-github-config.mjs && node --test scripts/check-github-config.test.mjs", diff --git a/release-please-config.json b/release-please-config.json index afc2ee5cf9..09ae628e6f 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -25,10 +25,6 @@ { "type": "generic", "path": "src/apps/relay-server/Cargo.toml" - }, - { - "type": "generic", - "path": "src/apps/mobile/harmonyos/AppScope/app.json5" } ] } diff --git a/scripts/audit-theme-colors.test.mjs b/scripts/audit-theme-colors.test.mjs index d7493560f2..15af2a32ed 100644 --- a/scripts/audit-theme-colors.test.mjs +++ b/scripts/audit-theme-colors.test.mjs @@ -23,7 +23,6 @@ const SOURCE_OWNER_ROOTS = [ 'OpenBitFun-Installer/src', 'design-system/packages/design-tokens/src', 'design-system/packages/theme-openbitfun/src', - 'src/apps/mobile/design-system/preview', 'src/mobile-web/src', 'src/web-ui', ]; diff --git a/scripts/build-mobile-terminal.mjs b/scripts/build-mobile-terminal.mjs deleted file mode 100644 index 0dcf7a332b..0000000000 --- a/scripts/build-mobile-terminal.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import {createRequire} from 'node:module'; -import {mkdir,readFile,writeFile,copyFile} from 'node:fs/promises'; -import {fileURLToPath} from 'node:url'; -import path from 'node:path'; -const root=fileURLToPath(new URL('../',import.meta.url)); -const require=createRequire(path.join(root,'src/mobile-web/package.json')); -const {build}=createRequire(require.resolve('vite'))('esbuild'); -const output=path.join(root,'src/shared/terminal/webview/generated'); -await mkdir(output,{recursive:true}); -await build({entryPoints:[path.join(root,'src/shared/terminal/webview/index.ts')],outfile:path.join(output,'terminal.js'),bundle:true,minify:true,format:'iife',platform:'browser',target:'es2020',legalComments:'inline',nodePaths:[path.join(root,'src/mobile-web/node_modules')]}); -await writeFile(path.join(output,'index.html'),`
`); -if(process.argv.includes('--harmony')){ - const dest=path.join(root,'src/apps/mobile/harmonyos/entry/src/main/resources/rawfile/terminal');await mkdir(dest,{recursive:true}); - for(const name of ['index.html','terminal.js','terminal.css'])await copyFile(path.join(output,name),path.join(dest,name)); -} -console.log('Built shared native terminal assets.'); diff --git a/scripts/check-github-config.test.mjs b/scripts/check-github-config.test.mjs index 9dd1bc0431..c6a7a42902 100644 --- a/scripts/check-github-config.test.mjs +++ b/scripts/check-github-config.test.mjs @@ -1437,7 +1437,7 @@ test('stages unique release asset names before publishing', () => { assert.match(steps[uploadIndex].run, /--clobber release-upload-assets\/\*/); }); -test('Desktop release notes link the separately published Android prerelease', () => { +test('Desktop release notes link the migrated native mobile repository', () => { const workflow = yaml.parse( readFileSync( path.join(repoRoot, '.github/workflows/desktop-package.yml'), @@ -1447,26 +1447,11 @@ test('Desktop release notes link the separately published Android prerelease', ( const uploadStep = workflow.jobs['upload-release-assets'].steps.find( (step) => step.name === 'Upload to release', ); - assert.match(uploadStep.run, /mobile-v\$\{MOBILE_VERSION\}/); - assert.match(uploadStep.run, /runner-generated debug signing key/); + assert.match(uploadStep.run, /github\.com\/openBitFun\/OpenBitFun-Mobile\/releases/); + assert.doesNotMatch(uploadStep.run, /src\/apps\/mobile\//); assert.match(uploadStep.run, /--notes-file release-notes\.md/); }); -test('Mobile Package publishes Android assets from mobile-v tags', () => { - const workflow = yaml.parse( - readFileSync(path.join(repoRoot, '.github/workflows/mobile-package.yml'), 'utf8'), - ); - assert.ok(workflow.on.push.tags.includes('mobile-v*')); - assert.match( - workflow.jobs.android.steps.find((step) => step.name === 'Build signed Android package').run, - /:app:assembleRelease/, - ); - assert.equal(workflow.jobs.publish.needs.includes('android'), true); - assert.match( - workflow.jobs.publish.steps.find((step) => step.name === 'Create mobile release').run, - /gh release create/, - ); -}); test('Desktop packaging preserves old-tag source bytes before Windows checkout', () => { const workflow = yaml.parse( diff --git a/scripts/check-harmonyos-architecture.mjs b/scripts/check-harmonyos-architecture.mjs deleted file mode 100644 index 40d6cc96de..0000000000 --- a/scripts/check-harmonyos-architecture.mjs +++ /dev/null @@ -1,479 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const repoRoot = path.resolve(scriptDir, '..'); -const etsRoot = path.join(repoRoot, 'src/apps/mobile/harmonyos/entry/src/main/ets'); -const pagesRoot = path.join(etsRoot, 'pages'); - -function walkEts(root) { - const entries = fs.readdirSync(root, { withFileTypes: true }); - const files = []; - for (const entry of entries) { - const entryPath = path.join(root, entry.name); - if (entry.isDirectory()) { - files.push(...walkEts(entryPath)); - } else if (entry.isFile() && entry.name.endsWith('.ets')) { - files.push(entryPath); - } - } - return files; -} - -function relative(file) { - return path.relative(repoRoot, file).split(path.sep).join('/'); -} - -function imports(file) { - const source = fs.readFileSync(file, 'utf8'); - const specs = [...source.matchAll(/from\s+['"]([^'"]+)['"]/g)].map((match) => match[1]); - return specs.map((spec) => { - if (!spec.startsWith('.')) { - return spec; - } - return path.relative(etsRoot, path.resolve(path.dirname(file), spec)).split(path.sep).join('/'); - }); -} - -function filesUnder(root) { - return walkEts(root).sort(); -} - -const allPages = filesUnder(pagesRoot); -const services = filesUnder(path.join(etsRoot, 'services')); -const components = allPages.filter((file) => file.includes(`${path.sep}pages${path.sep}components${path.sep}`)); -const viewmodels = allPages.filter((file) => file.includes(`${path.sep}pages${path.sep}viewmodel${path.sep}`)); -const stateFiles = allPages.filter((file) => file.includes(`${path.sep}pages${path.sep}state${path.sep}`)); -const forbiddenComponentPlatformImports = new Set([ - '@kit.AbilityKit', - '@kit.IMEKit', - '@kit.ScanKit' -]); - -const serviceToPages = services - .filter((file) => imports(file).some((spec) => spec === 'pages' || spec.startsWith('pages/'))) - .map(relative); -const componentToViewmodel = components - .filter((file) => imports(file).some((spec) => spec === 'pages/viewmodel' || spec.startsWith('pages/viewmodel/'))) - .map(relative); -const viewmodelToComponents = viewmodels - .filter((file) => imports(file).some((spec) => spec === 'pages/components' || spec.startsWith('pages/components/'))) - .map(relative); -const stateToComponents = stateFiles - .filter((file) => imports(file).some((spec) => spec === 'pages/components' || spec.startsWith('pages/components/'))) - .map(relative); -const componentToRawPlatformServices = components - .filter((file) => imports(file).some((spec) => forbiddenComponentPlatformImports.has(spec))) - .map(relative); -const hardcodedTextFontSizes = components.flatMap((file) => { - const source = fs.readFileSync(file, 'utf8'); - const builderMatcher = /\b(SymbolGlyph|Text|Button|TextInput|TextArea|Search|Span|RichEditor)\s*\(/g; - const builders = [...source.matchAll(builderMatcher)]; - return [...source.matchAll(/\.fontSize\((\d+(?:\.\d+)?)\)/g)].flatMap((match) => { - const builder = builders.filter((candidate) => candidate.index < match.index).at(-1); - if (builder?.[1] === 'SymbolGlyph') { - return []; - } - const line = source.slice(0, match.index).split('\n').length; - return [`${relative(file)}:${line}:${match[1]}`]; - }); -}); -const indirectHardcodedTypography = components.flatMap((file) => { - const source = fs.readFileSync(file, 'utf8'); - return [...source.matchAll(/this\.InlineText\([^;]*?,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,/gs)] - .map((match) => { - const line = source.slice(0, match.index).split('\n').length; - return `${relative(file)}:${line}:${match[1]}/${match[2]}`; - }); -}); -const v1Components = allPages - .filter((file) => /^\s*@Component\s*$/m.test(fs.readFileSync(file, 'utf8'))) - .map(relative); -const positionalActionConstructors = allPages - .filter((file) => /export\s+class\s+\w+(?:Actions|Hooks)\b/.test(fs.readFileSync(file, 'utf8')) && - /\bconstructor\s*\(/.test(fs.readFileSync(file, 'utf8'))) - .map(relative); -const sharedConversationFields = [ - 'sessions', - 'activeSession', - 'persistedMessages', - 'optimisticMessages', - 'activeTurnMessage', - 'hasMoreMessages', - 'timelineItems', - 'timelineRevision', - 'isBusy', - 'modelCatalog', - 'selectedModelId', - 'statusText', - 'chatInput', - 'selectedImages', - 'isVoiceListening' -]; -const conversationPageStateFiles = [ - path.join(pagesRoot, 'state/GeneralChatPageState.ets'), - path.join(pagesRoot, 'state/RemotePageState.ets') -]; -const duplicatedConversationTraceFields = conversationPageStateFiles.flatMap((file) => { - const source = fs.readFileSync(file, 'utf8'); - return sharedConversationFields - .filter((field) => new RegExp(`@Trace\\s+${field}\\s*:`).test(source)) - .map((field) => `${relative(file)}:${field}`); -}); -const appRootRuntimeFile = path.join(pagesRoot, 'runtime/AppRootRuntime.ets'); -const appRootRuntimeSource = fs.readFileSync(appRootRuntimeFile, 'utf8'); -const requiredPresentationFiles = [ - 'components/AppRootOverlaySurfaces.ets', - 'components/ChatMessageChrome.ets', - 'components/RemoteSessionRow.ets', - 'components/ConversationHeader.ets', - 'components/ConversationRouteSurface.ets', - 'components/ToolInteractionPanels.ets', - 'components/WideConversationHost.ets', - 'components/remote/RemoteSurfaceHost.ets', - 'policy/ConversationHeaderPolicy.ets', - 'policy/ChatMessageStructurePolicy.ets', - 'policy/ToolStatusPresentationPolicy.ets', - 'viewmodel/ConversationRuntime.ets', - 'viewmodel/RemoteTranscriptController.ets', - 'viewmodel/RemoteCreateFlowController.ets', - 'viewmodel/VisibleConversationController.ets' -]; -const missingPresentationFiles = requiredPresentationFiles - .filter((file) => !fs.existsSync(path.join(pagesRoot, file))); -// Phones are remote controllers: check the runtime and both responsive hosts. -const localControllerOwners = [ - 'runtime/AppRootRuntimeComposition.ets', - 'runtime/AppRootRuntime.ets', - 'viewmodel/ConversationRuntime.ets', - 'viewmodel/SettingsController.ets', - 'viewmodel/VisibleConversationController.ets', - 'components/AppRootOverlaySurfaces.ets', - 'components/WideConversationHost.ets', - 'components/SettingsSheet.ets', - 'components/AppSidebar.ets' -]; -const localControllerRuntimeLeaks = localControllerOwners - .filter((file) => /GeneralChat(?:Controller|ConfigStore|BootstrapController|CommandController|DraftLifecycleController|ConversationViewModel)|showConversationSection|ModelServiceSettingsPanel|generalPageState\.recentSessions/.test( - fs.readFileSync(path.join(pagesRoot, file), 'utf8'))) - .map((file) => relative(path.join(pagesRoot, file))); -const chatTimelineSource = fs.readFileSync(path.join(pagesRoot, 'components/ChatTimeline.ets'), 'utf8'); -const chatMessageContentSource = fs.readFileSync( - path.join(pagesRoot, 'components/ChatMessageContent.ets'), - 'utf8' -); -const lazyHistoryTimeline = - chatTimelineSource.includes('Repeat(this.historyTimelineItems())') && - chatTimelineSource.includes('.virtualScroll()'); -const stableActiveTimeline = - chatTimelineSource.includes('ForEach(this.activeTimelineItems()') && - chatTimelineSource.includes('ChatTimelineRevisionTracker.itemKey(item)') && - chatMessageContentSource.includes("import { StreamingMarkdownContent } from './StreamingMarkdownContent'"); -const eagerChatTimeline = !lazyHistoryTimeline || !stableActiveTimeline ? - ['src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets'] : []; -const chatMessageBubbleSource = fs.readFileSync( - path.join(pagesRoot, 'components/ChatMessageBubble.ets'), - 'utf8' -); -const missingTimelineReuse = !chatTimelineSource.includes('.virtualScroll()') || - (chatMessageBubbleSource.match(/@ReusableV2\n@ComponentV2/g) || []).length < 2 || - !chatMessageBubbleSource.includes('export struct ChatUserMessageRow') || - !chatTimelineSource.includes('ChatUserMessageRow({') || - !chatTimelineSource.includes(".reuse({ reuseId: () => 'chat_user' })") || - !chatTimelineSource.includes(".reuse({ reuseId: () => 'chat_assistant' })") ? - ['src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets'] : []; -const snapshottedTimelineRepeatItem = chatTimelineSource.includes('this.TimelineItem(repeatItem') || - chatTimelineSource.includes('this.MessageBubble(repeatItem') || - chatTimelineSource.includes('message: repeatItem.item.message!') || - !chatTimelineSource.includes('item: toConversationUiMessage(repeatItem.item.message!)') || - !chatMessageBubbleSource.includes('@Param item: ConversationUiMessage') || - chatMessageBubbleSource.includes('@Param @Once item: ConversationUiMessage') ? - ['src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets'] : []; -const snapshottedMessageBuilderInput = - chatMessageBubbleSource.includes('this.FinalContent(this.item)') || - chatMessageBubbleSource.includes('this.ProcessContent(this.item)') || - !chatMessageBubbleSource.includes('@Param item: ConversationUiMessage') ? - ['src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets'] : []; -const timelineModelsPath = path.join(etsRoot, 'model/ChatTimelineModels.ets'); -const timelineModelsSource = fs.readFileSync(timelineModelsPath, 'utf8'); -const conversationCoreStatePath = path.join(pagesRoot, 'state/ConversationCoreState.ets'); -const conversationCoreStateSource = fs.readFileSync(conversationCoreStatePath, 'utf8'); -const missingObservableTimelineRows = - !timelineModelsSource.includes('@ObservedV2\nexport class ObservableChatTimelineItem') || - !timelineModelsSource.includes('@Trace message: ChatMessage | undefined') || - !conversationCoreStateSource.includes('this.timelineRowStore.reconcile(timelineItems)') ? - [relative(timelineModelsPath)] : []; -const conversationViewPath = path.join(pagesRoot, 'components/ConversationView.ets'); -const conversationViewSource = fs.readFileSync(conversationViewPath, 'utf8'); -const conversationViewInputCount = [...conversationViewSource.matchAll(/^\s+@(Param|Event)\b/gm)].length; -const wideConversationViewContract = conversationViewInputCount > 10 ? - [`${relative(conversationViewPath)}:${conversationViewInputCount}`] : []; -// SheetLayout may adapt cross-platform geometry for ArkUI, but it must not -// become a second numeric source of truth for geometry already in the mobile -// design contract. This deliberately checks ownership, not page-level sizes. -const sheetLayoutPath = path.join(pagesRoot, 'components/SheetLayout.ets'); -const sheetLayoutSource = fs.readFileSync(sheetLayoutPath, 'utf8'); -const duplicateSheetGeometry = - !sheetLayoutSource.includes("from '../../generated/MobileDesignTokens'") || - /export\s+const\s+SHEET_(?:HORIZONTAL_PADDING|HEADER_HEIGHT|ACTION_HEIGHT|TOP_RADIUS|SIDE_RADIUS)\s*:\s*number\s*=\s*\d/.test( - sheetLayoutSource - ) ? [relative(sheetLayoutPath)] : []; -const cryptoDeclarationPath = path.join( - repoRoot, - 'src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/index.d.ts' -); -const cryptoDeclarationSource = fs.readFileSync(cryptoDeclarationPath, 'utf8'); -const synchronousArgon2Declaration = /argon2idRaw[\s\S]*\):\s*Uint8Array\s*;/.test(cryptoDeclarationSource) ? - [relative(cryptoDeclarationPath)] : []; -const nativeArgon2Path = path.join(repoRoot, 'src/apps/mobile/harmonyos/entry/src/main/cpp/napi_argon2.cpp'); -const nativeArgon2Source = fs.readFileSync(nativeArgon2Path, 'utf8'); -const synchronousNativeArgon2 = - !nativeArgon2Source.includes('napi_create_async_work') || !nativeArgon2Source.includes('napi_create_promise') ? - [relative(nativeArgon2Path)] : []; -const misplacedPresentationPolicies = [ - 'src/apps/mobile/harmonyos/entry/src/main/ets/services/FileTargetResolver.ets', - 'src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageFileReferenceProjector.ets', - 'src/apps/mobile/harmonyos/entry/src/main/ets/services/ToolFileReferenceResolver.ets' -].filter((file) => fs.existsSync(path.join(repoRoot, file))); -const extractedFilePreviewMethods = [ - 'openFilePreview', - 'closeFilePreview', - 'refreshFilePreview', - 'openFilePreviewLink', - 'invalidateFilePreviewTarget' -].filter((method) => new RegExp(`^\\s{2}${method}\\s*\\(`, 'm').test(appRootRuntimeSource)); -const extractedSettingsMethods = [ - 'saveGeneralChatConfig', - 'testGeneralChatConfig', - 'validateGeneralChatConfig', - 'probeGeneralChatConfig', - 'effectiveGeneralChatApiKey', - 'applyGeneralChatConfig', - 'refreshGeneralChatModelCatalog' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const extractedCloudAccountMethods = [ - 'persistDelegatedAccountSession', - 'loginCloudAccount', - 'restoreCloudAccountSession', - 'loadGeneralChatAccountModels', - 'applyCloudAccountSession', - 'logoutCloudAccount', - 'listCloudAccountDevices', - 'getRemotePermissionMode', - 'setRemotePermissionMode', - 'restoreCloudTarget', - 'expireCloudAccountSession', - 'handleRemoteConnectionError', - 'selectCloudAccountDevice' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+|protected\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const extractedConversationMethods = [ - 'isGeneralComposerRoute', - 'visibleChatInput', - 'visibleSelectedImages', - 'visibleVoiceListening', - 'setChatInputForRoute', - 'setSelectedImagesForRoute', - 'addSelectedImagesForRoute', - 'removeSelectedImageForRoute', - 'clearComposerForRoute', - 'setVoiceListeningForRoute', - 'setAllVoiceListening', - 'voiceInputSnapshot', - 'visibleChatBusy', - 'visibleStatusText', - 'setVisibleStatusText' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const extractedRemoteConversationMethods = [ - 'sendChatMessage', - 'stopActiveTask', - 'renameActiveSession', - 'copyMessage', - 'downloadFile', - 'retryMessage', - 'approveTool', - 'rejectTool', - 'cancelTool', - 'answerQuestion', - 'resetChatTimeline', - 'syncChatTimelineFromStore', - 'startPolling', - 'currentChatPollingCursor', - 'updateChatPollingCursor', - 'applyChatSessionSnapshot', - 'hasRunningActiveTurn', - 'projectedTimelineItems', - 'syncAfterTurnEnded' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const extractedRemoteCreateMethods = [ - 'createSession', - 'openRemoteCreateSession', - 'closeRemoteCreateSession', - 'loadRemoteCreateChoices', - 'loadRemoteCreateModelCatalog', - 'loadRemoteCreateDevices', - 'loadRemoteCreateWorkspaces', - 'toggleRemoteCreateDevices', - 'toggleRemoteCreateWorkspaces', - 'selectRemoteCreateDevice', - 'selectRemoteCreateWorkspace', - 'submitRemoteCreateSession', - 'createSessionInWorkspace', - 'openSession', - 'applyRemoteActiveSession', - 'deleteSession' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const extractedGeneralConversationMethods = [ - 'openHomeSession', - 'openHomeSessionInPlace', - 'deleteHomeSession', - 'activeGeneralChatAsRemoteSession', - 'activeGeneralUploadedFileCount', - 'archiveHomeSession', - 'exportHomeSession', - 'openGeneralSession', - 'startGeneralChat', - 'sendVisibleChatMessage', - 'stopActiveChatTask', - 'closeActiveChat', - 'renameVisibleSession', - 'retryVisibleMessage', - 'downloadVisibleFile', - 'selectModel', - 'sendGeneralChatMessage', - 'stopGeneralChatStream', - 'startVisibleGeneralChat', - 'generalChatHomeStatusText', - 'prepareNewGeneralChat', - 'onVisibleChatInputChange', - 'visibleGeneralChatDraftId', - 'restoreGeneralChatDraft', - 'latestUserMessageText', - 'showHomeToast', - 'resetGeneralChatTimeline', - 'syncGeneralChatTimelineFromStore' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const extractedRemoteConnectionForwards = [ - 'applyWorkspace', - 'applyRemotePairingProjection', - 'ensureRemoteAvailable', - 'setRemoteConnectionState', - 'setRemoteUrl', - 'setRemoteUserId', - 'setRemoteAuthenticatedUserId', - 'setRemoteStatusText', - 'setRemoteConnectionFailureKind', - 'setRemoteBusy', - 'setRemoteUrlInputVisible' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); -const appRootRuntimeStateGetters = [ - 'remoteUrl', 'userId', 'authenticatedUserId', 'statusText', 'connectionState', - 'connectionFailureKind', 'isBusy', 'showRemoteUrlInput', 'workspaceName', 'workspacePath', - 'workspaceBranch', 'workspaceKind', 'assistantId', 'desktopName', 'desktopId', 'activeSession', - 'messages', 'pendingMessages', 'activeTurnMessage', 'timelineItems', 'hasMoreMessages' -].filter((getter) => new RegExp(`^\\s{2}get\\s+${getter}\\s*\\(`, 'm').test(appRootRuntimeSource)); -const extractedOwnerForwards = [ - 'currentRoute', 'isRoute', 'isGeneralChatVisible', 'pushRoute', 'replaceRoute', 'popRoute', - 'handleConversationIntent', 'pasteRemoteUrl', 'scanRemoteUrl', 'handleDetectedRemoteUrl', - 'showRecentWorkspaces', 'showAssistants', 'refreshSessions', 'loadMoreSessions', 'setSessionFilter', - 'openAddConnection', 'selectRemoteCreateModel', 'loadRecentWorkspacesInBackground', - 'loadOlderMessages', 'removeSelectedImage', 'persistVisibleGeneralChatDraft', 'stopPolling', - 'nudgeChatPolling', 'pollActiveSession', 'startHeartbeat', 'stopHeartbeat', - 'checkConnectionHealth', 'resumeRemoteActivity' -].filter((method) => new RegExp(`^\\s{2}(?:private\\s+)?(?:async\\s+)?${method}\\s*\\(`, 'm') - .test(appRootRuntimeSource)); - -const expected = { - serviceToPages: [], - componentToViewmodel: [], - viewmodelToComponents: [], - stateToComponents: [], - componentToRawPlatformServices: [], - hardcodedTextFontSizes: [], - indirectHardcodedTypography: [], - v1Components: [], - positionalActionConstructors: [], - duplicatedConversationTraceFields: [], - extractedFilePreviewMethods: [], - extractedSettingsMethods: [], - extractedCloudAccountMethods: [], - extractedConversationMethods: [], - extractedRemoteConversationMethods: [], - extractedRemoteCreateMethods: [], - extractedGeneralConversationMethods: [], - extractedRemoteConnectionForwards: [], - appRootRuntimeStateGetters: [], - extractedOwnerForwards: [], - missingPresentationFiles: [], - localControllerRuntimeLeaks: [], - eagerChatTimeline: [], - missingTimelineReuse: [], - snapshottedTimelineRepeatItem: [], - snapshottedMessageBuilderInput: [], - missingObservableTimelineRows: [], - wideConversationViewContract: [], - duplicateSheetGeometry: [], - synchronousArgon2Declaration: [], - synchronousNativeArgon2: [], - misplacedPresentationPolicies: [] -}; - -function sameSet(actual, wanted) { - return actual.length === wanted.length && actual.every((item, index) => item === wanted[index]); -} - -const actual = { - serviceToPages, - componentToViewmodel, - viewmodelToComponents, - stateToComponents, - componentToRawPlatformServices, - hardcodedTextFontSizes, - indirectHardcodedTypography, - v1Components, - positionalActionConstructors, - duplicatedConversationTraceFields, - extractedFilePreviewMethods, - extractedSettingsMethods, - extractedCloudAccountMethods, - extractedConversationMethods, - extractedRemoteConversationMethods, - extractedRemoteCreateMethods, - extractedGeneralConversationMethods, - extractedRemoteConnectionForwards, - appRootRuntimeStateGetters, - extractedOwnerForwards, - missingPresentationFiles, - localControllerRuntimeLeaks, - eagerChatTimeline, - missingTimelineReuse, - snapshottedTimelineRepeatItem, - snapshottedMessageBuilderInput, - missingObservableTimelineRows, - wideConversationViewContract, - duplicateSheetGeometry, - synchronousArgon2Declaration, - synchronousNativeArgon2, - misplacedPresentationPolicies -}; -let failed = false; -for (const [name, wanted] of Object.entries(expected)) { - if (!sameSet(actual[name], wanted)) { - failed = true; - console.error(`${name} mismatch`); - console.error(`expected: ${JSON.stringify(wanted)}`); - console.error(`actual: ${JSON.stringify(actual[name])}`); - } -} -if (failed) { - process.exitCode = 1; -} else { - console.log('HarmonyOS architecture contracts are satisfied.'); -} diff --git a/scripts/check-mobile-architecture.mjs b/scripts/check-mobile-architecture.mjs deleted file mode 100644 index e95d6f062d..0000000000 --- a/scripts/check-mobile-architecture.mjs +++ /dev/null @@ -1,462 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const repoRoot = path.resolve(scriptDir, '..'); -const mobileRoot = path.join(repoRoot, 'src/apps/mobile'); -const sharedRoot = path.join(mobileRoot, 'shared'); - -// The complete set of edges the production dependency graph is allowed to -// contain. :core-domain is pure logic, so transport and -// persistence are absent from its row on purpose — they are adapters behind -// ports that :core-feature wires. -const allowedProductionDeps = new Map([ - ['core-protocol', []], - ['core-crypto', ['core-protocol']], - ['core-transport', ['core-protocol', 'core-crypto']], - ['core-persistence', ['core-protocol']], - ['core-domain', ['core-protocol']], - ['core-feature', ['core-domain', 'core-transport', 'core-persistence']], - ['core-testing', []] -]); - -// Rule 3: the seam. Platform apps see UiState and Intent from :core-feature and -// nothing else. -const appVisibleModules = ['core-feature']; - -// Rule 6: shared/ is platform-agnostic; these trees must stay invisible to it. -const forbiddenTrees = ['harmonyos', 'src/apps/desktop', 'src/web-ui', 'src/mobile-web']; - -const modules = [...allowedProductionDeps.keys()]; - -function relative(file) { - return path.relative(repoRoot, file).split(path.sep).join('/'); -} - -function walk(root, extension) { - if (!fs.existsSync(root)) { - return []; - } - const files = []; - for (const entry of fs.readdirSync(root, { withFileTypes: true })) { - const entryPath = path.join(root, entry.name); - if (entry.isDirectory()) { - if (entry.name === 'build' || entry.name === '.gradle' || entry.name === '.kotlin') { - continue; - } - files.push(...walk(entryPath, extension)); - } else if (entry.isFile() && entry.name.endsWith(extension)) { - files.push(entryPath); - } - } - return files.sort(); -} - -/** - * Blanks out `//` and block comments while preserving line numbering, so the - * content checks below judge code rather than prose. A comment can document a - * platform tree or carry a Chinese note without creating a dependency on it. - */ -function stripComments(source) { - let output = ''; - let inBlock = false; - for (const line of source.split(/\r?\n/)) { - let kept = ''; - let index = 0; - while (index < line.length) { - if (inBlock) { - const end = line.indexOf('*/', index); - if (end === -1) { - index = line.length; - } else { - inBlock = false; - index = end + 2; - } - continue; - } - if (line.startsWith('//', index)) break; - if (line.startsWith('/*', index)) { - inBlock = true; - index += 2; - continue; - } - kept += line[index]; - index += 1; - } - output += `${kept}\n`; - } - return output; -} - -/** - * Extracts the body of every `.dependencies { ... }` block, keyed by - * source set name, by matching braces rather than trusting a flat regex. - */ -function dependencyBlocks(source) { - const blocks = []; - const opener = /(\w+)\.dependencies\s*\{/g; - let match; - while ((match = opener.exec(source)) !== null) { - let depth = 1; - let cursor = opener.lastIndex; - while (cursor < source.length && depth > 0) { - if (source[cursor] === '{') depth += 1; - else if (source[cursor] === '}') depth -= 1; - cursor += 1; - } - blocks.push({ sourceSet: match[1], body: source.slice(opener.lastIndex, cursor - 1) }); - } - return blocks; -} - -/** - * Splits a parameter list on the commas that separate parameters, ignoring the - * ones inside generics, nested calls and strings, and reports whether each - * parameter carries a default value. - */ -function parametersOf(list) { - const parameters = []; - let current = ''; - let depth = 0; - let angle = 0; - let quote = null; - for (let index = 0; index < list.length; index += 1) { - const character = list[index]; - if (quote) { - if (character === '\\') { - current += character + (list[index + 1] ?? ''); - index += 1; - continue; - } - if (character === quote) quote = null; - current += character; - continue; - } - if (character === '"' || character === "'") { - quote = character; - current += character; - continue; - } - if (character === '(' || character === '[') depth += 1; - else if (character === ')' || character === ']') depth -= 1; - else if (character === '<') angle += 1; - else if (character === '>') angle = Math.max(0, angle - 1); - if (character === ',' && depth === 0 && angle === 0) { - parameters.push(current); - current = ''; - continue; - } - current += character; - } - if (current.trim()) parameters.push(current); - return parameters; -} - -function hasDefault(parameter) { - let depth = 0; - let angle = 0; - let quote = null; - for (let index = 0; index < parameter.length; index += 1) { - const character = parameter[index]; - if (quote) { - if (character === '\\') index += 1; - else if (character === quote) quote = null; - continue; - } - if (character === '"' || character === "'") { - quote = character; - continue; - } - if (character === '(' || character === '[') depth += 1; - else if (character === ')' || character === ']') depth -= 1; - else if (character === '<') angle += 1; - else if (character === '>') angle = Math.max(0, angle - 1); - else if ( - character === '=' && - depth === 0 && - angle === 0 && - parameter[index + 1] !== '=' && - parameter[index - 1] !== '!' && - parameter[index - 1] !== '<' && - parameter[index - 1] !== '>' - ) { - return true; - } - } - return false; -} - -/** - * Finds public declarations whose parameter list carries a default value. - * - * Three shapes qualify: a public function, a public secondary constructor, and - * the primary constructor of a public class — the last only when it is not - * explicitly narrowed with `internal constructor` or `private constructor`, - * since a narrowed one is not part of the public surface. - */ -function publicDefaults(source) { - const findings = []; - const declaration = - /\bpublic\s+(?:(?:inline|infix|operator|suspend|expect|actual|external|tailrec|override)\s+)*(?:(fun)\s+[\w<>.,\s?]*?\(|(constructor)\s*\(|(?:(?:data|value|sealed|abstract|open|annotation|inner)\s+)*class\s+\w+\s*(?:<[^>()]*>)?\s*(?:(internal|private|protected)\s+)?(?:constructor\s*)?\()/g; - let match; - while ((match = declaration.exec(source)) !== null) { - // A primary constructor narrowed below public is not public API. Group 3 — - // the only other capturing groups are `fun` and `constructor`. - if (match[3]) continue; - const open = source.lastIndexOf('(', declaration.lastIndex); - let depth = 1; - let cursor = open + 1; - while (cursor < source.length && depth > 0) { - if (source[cursor] === '(') depth += 1; - else if (source[cursor] === ')') depth -= 1; - cursor += 1; - } - const list = source.slice(open + 1, cursor - 1); - if (!parametersOf(list).some(hasDefault)) continue; - const line = source.slice(0, match.index).split('\n').length; - findings.push({ line, text: source.slice(match.index, open).trim() }); - } - return findings; -} - -function projectRefs(body) { - return [...body.matchAll(/project\(\s*["']:([\w-]+)["']\s*\)/g)].map((match) => match[1]); -} - -const buildFiles = new Map( - modules - .filter((module) => fs.existsSync(path.join(sharedRoot, module, 'build.gradle.kts'))) - .map((module) => [module, fs.readFileSync(path.join(sharedRoot, module, 'build.gradle.kts'), 'utf8')]) -); - -const missingModules = modules.filter((module) => !buildFiles.has(module)); - -// ── Rule 1: commonMain stays free of platform APIs ──────────────────── -const platformImportsInCommonMain = []; -for (const module of buildFiles.keys()) { - const commonMain = path.join(sharedRoot, module, 'src/commonMain'); - for (const file of walk(commonMain, '.kt')) { - const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/); - lines.forEach((line, index) => { - if (/^\s*import\s+(java|javax|android)\./.test(line)) { - platformImportsInCommonMain.push(`${relative(file)}:${index + 1}`); - } - }); - } -} - -// ── Rules 2 and 4: the production dependency graph ──────────────────── -const forbiddenModuleDeps = []; -const testOnlyModuleLeaks = []; -const productionGraph = new Map(); -for (const [module, source] of buildFiles) { - const allowed = allowedProductionDeps.get(module); - const production = new Set(); - for (const block of dependencyBlocks(stripComments(source))) { - const isTest = block.sourceSet.endsWith('Test'); - for (const dep of projectRefs(block.body)) { - if (isTest) { - // Any module may lean on :core-testing from a test source set. - if (dep !== 'core-testing' && !allowed.includes(dep)) { - forbiddenModuleDeps.push(`${module}:${block.sourceSet} -> ${dep}`); - } - continue; - } - production.add(dep); - if (dep === 'core-testing') { - testOnlyModuleLeaks.push(`${module}:${block.sourceSet} -> core-testing`); - } else if (!allowed.includes(dep)) { - forbiddenModuleDeps.push(`${module}:${block.sourceSet} -> ${dep}`); - } - } - } - productionGraph.set(module, [...production]); -} - -// Cycle detection over the production graph. The allowlist above is already -// acyclic, but it is edited by hand and this is the cheap guard against a -// future edit that is locally reasonable and globally circular. -const dependencyCycles = []; -const visitState = new Map(); -function visit(module, stack) { - if (visitState.get(module) === 'done') return; - if (visitState.get(module) === 'visiting') { - dependencyCycles.push([...stack.slice(stack.indexOf(module)), module].join(' -> ')); - return; - } - visitState.set(module, 'visiting'); - for (const dep of productionGraph.get(module) ?? []) { - visit(dep, [...stack, module]); - } - visitState.set(module, 'done'); -} -for (const module of productionGraph.keys()) { - visit(module, []); -} - -// ── Rule 3: platform apps only reach :core-feature ──────────────────── -const appReachesInternalModules = []; -for (const platform of ['android', 'ios']) { - const platformRoot = path.join(mobileRoot, platform); - const sources = [...walk(platformRoot, '.kts'), ...walk(platformRoot, '.kt'), ...walk(platformRoot, '.swift')]; - for (const file of sources) { - const source = fs.readFileSync(file, 'utf8'); - for (const module of modules) { - if (appVisibleModules.includes(module)) continue; - const packageSuffix = module.replace(/^core-/, ''); - // Two spellings, because an app includes shared/ as a composite build - // rather than as subprojects: `project(":core-x")` inside shared/, and the - // substituted coordinate `"com.openbitfun.mobile:core-x"` (optionally - // versioned) from an app. Matching only the first would let an app declare - // a forbidden edge in the one form it is actually able to write. - const referencesModule = - new RegExp(`["'][\\w.-]*:${module}(?::[^"']*)?["']`).test(source) || - new RegExp(`com\\.openbitfun\\.mobile\\.core\\.${packageSuffix}\\b`).test(source); - if (referencesModule) { - appReachesInternalModules.push(`${relative(file)} -> ${module}`); - } - } - } -} - -// ── §4.1 rule 2: no default arguments on the Swift-facing surface ───── -// Kotlin default arguments do not survive into Swift — an iOS caller sees the -// full initializer and has to name every parameter, including the ones the -// default existed to hide. -// -// Two modules are in scope, not one: :core-feature because the apps see it, and -// :core-domain because :core-feature re-exports it with api(), which puts its -// public types on the very same Swift surface. The rest sit behind -// implementation() and never reach Swift, so defaults there are ordinary Kotlin. -// -// The scan keys on the `public` keyword, which is only trustworthy if the -// compiler requires it — hence the explicitApi() precondition below. Without -// it a declaration with no visibility modifier is public too, and would slip past. -const swiftFacingModules = ['core-feature', 'core-domain']; -const featureApiNotExplicit = []; -const defaultArgsInFeatureApi = []; -for (const module of swiftFacingModules) { - const buildFile = path.join(sharedRoot, module, 'build.gradle.kts'); - // Comments stripped first: a commented-out explicitApi() must not satisfy the - // precondition, or the scan below silently goes back to being unsound. - if (!/\bexplicitApi\s*\(/.test(stripComments(fs.readFileSync(buildFile, 'utf8')))) { - featureApiNotExplicit.push(relative(buildFile)); - } - for (const file of walk(path.join(sharedRoot, module, 'src/commonMain'), '.kt')) { - const source = stripComments(fs.readFileSync(file, 'utf8')); - for (const finding of publicDefaults(source)) { - defaultArgsInFeatureApi.push(`${relative(file)}:${finding.line} ${finding.text}`); - } - } -} - -// ── Rule 5: the core never returns display strings ──────────────────── -// Approximated as "no CJK anywhere in commonMain". Every localized string in -// this repo has a CJK counterpart, so a Chinese character in shared logic means -// a display string escaped into the core instead of a typed state. -const localizedStringsInCore = []; -for (const module of buildFiles.keys()) { - for (const file of walk(path.join(sharedRoot, module, 'src'), '.kt')) { - const lines = stripComments(fs.readFileSync(file, 'utf8')).split(/\r?\n/); - lines.forEach((line, index) => { - if (/[一-鿿]/.test(line)) { - localizedStringsInCore.push(`${relative(file)}:${index + 1}`); - } - }); - } -} - -// ── Rule 6: shared/ never reaches into a platform tree ──────────────── -const sharedReachesPlatformTrees = []; -for (const file of [...walk(sharedRoot, '.kt'), ...walk(sharedRoot, '.kts'), ...walk(sharedRoot, '.toml')]) { - const lines = stripComments(fs.readFileSync(file, 'utf8')).split(/\r?\n/); - lines.forEach((line, index) => { - for (const tree of forbiddenTrees) { - if (line.includes(tree)) { - sharedReachesPlatformTrees.push(`${relative(file)}:${index + 1} -> ${tree}`); - } - } - }); -} - -// ── Rule 8: the two Android string tables stay in sync ─────────────── -// Rule 5 pushes every user-facing word out of the core and into resources, so -// resources are the only place a missing translation can hide. A key present in -// one table and absent from the other ships as English to a Chinese user — the -// exact regression this rule was added after. -const androidValues = path.join(mobileRoot, 'android/app/src/main/res'); -// Brand names are deliberately identical in both locales; duplicating them -// would only invite a "translation" that shouldn't exist. -const untranslatedByDesign = new Set(['app_name']); - -function stringKeys(file) { - if (!fs.existsSync(file)) return null; - return new Set( - [...fs.readFileSync(file, 'utf8').matchAll(/ match[1]) - ); -} - -const stringTablesOutOfSync = []; -const baseStrings = stringKeys(path.join(androidValues, 'values/strings.xml')); -const zhStrings = stringKeys(path.join(androidValues, 'values-zh/strings.xml')); -if (baseStrings === null || zhStrings === null) { - stringTablesOutOfSync.push('values/strings.xml or values-zh/strings.xml is missing'); -} else { - for (const key of baseStrings) { - if (!zhStrings.has(key) && !untranslatedByDesign.has(key)) { - stringTablesOutOfSync.push(`values-zh/strings.xml is missing ${key}`); - } - } - for (const key of zhStrings) { - if (!baseStrings.has(key)) { - stringTablesOutOfSync.push(`values/strings.xml is missing ${key}`); - } - } - stringTablesOutOfSync.sort(); -} - -const expected = { - missingModules: [], - platformImportsInCommonMain: [], - forbiddenModuleDeps: [], - testOnlyModuleLeaks: [], - dependencyCycles: [], - appReachesInternalModules: [], - localizedStringsInCore: [], - sharedReachesPlatformTrees: [], - featureApiNotExplicit: [], - defaultArgsInFeatureApi: [], - stringTablesOutOfSync: [] -}; - -const actual = { - missingModules, - platformImportsInCommonMain, - forbiddenModuleDeps, - testOnlyModuleLeaks, - dependencyCycles, - appReachesInternalModules, - localizedStringsInCore, - sharedReachesPlatformTrees, - featureApiNotExplicit, - defaultArgsInFeatureApi, - stringTablesOutOfSync -}; - -let failed = false; -for (const [name, wanted] of Object.entries(expected)) { - const found = actual[name]; - if (found.length !== wanted.length || !found.every((item, index) => item === wanted[index])) { - failed = true; - console.error(`${name} mismatch`); - console.error(`expected: ${JSON.stringify(wanted)}`); - console.error(`actual: ${JSON.stringify(found)}`); - } -} - -if (failed) { - process.exitCode = 1; -} else { - console.log('Mobile shared core architecture contracts are satisfied.'); -} diff --git a/scripts/frontend-color-surface-registry.json b/scripts/frontend-color-surface-registry.json index 40b9254fdc..50cc58728e 100644 --- a/scripts/frontend-color-surface-registry.json +++ b/scripts/frontend-color-surface-registry.json @@ -4,8 +4,7 @@ "contracts": { "webSystem": "design-system/packages/design-tokens/src/system.tokens.json", "webTheme": "design-system/packages/theme-openbitfun/src/light.tokens.json", - "miniappAppearance": "src/shared/miniapp-appearance/contract.json", - "nativeMobile": "src/apps/mobile/design-system/tokens/mobile-tokens.json" + "miniappAppearance": "src/shared/miniapp-appearance/contract.json" }, "discovery": { "miniappParents": [ @@ -199,19 +198,6 @@ "packageContracts": ["@openbitfun/design-tokens", "@openbitfun/theme-openbitfun"] } }, - { - "id": "mobile-design-preview", - "label": "Native mobile comparison preview", - "kind": "canonical-web", - "owner": "canonical web tokens for chrome and generated native mobile tokens for device content", - "root": "src/apps/mobile/design-system/preview", - "audit": { - "engine": "theme", - "policy": "canonical-ui-zero", - "packageContracts": ["@openbitfun/design-tokens", "@openbitfun/theme-openbitfun"], - "excludePaths": ["generated"] - } - }, { "id": "cli", "label": "CLI and TUI", @@ -223,51 +209,6 @@ "baseline": "scripts/theme-color-governance-baseline.cli.json" } }, - { - "id": "native-android", - "label": "Native Android", - "kind": "native-mobile", - "owner": "src/apps/mobile/design-system/tokens/mobile-tokens.json", - "root": "src/apps/mobile/android/app/src/main/kotlin", - "audit": { - "engine": "native", - "platform": "android", - "extensions": [".kt"], - "excludePaths": [ - "com/openbitfun/mobile/app/ui/theme/generated", - "com/openbitfun/mobile/app/ui/preview/generated" - ] - } - }, - { - "id": "native-ios", - "label": "Native iOS", - "kind": "native-mobile", - "owner": "src/apps/mobile/design-system/tokens/mobile-tokens.json", - "root": "src/apps/mobile/ios/OpenBitFun", - "audit": { - "engine": "native", - "platform": "ios", - "extensions": [".swift"], - "excludeFiles": [ - "Features/DesignSystem/GeneratedMobileDesignTokens.swift", - "Features/DesignSystem/GeneratedMobilePreviewScenarios.swift" - ] - } - }, - { - "id": "native-harmonyos", - "label": "Native HarmonyOS", - "kind": "native-mobile", - "owner": "src/apps/mobile/design-system/tokens/mobile-tokens.json", - "root": "src/apps/mobile/harmonyos/entry/src/main/ets", - "audit": { - "engine": "native", - "platform": "harmonyos", - "extensions": [".ets"], - "excludePaths": ["generated"] - } - }, { "id": "miniapp-coding-selfie", "label": "Coding Selfie MiniApp", @@ -499,18 +440,6 @@ "id": "miniapp-appearance-projection", "surfaceKinds": ["miniapp"], "command": ["node", "scripts/generate-miniapp-appearance-contract.mjs", "--check"] - }, - { - "id": "native-mobile-token-projection", - "surfaceKinds": ["native-mobile"], - "surfaceIds": ["mobile-design-preview"], - "command": ["node", "scripts/mobile-ui-design-system.mjs", "--check"] - }, - { - "id": "native-mobile-preview-assets", - "surfaceKinds": ["native-mobile"], - "surfaceIds": ["mobile-design-preview"], - "command": ["node", "scripts/mobile-ui-preview.mjs", "--check"] } ], "exclusions": [ @@ -577,34 +506,6 @@ "owner": "PPT Live build-openbitfun.mjs", "reason": "Bundled JavaScript is generated from the registered PPT source owner." }, - { - "id": "android-template-icons", - "path": "src/apps/mobile/android/app/src/main/res/drawable", - "kind": "native-template-asset", - "owner": "Android resource layer", - "reason": "Monochrome vector templates are tinted by native semantic tokens at render time." - }, - { - "id": "ios-template-icons", - "path": "src/apps/mobile/ios/OpenBitFun/Resources.xcassets", - "kind": "native-template-asset", - "owner": "iOS asset catalog", - "reason": "Template images and app metadata are tinted or consumed by the platform asset layer." - }, - { - "id": "harmony-template-media", - "path": "src/apps/mobile/harmonyos/entry/src/main/resources/base/media", - "kind": "native-template-asset", - "owner": "HarmonyOS resource layer", - "reason": "Template media is tinted by semantic ResourceColor values in the native UI." - }, - { - "id": "mobile-preview-generated", - "path": "src/apps/mobile/design-system/preview/generated", - "kind": "generated-output", - "owner": "scripts/mobile-ui-design-system.mjs", - "reason": "Preview data is generated from the native mobile token contract and checked for drift." - }, { "id": "data-tools-generated", "path": "src/apps/data-tools/ui/generated", diff --git a/scripts/generate-brand-assets.mjs b/scripts/generate-brand-assets.mjs index 90967c080d..9d7a8c0e48 100644 --- a/scripts/generate-brand-assets.mjs +++ b/scripts/generate-brand-assets.mjs @@ -20,15 +20,7 @@ const BRAND_SIZE = 512; const APP_ICON_SIZE = 1024; const APP_ICON_CORNER_RADIUS = 96; const APP_MARK_LIFT = 28; -const ANDROID_FOREGROUND_SCALE = 0.66; - -const ANDROID_DENSITIES = { - mdpi: { icon: 48, adaptive: 108 }, - hdpi: { icon: 72, adaptive: 162 }, - xhdpi: { icon: 96, adaptive: 216 }, - xxhdpi: { icon: 144, adaptive: 324 }, - xxxhdpi: { icon: 192, adaptive: 432 }, -}; + const DESKTOP_HICOLOR_SIZES = [16, 32, 48, 64, 96, 128, 256, 512]; const EXPORT_SIZES = [16, 24, 32, 48, 64, 96, 128, 192, 256, 512, 1024, 2048]; @@ -57,20 +49,6 @@ const LEGACY_APPLICATION_ASSETS = [ 'OpenBitFun-Installer/src-tauri/icons/icon.png', 'OpenBitFun-Installer/src-tauri/icons/icon.ico', 'OpenBitFun-Installer/src-tauri/icons/icon.icns', - 'src/apps/mobile/harmonyos/AppScope/resources/base/media/openbitfun_icon.png', - 'src/apps/mobile/harmonyos/AppScope/resources/base/media/openbitfun-app-icon.png', - 'src/apps/mobile/harmonyos/AppScope/resources/base/media/background.png', - 'src/apps/mobile/harmonyos/AppScope/resources/base/media/foreground.png', - 'src/apps/mobile/harmonyos/AppScope/resources/base/media/layered_image.json', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/openbitfun_icon.png', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/openbitfun-app-icon.png', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/openbitfun-start-window.png', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/background.png', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/foreground.png', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/layered_image.json', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media/startIcon.png', - 'src/apps/mobile/ios/OpenBitFun/Resources.xcassets/AppIcon.appiconset/openbitfun_icon.png', - 'src/apps/mobile/ios/OpenBitFun/Resources.xcassets/OpenBitFunLogo.imageset', 'src/apps/relay-server/static/assets/Logo-ICON-BOaKcXgO.png', ]; @@ -178,26 +156,6 @@ async function createApplicationIcon(applicationMark) { .toBuffer(); } -async function createAdaptiveForeground(applicationMark, size) { - const artworkSize = Math.round(size * ANDROID_FOREGROUND_SCALE); - const artwork = await resizePng(applicationMark, artworkSize); - - return sharp({ - create: { - width: size, - height: size, - channels: 4, - background: { r: 255, g: 255, b: 255, alpha: 0 }, - }, - }) - .composite([{ - input: artwork, - left: Math.floor((size - artworkSize) / 2), - top: Math.floor((size - artworkSize) / 2), - }]) - .png({ compressionLevel: 9, adaptiveFiltering: true }) - .toBuffer(); -} async function generateWindowsIcon(applicationIcon, renderIcon) { const tempDir = await mkdtemp(path.join(os.tmpdir(), 'openbitfun-tauri-icons-')); @@ -349,39 +307,6 @@ async function generateBrandAssets() { } } - for (const [density, sizes] of Object.entries(ANDROID_DENSITIES)) { - const legacyIcon = await renderIcon(sizes.icon); - const adaptiveForeground = await createAdaptiveForeground(applicationMark, sizes.adaptive); - const androidDir = outputPath('src', 'apps', 'mobile', 'android', 'app', 'src', 'main', 'res', `mipmap-${density}`); - await writePng(path.join(androidDir, 'ic_launcher.png'), legacyIcon); - await writePng(path.join(androidDir, 'ic_launcher_round.png'), legacyIcon); - await writePng(path.join(androidDir, 'ic_launcher_foreground.png'), adaptiveForeground); - await writePng(path.join(androidDir, 'ic_launcher_monochrome.png'), adaptiveForeground); - } - - await writePng( - outputPath('src', 'apps', 'mobile', 'ios', 'OpenBitFun', 'Resources.xcassets', 'AppIcon.appiconset', 'openbitfun-app-icon.png'), - // App Store icons must be opaque; iOS applies its own corner mask. - await sharp(applicationIconLarge).flatten({ background: '#000000' }).png().toBuffer(), - ); - await writePng( - outputPath('src', 'apps', 'mobile', 'ios', 'OpenBitFun', 'Resources.xcassets', 'OpenBitFunMark.imageset', 'openbitfun-mark-light.png'), - lightMark, - ); - - await writePng( - outputPath('src', 'apps', 'mobile', 'harmonyos', 'AppScope', 'resources', 'base', 'media', 'openbitfun_app_icon.png'), - applicationIconLarge, - ); - await writePng( - outputPath('src', 'apps', 'mobile', 'harmonyos', 'entry', 'src', 'main', 'resources', 'base', 'media', 'openbitfun_app_icon.png'), - applicationIconLarge, - ); - await writePng( - outputPath('src', 'apps', 'mobile', 'harmonyos', 'entry', 'src', 'main', 'resources', 'base', 'media', 'openbitfun_start_window.png'), - await resizePng(lightMark, 144), - ); - await removeLegacyApplicationAssets(); console.log('Generated OpenBitFun application brand assets.'); diff --git a/scripts/generate-brand-assets.test.mjs b/scripts/generate-brand-assets.test.mjs index adfc7ea1a2..6e96187389 100644 --- a/scripts/generate-brand-assets.test.mjs +++ b/scripts/generate-brand-assets.test.mjs @@ -10,10 +10,6 @@ const GENERATED_ICNS_FILES = [ 'OpenBitFun-Installer/src-tauri/icons/openbitfun-app-icon.icns', ]; -const HARMONY_MEDIA_DIRS = [ - 'src/apps/mobile/harmonyos/AppScope/resources/base/media', - 'src/apps/mobile/harmonyos/entry/src/main/resources/base/media', -]; test('design-system brand masters and packaged icons agree with native projections', () => { const componentAssets = 'design-system/packages/ui/src/brand/assets'; @@ -133,14 +129,6 @@ test('application icons preserve the submitted artwork independently from the st assert.equal(metadata.hasAlpha, true); }); -test('iOS App Store icon is a 1024 pixel RGB image without alpha', async () => { - const metadata = await sharp('src/apps/mobile/ios/OpenBitFun/Resources.xcassets/AppIcon.appiconset/openbitfun-app-icon.png').metadata(); - assert.equal(metadata.width, 1024); - assert.equal(metadata.height, 1024); - assert.equal(metadata.hasAlpha, false); - assert.equal(metadata.channels, 3); -}); - test('brand exports provide decodable transparent PNGs at every advertised size', async () => { const sizes = [16, 24, 32, 48, 64, 96, 128, 192, 256, 512, 1024, 2048]; for (const size of sizes) { @@ -240,25 +228,6 @@ test('browser entry points reference generated application favicons', () => { } }); -test('HarmonyOS generated media use valid resource identifiers', () => { - for (const directory of HARMONY_MEDIA_DIRS) { - for (const fileName of readdirSync(directory)) { - const resourceName = fileName.replace(/\.[^.]+$/, ''); - assert.match( - resourceName, - /^[a-zA-Z0-9_]+$/, - `${directory}/${fileName} is not a valid HarmonyOS resource name`, - ); - } - } - - const appConfig = readFileSync('src/apps/mobile/harmonyos/AppScope/app.json5', 'utf8'); - const moduleConfig = readFileSync('src/apps/mobile/harmonyos/entry/src/main/module.json5', 'utf8'); - assert.match(appConfig, /\$media:openbitfun_app_icon/); - assert.match(moduleConfig, /\$media:openbitfun_app_icon/); - assert.match(moduleConfig, /\$media:openbitfun_start_window/); -}); - test('ICNS canonicalization rejects malformed containers', () => { assert.throws( () => canonicalizeIcns(Buffer.from('not-an-icns')), diff --git a/scripts/generate-i18n-contract.mjs b/scripts/generate-i18n-contract.mjs index 42c5ca063b..8153549ded 100644 --- a/scripts/generate-i18n-contract.mjs +++ b/scripts/generate-i18n-contract.mjs @@ -7,14 +7,6 @@ const checkOnly = process.argv.includes('--check'); const contractPath = path.join(root, 'src', 'shared', 'i18n', 'contract', 'locales.json'); const outputs = [ - { - path: path.join(root, 'src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/GeneratedLocaleContract.kt'), - generate: (contract) => `// Generated by scripts/generate-i18n-contract.mjs. Do not edit. -package com.openbitfun.mobile.app.platform - -internal const val DEFAULT_APP_LANGUAGE_TAG = "${contract.surfaceDefaults.android}" -`, - }, { path: path.join(root, 'src', 'web-ui', 'src', 'infrastructure', 'i18n', 'presets', 'generatedLocaleContract.ts'), generate: generateWebLocaleContract, diff --git a/scripts/mobile-client-build.contract.test.mjs b/scripts/mobile-client-build.contract.test.mjs index d5947da58c..b8c56bbeb8 100644 --- a/scripts/mobile-client-build.contract.test.mjs +++ b/scripts/mobile-client-build.contract.test.mjs @@ -1,41 +1,8 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; import test from 'node:test'; - -// Cross-platform source contracts belong to the repository, not a shared -// runtime module that would then need to reach into a platform's implementation. -const root = path.resolve(import.meta.dirname, '..'); -const source = relative => fs.readFileSync(path.join(root, relative), 'utf8'); -const services = 'src/apps/mobile/harmonyos/entry/src/main/ets/services'; - -function protocolVersion(file, declaration) { - const match = source(file).match(declaration); - assert.ok(match, `Missing protocol version declaration in ${file}`); - return Number(match[1]); -} - -test('mobile and web protocol versions match the Rust account contract', () => { - const expected = protocolVersion( - 'src/crates/contracts/product-domains/src/account.rs', - /^pub const CLIENT_PROTOCOL_VERSION: u32 = (\d+);$/m, - ); - for (const [file, declaration] of [ - ['src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/ClientBuild.kt', - /^public const val CLIENT_PROTOCOL_VERSION: Int = (\d+)$/m], - [`${services}/ClientBuild.ets`, /^export const CLIENT_PROTOCOL_VERSION: number = (\d+);$/m], - ['src/shared/relay-transport/ClientBuild.ts', /^export const CLIENT_PROTOCOL_VERSION = (\d+);$/m], - ]) { - assert.equal(protocolVersion(file, declaration), expected, `${file} must match the Rust contract`); - } -}); - -test('HarmonyOS reports its bundle build and protocol on login and every handshake', () => { - // Preserve the transport assertions formerly owned by the shared JVM suite. - // The version string is resolved from this platform's bundle at runtime. - const realtime = source(`${services}/AccountRealtime.ets`); - assert.ok(realtime.includes('clientVersion: clientVersion()')); - assert.ok(realtime.includes('clientProtocol: CLIENT_PROTOCOL_VERSION')); - const client = source(`${services}/CloudAccountClient.ets`); - assert.ok(client.includes('clientVersion: clientVersion(), clientProtocol: CLIENT_PROTOCOL_VERSION')); +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +test('web protocol version matches the host account contract', () => { + const host = readFileSync('src/crates/contracts/product-domains/src/account.rs','utf8').match(/CLIENT_PROTOCOL_VERSION: u32 = (\d+)/)[1]; + const web = readFileSync('src/shared/relay-transport/ClientBuild.ts','utf8').match(/CLIENT_PROTOCOL_VERSION = (\d+)/)[1]; + assert.equal(web,host); }); diff --git a/scripts/mobile-ui-design-system.mjs b/scripts/mobile-ui-design-system.mjs deleted file mode 100644 index 142e9ce50b..0000000000 --- a/scripts/mobile-ui-design-system.mjs +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/env node - -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); -const DESIGN_DIR = join(ROOT, 'src', 'apps', 'mobile', 'design-system'); -const TOKENS_PATH = join(DESIGN_DIR, 'tokens', 'mobile-tokens.json'); -const COMPONENTS_PATH = join(DESIGN_DIR, 'components', 'mobile-components.json'); -const SCENARIOS_PATH = join(DESIGN_DIR, 'scenarios', 'mobile-preview-scenarios.json'); -const CHECK = process.argv.includes('--check'); - -const tokens = readJson(TOKENS_PATH); -const components = readJson(COMPONENTS_PATH); -const scenarios = readJson(SCENARIOS_PATH); - -validateContract(tokens, components, scenarios); - -const outputs = new Map([ - [ - join(ROOT, 'src', 'apps', 'mobile', 'harmonyos', 'entry', 'src', 'main', 'resources', 'base', 'element', 'color.json'), - renderHarmonyColors(tokens.colors, 'light'), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'harmonyos', 'entry', 'src', 'main', 'resources', 'dark', 'element', 'color.json'), - renderHarmonyColors(tokens.colors, 'dark'), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'harmonyos', 'entry', 'src', 'main', 'ets', 'generated', 'MobileDesignTokens.ets'), - renderHarmonyTokens(tokens), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'harmonyos', 'entry', 'src', 'main', 'ets', 'generated', 'MobilePreviewScenarios.ets'), - renderHarmonyScenarios(scenarios), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'android', 'app', 'src', 'main', 'kotlin', 'com', 'openbitfun', 'mobile', 'app', 'ui', 'theme', 'generated', 'MobileDesignTokens.kt'), - renderAndroidTokens(tokens), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'android', 'app', 'src', 'main', 'kotlin', 'com', 'openbitfun', 'mobile', 'app', 'ui', 'preview', 'generated', 'MobilePreviewScenarios.kt'), - renderAndroidScenarios(scenarios), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'shared', 'core-feature', 'src', 'commonMain', 'kotlin', 'com', 'openbitfun', 'mobile', 'core', 'feature', 'layout', 'generated', 'MobileDesignBreakpoints.kt'), - renderSharedLayoutTokens(tokens), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'ios', 'OpenBitFun', 'Features', 'DesignSystem', 'GeneratedMobileDesignTokens.swift'), - renderIosTokens(tokens), - ], - [ - join(ROOT, 'src', 'apps', 'mobile', 'ios', 'OpenBitFun', 'Features', 'DesignSystem', 'GeneratedMobilePreviewScenarios.swift'), - renderIosScenarios(scenarios), - ], - [ - join(DESIGN_DIR, 'preview', 'generated', 'mobile-design-data.js'), - renderPreviewData(tokens, components, scenarios), - ], -]); - -let changed = 0; -for (const [path, content] of outputs) { - const current = existsSync(path) ? readFileSync(path, 'utf8') : null; - if (current !== null && normalizeLineEndings(current) === normalizeLineEndings(content)) continue; - changed += 1; - const relativePath = path.slice(ROOT.length + 1); - if (CHECK) { - console.error(`[mobile-ui] Generated file is stale: ${relativePath}`); - continue; - } - mkdirSync(dirname(path), { recursive: true }); - writeFileSync(path, content, 'utf8'); - console.log(`[mobile-ui] Wrote ${relativePath}`); -} - -if (CHECK && changed > 0) { - console.error(`[mobile-ui] ${changed} generated file(s) need regeneration.`); - process.exit(1); -} - -if (changed === 0) { - console.log(`[mobile-ui] ${CHECK ? 'Contract and generated files are in sync' : 'Generated files are already current'}.`); -} - -function normalizeLineEndings(content) { - return content.replace(/\r\n?/g, '\n'); -} - -function readJson(path) { - return JSON.parse(readFileSync(path, 'utf8')); -} - -function validateContract(tokenContract, componentContract, scenarioContract) { - if (tokenContract.version !== 1 || componentContract.version !== 1 || scenarioContract.version !== 1) { - throw new Error('Unsupported mobile design contract version.'); - } - for (const [name, pair] of Object.entries(tokenContract.colors ?? {})) { - for (const appearance of ['light', 'dark']) { - if (!/^#(?:[0-9A-F]{6}|[0-9A-F]{8})$/.test(pair[appearance] ?? '')) { - throw new Error(`Invalid ${appearance} color for ${name}.`); - } - } - } - for (const [name, value] of Object.entries(tokenContract.geometry ?? {})) { - if (!Number.isFinite(value) || value <= 0) throw new Error(`Invalid geometry token ${name}.`); - } - validateTextScale(tokenContract.text_scale); - const availableTokenNames = new Set([ - ...Object.keys(tokenContract.colors ?? {}), - ...Object.keys(tokenContract.typography ?? {}), - ...Object.keys(tokenContract.geometry ?? {}), - ...Object.keys(tokenContract.breakpoints ?? {}), - ...Object.keys(tokenContract.motion ?? {}), - ]); - for (const [componentName, component] of Object.entries(componentContract.components ?? {})) { - for (const tokenName of component.tokens ?? []) { - if (!availableTokenNames.has(tokenName)) { - throw new Error(`Component ${componentName} references unknown mobile token ${tokenName}.`); - } - } - } - const ids = new Set(); - for (const scenario of scenarioContract.scenarios ?? []) { - if (!scenario.id || ids.has(scenario.id)) throw new Error(`Invalid or duplicate preview scenario id: ${scenario.id}.`); - ids.add(scenario.id); - if (!['light', 'dark'].includes(scenario.appearance)) throw new Error(`Invalid appearance for ${scenario.id}.`); - if (!scenario.viewport?.width || !scenario.viewport?.height) throw new Error(`Missing viewport for ${scenario.id}.`); - } -} - -// The text scale normalises how big one logical unit of type is on the glass. -// The ramp was tuned on the iPhone Pro class (460 ppi at 3x = 153.3 logical -// units per inch); a screen whose logical unit is physically larger shrinks -// its text by the ratio, clamped, so a 16 reads as the same millimetres. -function validateTextScale(textScale) { - if (!textScale) throw new Error('Missing text_scale in mobile tokens.'); - const { reference_logical_dpi: reference, min_factor: min, max_factor: max } = textScale; - if (!Number.isFinite(reference) || reference <= 0) throw new Error('Invalid text_scale.reference_logical_dpi.'); - if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || min > max || max > 1) { - throw new Error('text_scale factors must satisfy 0 < min_factor <= max_factor <= 1.'); - } -} - -function renderHarmonyColors(colors, appearance) { - return `${JSON.stringify({ - color: Object.entries(colors).map(([name, pair]) => ({ name, value: pair[appearance] })), - }, null, 2)}\n`; -} - -function renderHarmonyTokens(contract) { - const textScale = contract.text_scale; - const colors = Object.entries(contract.colors) - .map(([name, pair]) => ` static readonly ${camel(name)}: MobileColorPair = new MobileColorPair(${quoted(pair.light)}, ${quoted(pair.dark)});`) - .join('\n'); - const typography = Object.entries(contract.typography) - .map(([name, token]) => ` static readonly ${camel(name)}: MobileTypographyToken = new MobileTypographyToken(${token.size}, ${token.lineHeight}, ${token.weight});`) - .join('\n'); - const geometry = renderNumberProperties(contract.geometry, ' static readonly'); - const breakpoints = renderNumberProperties(contract.breakpoints, ' static readonly'); - const motion = renderNumberProperties(contract.motion, ' static readonly'); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\n\nexport class MobileColorPair {\n readonly light: string;\n readonly dark: string;\n\n constructor(light: string, dark: string) {\n this.light = light;\n this.dark = dark;\n }\n}\n\nexport class MobileDesignColors {\n${colors}\n}\n\nexport class MobileTextScale {\n static readonly referenceLogicalDpi: number = ${textScale.reference_logical_dpi};\n static readonly minFactor: number = ${textScale.min_factor};\n static readonly maxFactor: number = ${textScale.max_factor};\n private static current: number = 1;\n\n static get factor(): number {\n return MobileTextScale.current;\n }\n\n // xdpi is physical pixels per inch along the horizontal axis; densityPixels is\n // physical pixels per logical unit. Their ratio is logical units per inch,\n // compared against the reference the type ramp was tuned on. Displays that\n // report an implausible xdpi against their nominal 160-per-unit density fall\n // back to the unscaled ramp rather than trusting bad metrics.\n static resolve(xdpi: number, densityPixels: number): number {\n if (!(xdpi > 0) || !(densityPixels > 0)) {\n return 1;\n }\n const nominalDpi = densityPixels * 160;\n if (xdpi < nominalDpi * 0.5 || xdpi > nominalDpi * 2) {\n return 1;\n }\n const factor = xdpi / densityPixels / MobileTextScale.referenceLogicalDpi;\n const clamped = Math.min(MobileTextScale.maxFactor, Math.max(MobileTextScale.minFactor, factor));\n return Math.round(clamped * 1000) / 1000;\n }\n\n static apply(xdpi: number, densityPixels: number): number {\n MobileTextScale.current = MobileTextScale.resolve(xdpi, densityPixels);\n return MobileTextScale.current;\n }\n\n static reset(): void {\n MobileTextScale.current = 1;\n }\n\n static scaled(value: number): number {\n return Math.round(value * MobileTextScale.current * 2) / 2;\n }\n}\n\nexport class MobileTypographyToken {\n readonly baseSize: number;\n readonly baseLineHeight: number;\n readonly weight: number;\n\n constructor(size: number, lineHeight: number, weight: number) {\n this.baseSize = size;\n this.baseLineHeight = lineHeight;\n this.weight = weight;\n }\n\n get size(): number {\n return MobileTextScale.scaled(this.baseSize);\n }\n\n get lineHeight(): number {\n return MobileTextScale.scaled(this.baseLineHeight);\n }\n}\n\nexport class MobileDesignTypography {\n${typography}\n}\n\nexport class MobileDesignGeometry {\n${geometry}\n}\n\nexport class MobileDesignBreakpoints {\n${breakpoints}\n}\n\nexport class MobileDesignMotion {\n${motion}\n}\n`; -} - -function renderHarmonyScenarios(contract) { - const values = contract.scenarios.map((scenario) => ` static readonly ${camel(scenario.id.replaceAll('-', '_'))}: MobilePreviewScenario = new MobilePreviewScenario(\n ${quoted(scenario.id)},\n ${quoted(scenario.title)},\n ${quoted(scenario.description)},\n ${quoted(scenario.appearance)},\n ${scenario.viewport.width},\n ${scenario.viewport.height},\n ${quoted(scenario.header.title)},\n ${quoted(scenario.header.subtitle)},\n [${scenario.messages.map((message) => `new MobilePreviewMessage(${quoted(message.role)}, ${quoted(message.text)})`).join(', ')}],\n ${quoted(scenario.composer.draft)},\n ${quoted(scenario.composer.placeholder)},\n ${quoted(scenario.composer.phase)},\n ${scenario.composer.streaming}\n );`).join('\n\n'); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\n\nexport class MobilePreviewMessage {\n readonly role: string;\n readonly text: string;\n\n constructor(role: string, text: string) {\n this.role = role;\n this.text = text;\n }\n}\n\nexport class MobilePreviewScenario {\n readonly id: string;\n readonly title: string;\n readonly description: string;\n readonly appearance: string;\n readonly viewportWidth: number;\n readonly viewportHeight: number;\n readonly headerTitle: string;\n readonly headerSubtitle: string;\n readonly messages: MobilePreviewMessage[];\n readonly composerDraft: string;\n readonly composerPlaceholder: string;\n readonly connectionPhase: string;\n readonly streaming: boolean;\n\n constructor(\n id: string,\n title: string,\n description: string,\n appearance: string,\n viewportWidth: number,\n viewportHeight: number,\n headerTitle: string,\n headerSubtitle: string,\n messages: MobilePreviewMessage[],\n composerDraft: string,\n composerPlaceholder: string,\n connectionPhase: string,\n streaming: boolean\n ) {\n this.id = id;\n this.title = title;\n this.description = description;\n this.appearance = appearance;\n this.viewportWidth = viewportWidth;\n this.viewportHeight = viewportHeight;\n this.headerTitle = headerTitle;\n this.headerSubtitle = headerSubtitle;\n this.messages = messages;\n this.composerDraft = composerDraft;\n this.composerPlaceholder = composerPlaceholder;\n this.connectionPhase = connectionPhase;\n this.streaming = streaming;\n }\n}\n\nexport class MobilePreviewScenarios {\n${values}\n}\n`; -} - -function renderAndroidTokens(contract) { - const textScale = contract.text_scale; - const lightColors = renderKotlinColors(contract.colors, 'light'); - const darkColors = renderKotlinColors(contract.colors, 'dark'); - const typography = Object.entries(contract.typography) - .map(([name, token]) => ` val ${pascal(name)} = TextStyle(fontSize = ${token.size}.sp, lineHeight = ${token.lineHeight}.sp, fontWeight = ${kotlinWeight(token.weight)})`) - .join('\n'); - const geometry = Object.entries(contract.geometry) - .map(([name, value]) => ` val ${pascal(name)} = ${value}.dp`) - .join('\n'); - const breakpoints = renderKotlinInts(contract.breakpoints); - const motion = renderKotlinInts(contract.motion); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\npackage com.openbitfun.mobile.app.ui.theme.generated\n\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.text.TextStyle\nimport androidx.compose.ui.text.font.FontWeight\nimport androidx.compose.ui.unit.dp\nimport androidx.compose.ui.unit.sp\n\ninternal object MobileDesignColors {\n object Light {\n${lightColors}\n }\n\n object Dark {\n${darkColors}\n }\n}\n\ninternal object MobileDesignTypography {\n${typography}\n}\n\n/**\n * Normalises how big one logical unit of type is on the glass. The ramp was\n * tuned on 153.3 logical units per inch; a screen whose dp is physically larger\n * shrinks its text by the ratio, clamped, so a 16.sp reads as the same\n * millimetres. Returns 1 for displays whose xdpi is implausible against their\n * nominal 160-per-dp density rather than trusting bad metrics.\n */\ninternal object MobileTextScale {\n const val ReferenceLogicalDpi: Float = ${textScale.reference_logical_dpi}f\n const val MinFactor: Float = ${textScale.min_factor}f\n const val MaxFactor: Float = ${textScale.max_factor}f\n\n fun resolve(xdpi: Float, density: Float): Float {\n if (!(xdpi > 0f) || !(density > 0f)) return 1f\n val nominalDpi = density * 160f\n if (xdpi < nominalDpi * 0.5f || xdpi > nominalDpi * 2f) return 1f\n val factor = (xdpi / density / ReferenceLogicalDpi).coerceIn(MinFactor, MaxFactor)\n return Math.round(factor * 1000f) / 1000f\n }\n}\n\ninternal object MobileDesignGeometry {\n${geometry}\n}\n\ninternal object MobileDesignBreakpoints {\n${breakpoints}\n}\n\ninternal object MobileDesignMotion {\n${motion}\n}\n`; -} - -function renderAndroidScenarios(contract) { - const values = contract.scenarios.map((scenario) => ` val ${pascal(scenario.id.replaceAll('-', '_'))} = MobilePreviewScenario(\n id = ${quoted(scenario.id)},\n title = ${quoted(scenario.title)},\n description = ${quoted(scenario.description)},\n appearance = ${quoted(scenario.appearance)},\n viewportWidth = ${scenario.viewport.width},\n viewportHeight = ${scenario.viewport.height},\n headerTitle = ${quoted(scenario.header.title)},\n headerSubtitle = ${quoted(scenario.header.subtitle)},\n messages = listOf(${scenario.messages.map((message) => `MobilePreviewMessage(${quoted(message.role)}, ${quoted(message.text)})`).join(', ')}),\n composerDraft = ${quoted(scenario.composer.draft)},\n composerPlaceholder = ${quoted(scenario.composer.placeholder)},\n connectionPhase = ${quoted(scenario.composer.phase)},\n streaming = ${scenario.composer.streaming},\n )`).join('\n\n'); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\npackage com.openbitfun.mobile.app.ui.preview.generated\n\ninternal data class MobilePreviewMessage(val role: String, val text: String)\n\ninternal data class MobilePreviewScenario(\n val id: String,\n val title: String,\n val description: String,\n val appearance: String,\n val viewportWidth: Int,\n val viewportHeight: Int,\n val headerTitle: String,\n val headerSubtitle: String,\n val messages: List,\n val composerDraft: String,\n val composerPlaceholder: String,\n val connectionPhase: String,\n val streaming: Boolean,\n)\n\ninternal object MobilePreviewScenarios {\n${values}\n}\n`; -} - -function renderIosTokens(contract) { - const colors = Object.entries(contract.colors) - .map(([name, pair]) => ` static let ${camel(name)} = dynamic(light: ${swiftHex(pair.light)}, dark: ${swiftHex(pair.dark)})`) - .join('\n'); - const typography = Object.entries(contract.typography) - .map(([name, token]) => ` static let ${camel(name)} = MobileTypographyToken(size: ${token.size}, lineHeight: ${token.lineHeight}, weight: .${swiftWeight(token.weight)}, textStyle: .${swiftTextStyle(name)})`) - .join('\n'); - const geometry = renderSwiftNumbers(contract.geometry); - const breakpoints = renderSwiftNumbers(contract.breakpoints); - const motion = renderSwiftNumbers(contract.motion); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\nimport SwiftUI\nimport UIKit\n\nstruct MobileTypographyToken {\n let size: CGFloat\n let lineHeight: CGFloat\n let weight: UIFont.Weight\n let textStyle: UIFont.TextStyle\n\n private var scaledFont: UIFont {\n UIFontMetrics(forTextStyle: textStyle).scaledFont(\n for: UIFont.systemFont(ofSize: size, weight: weight)\n )\n }\n\n var font: Font { Font(scaledFont) }\n var lineSpacing: CGFloat {\n let scaledLineHeight = UIFontMetrics(forTextStyle: textStyle).scaledValue(for: lineHeight)\n return max(0, scaledLineHeight - scaledFont.lineHeight)\n }\n}\n\nenum MobileDesignColors {\n${colors}\n\n private static func dynamic(light: UInt32, dark: UInt32) -> Color {\n Color(uiColor: UIColor { traits in\n rgba(traits.userInterfaceStyle == .dark ? dark : light)\n })\n }\n\n private static func rgba(_ value: UInt32) -> UIColor {\n UIColor(\n red: CGFloat((value >> 16) & 0xFF) / 255,\n green: CGFloat((value >> 8) & 0xFF) / 255,\n blue: CGFloat(value & 0xFF) / 255,\n alpha: CGFloat((value >> 24) & 0xFF) / 255\n )\n }\n}\n\nenum MobileDesignTypography {\n${typography}\n}\n\nenum MobileDesignGeometry {\n${geometry}\n}\n\nenum MobileDesignBreakpoints {\n${breakpoints}\n}\n\nenum MobileDesignMotion {\n${motion}\n}\n`; -} - -function renderIosScenarios(contract) { - const values = contract.scenarios.map((scenario) => ` static let ${camel(scenario.id.replaceAll('-', '_'))} = MobilePreviewScenario(\n id: ${quoted(scenario.id)},\n title: ${quoted(scenario.title)},\n description: ${quoted(scenario.description)},\n appearance: ${quoted(scenario.appearance)},\n viewportWidth: ${scenario.viewport.width},\n viewportHeight: ${scenario.viewport.height},\n headerTitle: ${quoted(scenario.header.title)},\n headerSubtitle: ${quoted(scenario.header.subtitle)},\n messages: [${scenario.messages.map((message) => `MobilePreviewMessage(role: ${quoted(message.role)}, text: ${quoted(message.text)})`).join(', ')}],\n composerDraft: ${quoted(scenario.composer.draft)},\n composerPlaceholder: ${quoted(scenario.composer.placeholder)},\n connectionPhase: ${quoted(scenario.composer.phase)},\n streaming: ${scenario.composer.streaming}\n )`).join('\n\n'); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\nimport CoreGraphics\n\nstruct MobilePreviewMessage {\n let role: String\n let text: String\n}\n\nstruct MobilePreviewScenario {\n let id: String\n let title: String\n let description: String\n let appearance: String\n let viewportWidth: CGFloat\n let viewportHeight: CGFloat\n let headerTitle: String\n let headerSubtitle: String\n let messages: [MobilePreviewMessage]\n let composerDraft: String\n let composerPlaceholder: String\n let connectionPhase: String\n let streaming: Bool\n}\n\nenum MobilePreviewScenarios {\n${values}\n}\n`; -} - -function renderSharedLayoutTokens(contract) { - const breakpoints = Object.entries(contract.breakpoints) - .map(([name, value]) => ` public const val ${pascal(name)}: Int = ${value}`) - .join('\n'); - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\npackage com.openbitfun.mobile.core.feature.layout.generated\n\npublic object MobileDesignBreakpoints {\n${breakpoints}\n}\n`; -} - -function renderPreviewData(tokenContract, componentContract, scenarioContract) { - return `// Generated by scripts/mobile-ui-design-system.mjs. Do not edit.\nexport const mobileTokens = ${JSON.stringify(tokenContract, null, 2)};\nexport const mobileComponents = ${JSON.stringify(componentContract, null, 2)};\nexport const mobilePreviewScenarios = ${JSON.stringify(scenarioContract, null, 2)};\n`; -} - -function renderNumberProperties(values, prefix) { - return Object.entries(values).map(([name, value]) => `${prefix} ${camel(name)}: number = ${value};`).join('\n'); -} - -function renderKotlinColors(colors, appearance) { - return Object.entries(colors) - .map(([name, pair]) => ` val ${pascal(name)} = Color(0x${normalizeArgb(pair[appearance])})`) - .join('\n'); -} - -function renderKotlinInts(values) { - return Object.entries(values).map(([name, value]) => ` const val ${pascal(name)}: Int = ${value}`).join('\n'); -} - -function renderSwiftNumbers(values) { - return Object.entries(values).map(([name, value]) => ` static let ${camel(name)}: CGFloat = ${value}`).join('\n'); -} - -function normalizeArgb(hex) { - const value = hex.slice(1); - return value.length === 6 ? `FF${value}` : value; -} - -function swiftHex(hex) { - return `0x${normalizeArgb(hex)}`; -} - -function words(name) { - return name.split('_').filter(Boolean); -} - -function camel(name) { - const [head, ...tail] = words(name); - return head + tail.map((word) => word[0].toUpperCase() + word.slice(1)).join(''); -} - -function pascal(name) { - return words(name).map((word) => word[0].toUpperCase() + word.slice(1)).join(''); -} - -function kotlinWeight(weight) { - if (weight >= 700) return 'FontWeight.Bold'; - if (weight >= 500) return 'FontWeight.Medium'; - return 'FontWeight.Normal'; -} - -function swiftWeight(weight) { - if (weight >= 700) return 'bold'; - if (weight >= 500) return 'medium'; - return 'regular'; -} - -function swiftTextStyle(name) { - const styles = { - brand_wordmark: 'largeTitle', - display_large: 'largeTitle', - display_medium: 'title1', - display_small: 'title2', - headline_large: 'title1', - headline_medium: 'title2', - headline_small: 'title3', - title_large: 'title2', - conversation_header_title: 'headline', - title_medium: 'headline', - title_small: 'subheadline', - body_large: 'body', - body_medium: 'callout', - body_small: 'footnote', - label_large: 'subheadline', - label_medium: 'footnote', - label_small: 'caption1', - }; - const style = styles[name]; - if (!style) throw new Error(`Missing iOS text style mapping for mobile typography token ${name}.`); - return style; -} - -function quoted(value) { - return JSON.stringify(value); -} diff --git a/scripts/mobile-ui-preview.mjs b/scripts/mobile-ui-preview.mjs deleted file mode 100644 index 07525cfb05..0000000000 --- a/scripts/mobile-ui-preview.mjs +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env node - -import { createReadStream, existsSync, readFileSync } from 'node:fs'; -import { createServer } from 'node:http'; -import { extname, join, normalize, resolve, sep } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { dirname } from 'node:path'; -import { spawn } from 'node:child_process'; - -const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); -const PREVIEW_ROOT = join(ROOT, 'src', 'apps', 'mobile', 'design-system', 'preview'); -const SHARED_ASSETS = new Map([ - ['/design-system-tokens.css', join(ROOT, 'design-system', 'packages', 'design-tokens', 'dist', 'tokens.css')], - ['/design-system-theme.css', join(ROOT, 'design-system', 'packages', 'theme-openbitfun', 'dist', 'themes.css')], -]); -const requiredFiles = ['index.html', 'preview.css', 'preview.js', 'generated/mobile-design-data.js']; - -for (const file of requiredFiles) { - const path = join(PREVIEW_ROOT, file); - if (!existsSync(path) || readFileSync(path, 'utf8').trim().length === 0) { - console.error(`[mobile-ui-preview] Missing preview asset: ${file}`); - process.exit(1); - } -} -for (const [requestPath, assetPath] of SHARED_ASSETS) { - if (!existsSync(assetPath) || readFileSync(assetPath, 'utf8').trim().length === 0) { - console.error(`[mobile-ui-preview] Missing canonical design-system asset for ${requestPath}.`); - process.exit(1); - } -} - -if (process.argv.includes('--check')) { - console.log('[mobile-ui-preview] Preview assets are present.'); - process.exit(0); -} - -const portArgIndex = process.argv.indexOf('--port'); -const port = portArgIndex >= 0 ? Number(process.argv[portArgIndex + 1]) : 4178; -const host = '127.0.0.1'; -const url = `http://${host}:${port}`; -const server = createServer((request, response) => { - const requestPath = decodeURIComponent((request.url ?? '/').split('?')[0]); - const sharedAsset = SHARED_ASSETS.get(requestPath); - if (sharedAsset) { - response.setHeader('X-OpenBitFun-Mobile-Preview', '1'); - response.setHeader('Content-Type', contentType(extname(sharedAsset))); - createReadStream(sharedAsset).pipe(response); - return; - } - const relativePath = requestPath === '/' ? 'index.html' : requestPath.replace(/^\/+/, ''); - const path = normalize(join(PREVIEW_ROOT, relativePath)); - if (!path.startsWith(`${PREVIEW_ROOT}${sep}`) && path !== join(PREVIEW_ROOT, 'index.html')) { - response.writeHead(403).end('Forbidden'); - return; - } - if (!existsSync(path)) { - response.writeHead(404).end('Not found'); - return; - } - response.setHeader('X-OpenBitFun-Mobile-Preview', '1'); - response.setHeader('Content-Type', contentType(extname(path))); - createReadStream(path).pipe(response); -}); - -server.on('error', async (error) => { - if (error.code === 'EADDRINUSE' && await isOpenBitFunPreview(url)) { - console.log(`[mobile-ui-preview] Reusing existing preview at ${url}`); - openPreview(url); - process.exit(0); - } - if (error.code === 'EADDRINUSE') { - console.error(`[mobile-ui-preview] Port ${port} is already used by another application. Pass --port to choose another port.`); - } else { - console.error(`[mobile-ui-preview] Failed to start: ${error.message}`); - } - process.exit(1); -}); - -server.listen(port, host, () => { - console.log(`[mobile-ui-preview] ${url}`); - openPreview(url); -}); - -async function isOpenBitFunPreview(target) { - try { - const response = await fetch(target, { signal: AbortSignal.timeout(1500) }); - if (response.headers.get('x-openbitfun-mobile-preview') === '1') return true; - return (await response.text()).includes('OpenBitFun Mobile Parity Bench'); - } catch { - return false; - } -} - -function openPreview(target) { - if (!process.argv.includes('--no-open') && process.platform === 'darwin') { - spawn('open', [target], { detached: true, stdio: 'ignore' }).unref(); - } -} - -function contentType(extension) { - return ({ - '.html': 'text/html; charset=utf-8', - '.css': 'text/css; charset=utf-8', - '.js': 'text/javascript; charset=utf-8', - '.json': 'application/json; charset=utf-8', - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - })[extension] ?? 'application/octet-stream'; -} diff --git a/scripts/theme-css-var-contract.mjs b/scripts/theme-css-var-contract.mjs index a967a8f1c9..28057454e7 100644 --- a/scripts/theme-css-var-contract.mjs +++ b/scripts/theme-css-var-contract.mjs @@ -346,11 +346,6 @@ export const DYNAMIC_VAR_FAMILY_CONTRACTS = [ owner: 'src/web-ui/src/infrastructure/font-preference/core/FontPreferenceService.ts', reason: 'Font preference runtime overrides the canonical design-system font-size primitives so every semantic role follows one global scale.', }, - { - prefix: '--mobile-', - owner: 'src/apps/mobile/design-system/preview/preview.js; src/apps/mobile/design-system/preview/preview.css', - reason: 'The native comparison preview projects the validated mobile token contract into a scoped device canvas without exposing those values as canonical web theme tokens.', - }, ]; export const REGISTERED_DYNAMIC_VAR_PREFIXES = new Set( diff --git a/scripts/verify-release-version-sync.mjs b/scripts/verify-release-version-sync.mjs index f55a002766..9c3f9d150c 100644 --- a/scripts/verify-release-version-sync.mjs +++ b/scripts/verify-release-version-sync.mjs @@ -2,8 +2,7 @@ import { readFileSync } from 'fs'; const args = parseArgs(process.argv.slice(2)); -// Desktop release workflows resolve their version from the root package. Mobile -// apps ship on their own cadence, so they form a separate consistency group. +// Native mobile releases are owned by openBitFun/OpenBitFun-Mobile. const expected = args.version || readJsonVersion('package.json'); const versions = new Map([ ['package.json', readJsonVersion('package.json')], @@ -18,30 +17,19 @@ const versions = new Map([ ['src/crates/services/page-function-runtime/Cargo.toml', readTomlVersion('src/crates/services/page-function-runtime/Cargo.toml', /^version = "([^"]+)"/m)], ]); -const mobileVersions = new Map([ - ['src/apps/mobile/android/app/build.gradle.kts', readTextVersion('src/apps/mobile/android/app/build.gradle.kts', /versionName\s*=\s*"([^"]+)"/)], - ['src/apps/mobile/ios/OpenBitFun/Info.plist', readTextVersion('src/apps/mobile/ios/OpenBitFun/Info.plist', /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/)], - ['src/apps/mobile/harmonyos/AppScope/app.json5', readTextVersion('src/apps/mobile/harmonyos/AppScope/app.json5', /"versionName"\s*:\s*"([^"]+)"/)], -]); - if (!expected.includes('-')) { const releasePleaseManifest = JSON.parse(readFileSync('.release-please-manifest.json', 'utf8')); versions.set('.release-please-manifest.json', releasePleaseManifest['.']); } const mismatches = [...versions].filter(([, version]) => version !== expected); -const mobileExpected = args['mobile-version'] || mobileVersions.values().next().value; -const mobileMismatches = [...mobileVersions].filter(([, version]) => version !== mobileExpected); for (const [file, version] of mismatches) { console.error(`[release-version] ${file}: expected ${expected}, found ${version}`); } -for (const [file, version] of mobileMismatches) { - console.error(`[release-version] ${file}: expected mobile ${mobileExpected}, found ${version}`); -} -if (mismatches.length > 0 || mobileMismatches.length > 0) { +if (mismatches.length > 0) { process.exit(1); } -console.log(`[release-version] OK: desktop ${expected}; mobile ${mobileExpected}`); +console.log(`[release-version] OK: desktop ${expected}`); function readJsonVersion(file) { return JSON.parse(readFileSync(file, 'utf8')).version; diff --git a/src/apps/mobile/AGENTS.md b/src/apps/mobile/AGENTS.md deleted file mode 100644 index f8109397e9..0000000000 --- a/src/apps/mobile/AGENTS.md +++ /dev/null @@ -1,143 +0,0 @@ -# AGENTS.md - -Native mobile applications are product entrypoints under `src/apps/mobile`. - -## Boundaries - -- Keep Android, iOS, and HarmonyOS lifecycle and platform API usage inside the - corresponding platform directory. -- Keep reusable product logic platform-agnostic and expose it through stable - contracts or adapters. -- Do not import implementation details from `src/apps/desktop` or - `src/web-ui`. -- Treat remote workspace support as part of feature design. Gate unsupported - behavior with a clear user-facing state. -- Keep credentials, signing files, provisioning profiles, device identifiers, - and local SDK paths out of the repository. -- Add platform-specific build and verification commands here when a native - toolchain is selected. - -## Directory Ownership - -| Directory | Ownership | -|---|---| -| `android/` | Android app, resources, lifecycle, and adapters | -| `ios/` | iOS app, resources, lifecycle, and adapters | -| `harmonyos/` | HarmonyOS app, resources, lifecycle, and adapters | -| `shared/` | Kotlin Multiplatform core: protocol, crypto, transport, persistence, domain, feature stores | -| `miniapps/` | Build-time packaging and isolated document bridge for product-owned offline tools; native storage and WebView lifecycle stay in each app | -| `design-system/` | HarmonyOS-derived mobile tokens, component contracts, deterministic preview scenarios, and the desktop comparison surface | - -## Native UI Contract - -HarmonyOS is the visual reference implementation. Stable colors, typography, -geometry, breakpoints, motion durations, component anatomy, and comparison -scenarios are recorded under `design-system/`; Android and iOS consume generated -native constants but continue to render with Compose and SwiftUI respectively. -Do not introduce a shared cross-platform renderer or make generated files the -source of truth. - -- Change the HarmonyOS implementation and the source contract together when a - stable visual fact changes. -- Run `pnpm run mobile:ui:generate` after contract changes and commit the - generated native files. -- Run `pnpm run mobile:ui:check` before pushing to reject generated drift. -- Use `pnpm run mobile:ui:preview` for the local three-column HarmonyOS / Android - / iOS comparison surface. Native captures belong under the documented - `design-system/preview/snapshots/` convention and are local evidence unless a - fixture is intentionally reviewed into the repository. -- Keep safe areas, keyboard behavior, accessibility, navigation gestures, and - platform presentation primitives in each native app. - -## Shared Core - -`shared/` holds the Kotlin Multiplatform modules that `android/` and `ios/` -build on. `core-feature` is the platform seam: everything the apps see is a -UiState or an Intent declared there, and no module above it is visible to them. - -- `android/` and `ios/` may depend on `shared/`. `shared/` must not depend on - any platform directory, and `harmonyos/` and `shared/` do not depend on each - other. -- `android/` is its own build root and pulls `shared/` in with - `includeBuild("../shared")`, so the arrow points one way only: the app knows - the shared build, never the reverse. That makes app dependencies read as - coordinates — `implementation("com.openbitfun.mobile:core-feature")` — rather than - `project(":core-feature")`. Both spellings are subject to the seam rule below. -- `core-feature` is the only shared module the apps may reference. Everything - crossing that seam is a UiState or an Intent, never a repository or a DTO. -- `core-domain` is pure logic. Transport and persistence are adapters behind - ports it declares, wired by `core-feature`. -- Shared code returns typed states, never localized display strings; the apps - own all user-facing text. -- Remote session content is read on demand from the online desktop - (`core-transport/.../HostStream.kt`, `read_stream` device RPC plus encrypted - `host-stream-changed` hints). The relay stores none of it and the apps keep - no relay stream replica: a `STREAM_EVENT_GAP` means the desktop restarted the - stream and derived state must be dropped, and a host without `host_stream_v1` - is surfaced as `RemoteSessionFailureReason.HOST_STREAM_UNSUPPORTED`, never - probed with unknown commands. Do not reintroduce `relay_stream_*` tables. -- Run `pnpm run mobile:architecture` before pushing. It enforces the rules - above, mirroring `pnpm run harmony:architecture`. -- Build and test from `shared/`: `./gradlew jvmTest` for host logic, - `./gradlew assembleAndroidMain testAndroidHostTest` for Android, and - `./gradlew compileKotlinIosSimulatorArm64` for iOS. Run iOS pure Swift - infrastructure checks from the repository root with - `(cd src/apps/mobile/ios && ./Testing/run-pure-swift-tests.sh)`. - The isolated native streaming fixture (no remote requests) is covered by - `xcodebuild -project src/apps/mobile/ios/OpenBitFun.xcodeproj -scheme OpenBitFun -configuration Debug -destination 'platform=iOS Simulator,name=iPhone 16 Plus' -parallel-testing-enabled NO -only-testing:OpenBitFunUITests/StreamingPresentationUITests test`. - Run it on one phone and one iPad destination when changing timeline layout, - streaming reveal, keyboard dismissal, or history anchoring. The Debug-only - launch argument `--streaming-regression` opens the same deterministic fixture. - `local.properties` holds - the local SDK path and is not committed. -- The Android app builds from `android/`: `./gradlew :app:assembleDebug` and - `:app:installDebug`; release verification is `./gradlew :app:assembleRelease`. - Release builds use the standard local Android debug keystore when formal - signing credentials are absent; all four `OPENBITFUN_ANDROID_KEYSTORE`, - `OPENBITFUN_ANDROID_KEYSTORE_PASSWORD`, `OPENBITFUN_ANDROID_KEY_ALIAS`, and - `OPENBITFUN_ANDROID_KEY_PASSWORD` environment variables override it. Signing - files and values must never be committed. AGP 9 compiles Kotlin itself — applying - `org.jetbrains.kotlin.android` is an error, not a no-op, and - `kotlin { jvmToolchain(...) }` is no longer available in an app module. -- Crypto and transport also run on a device: `./gradlew - :core-crypto:connectedAndroidDeviceTest :core-transport:connectedAndroidDeviceTest` - from `shared/`, with an emulator or handset attached. Those suites compile the - same `commonTest` sources onto ART; they are not in CI, so run them by hand - when touching either module. - -## Chat Markdown verification - -For chat Markdown ranges, double-tilde strikethrough, escapes and streaming -prefixes, run from `shared/` with the Android guide's Java runtime: -`./gradlew :core-feature:jvmTest --tests '*MarkdownParserTest*'`. -Android and iOS share this parser; their native inline renderers own styles. - -## Remote capability ownership - -For next-input suggestion replay, stale-turn retirement, host restart and session -isolation, run from `shared/` with the Android guide's Java runtime: -`./gradlew :core-feature:jvmTest --tests '*promptSuggestion*' --tests '*SessionRecordReplicaTest*'`. -These are simulated host streams, not evidence of a live remote connection. - -Native mobile surfaces are controllers. Desktop and CLI own execution, files, terminals and SSH credentials. Mobile workspace selection may use only connections already saved on the controlled runtime; it must not create an SSH connection or instantiate another runtime. Carry the selected connection identity through every operation, and report missing identity instead of falling back to local files. - -## Offline Mini Apps - -Android preBuild and the iOS resource phase run `miniapps/generate.cjs` (Node.js -must be on PATH). Generated native HTML is ignored; update product-owned built-in -sources or the packaging owner, never the generated resources. Harmony retains -its existing native host and invokes the same generator without native wrappers. -Run `node --test src/apps/mobile/miniapps/*.test.cjs src/apps/mobile/harmonyos/miniapps/*.test.cjs` -from the repository root after bundle/bridge changes. Storage keys remain scoped -to an allowlisted app; retain unreadable records and surface the error. - -For host-queue negotiation, stale replies, disconnect retention and mutation -conflicts, run from `shared/`: - -```bash -./gradlew :core-feature:jvmTest --tests '*MessageQueueStoreTest*' -``` - -These simulated-host tests do not establish live Relay, SSH, Peer Device or -Detached Dispatch behavior. Queue ordering belongs to the execution host; -native views submit intents and never optimistically replace its order. diff --git a/src/apps/mobile/README.md b/src/apps/mobile/README.md deleted file mode 100644 index fb938a04b8..0000000000 --- a/src/apps/mobile/README.md +++ /dev/null @@ -1,169 +0,0 @@ -# OpenBitFun Native Mobile Apps - -This directory contains the native mobile product surfaces for OpenBitFun: - -- `android/`: Android application code and resources. -- `ios/`: iOS application code and resources. -- `harmonyos/`: HarmonyOS application code and resources. - -The mobile apps are remote controllers: OpenBitFun account sign-in and the device -directory select a desktop or CLI host that owns configuration and Agent Runtime -execution. Phones submit tasks and display results; they do not synchronize model -configuration or execute agents locally. - -The official Relay needs no user deployment. Use the same login method and -account on the phone and host; GitHub and email-code accounts are independent. -See the [Relay FAQ](../relay-server/FAQ.md) for connection and privacy boundaries. - -Each platform directory owns its native UI, lifecycle, permissions, packaging, -and platform adapters. Product logic and stable contracts should remain in the -platform-agnostic Rust layers and be exposed to these apps through explicit -interfaces. - -## Chat Markdown - -Android, iOS and HarmonyOS keep single tildes literal in chat, matching the -desktop and mobile-web renderers: `24~30°C`, `1~2mm` and `~5 min` remain plain -text. Use `~~removed~~` for strikethrough. Escaped tildes (`\~`) and inline code -keep their literal text; unfinished double pairs remain literal while streaming. -This rendering policy applies to existing transcripts without changing the -host's saved Markdown or requiring a protocol upgrade. - -## Image messages - -All three apps can send images with or without text. Camera photos are decoded -on the phone and converted to a supported format before upload. Failed sends -retain the draft and images; acknowledgement removes only the submitted content. -Android supports selecting several photos at once and retains prepared attachments -across Activity recreation and process restarts. Android stores prepared image drafts -in app-private files excluded from backups, scoped by account endpoint, account, -device and session. Failed saves and unreadable records offer retry without erasing -the stored draft. An in-progress photo conversion still needs to be retried if the -process stops before preparation and saving finish. - -Model selection belongs to the connected host. A primary model that supports -images receives their pixels directly. For a text-only primary model, select an -enabled image-understanding model in the host settings and keep `analyze_image` -enabled for the agent. The receiving runtime saves inline attachments so the -same images remain available after restoring a conversation, including sessions -in SSH workspaces. An unavailable model or unreadable image produces an error. - -## Shared visual contract - -HarmonyOS is the current visual baseline. The source contract in -[`design-system/`](design-system/README.md) records the stable HarmonyOS colors, -type scale, geometry, breakpoints, motion, component anatomy, and deterministic -preview scenarios. A generator emits native constants for ArkUI, Compose, and -SwiftUI; each platform still owns its native component implementation. - -```bash -pnpm run mobile:ui:generate -pnpm run mobile:ui:check -pnpm run mobile:ui:preview -``` - -The preview command opens a local three-column desktop surface for HarmonyOS, -Android, and iOS. It renders the same scenario from the contract and can overlay -native simulator or IDE-preview captures for pixel-level comparison. - -## Native feature parity - -HarmonyOS is the behavioral and visual reference for the mobile controller. -The Android and iOS implementations share capability negotiation, account display -metadata, execution-mode IDs, speech draft merging, and completion observation in -`shared/core-feature`; native views and OS adapters remain platform-owned. - -| Capability | Android and iOS behavior | Compatibility and verification boundary | -|---|---|---| -| Execution modes | Minimal / Standard / Ultimate, with the HarmonyOS density glyph; workspace menus also retain Cowork | Enabled only by live `get_workspace_info.capabilities` containing `harness_profiles_v1`; older hosts keep Code / Cowork. Capability absence in old payloads is covered by a round-trip test. | -| Running-turn input | A nonempty remote draft offers Send; an empty composer retains Stop | Hosts advertising `dialog_steer_v1` receive `steer_turn` with the active turn ID. Older hosts retain `send_message` queueing; failed sends retain the draft and attachments. | -| Pending messages | Android, iOS and HarmonyOS show the execution host’s queue above the composer. Drag the handle, or use Move up/down in the menu; Send now and Remove affect only the selected message. | Requires `dialog_queue_v1`; reordering additionally requires `supportsReorder` in the snapshot. Older hosts retain their working controls and show why sorting is unavailable. Offline or failed replies retain the list, and changing sessions cancels stale gestures and replies. | -| Next-input suggestions | Android, iOS and HarmonyOS show the host's suggestion above an empty, idle composer; tapping fills and focuses the editor without sending | Uses the existing host session stream. Hints retain their exact text and retire on newer turns, session changes or host restarts. Older hosts simply show no hint; no new Relay API or migration is needed. | -| Plans | Legacy CreatePlan, structured plans and `.plan.md` writes show a plan card with file preview and Build | Build requires `plan_build_v1`, a completed plan tool and an idle connected session. Paths remain remote; the mobile app never runs the plan locally. | -| Offline Mini Apps | Gomoku, Regex Playground and Daily Divination open from welcome and sidebar without login | Product-owned sources are bundled by `miniapps/generate.cjs`; native WebView hosts expose only per-app allowlisted storage and clipboard. No network, Node or shell bridge. | -| Code preview | Native lexical colors, line numbers and referenced-line backgrounds | Both apps use the core-feature highlighter with native theme tokens; large files retain its bounded plain-text fallback. | -| Account profile | Public GitHub login and avatar replace the numeric-ID placeholder | The immutable Relay user ID still authorizes devices. Display metadata uses a separate encrypted 24-hour cache; offline refreshes preserve credentials and cached display. | -| Task completion | Notify for a previously observed successful remote turn while backgrounded | Identity includes target, session and turn. Replayed, failed and cancelled turns do not notify. These are local notifications, not server push. iOS observes within its OS background-task allowance; Android observes while the controller process remains alive. Neither promises notification after process termination. | -| Speech input | Continue an existing draft without trimming its whitespace or inserting spaces into Chinese text | iOS owns Speech/AVAudio lifecycle in a platform adapter and cancels on route, target or scene changes. Android uses the system recognition activity. | -| Conversation UI | Shared native tokens, neutral send/stop discs, supplementary voice action with a nonempty draft, plain assistant body | Native previews reuse production message rendering; compare the same scenario under `design-system`, then verify real app menus separately. | -| Remote operations | Existing session creation, tools/approvals/questions, models, images, remote file preview/download, and compact/wide layouts remain native | Simulator screenshots are presentation evidence, not evidence of a live SSH workspace, peer-device, or detached-dispatch session. | -| HarmonyOS watch provisioning | Remains HarmonyOS-specific | Android/iOS do not advertise watch provisioning without a supported platform transport and negotiated host contract. | - -Focused checks are documented in `AGENTS.md` and each platform guide. Keep -comparison screenshots local under the design-system snapshot convention, or -with the task's local artifacts; do not commit account or device captures. - -## Notification permission onboarding - -iOS, Android 13+, and HarmonyOS offer an optional task-completion notification -introduction on first launch. Enable opens the system authorization dialog; -Later dismisses the introduction. The choice is stored per installation and -survives account changes and process restarts. Already-authorized installations -skip the introduction. Sending or observing a task never requests notification -permission. System settings remain the recovery path after skipping or denying. iOS also -provides a Notifications entry in app settings: it requests undecided permission -or opens system notification settings for an existing decision. -Camera and microphone access stays contextual to scanning and voice input. -Notification authorization does not extend the platform background-execution -limits described above. - -## Runtime control and conversation synchronization - -The mobile apps control a selected Desktop or CLI runtime. Workspace paths, files, terminals, and saved SSH connections belong to that runtime. Mobile workspace selection lists only connections already saved there and never collects runtime SSH credentials. - -Android/iOS conversation synchronization uses the same revisioned rich session records for initial history, live updates, and recovery. The latest page opens first; earlier encrypted pages prefetch in the background through the same single flight used by explicit history requests. Complete fragment boundaries, stable record revisions, and ancestor deletion markers are preserved during backward reads. Encrypted fragments, the forward cursor, and the older-page boundary commit atomically to the local replica. Returning to the foreground actively checks the forward cursor even when the socket did not report a disconnect. - -HarmonyOS also publishes the latest page before scheduling older-page prefetch. -Background and manual history requests share the same serialized reader, and -leaving the session cancels scheduled prefetch. - -Workspace tools expose directory browsing, text editing with runtime-enforced content-hash conflict detection, file/folder creation, file renaming/deletion, binary upload/download, and bundled xterm PTY control. The terminal executes on the selected runtime or its saved SSH connection; durable notifications request incremental output from the runtime cursor. - -Pending approvals are a separate runtime mailbox, refreshed at initial attachment, reconnect/foreground recovery, and relevant permission control events. Android/iOS answer the stable request identity even when no tool call is attached, and support approving edited JSON input through the same runtime permission owner. - -Android, iOS, and HarmonyOS terminal WebViews share `src/shared/terminal/webview` assets. The native adapter only bridges keyboard input, dimensions, and cursor-derived output; it has no Relay token or local process access. Android/iOS downloads stage chunks into a controller-local temporary file and hand its URL or input stream to the platform document exporter. They do not retain the full download in a Kotlin ByteArray or Swift Data. Preview buffers have their own bounded presentation policy. - -Android, iOS, and HarmonyOS expose a device-tools button at the bottom of the sidebar. -The page selects a runtime location (the controlled device or one of its saved SSH -connections) and provides Files and Terminal tabs independently of any workspace. -Switching tabs retains the selected location and does not create a terminal; -opening a PTY is an explicit action. -Local defaults come from the runtime's `get_system_info.homeDir`; SSH defaults to -`/`. A successful directory change captures that directory and provider for file -transfers. No workspace registration or current-workspace switch is required. -Local filesystem and PTY requests explicitly select the local provider, so an -identically named SSH path cannot redirect them. Workspace and assistant “+” -menus contain Minimal, Standard, and Ultimate creation modes only. - -Android and iOS expose a runtime directory picker using the selected saved SSH -connection, plus server-side name and modification-time sorting before directory -pagination. File editing opens a separate full-screen native view; returning -preserves the directory and asks before discarding edits. Its line-number gutter -shares vertical scrolling with unwrapped source text and never changes file -contents. Rename and delete remain available in that editor. The terminal tab -fits its PTY viewport into the remaining safe-area and keyboard-adjusted space; -leaving the page keeps the terminal running until an explicit close. Native build checks cover integration, while keyboard, scrolling, -and live runtime behavior still require device or simulator interaction checks. - -Creating an ordinary chat sends `Claw` without a workspace override and lets the -runtime resolve or create its primary assistant workspace. Selecting a project -or a particular assistant sends its explicit path instead. Neither flow changes -the runtime’s current workspace as a prerequisite. Creation results use the -runtime-returned `workspace_path` for immediate session placement; a saved SSH -project carries its connection identity through the create request. - -## Connection recovery - -Native iOS and Android controllers probe the selected runtime while in the -foreground, including idle open conversations. Each probe has a ten-second -deadline, and the next starts fifteen seconds after the previous one finishes. -Backgrounding cancels the probe. Durable replay recovers conversation records, -but Relay availability alone does not prove the execution host is online. -Temporary transport failures keep the displayed list, transcript, and draft; a -successful response restores the connected state. Connection feedback stays in -the sidebar instead of inserting a banner above the conversation. - -Account sign-in on Android, iOS and HarmonyOS opens the shared authorization page -with separate GitHub and email-code options. Email users need no password and are -not automatically linked to GitHub users. Sign in with the same method and account -on the phone and the controlled desktop/CLI. diff --git a/src/apps/mobile/android/AGENTS.md b/src/apps/mobile/android/AGENTS.md deleted file mode 100644 index d770017431..0000000000 --- a/src/apps/mobile/android/AGENTS.md +++ /dev/null @@ -1,83 +0,0 @@ -# Android App Guide - -This directory owns the native Android application and is an independent -Gradle build root over `../shared`. - -## Java Runtime - -Use the JetBrains Runtime bundled with Android Studio. The system `java` -launcher may exist without a configured macOS Java runtime, so do not rely on -it for Gradle commands in this directory. - -```bash -export JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' -"$JAVA_HOME/bin/java" -version -``` - -Android Studio uses the standard macOS SDK location `~/Library/Android/sdk`. -Export that location once so commands do not bake a machine-specific absolute -home directory into repository documentation: - -```bash -export ANDROID_SDK_ROOT="$HOME/Library/Android/sdk" -"$ANDROID_SDK_ROOT/platform-tools/adb" devices -``` - -For a one-off command, keep the runtime selection local to that process: - -```bash -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:assembleDebug -``` - -## Focused Verification - -Run commands from `src/apps/mobile/android` unless a command says otherwise. - -```bash -# Compile the Android app. -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:assembleDebug - -# Run Android host tests. -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:testDebugUnitTest - -# Run instrumentation tests on an attached emulator or device. -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:connectedDebugAndroidTest - -# Verify notification onboarding persistence and existing grants. -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.NotificationOnboardingTest - -# Verify negotiated execution modes and legacy fallback on an emulator. -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.HarnessProfileMenuTest - -# Verify running-input, plan gating, offline tools, and attachment retention. -./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.MobileParityTest - -# Verify unavailable media handlers, photo decoding/sending, and dictation lifecycle. -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.ComposerMediaInputTest - -# Verify terminal WebView focus and native keyboard routing inside the dialog. -./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.RuntimeTerminalViewTest - -# Run shared JVM tests after core-feature changes. -cd ../shared -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew jvmTest -``` - -Use the narrowest command covering the changed behavior. Keep credentials, -keystores, signing values, device identifiers, and local SDK paths out of the -repository. - -Run instrumented Gradle tests on a dedicated test emulator, not an authenticated -manual-acceptance device. The test runner can uninstall the target application -after the suite and remove its local account state. Use `adb install -r` for -manual acceptance updates to preserve that state. - -For queue menus, touch targets, drag completion and cancellation on host revision: - -```bash -./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.MessageQueuePanelTest -``` - -The isolated `message-queue` design-preview scenario uses the production panel -with simulated host replies. Review compact/wide widths and light/dark themes; -this does not establish live remote dispatch behavior. diff --git a/src/apps/mobile/android/README.md b/src/apps/mobile/android/README.md deleted file mode 100644 index 6e6f7aff06..0000000000 --- a/src/apps/mobile/android/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# OpenBitFun Android - -Android application entrypoint over the Kotlin Multiplatform shared core. - -Provisional source layout: - -- `app/src/main/kotlin/`: Kotlin application code. -- `app/src/main/res/`: Android resources. - -Build a debug artifact with: - -```bash -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew :app:assembleDebug -``` - -Release builds use the standard Android debug keystore by default when formal -release signing credentials are not configured. This keeps locally packaged -APKs installable and upgrade-compatible with other APKs signed by the same -local debug keystore. - -For a deliberately unsigned artifact used only for local inspection, request -it explicitly: - -```bash -JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home' ./gradlew -PallowUnsignedRelease=true :app:assembleRelease -``` - -For a release signed with a formal keystore, set `OPENBITFUN_ANDROID_KEYSTORE`, -`OPENBITFUN_ANDROID_KEYSTORE_PASSWORD`, `OPENBITFUN_ANDROID_KEY_ALIAS`, and -`OPENBITFUN_ANDROID_KEY_PASSWORD`. Release builds enable R8 and resource shrinking. diff --git a/src/apps/mobile/android/app/build.gradle.kts b/src/apps/mobile/android/app/build.gradle.kts deleted file mode 100644 index 6965bb3dcf..0000000000 --- a/src/apps/mobile/android/app/build.gradle.kts +++ /dev/null @@ -1,107 +0,0 @@ -// AGP 9 compiles Kotlin itself; applying org.jetbrains.kotlin.android on top is -// an error rather than a no-op. Only the Compose compiler plugin is added. -plugins { - alias(libs.plugins.android.application) - alias(libs.plugins.kotlin.compose) -} - -val releaseKeystorePath = providers.environmentVariable("OPENBITFUN_ANDROID_KEYSTORE").orNull -val releaseKeystorePassword = providers.environmentVariable("OPENBITFUN_ANDROID_KEYSTORE_PASSWORD").orNull -val releaseKeyAlias = providers.environmentVariable("OPENBITFUN_ANDROID_KEY_ALIAS").orNull -val releaseKeyPassword = providers.environmentVariable("OPENBITFUN_ANDROID_KEY_PASSWORD").orNull -val hasReleaseSigning = listOf( - releaseKeystorePath, - releaseKeystorePassword, - releaseKeyAlias, - releaseKeyPassword, -).all { !it.isNullOrBlank() } -val allowUnsignedRelease = providers.gradleProperty("allowUnsignedRelease") - .map { it.equals("true", ignoreCase = true) } - .orElse(false) - .get() -android { - sourceSets.getByName("main").assets.srcDir(file("../../../../shared/terminal/webview/generated")) - namespace = "com.openbitfun.mobile.app" - compileSdk = libs.versions.androidCompileSdk.get().toInt() - - defaultConfig { - // Same family as com.openbitfun.desktop; see the implementation plan section 3. - applicationId = "com.openbitfun.mobile" - minSdk = libs.versions.androidMinSdk.get().toInt() - targetSdk = libs.versions.androidTargetSdk.get().toInt() - versionCode = 1 - versionName = "1.0.0" - testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - } - - buildFeatures { - compose = true - } - - signingConfigs { - if (hasReleaseSigning) { - create("release") { - storeFile = file(releaseKeystorePath!!) - storePassword = releaseKeystorePassword - keyAlias = releaseKeyAlias - keyPassword = releaseKeyPassword - } - } - } - - buildTypes { - debug { - // Suffixed so a debug build can sit next to a release one on the - // same device while pairing against different desktops. - applicationIdSuffix = ".debug" - } - release { - isMinifyEnabled = true - isShrinkResources = true - isDebuggable = false - proguardFiles( - getDefaultProguardFile("proguard-android-optimize.txt"), - "proguard-rules.pro", - ) - signingConfig = when { - hasReleaseSigning -> signingConfigs.getByName("release") - allowUnsignedRelease -> null - else -> signingConfigs.getByName("debug") - } - } - } -} - -dependencies { - // The only shared module an app may name. Everything below it — transport, - // crypto, persistence — is reached through UiState and Intent or not at all. - implementation("com.openbitfun.mobile:core-feature") - - implementation(platform(libs.compose.bom)) - implementation(libs.compose.ui) - implementation(libs.compose.material3) - implementation(libs.compose.ui.tooling.preview) - implementation(libs.androidx.activity.compose) - implementation(libs.androidx.lifecycle.viewmodel.compose) - implementation(libs.androidx.lifecycle.runtime.compose) - implementation(libs.androidx.window) - - testImplementation("junit:junit:4.13.2") - - debugImplementation(libs.compose.ui.tooling) - debugImplementation(libs.compose.ui.test.manifest) - androidTestImplementation(platform(libs.compose.bom)) - androidTestImplementation(libs.compose.ui.test.junit4) - androidTestImplementation(libs.androidx.test.runner) - // Compose BOM 2026.06.01 still selects Espresso 3.5.0, whose reflective - // InputManager path is removed on Android 17. Pin the fixed AndroidX Test - // release explicitly until the BOM updates its transitive constraint. - androidTestImplementation(libs.androidx.test.espresso) -} - -// Project product-owned offline tools into Android assets before packaging. -val generateMiniApps by tasks.registering(Exec::class) { - workingDir(rootProject.file("../miniapps")) - commandLine("node", "generate.cjs", "android") -} -tasks.named("preBuild").configure { dependsOn(generateMiniApps) } diff --git a/src/apps/mobile/android/app/proguard-rules.pro b/src/apps/mobile/android/app/proguard-rules.pro deleted file mode 100644 index 65cbdfb1cc..0000000000 --- a/src/apps/mobile/android/app/proguard-rules.pro +++ /dev/null @@ -1,16 +0,0 @@ -# Kotlin serialization serializers are referenced from generated code. --keepattributes *Annotation*,InnerClasses,EnclosingMethod - -# SQLDelight schemas and Ktor engines are referenced through generated/service metadata. --keep class com.openbitfun.mobile.core.persistence.db.** { *; } --dontwarn org.slf4j.** - -# BouncyCastle registers these services by class name. R8 cannot see those -# reflective edges; keep the mappings and implementations used by relay crypto. --keep class org.bouncycastle.jcajce.provider.asymmetric.EdEC$Mappings { *; } --keepnames class org.bouncycastle.jcajce.provider.asymmetric.EdEC --keep class org.bouncycastle.jcajce.provider.asymmetric.edec.** { *; } --keepnames class org.bouncycastle.jcajce.provider.symmetric.AES --keep class org.bouncycastle.jcajce.provider.symmetric.AES$* { *; } --keepnames class org.bouncycastle.jcajce.provider.digest.SHA256 --keep class org.bouncycastle.jcajce.provider.digest.SHA256$* { *; } diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountLoginPageTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountLoginPageTest.kt deleted file mode 100644 index ee502f39f7..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountLoginPageTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.foundation.layout.requiredWidth -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.unit.dp -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.account.AccountLoginPage -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.account.AccountUiState -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -class AccountLoginPageTest { - @get:Rule val rule = createComposeRule() - private fun text(id: Int) = InstrumentationRegistry.getInstrumentation().targetContext.getString(id) - - @Test fun loginAutomaticallyOpensAuthorizationOnceWithoutAddingAButtonOrGrowingTheSheet() { - val state = mutableStateOf(AccountUiState.SignedOut) - val width = mutableStateOf(386.dp) - val opened = mutableListOf() - rule.setContent { - OpenBitFunTheme(dark = false) { - AccountLoginPage(state.value, {}, { state.value = AccountUiState.SigningIn }, - Modifier.requiredWidth(width.value).testTag("login-panel"), opened::add) - } - } - rule.onNodeWithTag("login-panel").assertHeightIsEqualTo(280.dp) - rule.onAllNodesWithText(text(R.string.account_login_title))[1].performClick() - rule.onNodeWithText(text(R.string.account_signing_in)).assertIsNotEnabled() - rule.runOnIdle { state.value = AccountUiState.Authorizing("https://github.com/login/oauth/authorize?state=first") } - rule.waitForIdle() - assertEquals(1, opened.size) - rule.onNodeWithText(text(R.string.account_open_github)).assertDoesNotExist() - rule.onNodeWithTag("login-panel").assertHeightIsEqualTo(280.dp) - rule.runOnIdle { width.value = 560.dp } - rule.waitForIdle() - assertEquals(1, opened.size) - rule.onNodeWithTag("login-panel").assertHeightIsEqualTo(280.dp) - rule.runOnIdle { state.value = AccountUiState.Authorizing("https://github.com/login/oauth/authorize?state=second") } - rule.waitForIdle() - assertEquals(2, opened.size) - } - - @Test fun browserFailureUsesTheExistingFooterToRetryTheSameAuthorization() { - var attempts = 0 - rule.setContent { - OpenBitFunTheme(dark = false) { - AccountLoginPage(AccountUiState.Authorizing("https://github.com/login/oauth/authorize?state=retry"), - {}, { error("Must not start a second login transaction") }, Modifier.requiredWidth(386.dp), - openAuthorization = { - attempts++ - if (attempts == 1) throw IllegalArgumentException("No browser activity") - }) - } - } - rule.onNodeWithText(text(R.string.account_authorization_open_failed)).assertIsDisplayed() - rule.onNodeWithText(text(R.string.account_open_github)).assertDoesNotExist() - rule.onNodeWithText(text(R.string.sessions_retry)).assertIsEnabled().performClick() - rule.onNodeWithText(text(R.string.account_authorization_open_failed)).assertDoesNotExist() - rule.onNodeWithText(text(R.string.account_signing_in)).assertIsNotEnabled() - assertEquals(2, attempts) - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountRemoteScreenTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountRemoteScreenTest.kt deleted file mode 100644 index 68b94b2f9c..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/AccountRemoteScreenTest.kt +++ /dev/null @@ -1,172 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.mutableStateOf -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionFailureReason -import com.openbitfun.mobile.app.ui.chat.CONVERSATION_LOADING_TEST_TAG -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import com.openbitfun.mobile.app.ui.remote.CONNECT_ACCOUNT_DEVICE_REFRESH_TEST_TAG -import com.openbitfun.mobile.app.ui.remote.CONNECT_ACCOUNT_DEVICE_ROW_TEST_TAG_PREFIX -import com.openbitfun.mobile.app.ui.remote.ConnectAccountDeviceScreen -import com.openbitfun.mobile.app.ui.remote.AccountRemoteScreen -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.account.AccountDeviceUi -import com.openbitfun.mobile.core.feature.account.AccountUiState -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementMode -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import org.junit.Rule -import org.junit.Test -import org.junit.Assert.assertEquals - -class AccountRemoteScreenTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun aSelectedAccountDeviceBypassesThePairingForm() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - AccountRemoteScreen( - remoteState = RemoteSessionUiState.Idle, - workspaceState = RemoteWorkspaceUiState.Idle, - deviceId = "device-1", - deviceName = "Studio Mac", - createDevices = emptyList(), - accountUsername = "tester", - phase = ConnectionPhase.CONNECTED, - settingsPlacement = SettingsPlacement( - mode = SettingsPlacementMode.BOTTOM, - width = 0, - height = 0, - maxHeight = 0, - ), - sessionDetailsPlacement = SettingsPlacement( - mode = SettingsPlacementMode.BOTTOM, - width = 0, - height = 0, - maxHeight = 0, - ), - viewSettingsPlacement = SettingsPlacement( - mode = SettingsPlacementMode.BOTTOM, - width = 0, - height = 0, - maxHeight = 0, - ), - onOpenRemoteSettings = {}, - onCreateDevicePick = {}, - onSessionIntent = {}, - onWorkspaceIntent = {}, - modifier = Modifier, - ) - } - } - - composeRule.onAllNodesWithText(testString(R.string.pairing_title)).assertCountEquals(0) - } - - @Test - fun aRequestedSessionRoutesImmediatelyAndCanRetryALoadFailure() { - val state = mutableStateOf(RemoteSessionUiState.Idle) - val intents = mutableListOf() - var wentBack = false - composeRule.setContent { - OpenBitFunTheme(dark = false) { - val placement = SettingsPlacement(SettingsPlacementMode.BOTTOM, 0, 0, 0) - AccountRemoteScreen( - remoteState = state.value, workspaceState = RemoteWorkspaceUiState.Idle, - deviceId = "device-1", deviceName = "Studio Mac", createDevices = emptyList(), - accountUsername = "tester", phase = ConnectionPhase.RECONNECTING, - settingsPlacement = placement, sessionDetailsPlacement = placement, - viewSettingsPlacement = placement, onOpenRemoteSettings = {}, onCreateDevicePick = {}, - onSessionIntent = { intents += it }, onWorkspaceIntent = {}, - requestedSessionId = "requested", onRemoteHome = { wentBack = true }, - modifier = Modifier.fillMaxSize(), - ) - } - } - composeRule.mainClock.advanceTimeBy(200) - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.home_recent_title)).assertDoesNotExist() - composeRule.runOnIdle { state.value = RemoteSessionUiState.Failed(RemoteSessionFailureReason.TRANSPORT) } - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertDoesNotExist() - composeRule.onNodeWithText(testString(R.string.sessions_failed)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.sessions_retry)).performClick() - assertEquals(listOf(RemoteSessionIntent.Open("requested")), intents) - composeRule.onNodeWithText(testString(R.string.conversation_back)).performClick() - assertEquals(true, wentBack) - } - - @Test - fun aSignedInAccountWithoutATargetCanRefreshOrSelect() { - var refreshes = 0 - var selected = "" - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ConnectAccountDeviceScreen( - state = AccountUiState.Ready( - userId = "user-1", - username = "tester", - devices = listOf( - AccountDeviceUi("desk-1", "Studio Mac", online = true, lastSeenAt = null), - AccountDeviceUi("desk-2", "Office PC", online = false, lastSeenAt = null), - ), - selectedDeviceId = null, - selectedDeviceName = null, - ), - onBack = {}, - onRefresh = { refreshes += 1 }, - onSelect = { selected = it }, - modifier = Modifier, - ) - } - } - - composeRule.onNodeWithText(testString(R.string.connect_account_devices_title)).assertIsDisplayed() - composeRule.onNodeWithTag(CONNECT_ACCOUNT_DEVICE_REFRESH_TEST_TAG).performClick() - composeRule.onNodeWithTag(CONNECT_ACCOUNT_DEVICE_ROW_TEST_TAG_PREFIX + "desk-1").performClick() - composeRule.onNodeWithTag(CONNECT_ACCOUNT_DEVICE_ROW_TEST_TAG_PREFIX + "desk-2").performClick() - - assertEquals(1, refreshes) - assertEquals("desk-1", selected) - } - - @Test - fun aSelectedOfflineAccountDeviceCanReconnect() { - var selected = "" - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ConnectAccountDeviceScreen( - state = AccountUiState.Ready( - userId = "user-1", - username = "tester", - devices = listOf( - AccountDeviceUi("desk-1", "Studio Mac", online = true, lastSeenAt = null), - AccountDeviceUi("desk-2", "Office PC", online = false, lastSeenAt = null), - ), - selectedDeviceId = "desk-2", - selectedDeviceName = "Office PC", - ), - onBack = {}, - onRefresh = {}, - onSelect = { selected = it }, - modifier = Modifier, - ) - } - } - - composeRule.onNodeWithTag(CONNECT_ACCOUNT_DEVICE_ROW_TEST_TAG_PREFIX + "desk-2").performClick() - - assertEquals("desk-2", selected) - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt deleted file mode 100644 index 694a2852ee..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ChatMessageBubbleTest.kt +++ /dev/null @@ -1,421 +0,0 @@ -package com.openbitfun.mobile.app - -import android.content.ClipboardManager -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getUnclippedBoundsInRoot -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.chat.ChatMessageBubble -import com.openbitfun.mobile.app.ui.chat.message.SUBAGENT_GROUP_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.message.TYPING_DOTS_TEST_TAG -import com.openbitfun.mobile.core.feature.session.ConversationRow -import com.openbitfun.mobile.core.feature.session.ConversationRowKind -import com.openbitfun.mobile.core.feature.session.MessageBlock -import com.openbitfun.mobile.core.feature.session.ToolCard -import com.openbitfun.mobile.core.feature.session.ToolKind -import com.openbitfun.mobile.core.feature.session.ToolOperation -import com.openbitfun.mobile.core.feature.session.ToolPhase -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -/** - * A turn as the agent produced it, ported from `ChatMessageBubble.ets`. - * - * What is worth pinning is the ordering: a turn that worked in steps has to read - * as steps. The flat bubble this replaced put every tool below every paragraph, - * so the agent appeared to have explained the whole job before touching any of - * it — which is the one thing about the transcript that is not true. - */ -class ChatMessageBubbleTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun userAndAssistantTimesRenderBelowTheirMessages() { - var kind by mutableStateOf(ConversationRowKind.USER) - composeRule.setContent { - Bubble(row(kind, text = "Dated message").copy(timestampMs = 1700000000000L)) - } - for (role in listOf(ConversationRowKind.USER, ConversationRowKind.ASSISTANT)) { - composeRule.runOnIdle { kind = role } - composeRule.onNodeWithTag("chat-message-timestamp").assertIsDisplayed() - val content = composeRule.onNodeWithText("Dated message").getUnclippedBoundsInRoot() - val time = composeRule.onNodeWithTag("chat-message-timestamp").getUnclippedBoundsInRoot() - assertTrue(time.top >= content.bottom) - } - } - - @Test - fun aTurnThatWorkedInStepsIsDrawnInSteps() { - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - blocks = listOf( - MessageBlock.Text("b1", "Checking the manifest.", false), - MessageBlock.Tools("b2", listOf(runningTool())), - MessageBlock.Text("b3", "It targets API 35.", false), - ), - ), - ) - } - - val first = composeRule.onNodeWithText("Checking the manifest.").getUnclippedBoundsInRoot() - val tool = composeRule.onNodeWithText(testString(R.string.tool_line_running, "AndroidManifest.xml")).getUnclippedBoundsInRoot() - val second = composeRule.onNodeWithText("It targets API 35.").getUnclippedBoundsInRoot() - - assertTrue(first.top < tool.top) - assertTrue(tool.top < second.top) - } - - @Test - fun aSubagentsWorkIsBoxedApartFromTheAgentThatStartedIt() { - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - blocks = listOf( - MessageBlock.Subagent( - id = "b1", - title = "Audit the auth flow", - running = false, - text = "", - children = listOf(MessageBlock.Text("b1-1", "No leaks found.", false)), - ), - ), - ), - ) - } - - composeRule.onNodeWithTag(SUBAGENT_GROUP_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText("Audit the auth flow").assertIsDisplayed() - assertTrue(composeRule.onAllNodesWithText("No leaks found.").fetchSemanticsNodes().isEmpty()) - - composeRule.onNodeWithText("Audit the auth flow").performClick() - composeRule.onNodeWithText("No leaks found.").assertIsDisplayed() - } - - @Test - fun aRunningSubagentKeepsChildrenCollapsedUntilOpened() { - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - blocks = listOf( - MessageBlock.Subagent( - id = "running-subagent", - title = "Inspect the build", - running = true, - text = "Still working", - children = listOf(MessageBlock.Text("child", "Build step started.", false)), - ), - ), - ), - ) - } - - composeRule.onNodeWithText("Build step started.").assertDoesNotExist() - composeRule.onNodeWithText("Inspect the build").performClick() - composeRule.onNodeWithText("Build step started.").assertIsDisplayed() - } - - @Test - fun aCompletedSubagentCanBeExpandedAndCollapsed() { - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - blocks = listOf( - MessageBlock.Subagent( - id = "completed-subagent", - title = "Inspect the build", - running = false, - text = "Finished", - children = listOf(MessageBlock.Text("child", "Build step finished.", false)), - ), - ), - ), - ) - } - - assertTrue(composeRule.onAllNodesWithText("Build step finished.").fetchSemanticsNodes().isEmpty()) - composeRule.onNodeWithText("Inspect the build").performClick() - composeRule.onNodeWithText("Build step finished.").assertIsDisplayed() - composeRule.onNodeWithText("Inspect the build").performClick() - assertTrue(composeRule.onAllNodesWithText("Build step finished.").fetchSemanticsNodes().isEmpty()) - } - - - @Test - fun anOpenSubagentReceivesNewStepsWithoutClosing() { - var block by mutableStateOf(MessageBlock.Subagent("live-owner", "Live task", true, "", - listOf(MessageBlock.Text("first", "First step", false)))) - composeRule.setContent { Bubble(row(kind = ConversationRowKind.ASSISTANT, blocks = listOf(block))) } - composeRule.onNodeWithText("Live task").performClick() - composeRule.runOnIdle { - block = block.copy(children = block.children + MessageBlock.Text("second", "Later step", false)) - } - composeRule.onNodeWithText("Later step").assertIsDisplayed() - composeRule.runOnIdle { block = block.copy(running = false, status = "completed") } - composeRule.onNodeWithText("First step").assertIsDisplayed() - composeRule.onNodeWithText("Later step").assertIsDisplayed() - } - - @Test - fun aRunningSubagentPreservesUserCollapseAcrossStreamUpdates() { - var block by mutableStateOf( - MessageBlock.Subagent( - id = "streaming-subagent", - title = "Inspect the build", - running = true, - text = "Working", - children = listOf(MessageBlock.Text("child", "Initial step.", false)), - ), - ) - composeRule.setContent { - Bubble(row(kind = ConversationRowKind.ASSISTANT, blocks = listOf(block))) - } - - composeRule.onNodeWithText("Inspect the build").performClick() - composeRule.onNodeWithText("Initial step.").assertIsDisplayed() - composeRule.onNodeWithText("Inspect the build").performClick() - assertTrue(composeRule.onAllNodesWithText("Initial step.").fetchSemanticsNodes().isEmpty()) - - composeRule.runOnIdle { - block = block.copy( - text = "Still working", - children = listOf(MessageBlock.Text("child-2", "Updated step.", false)), - ) - } - assertTrue(composeRule.onAllNodesWithText("Updated step.").fetchSemanticsNodes().isEmpty()) - - composeRule.runOnIdle { block = block.copy(running = false) } - assertTrue(composeRule.onAllNodesWithText("Updated step.").fetchSemanticsNodes().isEmpty()) - } - - @Test - fun aFailureSaysWhichHalfOfTheExchangeFailed() { - composeRule.setContent { - Bubble(row(kind = ConversationRowKind.ASSISTANT, text = "Half an ans", showRetry = true)) - } - - // The agent's reply started and stopped; it was never "not delivered". - composeRule.onNodeWithText(testString(R.string.chat_reply_interrupted)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.account_devices_retry)).assertIsDisplayed() - } - - @Test - fun aMessageThatNeverLeftTheDeviceUsesTheSendFailureCopy() { - composeRule.setContent { - Bubble(row(kind = ConversationRowKind.USER, text = "ship it", showRetry = true)) - } - - composeRule.onNodeWithText(string(R.string.chat_send_failed)).assertIsDisplayed() - } - - @Test - fun theWaitingDotsStandInForTheFirstTokenAndNothingMore() { - // The dots never settle, so the clock is driven by hand rather than - // waiting for an idle that will not come. - composeRule.mainClock.autoAdvance = false - - composeRule.setContent { - Bubble(row(kind = ConversationRowKind.ASSISTANT, streaming = true, typing = true)) - } - - composeRule.onNodeWithTag(TYPING_DOTS_TEST_TAG).assertIsDisplayed() - } - - @Test - fun onceTheAnswerStartsTheDotsAreGone() { - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - text = "Working on it", - streaming = true, - typing = false, - ), - ) - } - - composeRule.onNodeWithTag(TYPING_DOTS_TEST_TAG).assertDoesNotExist() - composeRule.waitUntil(timeoutMillis = 3_000L) { - composeRule.onAllNodesWithText("Working on it").fetchSemanticsNodes().isNotEmpty() - } - composeRule.onNodeWithText("Working on it").assertIsDisplayed() - } - - @androidx.compose.runtime.Composable - private fun Bubble(row: ConversationRow) { - ChatMessageBubble( - row = row, - enabled = true, - onApproveTool = { _, _ -> }, - onRejectTool = { _, _ -> }, - onCancelTool = { _, _ -> }, - onAnswerTool = { _, _ -> }, - onAnswerToolStructured = { _, _ -> }, - onRetry = {}, - onOpenLink = { _, _ -> }, - previewingRemotePath = "", - previewLoading = false, - modifier = Modifier, - ) - } - - private fun row( - kind: ConversationRowKind, - text: String = "", - blocks: List = emptyList(), - streaming: Boolean = false, - typing: Boolean = false, - showRetry: Boolean = false, - ) = ConversationRow( - id = "row-1", - kind = kind, - text = text, - thinking = null, - images = emptyList(), - tools = emptyList(), - blocks = blocks, - streaming = streaming, - typing = typing, - showRetry = showRetry, - error = null, - live = false, - timestampMs = null, - ) - - private fun runningTool(): ToolCard = ToolCard( - id = "tool-1", - name = "Read", - phase = ToolPhase.RUNNING, - kind = ToolKind.DOCUMENT, - operation = ToolOperation.READ_FILE, - target = "AndroidManifest.xml", - filePath = "", - fileLabel = "", - input = "", - output = "", - question = null, - actions = emptySet(), - ) - - private fun string(resource: Int): String = - InstrumentationRegistry.getInstrumentation().targetContext.getString(resource) - - @Test - fun thinkingCollapseSurvivesStreamedTokenUpdates() { - var block by mutableStateOf(MessageBlock.Thinking("stable-thinking", "Initial reasoning", true)) - - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - blocks = listOf(block), - ).copy(id = "thinking-row"), - ) - } - - composeRule.onNodeWithText("Initial reasoning").assertIsDisplayed() - composeRule.onNodeWithText(string(R.string.chat_thinking_in_progress)).performClick() - assertTrue(composeRule.onAllNodesWithText("Initial reasoning").fetchSemanticsNodes().isEmpty()) - - composeRule.runOnIdle { - block = MessageBlock.Thinking("stable-thinking", "Initial reasoning with more streamed tokens", true) - } - assertTrue( - composeRule.onAllNodesWithText("Initial reasoning with more streamed tokens") - .fetchSemanticsNodes() - .isEmpty(), - ) - - composeRule.runOnIdle { - block = MessageBlock.Thinking("stable-thinking", "Initial reasoning with more streamed tokens", false) - } - assertTrue( - composeRule.onAllNodesWithText("Initial reasoning with more streamed tokens") - .fetchSemanticsNodes() - .isEmpty(), - ) - } - - @Test - fun streamingCodeBlockCopyCopiesTheFullText() { - val fullCode = "```\necho full-command\n```" - composeRule.setContent { - Bubble( - row( - kind = ConversationRowKind.ASSISTANT, - text = fullCode, - streaming = true, - ).copy(id = "streaming-copy-row"), - ) - } - - val copyLabel = string(R.string.chat_copy) - composeRule.waitUntil(timeoutMillis = 3_000L) { - composeRule.onAllNodesWithText(copyLabel).fetchSemanticsNodes().isNotEmpty() - } - composeRule.onNodeWithText(copyLabel).performClick() - composeRule.waitUntil(timeoutMillis = 3_000L) { - val clipboard = InstrumentationRegistry.getInstrumentation().targetContext - .getSystemService(ClipboardManager::class.java) - clipboard.primaryClip?.getItemAt(0)?.text?.toString() == fullCode - } - val clipboard = InstrumentationRegistry.getInstrumentation().targetContext - .getSystemService(ClipboardManager::class.java) - assertTrue(clipboard.primaryClip?.getItemAt(0)?.text?.toString() == fullCode) - } - - @Test - fun streamingTextShowsEachDeltaImmediately() { - var currentRow by mutableStateOf( - row(kind = ConversationRowKind.ASSISTANT, text = "first.", streaming = true), - ) - composeRule.setContent { Bubble(currentRow) } - composeRule.onNodeWithText("first.").assertIsDisplayed() - - composeRule.runOnIdle { currentRow = currentRow.copy(text = "first. second.") } - composeRule.onNodeWithText("first. second.").assertIsDisplayed() - - composeRule.runOnIdle { currentRow = currentRow.copy(text = "first. second. third.") } - composeRule.onNodeWithText("first. second. third.").assertIsDisplayed() - } - - @Test - fun streamingTextRewriteShowsTheNewTextWithoutBlanking() { - var currentRow by mutableStateOf( - row(kind = ConversationRowKind.ASSISTANT, text = "old response.", streaming = true), - ) - composeRule.setContent { Bubble(currentRow) } - composeRule.onNodeWithText("old response.").assertIsDisplayed() - - composeRule.runOnIdle { currentRow = currentRow.copy(text = "new response.") } - composeRule.onNodeWithText("new response.").assertIsDisplayed() - assertTrue(composeRule.onAllNodesWithText("old response.").fetchSemanticsNodes().isEmpty()) - } - - @Test - fun streamingToCompleteShowsTheFullTextWithoutAnEndJump() { - var currentRow by mutableStateOf( - row(kind = ConversationRowKind.ASSISTANT, text = "A complete answer.", streaming = true), - ) - composeRule.setContent { Bubble(currentRow) } - composeRule.onNodeWithText("A complete answer.").assertIsDisplayed() - - composeRule.runOnIdle { currentRow = currentRow.copy(streaming = false) } - composeRule.onNodeWithText("A complete answer.").assertIsDisplayed() - } - -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt deleted file mode 100644 index d8f827393b..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerMediaInputTest.kt +++ /dev/null @@ -1,239 +0,0 @@ -package com.openbitfun.mobile.app - -import android.app.Activity -import android.content.ActivityNotFoundException -import android.content.Intent -import android.graphics.Bitmap -import android.net.Uri -import android.speech.RecognizerIntent -import android.util.Base64 -import androidx.activity.compose.LocalActivityResultRegistryOwner -import androidx.activity.result.ActivityResultRegistry -import androidx.activity.result.ActivityResultRegistryOwner -import androidx.activity.result.contract.ActivityResultContract -import androidx.compose.material3.Button -import androidx.compose.material3.Text -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.onAllNodesWithContentDescription -import androidx.compose.runtime.Composable -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.junit4.StateRestorationTester -import androidx.core.app.ActivityOptionsCompat -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.platform.launchComposerActivity -import com.openbitfun.mobile.app.platform.prepareComposerImage -import com.openbitfun.mobile.app.ui.chat.COMPOSER_INPUT_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.ConversationView -import com.openbitfun.mobile.app.ui.chat.decodeInlineImage -import com.openbitfun.mobile.app.ui.chat.rememberComposerVoiceInput -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementMode -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.SessionAgentFilter -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import java.io.File -import java.util.UUID -import kotlinx.coroutines.runBlocking -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test - -class ComposerMediaInputTest { - @get:Rule val rule = createComposeRule() - private val context get() = InstrumentationRegistry.getInstrumentation().targetContext - - @Test fun unavailableSystemActivitiesKeepRemoteDraftEditable() { - val registry = MediaRegistry { throw ActivityNotFoundException("No system handler") } - val intents = mutableListOf() - val sessionId = "media-${UUID.randomUUID()}" - rule.setContent { RemoteComposer(registry, sessionId, intents::add) } - rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() - rule.onNodeWithContentDescription(context.getString(R.string.message_attach_image)).performClick() - rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performClick() - rule.onNodeWithTag("composer-voice").performClick() - rule.onNodeWithText("Keep this draft").assertIsDisplayed() - rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() - rule.runOnIdle { - assertEquals(2, registry.launches) - assertTrue(intents.isEmpty()) - } - } - - @Test fun deniedSystemActivityIsRecoverable() { - rule.runOnIdle { - assertFalse(launchComposerActivity(context, R.string.chat_photo_picker_unavailable) { - throw SecurityException("Handler is not exported") - }) - } - } - - @Test fun dictationUsesCurrentDraftCallbackAndSurvivesRecreation() { - val registry = MediaRegistry() - val owner = mutableStateOf("device-a/session") - val draft = mutableStateOf("old draft") - val received = mutableListOf() - val restoration = StateRestorationTester(rule) - restoration.setContent { - CompositionLocalProvider(LocalActivityResultRegistryOwner provides registry) { - val before = draft.value - val launch = rememberComposerVoiceInput(owner.value) { received += "$before/$it" } - Button(onClick = launch) { Text("Dictate") } - } - } - rule.onNodeWithText("Dictate").performClick() - restoration.emulateSavedInstanceStateRestore() - rule.runOnIdle { draft.value = "new draft" } - rule.waitForIdle() - rule.runOnIdle { registry.replySpeech("recognized") } - rule.runOnIdle { assertEquals(listOf("new draft/recognized"), received) } - } - - @Test fun dictationDoesNotCrossDeviceOrSessionBoundaries() { - val registry = MediaRegistry() - val owner = mutableStateOf("device-a/session") - val received = mutableListOf() - rule.setContent { - CompositionLocalProvider(LocalActivityResultRegistryOwner provides registry) { - val launch = rememberComposerVoiceInput(owner.value, received::add) - Button(onClick = launch) { Text("Dictate") } - } - } - rule.onNodeWithText("Dictate").performClick() - rule.runOnIdle { owner.value = "device-b/session" } - rule.waitForIdle() - rule.runOnIdle { registry.replySpeech("another device's text") } - rule.runOnIdle { assertTrue(received.isEmpty()) } - rule.onNodeWithText("Dictate").performClick() - rule.runOnIdle { registry.dispatchResult(registry.requestCode, Activity.RESULT_CANCELED, null) } - rule.runOnIdle { assertTrue(received.isEmpty()) } - rule.onNodeWithText("Dictate").performClick() - rule.runOnIdle { registry.replySpeech("current device") } - rule.runOnIdle { assertEquals(listOf("current device"), received) } - } - - @Test fun cameraPhotoIsResizedForUploadAndInlinePreview() = runBlocking { - val file = File(context.cacheDir, "media-${UUID.randomUUID()}.jpg") - val bitmap = Bitmap.createBitmap(4000, 3000, Bitmap.Config.ARGB_8888) - try { - file.outputStream().use { assertTrue(bitmap.compress(Bitmap.CompressFormat.JPEG, 95, it)) } - } finally { bitmap.recycle() } - try { - val image = prepareComposerImage(context.contentResolver, Uri.fromFile(file)) - assertEquals("image/jpeg", image.mimeType) - val bytes = Base64.decode(image.dataUrl.substringAfter(','), Base64.DEFAULT) - assertTrue(bytes.size <= 1024 * 1024) - val bounds = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true } - android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) - assertEquals(1920, maxOf(bounds.outWidth, bounds.outHeight)) - val preview = requireNotNull(decodeInlineImage(image.dataUrl)) - try { assertTrue(maxOf(preview.width, preview.height) <= 512) } - finally { preview.recycle() } - // History from older clients can still carry the original full-size photo. - val original = "data:image/jpeg;base64," + Base64.encodeToString(file.readBytes(), Base64.NO_WRAP) - val legacyPreview = requireNotNull(decodeInlineImage(original)) - try { assertTrue(maxOf(legacyPreview.width, legacyPreview.height) <= 512) } - finally { legacyPreview.recycle() } - } finally { file.delete() } - } - - @Test fun invalidInlineImagesRemainCaptionOnly() { - assertNull(decodeInlineImage("https://example.com/image.jpg")) - assertNull(decodeInlineImage("data:image/png;base64,not-base64")) - assertNull(decodeInlineImage("data:image/png;base64," + Base64.encodeToString(byteArrayOf(1, 2, 3), Base64.NO_WRAP))) - } - - @Test fun selectedPhotoCanBeSentAndRetainedWithoutAcknowledgement() { - val registry = MediaRegistry() - val intents = mutableListOf() - val sessionId = "media-${UUID.randomUUID()}" - val file = File(context.cacheDir, "$sessionId.png") - val bitmap = Bitmap.createBitmap(32, 24, Bitmap.Config.ARGB_8888) - try { file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } } - finally { bitmap.recycle() } - try { - rule.setContent { RemoteComposer(registry, sessionId, intents::add) } - rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() - rule.onNodeWithContentDescription(context.getString(R.string.message_attach_image)).performClick() - rule.runOnIdle { - registry.dispatchResult(registry.requestCode, Activity.RESULT_OK, Intent().setData(Uri.fromFile(file))) - } - rule.waitUntil(5_000) { - rule.onAllNodesWithContentDescription(context.getString(R.string.message_remove_image)) - .fetchSemanticsNodes().size == 1 - } - rule.onNodeWithContentDescription(context.getString(R.string.message_remove_image)).assertIsEnabled() - rule.onNodeWithTag(com.openbitfun.mobile.app.ui.chat.COMPOSER_SEND_TEST_TAG).performClick() - rule.runOnIdle { - val image = intents.filterIsInstance().single().images!!.single() - assertEquals("image/jpeg", image.mimeType) - assertTrue(image.dataUrl.startsWith("data:image/jpeg;base64,")) - } - // The controlled host has not acknowledged this send. Keep its attachment. - rule.onNodeWithContentDescription(context.getString(R.string.message_remove_image)).assertIsDisplayed() - } finally { file.delete() } - } - - @Test fun unreadableSelectedPhotoDoesNotCrashOrEraseDraft() { - val registry = MediaRegistry() - val sessionId = "media-${UUID.randomUUID()}" - rule.setContent { RemoteComposer(registry, sessionId) {} } - rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() - rule.onNodeWithContentDescription(context.getString(R.string.message_attach_image)).performClick() - rule.runOnIdle { - registry.dispatchResult(registry.requestCode, Activity.RESULT_OK, - Intent().setData(Uri.parse("content://com.openbitfun.missing-provider/photo"))) - } - rule.waitForIdle() - rule.onNodeWithText("Keep this draft").assertIsDisplayed() - rule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsEnabled() - } - - @Composable - private fun RemoteComposer(registry: MediaRegistry, sessionId: String, onIntent: (RemoteSessionIntent) -> Unit) { - CompositionLocalProvider(LocalActivityResultRegistryOwner provides registry) { - OpenBitFunTheme(dark = false) { - ConversationView( - state = RemoteSessionUiState.Ready( - sessions = emptyList(), selectedSessionId = sessionId, - timeline = null, busy = false, permissionMode = null, permissionModeFailure = null, - query = "", agentFilter = SessionAgentFilter.ALL, hasMore = false, - hasMoreMessages = false, modelCatalog = null, modelCatalogFailure = null, - draft = "Keep this draft", - ), - phase = ConnectionPhase.CONNECTED, - settingsPlacement = SettingsPlacement(SettingsPlacementMode.BOTTOM, 0, 0, 0), - onBack = {}, onIntent = onIntent, contextTitle = "Test desktop", - onOpenFile = { _, _ -> }, previewingRemotePath = "", previewLoading = false, - download = RemoteFileDownloadUiState.None, onDownloadFile = { _, _ -> }, - modifier = Modifier, - ) - } - } - } - - private class MediaRegistry(private val fail: (() -> Unit)? = null) : ActivityResultRegistry(), ActivityResultRegistryOwner { - override val activityResultRegistry: ActivityResultRegistry get() = this - var launches = 0 - var requestCode = 0 - override fun onLaunch(requestCode: Int, contract: ActivityResultContract, input: I, options: ActivityOptionsCompat?) { - launches++ - this.requestCode = requestCode - fail?.invoke() - } - fun replySpeech(text: String) { - dispatchResult(requestCode, Activity.RESULT_OK, - Intent().putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, arrayListOf(text))) - } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerModelSelectorTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerModelSelectorTest.kt deleted file mode 100644 index 882a358a9a..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ComposerModelSelectorTest.kt +++ /dev/null @@ -1,130 +0,0 @@ -package com.openbitfun.mobile.app - -import android.graphics.Bitmap -import androidx.test.platform.app.InstrumentationRegistry -import java.io.File -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.assertTextEquals -import androidx.compose.runtime.mutableStateOf -import com.openbitfun.mobile.app.ui.chat.COMPOSER_INPUT_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.ComposerBar -import com.openbitfun.mobile.app.ui.chat.MODEL_CONTROL_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX -import com.openbitfun.mobile.app.ui.chat.MODEL_SELECTOR_TEST_TAG -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ModelOption -import com.openbitfun.mobile.core.feature.session.ModelRole -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -class ComposerModelSelectorTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun suggestionFillsTheEmptyDraftExactlyWithoutSending() { - val draft = mutableStateOf("") - val streaming = mutableStateOf(false) - var sends = 0 - val suggestion = " Run the tests " - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ComposerBar(draft = draft.value, images = emptyList(), busy = false, - streaming = streaming.value, phase = ConnectionPhase.CONNECTED, - model = null, capabilities = ChatComposerCapabilities.RemoteChat, placeholder = "Message", - promptSuggestion = suggestion, onDraftChange = {draft.value = it}, - onRemoveImage = {}, onAttach = {}, onVoice = {}, onSend = {sends++}, - onStop = {}, onOpenModels = {}, modifier = androidx.compose.ui.Modifier) - } - } - composeRule.onNodeWithTag("composer-prompt-suggestion").assertIsDisplayed() - capture("prompt-suggestion-before.png") - composeRule.onNodeWithTag("composer-prompt-suggestion").performClick() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals(suggestion) - composeRule.onNodeWithTag("composer-prompt-suggestion").assertDoesNotExist() - capture("prompt-suggestion-accepted.png") - composeRule.runOnIdle { assertEquals(0, sends); draft.value = ""; streaming.value = true } - composeRule.onNodeWithTag("composer-prompt-suggestion").assertDoesNotExist() - composeRule.runOnIdle { streaming.value = false } - composeRule.onNodeWithTag("composer-prompt-suggestion").assertIsDisplayed() - } - - private fun capture(name: String) { - composeRule.waitForIdle() - val instrumentation = InstrumentationRegistry.getInstrumentation() - val bitmap = instrumentation.uiAutomation.takeScreenshot() - File(instrumentation.targetContext.getExternalFilesDir(null), name).outputStream().use { - bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) - } - bitmap.recycle() - } - - @Test - fun collapsedDraftHasNoSupplementalMicrophone() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ComposerBar(draft = "A long draft that must keep its room in the collapsed input".repeat(4), - images = emptyList(), busy = false, streaming = false, phase = ConnectionPhase.CONNECTED, - model = null, capabilities = ChatComposerCapabilities.RemoteChat, placeholder = "Message", - onDraftChange = {}, onRemoveImage = {}, onAttach = {}, onVoice = {}, onSend = {}, - onStop = {}, onOpenModels = {}, modifier = androidx.compose.ui.Modifier) - } - } - composeRule.onNodeWithTag("composer-voice").assertDoesNotExist() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsDisplayed() - capture("parity-collapsed-draft.png") - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performClick() - composeRule.onNodeWithTag("composer-voice").assertIsDisplayed() - } - - @Test - fun theExpandedComposerSelectsAConfiguredModel() { - var selected = "account-primary" - val models = listOf( - ModelOption("primary", "Primary", "Account model", false, ModelRole.PRIMARY, emptyList(), false), - ModelOption("fast", "Fast", "Account model", false, ModelRole.FAST, emptyList(), true), - ModelOption("account-primary", "Primary", "Account model", true, null, listOf(ModelRole.PRIMARY), false), - ModelOption("account-fast", "Fast", "Account model", false, null, listOf(ModelRole.FAST), false), - ) - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ComposerBar( - draft = "", - images = emptyList(), - busy = false, - streaming = false, - phase = ConnectionPhase.DISCONNECTED, - model = models.first(), - modelOptions = models, - capabilities = ChatComposerCapabilities.GeneralChat, - placeholder = "Message", - onDraftChange = {}, - onRemoveImage = {}, - onAttach = {}, - onVoice = {}, - onSend = {}, - onStop = {}, - onOpenModels = {}, - onSelectModel = { selected = it }, - modifier = androidx.compose.ui.Modifier, - ) - } - } - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performClick() - composeRule.onNodeWithTag(MODEL_CONTROL_TEST_TAG).assertIsDisplayed().performClick() - composeRule.onNodeWithTag(MODEL_SELECTOR_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX + "primary").assertIsDisplayed() - composeRule.onNodeWithTag(MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX + "fast").assertIsDisplayed() - capture("parity-model-roles.png") - composeRule.onNodeWithTag(MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX + "fast").performClick() - - assertEquals("fast", selected) - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConnectionSheetChromeTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConnectionSheetChromeTest.kt deleted file mode 100644 index 50ffb5590b..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConnectionSheetChromeTest.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.foundation.layout.* -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.runtime.getValue -import androidx.compose.runtime.setValue -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.ui.common.connectionSheetTextStyle -import com.openbitfun.mobile.app.ui.common.ConnectionSheetHeader -import com.openbitfun.mobile.app.ui.common.ConnectionSheetFooter -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class ConnectionSheetChromeTest { - @get:Rule val composeRule = createComposeRule() - - @Test fun closeAndManualActionsKeepHarmonyGeometryAndRemainClickable() { - var closed = false - var manual = false - composeRule.setContent { - OpenBitFunTheme(dark = false) { - Column(Modifier.requiredSize(360.dp, 700.dp)) { - ConnectionSheetHeader { closed = true } - Spacer(Modifier.weight(1f)) - ConnectionSheetFooter("Pair manually", onClick = { manual = true }) - } - } - } - composeRule.onNodeWithContentDescription( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext.getString(R.string.common_close)) - .assertWidthIsEqualTo(48.dp).assertHeightIsEqualTo(48.dp).performClick() - composeRule.onNodeWithText("Pair manually").assertHeightIsEqualTo(48.dp) - .assertWidthIsEqualTo(320.dp).performClick() - composeRule.runOnIdle { assertTrue(closed); assertTrue(manual) } - } - @Test fun chineseSheetTextUsesTheReferenceLineBoxes() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - Column { - androidx.compose.material3.Text("扫描桌面端二维码", - style = androidx.compose.material3.MaterialTheme.typography.displayMedium.connectionSheetTextStyle()) - androidx.compose.material3.Text("第一行说明\n第二行说明", - style = androidx.compose.material3.MaterialTheme.typography.bodyMedium.connectionSheetTextStyle()) - } - } - } - composeRule.onNodeWithText("扫描桌面端二维码").assertIsDisplayed().assertHeightIsEqualTo(28.dp) - val body = composeRule.onNodeWithText("第一行说明\n第二行说明").assertIsDisplayed() - // Android rounds the first/last font baselines independently; preserve - // the two 21dp lines within one layout unit without padding the glyphs. - val bounds = body.getUnclippedBoundsInRoot() - assertTrue(kotlin.math.abs((bounds.bottom - bounds.top).value - 42f) <= 1f) - } - - @Test fun compactLoginKeepsContentGeometryAtPhoneAndWideWidths() { - var width by androidx.compose.runtime.mutableStateOf(386.dp) - composeRule.setContent { - OpenBitFunTheme(dark = false) { - com.openbitfun.mobile.app.ui.account.AccountLoginPage( - state = com.openbitfun.mobile.core.feature.account.AccountUiState.SignedOut, - onBack = {}, onLogin = {}, - modifier = Modifier.requiredWidth(width).testTag("login-panel")) - } - } - val context = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext - for (panelWidth in listOf(386.dp, 560.dp)) { - composeRule.runOnIdle { width = panelWidth } - val panel = composeRule.onNodeWithTag("login-panel").assertHeightIsEqualTo(280.dp) - .assertWidthIsEqualTo(panelWidth).getUnclippedBoundsInRoot() - val labels = composeRule.onAllNodesWithText(context.getString(R.string.account_login_title)) - val title = labels[0].getUnclippedBoundsInRoot() - val action = labels[1].getUnclippedBoundsInRoot() - assertTrue(kotlin.math.abs((title.top - panel.top).value - 56f) < 1f) - assertTrue(kotlin.math.abs((action.top - panel.top).value - 208f) < 1f) - labels[1].assertHeightIsEqualTo(48.dp).assertWidthIsEqualTo(panelWidth - 40.dp) - } - } - -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationHeaderTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationHeaderTest.kt deleted file mode 100644 index 646a950c6b..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationHeaderTest.kt +++ /dev/null @@ -1,205 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.getUnclippedBoundsInRoot -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextClearance -import androidx.compose.ui.test.performTextInput -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.chat.CONVERSATION_MENU_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.CONVERSATION_RENAME_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.CONVERSATION_TITLE_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.ConversationHeader -import com.openbitfun.mobile.app.ui.chat.HEADER_ACTION_MENU_TEST_TAG -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -/** - * The conversation header, ported from `RemoteChatHeader.ets`. - * - * What is worth pinning is the rename: it is the one destructive-ish thing the - * header does, it is reached by tapping a label that otherwise looks inert, and - * a stale draft surviving into another session would rename the wrong one. - */ -class ConversationHeaderTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun bothLinesAreShownAndAnUntitledSessionStillHasAName() { - composeRule.setContent { - ConversationHeader( - title = "", - contextTitle = "OpenBitFun · main", - canStop = false, - enabled = true, - onBack = {}, - onRename = {}, - onStop = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(string(R.string.conversation_title_default)).assertIsDisplayed() - composeRule.onNodeWithText("OpenBitFun · main").assertIsDisplayed() - } - - @Test - fun aCompactConversationOpensTheSidebarInsteadOfNavigatingBack() { - var sidebarOpens = 0 - - composeRule.setContent { - ConversationHeader( - title = "Session", - contextTitle = "Studio", - canStop = false, - enabled = true, - onBack = { error("Compact conversation must not navigate back") }, - onOpenSidebar = { sidebarOpens += 1 }, - onRename = {}, - onStop = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithContentDescription(string(R.string.shell_open_sidebar)).performClick() - composeRule.onNodeWithContentDescription(string(R.string.conversation_back)).assertDoesNotExist() - assertEquals(1, sidebarOpens) - } - - @Test - fun tappingTheTitleOpensTheEditorAndSavingSendsTheTrimmedTitle() { - var renamed: String? = null - - composeRule.setContent { - ConversationHeader( - title = "Old title", - contextTitle = "Studio", - canStop = false, - enabled = true, - onBack = {}, - onRename = { renamed = it }, - onStop = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(CONVERSATION_RENAME_TEST_TAG).assertDoesNotExist() - composeRule.onNodeWithTag(CONVERSATION_TITLE_TEST_TAG).performClick() - composeRule.onNodeWithTag(CONVERSATION_RENAME_TEST_TAG).performTextClearance() - composeRule.onNodeWithTag(CONVERSATION_RENAME_TEST_TAG).performTextInput(" New title ") - composeRule.onNodeWithText(string(R.string.session_rename_confirm)).performClick() - - assertEquals("New title", renamed) - // The editor closes behind the save, so the header goes back to being a - // header rather than staying a form over the transcript. - composeRule.onNodeWithTag(CONVERSATION_RENAME_TEST_TAG).assertDoesNotExist() - } - - @Test - fun anEmptyTitleCannotBeSavedAndCancelChangesNothing() { - var renamed: String? = null - - composeRule.setContent { - ConversationHeader( - title = "Old title", - contextTitle = "Studio", - canStop = false, - enabled = true, - onBack = {}, - onRename = { renamed = it }, - onStop = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(CONVERSATION_TITLE_TEST_TAG).performClick() - composeRule.onNodeWithTag(CONVERSATION_RENAME_TEST_TAG).performTextClearance() - composeRule.onNodeWithText(string(R.string.session_rename_confirm)).assertIsNotEnabled() - composeRule.onNodeWithText(string(R.string.common_cancel)).performClick() - - assertNull(renamed) - composeRule.onNodeWithTag(CONVERSATION_RENAME_TEST_TAG).assertDoesNotExist() - } - - @Test - fun theMenuOffersUploadedFilesAndStopOnlyWhileATurnIsRunning() { - var stopped = 0 - - composeRule.setContent { - ConversationHeader( - title = "Session", - contextTitle = "Studio", - canStop = true, - enabled = true, - onBack = {}, - onRename = {}, - onStop = { stopped += 1 }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(CONVERSATION_MENU_TEST_TAG).performClick() - composeRule.onNodeWithText(string(R.string.session_uploaded_files)).assertIsDisplayed() - val menuBounds = composeRule.onNodeWithTag(HEADER_ACTION_MENU_TEST_TAG).getUnclippedBoundsInRoot() - assertTrue(kotlin.math.abs((menuBounds.right - menuBounds.left).value - 292f) < 1f) - assertTrue(kotlin.math.abs((menuBounds.bottom - menuBounds.top).value - 161f) < 1f) - composeRule.onNodeWithText(string(R.string.message_stop)).performClick() - - assertEquals(1, stopped) - } - - @Test - fun tappingTheMenuAgainDismissesIt() { - composeRule.setContent { - ConversationHeader( - title = "Session", - contextTitle = "Studio", - canStop = false, - enabled = true, - onBack = {}, - onRename = {}, - onStop = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(CONVERSATION_MENU_TEST_TAG).performClick() - composeRule.onNodeWithTag(HEADER_ACTION_MENU_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(CONVERSATION_MENU_TEST_TAG).performClick() - composeRule.onNodeWithTag(HEADER_ACTION_MENU_TEST_TAG).assertDoesNotExist() - } - - @Test - fun anIdleSessionStillOffersUploadedFilesButNotStop() { - composeRule.setContent { - ConversationHeader( - title = "Session", - contextTitle = "Studio", - canStop = false, - enabled = true, - onBack = {}, - onRename = {}, - onStop = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(CONVERSATION_MENU_TEST_TAG).performClick() - - composeRule.onNodeWithText(string(R.string.session_uploaded_files)).assertIsDisplayed() - composeRule.onNodeWithText(string(R.string.message_stop)).assertDoesNotExist() - } - - private fun string(resource: Int): String = - InstrumentationRegistry.getInstrumentation().targetContext.getString(resource) -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt deleted file mode 100644 index ea3fc3221c..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ConversationViewTest.kt +++ /dev/null @@ -1,615 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.asAndroidBitmap -import androidx.compose.ui.test.onRoot -import androidx.compose.ui.test.assert -import androidx.compose.ui.test.SemanticsMatcher -import androidx.compose.ui.semantics.SemanticsProperties -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.performScrollTo -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertTextEquals -import androidx.compose.ui.test.captureToImage -import androidx.compose.ui.test.getUnclippedBoundsInRoot -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextReplacement -import androidx.compose.ui.test.performTouchInput -import androidx.compose.ui.test.swipeDown -import androidx.compose.ui.test.performScrollToIndex -import com.openbitfun.mobile.core.feature.session.HistoryLoadState -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.chat.CONVERSATION_LIST_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.CONVERSATION_LOADING_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.CHAT_STATUS_BAR_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.ConversationEmptyState -import com.openbitfun.mobile.app.ui.chat.ConversationTimelineView -import com.openbitfun.mobile.app.ui.chat.COMPOSER_INPUT_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.COMPOSER_SEND_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.ConversationView -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementMode -import com.openbitfun.mobile.core.feature.session.ConversationRow -import com.openbitfun.mobile.core.feature.session.ConversationRowKind -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.SessionAgentFilter -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class ConversationViewTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun permissionDraftSurvivesSavedStateRestoration() { - val restoration = androidx.compose.ui.test.junit4.StateRestorationTester(composeRule) - val intents = mutableListOf() - val mailbox = com.openbitfun.mobile.core.feature.session.PermissionMailboxUiState(listOf( - com.openbitfun.mobile.core.feature.session.PermissionMailboxRequest( - "request-1", "write", listOf("/workspace/readme.md"), null, "Write") - ), false, false) - restoration.setContent { - OpenBitFunTheme(dark = false) { - com.openbitfun.mobile.app.ui.chat.PermissionMailboxView(mailbox, "session", 600.dp, intents::add) - } - } - val draft = """{"content":"retained edit"}""" - composeRule.onNodeWithText(string(R.string.tool_edit_approval_input)).performClick() - composeRule.onNodeWithText("{}").performTextReplacement(draft) - restoration.emulateSavedInstanceStateRestore() - composeRule.onNodeWithText(draft).assertIsDisplayed() - composeRule.onNodeWithText(string(R.string.tool_approve)).performClick() - val reply = intents.filterIsInstance().single() - assertEquals("request-1", reply.requestId) - assertEquals(draft, reply.updatedInput) - } - - @Test - fun permissionDraftDoesNotBlockRejectionAndMailboxStaysOutsideComposer() { - val intents = mutableListOf() - val state = readyState(sessionId = "session").copy(permissionMailbox = - com.openbitfun.mobile.core.feature.session.PermissionMailboxUiState(listOf( - com.openbitfun.mobile.core.feature.session.PermissionMailboxRequest( - "request-1", "write", listOf("/workspace/readme.md"), null, "Write") - ), false, false)) - val dark = androidx.test.platform.app.InstrumentationRegistry.getArguments().getString("mailboxDark") == "true" - setConversationContent(state = { state }, onIntent = intents::add, dark = dark) - composeRule.onNodeWithText("/workspace/readme.md").assertIsDisplayed() - val capture = composeRule.onRoot().captureToImage().asAndroidBitmap() - val context = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext - val values = android.content.ContentValues().apply { - put(android.provider.MediaStore.Downloads.DISPLAY_NAME, "openbitfun-permission-mailbox-${if (dark) "dark" else "light"}.png") - put(android.provider.MediaStore.Downloads.MIME_TYPE, "image/png") - } - val uri = requireNotNull(context.contentResolver.insert(android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)) - requireNotNull(context.contentResolver.openOutputStream(uri)).use { - capture.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) - } - val requestBounds = composeRule.onNodeWithText("/workspace/readme.md").getUnclippedBoundsInRoot() - val composerBounds = composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).getUnclippedBoundsInRoot() - assertTrue(requestBounds.bottom < composerBounds.top) - composeRule.onNodeWithText(string(R.string.tool_edit_approval_input)).performClick() - composeRule.onNodeWithText("{}").performTextReplacement("{invalid") - composeRule.onNodeWithText(string(R.string.tool_approve)).assertIsNotEnabled() - composeRule.onNodeWithText(string(R.string.tool_reject)).performScrollTo().performClick() - val reply = intents.filterIsInstance().single() - assertEquals("request-1", reply.requestId) - assertEquals(false, reply.approve) - assertEquals(null, reply.updatedInput) - } - - @Test - fun multiplePermissionsScrollIndependentlyWithoutHidingComposer() { - val intents = mutableListOf() - val requests = (1..10).map { index -> - com.openbitfun.mobile.core.feature.session.PermissionMailboxRequest( - "request-$index", "write", listOf("/workspace/file-$index.md"), null, "Write") - } - val state = readyState(sessionId = "session").copy(permissionMailbox = - com.openbitfun.mobile.core.feature.session.PermissionMailboxUiState(requests, false, false)) - setConversationContent(state = { state }, onIntent = intents::add) - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsDisplayed() - val composerBefore = composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).getUnclippedBoundsInRoot() - composeRule.onAllNodesWithText(string(R.string.tool_reject))[9].performScrollTo().assertIsDisplayed().performClick() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsDisplayed() - assertEquals(composerBefore, composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).getUnclippedBoundsInRoot()) - val reply = intents.filterIsInstance().single() - assertEquals("request-10", reply.requestId) - assertEquals(false, reply.approve) - } - - @Test - fun openingATallLastMessageStartsAtTheActualTail() { - val answer = List(500) { "A long answer line." }.joinToString(" ") + " tail-marker" - - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ConversationTimelineView( - rows = listOf(assistantRow(answer)), - hasMoreMessages = false, - onLoadOlder = {}, - enabled = true, - onApproveTool = { _, _ -> }, - onRejectTool = { _, _ -> }, - onCancelTool = { _, _ -> }, - onAnswerTool = { _, _ -> }, - onAnswerToolStructured = { _, _ -> }, - onRetry = {}, - onOpenFile = { _, _ -> }, - previewingRemotePath = "", - previewLoading = false, - download = RemoteFileDownloadUiState.None, - onDownloadFile = { _, _ -> }, - downloadEnabled = true, - modifier = Modifier.fillMaxSize(), - ) - } - } - - composeRule.waitForIdle() - - val listBounds = composeRule.onNodeWithTag(CONVERSATION_LIST_TEST_TAG) - .getUnclippedBoundsInRoot() - val answerBounds = composeRule.onNodeWithText("tail-marker", substring = true) - .getUnclippedBoundsInRoot() - assertTrue(answerBounds.bottom <= listBounds.bottom + 1.dp) - composeRule.onNodeWithContentDescription(string(R.string.chat_scroll_to_bottom)) - .assertDoesNotExist() - } - - @Test - fun streamingGrowthKeepsFollowingWhileTheReaderIsAtTheTail() { - val row = mutableStateOf(assistantRow("stream-start", streaming = true)) - - composeRule.setContent { - OpenBitFunTheme(dark = false) { - TimelineForTest(listOf(row.value)) - } - } - composeRule.runOnIdle { - row.value = assistantRow( - List(500) { "Streaming answer line." }.joinToString(" ") + " stream-tail-marker", - streaming = true, - ) - } - composeRule.waitForIdle() - - val listBounds = composeRule.onNodeWithTag(CONVERSATION_LIST_TEST_TAG) - .getUnclippedBoundsInRoot() - val answerBounds = composeRule.onNodeWithText("stream-tail-marker", substring = true) - .getUnclippedBoundsInRoot() - assertTrue(answerBounds.bottom <= listBounds.bottom + 1.dp) - composeRule.onNodeWithContentDescription(string(R.string.chat_scroll_to_bottom)) - .assertDoesNotExist() - } - - @Test - fun streamingGrowthDoesNotStealTheReaderAfterTheyLeaveTheTail() { - val rows = mutableStateOf((1..40).map { index -> assistantRow("message-$index", id = "message-$index") }) - - composeRule.setContent { - OpenBitFunTheme(dark = false) { - TimelineForTest(rows.value) - } - } - composeRule.waitForIdle() - composeRule.onNodeWithTag(CONVERSATION_LIST_TEST_TAG).performTouchInput { - swipeDown() - swipeDown() - } - composeRule.waitForIdle() - composeRule.onNodeWithContentDescription(string(R.string.chat_scroll_to_bottom)).assertIsDisplayed() - - composeRule.runOnIdle { - rows.value = rows.value.dropLast(1) + - assistantRow( - List(400) { "Growing final answer." }.joinToString(" ") + " reader-tail-marker", - id = "message-40", - streaming = true, - ) - } - composeRule.waitForIdle() - - composeRule.onNodeWithContentDescription(string(R.string.chat_scroll_to_bottom)) - .assertIsDisplayed() - .performClick() - composeRule.waitForIdle() - composeRule.onNodeWithText("reader-tail-marker", substring = true).assertIsDisplayed() - composeRule.onNodeWithContentDescription(string(R.string.chat_scroll_to_bottom)) - .assertDoesNotExist() - } - - @Test - fun historyPrependKeepsVisibleMessagesAndRepeatedDragsDoNotQueueRequests() { - val rows = mutableStateOf((0..5).map { assistantRow("history-$it", "history-$it") }) - val loading = mutableStateOf(HistoryLoadState.IDLE) - var requests = 0 - composeRule.setContent { - OpenBitFunTheme(dark = false) { - TimelineForTest(rows.value, hasMoreMessages = true, historyLoadState = loading.value, - onLoadOlder = { requests++; loading.value = HistoryLoadState.LOADING }) - } - } - val list = composeRule.onNodeWithTag(CONVERSATION_LIST_TEST_TAG) - repeat(3) { list.performTouchInput { swipeDown() }; composeRule.waitForIdle() } - composeRule.runOnIdle { assertEquals(1, requests) } - val before = composeRule.onNodeWithText("history-0").getUnclippedBoundsInRoot().top - composeRule.runOnIdle { - rows.value = (-12..-1).map { assistantRow("history-$it", "history-$it") } + rows.value - loading.value = HistoryLoadState.IDLE - } - composeRule.waitForIdle() - val after = composeRule.onNodeWithText("history-0").getUnclippedBoundsInRoot().top - assertTrue("Prepending moved the visible row from $before to $after", kotlin.math.abs((after - before).value) < 4) - composeRule.runOnIdle { assertEquals(1, requests) } - // Moving the list without a gesture must not fetch another page. - list.performScrollToIndex(0) - composeRule.waitForIdle() - composeRule.runOnIdle { assertEquals(1, requests) } - list.performTouchInput { swipeDown() } - composeRule.waitForIdle() - composeRule.runOnIdle { assertEquals(2, requests) } - } - - @Test - fun withLoadOlderHeaderStreamingGrowthStaysOnTheRealTail() { - val rows = mutableStateOf( - (1..40).map { index -> assistantRow("message-$index", id = "message-$index") }, - ) - - composeRule.setContent { - OpenBitFunTheme(dark = false) { - TimelineForTest(rows.value, hasMoreMessages = true) - } - } - composeRule.waitForIdle() - - composeRule.runOnIdle { - rows.value = rows.value.dropLast(1) + - assistantRow( - List(500) { "Growing tail line." }.joinToString(" ") + " header-tail-marker", - id = "message-40", - streaming = true, - ) - } - composeRule.waitForIdle() - - val listBounds = composeRule.onNodeWithTag(CONVERSATION_LIST_TEST_TAG) - .getUnclippedBoundsInRoot() - val tailBounds = composeRule.onNodeWithText("header-tail-marker", substring = true) - .getUnclippedBoundsInRoot() - assertTrue(tailBounds.bottom <= listBounds.bottom + 1.dp) - composeRule.onNodeWithContentDescription(string(R.string.chat_scroll_to_bottom)) - .assertDoesNotExist() - } - - @Test - fun conversationWithNoTimelineShowsLoadingStateInsteadOfBlankSurface() { - setConversationContent(state = { readyState() }) - - composeRule.mainClock.advanceTimeBy(200) - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertIsDisplayed() - } - - @Test - fun loadingDefersSkeletonAndNeverShowsAConnectionStrip() { - composeRule.mainClock.autoAdvance = false - setConversationContent( - state = { readyState(sessionId = "pending").copy(busy = true) }, - phase = ConnectionPhase.RECONNECTING, - ) - composeRule.mainClock.advanceTimeByFrame() - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertDoesNotExist() - composeRule.onNodeWithTag(CHAT_STATUS_BAR_TEST_TAG).assertDoesNotExist() - composeRule.mainClock.advanceTimeBy(200) - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(CHAT_STATUS_BAR_TEST_TAG).assertDoesNotExist() - } - - /** - * A placeholder that outlives its subject reads as a hang, so the skeleton - * gives up on a transcript that never lands and lets the pane speak for - * itself. Matches HarmonyOS's `DeferredLoadingGate` cap. - */ - @Test - fun loadingSkeletonStopsStandingForATranscriptThatNeverArrives() { - composeRule.mainClock.autoAdvance = false - setConversationContent(state = { readyState(sessionId = "pending") }) - composeRule.mainClock.advanceTimeBy(200) - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertIsDisplayed() - composeRule.mainClock.advanceTimeBy(20_000) - composeRule.onNodeWithTag(CONVERSATION_LOADING_TEST_TAG).assertDoesNotExist() - } - - @Test - fun composerShowsTheStoreDraftAndTypingDispatchesUpdateDraft() { - val intents = mutableListOf() - val state = mutableStateOf(readyState(sessionId = "s-code", draft = "existing draft")) - - setConversationContent(state = { state.value }, onIntent = { intents += it }) - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("existing draft") - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextReplacement("replaced draft") - - assertEquals( - listOf(RemoteSessionIntent.UpdateDraft("replaced draft")), - intents, - ) - } - - @Test - fun composerRemainsEditableWhileNewSessionHydrates() { - val intents = mutableListOf() - val state = mutableStateOf(readyState(sessionId = "pending", draft = "").copy(busy = true, timeline = null)) - - setConversationContent(state = { state.value }, onIntent = { intents += it }) - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextReplacement("draft during load") - assertEquals(listOf(RemoteSessionIntent.UpdateDraft("draft during load")), intents) - } - - @Test - fun composerFollowsStoreDraftUpdatesWithinTheSameSession() { - val state = mutableStateOf(readyState(sessionId = "s-code", draft = "first")) - - setConversationContent(state = { state.value }) - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("first") - composeRule.runOnIdle { state.value = state.value.copy(draft = "second") } - composeRule.waitForIdle() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("second") - } - - @Test - fun switchingSessionsShowsTheRestoredDraft() { - val state = mutableStateOf(readyState(sessionId = "s-a", draft = "draft-a")) - - setConversationContent(state = { state.value }) - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("draft-a") - composeRule.runOnIdle { - state.value = readyState(sessionId = "s-b", draft = "draft-b") - } - composeRule.waitForIdle() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("draft-b") - } - - @Test - fun acceptedSendClearsImmediatelyAndFailureRestoresDraft() { - val intents = mutableListOf() - - val state = mutableStateOf(readyState(sessionId = "s-code", draft = "send me")) - setConversationContent( - state = { state.value }, - onIntent = { intents += it; state.value = state.value.copy(busy = true) }, - ) - - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).performClick() - - assertEquals( - listOf(RemoteSessionIntent.SendMessage("s-code", "send me", null)), - intents, - ) - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assert( - SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("")), - ) - composeRule.runOnIdle { state.value = state.value.copy(busy = false) } - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("send me") - } - - @Test - fun submittedDraftStaysClearedAcrossRecreationWhileAwaitingAck() { - val restoration = androidx.compose.ui.test.junit4.StateRestorationTester(composeRule) - val state = mutableStateOf(readyState(sessionId = "s-code", draft = "send me")) - restoration.setContent { - OpenBitFunTheme(dark = false) { - ConversationView( - state = state.value, phase = ConnectionPhase.CONNECTED, - settingsPlacement = SettingsPlacement(SettingsPlacementMode.BOTTOM, 0, 0, 0), - onBack = {}, onIntent = { intent -> - state.value = when (intent) { - is RemoteSessionIntent.UpdateDraft -> state.value.copy(draft = intent.text) - else -> state.value.copy(busy = true) - } - }, contextTitle = "Test desktop", onOpenFile = { _, _ -> }, - previewingRemotePath = "", previewLoading = false, - download = RemoteFileDownloadUiState.None, onDownloadFile = { _, _ -> }, - modifier = Modifier.fillMaxSize(), - ) - } - } - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).performClick() - restoration.emulateSavedInstanceStateRestore() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assert( - SemanticsMatcher.expectValue(SemanticsProperties.EditableText, AnnotatedString("")), - ) - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextReplacement("next draft") - composeRule.runOnIdle { state.value = state.value.copy(busy = false) } - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertTextEquals("next draft") - } - - @Test - fun emptyStateShowsInvitationCopy() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ConversationEmptyState(modifier = Modifier.fillMaxSize()) - } - } - composeRule.onNodeWithText(string(R.string.chat_empty_title)).assertIsDisplayed() - composeRule.onNodeWithText(string(R.string.chat_empty_hint)).assertIsDisplayed() - } - - @Test - fun reconnectingKeepsConversationAndComposerWithoutHeaderBanner() { - setConversationContent( - state = { readyState() }, - phase = ConnectionPhase.RECONNECTING, - ) - composeRule.onNodeWithTag(CHAT_STATUS_BAR_TEST_TAG).assertDoesNotExist() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).assertIsNotEnabled() - } - - /** - * The composer and the header float over the transcript rather than sitting - * above and below it in a column, so the list runs the full height of the - * pane and these insets are the only thing keeping the first and last - * message out from under them. The insets are measured from the live - * overlays, so growing one — a composer going multiline, an image strip - * appearing — has to push the transcript rather than cover it. - */ - @Test - fun insetsKeepTheEndsOfTheTranscriptClearOfTheFloatingOverlays() { - val bottomInset = mutableStateOf(96.dp) - composeRule.setContent { - OpenBitFunTheme(dark = false) { - TimelineForTest( - rows = listOf(assistantRow("inset-marker")), - topInset = 72.dp, - bottomInset = bottomInset.value, - ) - } - } - composeRule.waitForIdle() - - val listBounds = composeRule.onNodeWithTag(CONVERSATION_LIST_TEST_TAG) - .getUnclippedBoundsInRoot() - val resting = composeRule.onNodeWithText("inset-marker", substring = true) - .getUnclippedBoundsInRoot() - assertTrue(resting.bottom <= listBounds.bottom - 96.dp + 1.dp) - assertTrue(resting.top >= listBounds.top) - - composeRule.runOnIdle { bottomInset.value = 180.dp } - composeRule.waitForIdle() - - val lifted = composeRule.onNodeWithText("inset-marker", substring = true) - .getUnclippedBoundsInRoot() - assertTrue(lifted.bottom <= listBounds.bottom - 180.dp + 1.dp) - assertTrue(lifted.bottom < resting.bottom) - } - - private fun setConversationContent( - state: () -> RemoteSessionUiState.Ready, - phase: ConnectionPhase = ConnectionPhase.CONNECTED, - onIntent: (RemoteSessionIntent) -> Unit = {}, - dark: Boolean = false, - ) { - composeRule.setContent { - OpenBitFunTheme(dark = dark) { - androidx.compose.material3.Surface( - modifier = Modifier.fillMaxSize(), - color = androidx.compose.material3.MaterialTheme.colorScheme.background, - contentColor = androidx.compose.material3.MaterialTheme.colorScheme.onBackground, - ) { - ConversationView( - state = state(), - phase = phase, - settingsPlacement = SettingsPlacement(SettingsPlacementMode.BOTTOM, 0, 0, 0), - onBack = {}, - onIntent = onIntent, - contextTitle = "Test desktop", - onOpenFile = { _, _ -> }, - previewingRemotePath = "", - previewLoading = false, - download = RemoteFileDownloadUiState.None, - onDownloadFile = { _, _ -> }, - modifier = Modifier.fillMaxSize(), - ) - } - } - } - } - - - private fun readyState( - sessionId: String = "", - draft: String = "", - ) = RemoteSessionUiState.Ready( - sessions = emptyList(), - selectedSessionId = sessionId, - timeline = null, - busy = false, - permissionMode = null, - permissionModeFailure = null, - query = "", - agentFilter = SessionAgentFilter.ALL, - hasMore = false, - hasMoreMessages = false, - modelCatalog = null, - modelCatalogFailure = null, - draft = draft, - ) - - @Composable - private fun TimelineForTest( - rows: List, - hasMoreMessages: Boolean = false, - topInset: Dp = 0.dp, - bottomInset: Dp = 0.dp, - historyLoadState: HistoryLoadState = HistoryLoadState.IDLE, - onLoadOlder: () -> Unit = {}, - ) { - ConversationTimelineView( - rows = rows, - hasMoreMessages = hasMoreMessages, - topInset = topInset, - bottomInset = bottomInset, - historyLoadState = historyLoadState, - onLoadOlder = onLoadOlder, - enabled = true, - onApproveTool = { _, _ -> }, - onRejectTool = { _, _ -> }, - onCancelTool = { _, _ -> }, - onAnswerTool = { _, _ -> }, - onAnswerToolStructured = { _, _ -> }, - onRetry = {}, - onOpenFile = { _, _ -> }, - previewingRemotePath = "", - previewLoading = false, - download = RemoteFileDownloadUiState.None, - onDownloadFile = { _, _ -> }, - downloadEnabled = true, - modifier = Modifier.fillMaxSize(), - ) - } - - private fun assistantRow( - answer: String, - id: String = "message-1", - streaming: Boolean = false, - ): ConversationRow = ConversationRow( - id = id, - kind = ConversationRowKind.ASSISTANT, - text = answer, - thinking = null, - images = emptyList(), - tools = emptyList(), - blocks = emptyList(), - streaming = streaming, - typing = false, - showRetry = false, - error = null, - live = false, - timestampMs = null, - ) - - private fun string(resource: Int): String = - InstrumentationRegistry.getInstrumentation().targetContext.getString(resource) -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/CreateSessionScreenTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/CreateSessionScreenTest.kt deleted file mode 100644 index 74baf2dc56..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/CreateSessionScreenTest.kt +++ /dev/null @@ -1,227 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextInput -import com.openbitfun.mobile.app.ui.chat.COMPOSER_INPUT_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.COMPOSER_SEND_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.MODEL_CONTROL_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX -import com.openbitfun.mobile.app.ui.remote.CREATE_SESSION_BACK_TEST_TAG -import com.openbitfun.mobile.app.ui.remote.CREATE_SESSION_WORKSPACE_TEST_TAG -import com.openbitfun.mobile.app.ui.remote.CreateDeviceChoice -import com.openbitfun.mobile.app.ui.remote.CreateSessionScreen -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.ModelOption -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteFilePreviewUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Rule -import org.junit.Test - -/** - * The new-session screen, ported from `RemoteCreateSessionView.ets`. - * - * What is worth pinning is what leaves the phone: the screen has no title field - * and no agent picker, so everything about the created session is inferred, and - * a wrong inference produces a session bound to the wrong place. - * - * The workspace-picked path is covered by `CreateSessionPresentationTest` in - * core-feature, where that decision actually lives. - */ -class CreateSessionScreenTest { - @get:Rule - val composeRule = createComposeRule() - - private fun readyWorkspace(): RemoteWorkspaceUiState = RemoteWorkspaceUiState.Ready( - workspaces = emptyList(), - assistants = emptyList(), - selected = null, - preview = RemoteFilePreviewUiState.None, - busy = false, - download = RemoteFileDownloadUiState.None, - ) - - @Test - fun withoutAWorkspaceTheScreenSaysChatAndCreatesAChatSession() { - var intent: RemoteSessionIntent? = null - - composeRule.setContent { - CreateSessionScreen( - workspaceState = readyWorkspace(), - phase = ConnectionPhase.CONNECTED, - deviceId = "desk-1", - devices = emptyList(), - compact = true, - onDevicePick = {}, - busy = false, - onBack = {}, - onWorkspaceIntent = {}, - onIntent = { intent = it }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(testString(R.string.navigation_general_chat)).assertIsDisplayed() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextInput("review the parser") - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).performClick() - - val create = intent as RemoteSessionIntent.CreateSession - // "Claw" is a wire value the desktop matches on, not a label. - assertEquals("Claw", create.agentType) - assertEquals("review the parser", create.instruction) - // The agent renames the session after reading the first message, so - // sending a title here would only be overwritten. - assertEquals("", create.title) - } - - @Test - fun withoutADesktopThereIsNothingToCreateOn() { - var intent: RemoteSessionIntent? = null - - composeRule.setContent { - CreateSessionScreen( - workspaceState = readyWorkspace(), - phase = ConnectionPhase.CONNECTED, - deviceId = "", - devices = emptyList(), - compact = true, - onDevicePick = {}, - busy = false, - onBack = {}, - onWorkspaceIntent = {}, - onIntent = { intent = it }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(testString(R.string.create_no_device)).assertIsDisplayed() - // The draft survives — it is worth keeping until a desktop comes back — - // but the send is the same dimmed control a dropout produces. - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextInput("review the parser") - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).performClick() - - assertNull(intent) - } - - @Test - fun selectedModelIsAppliedToTheNewSession() { - var intent: RemoteSessionIntent? = null - composeRule.setContent { - CreateSessionScreen( - workspaceState = readyWorkspace(), - phase = ConnectionPhase.CONNECTED, - deviceId = "desk-1", - devices = emptyList(), - modelOptions = listOf( - ModelOption("model-primary", "Primary", "Account", selected = true), - ModelOption("model-fast", "Fast", "Account", selected = false), - ), - compact = true, - onDevicePick = {}, - busy = false, - onBack = {}, - onWorkspaceIntent = {}, - onIntent = { intent = it }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextInput("review the parser") - composeRule.onNodeWithTag(MODEL_CONTROL_TEST_TAG).performClick() - composeRule.onNodeWithTag(MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX + "model-fast").performClick() - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).performClick() - - assertEquals("model-fast", (intent as RemoteSessionIntent.CreateSession).modelId) - } - - @Test - fun theWorkspaceRowOpensAPickerThatSaysWhenThereIsNothingToPick() { - composeRule.setContent { - CreateSessionScreen( - workspaceState = readyWorkspace(), - phase = ConnectionPhase.CONNECTED, - deviceId = "desk-1", - devices = emptyList(), - compact = true, - onDevicePick = {}, - busy = false, - onBack = {}, - onWorkspaceIntent = {}, - onIntent = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(CREATE_SESSION_WORKSPACE_TEST_TAG).performClick() - - composeRule.onNodeWithText(testString(R.string.create_workspace_picker)).assertIsDisplayed() - // A desktop with no recent projects is not a broken picker, and saying - // where to fix it is the only useful thing the sheet can offer. - composeRule.onNodeWithText(testString(R.string.create_no_workspaces)) - .assertIsDisplayed() - } - - @Test - fun wideCreateRouteAnchorsTheDesktopPickerAndSwitchesTargets() { - var picked: String? = null - composeRule.setContent { - CreateSessionScreen( - workspaceState = readyWorkspace(), - phase = ConnectionPhase.CONNECTED, - deviceId = "desk-1", - devices = listOf( - CreateDeviceChoice("desk-1", "Studio Mac", online = true, selected = true), - CreateDeviceChoice("desk-2", "Office PC", online = true, selected = false), - ), - compact = false, - onDevicePick = { picked = it }, - busy = false, - onBack = {}, - onWorkspaceIntent = {}, - onIntent = {}, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText("Studio Mac").performClick() - composeRule.onNodeWithText("Office PC").assertIsDisplayed().performClick() - - assertEquals("desk-2", picked) - } - - @Test - fun backLeavesWithoutCreatingAnything() { - var back = 0 - var intent: RemoteSessionIntent? = null - - composeRule.setContent { - CreateSessionScreen( - workspaceState = readyWorkspace(), - phase = ConnectionPhase.CONNECTED, - deviceId = "desk-1", - devices = emptyList(), - compact = true, - onDevicePick = {}, - busy = false, - onBack = { back += 1 }, - onWorkspaceIntent = {}, - onIntent = { intent = it }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG).performTextInput("never mind") - composeRule.onNodeWithTag(CREATE_SESSION_BACK_TEST_TAG).performClick() - - assertEquals(1, back) - assertNull(intent) - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/FileReferenceCardsTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/FileReferenceCardsTest.kt deleted file mode 100644 index 4fea9afd8f..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/FileReferenceCardsTest.kt +++ /dev/null @@ -1,129 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertHeightIsEqualTo -import androidx.compose.ui.test.assertWidthIsEqualTo -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onAllNodesWithTag -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.performClick -import com.openbitfun.mobile.app.ui.chat.FILE_REFERENCE_CARD_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.FILE_DOWNLOAD_ACTION_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.FileReferenceCards -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test -import androidx.compose.ui.unit.dp - -/** - * The file cards under an agent turn, ported from `MessageFileCards`. - * - * The projection itself is covered in `core-feature`; what is pinned here is the - * wiring — that a card carries the verbatim reference to whatever opens the - * preview, and that the card for the open file is the one that spins. - */ -class FileReferenceCardsTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun everyFileNamedInATurnGetsACardNamedByItsFile() { - composeRule.setContent { - FileReferenceCards( - text = "Look at [it](computer:///repo/README.md) and computer:///repo/src/main.kt.", - previewingRemotePath = "", - previewLoading = false, - onOpen = { _, _ -> }, - modifier = Modifier, - ) - } - - assertEquals(2, composeRule.onAllNodesWithTag(FILE_REFERENCE_CARD_TEST_TAG).fetchSemanticsNodes().size) - composeRule.onNodeWithText("README.md").assertIsDisplayed() - composeRule.onNodeWithText("main.kt").assertIsDisplayed() - } - - @Test - fun tappingACardReportsTheReferenceAsTheAgentWroteIt() { - var opened: Pair? = null - - composeRule.setContent { - FileReferenceCards( - // With a line marker, because that is what the preview needs in - // order to scroll to the line the agent was talking about. - text = "See computer:///repo/src/main.kt#L12-40 for the cause.", - previewingRemotePath = "", - previewLoading = false, - onOpen = { reference, label -> opened = reference to label }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText("main.kt").performClick() - - assertEquals("computer:///repo/src/main.kt#L12-40" to "main.kt", opened) - } - - @Test - fun aTurnThatNamesNoFileDrawsNothing() { - composeRule.setContent { - FileReferenceCards( - text = "Run `src/main.kt` and read https://example.com/README.md.", - previewingRemotePath = "", - previewLoading = false, - onOpen = { _, _ -> }, - modifier = Modifier, - ) - } - - assertEquals(0, composeRule.onAllNodesWithTag(FILE_REFERENCE_CARD_TEST_TAG).fetchSemanticsNodes().size) - } - - @Test - fun theOpenFileIsStillTappableWhileItIsLoading() { - var opens = 0 - - composeRule.setContent { - FileReferenceCards( - text = "computer:///repo/README.md", - previewingRemotePath = "/repo/README.md", - previewLoading = true, - onOpen = { _, _ -> opens += 1 }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText("README.md").assertIsDisplayed() - composeRule.onNodeWithText("README.md").performClick() - - assertEquals(1, opens) - } - - @Test - fun downloadIsASeparateActionAndKeepsTheOriginalReference() { - var downloaded: Pair? = null - var opens = 0 - - composeRule.setContent { - FileReferenceCards( - text = "See computer:///repo/src/main.kt#L12-40.", - previewingRemotePath = "", - previewLoading = false, - onOpen = { _, _ -> opens += 1 }, - onDownload = { reference, label -> downloaded = reference to label }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithContentDescription(testString(R.string.file_download)).assertIsDisplayed().performClick() - composeRule.onNodeWithTag(FILE_DOWNLOAD_ACTION_TEST_TAG) - .assertWidthIsEqualTo(44.dp) - .assertHeightIsEqualTo(44.dp) - - assertEquals(0, opens) - assertEquals("computer:///repo/src/main.kt#L12-40" to "main.kt", downloaded) - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/HarnessProfileMenuTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/HarnessProfileMenuTest.kt deleted file mode 100644 index 236381e190..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/HarnessProfileMenuTest.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.openbitfun.mobile.app - -import android.graphics.Bitmap -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.unit.dp -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.remote.ProjectCreateControl -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test -import java.io.File - -class HarnessProfileMenuTest { - @get:Rule val composeRule = createComposeRule() - @Test fun supportedHostOffersAllProfilesAndSendsCanonicalAgent() = verify(true, false) - @Test fun legacyHostRetainsCodeAndCoworkInDarkMode() = verify(false, true) - - private fun verify(supported: Boolean, dark: Boolean) { - var selected: String? = null - val context = InstrumentationRegistry.getInstrumentation().targetContext - composeRule.setContent { - OpenBitFunTheme(dark = dark) { - Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(32.dp)) { - var expanded by remember { mutableStateOf(true) } - ProjectCreateControl( - supportsHarnessProfiles = supported, path = "/remote/project", expanded = expanded, - onToggle = { expanded = !expanded }, onDismiss = { expanded = false }, - onCreateAgent = { selected = it; expanded = false }, - ) - } - } - } - val label = context.getString(if (supported) R.string.harness_ultimate else R.string.sessions_filter_code) - composeRule.onNodeWithText(label).assertIsDisplayed() - if (supported) { - composeRule.onNodeWithText(context.getString(R.string.harness_minimal)).assertIsDisplayed() - composeRule.onNodeWithText(context.getString(R.string.harness_standard)).assertIsDisplayed() - } - composeRule.waitForIdle() - val image = InstrumentationRegistry.getInstrumentation().uiAutomation.takeScreenshot() - File(context.getExternalFilesDir(null), "harness-${if (supported) "light" else "legacy-dark"}.png").outputStream().use { - image.compress(Bitmap.CompressFormat.PNG, 100, it) - } - composeRule.onNodeWithText(label).performClick() - composeRule.runOnIdle { assertEquals(if (supported) "Ultra" else "code", selected) } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt deleted file mode 100644 index d5a6852557..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.width -import androidx.compose.runtime.* -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.unit.dp -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.chat.MessageQueuePanel -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.session.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test - -class MessageQueuePanelTest { - @get:Rule val rule = createComposeRule() - private val context get() = InstrumentationRegistry.getInstrumentation().targetContext - private fun state(supports: Boolean = true) = MessageQueueUiState("s", true, supports, "e:1", listOf( - QueuedMessageUiState("a", "First", 1, "queued", null), - QueuedMessageUiState("b", "Second", 0, "queued", null), - QueuedMessageUiState("c", "Third", 0, "queued", null), - ), false, null) - - @Test fun compactMenuMovesUseStableMessageIdentityInBothThemes() { - var dark by mutableStateOf(true) - val intents = mutableListOf() - rule.setContent { OpenBitFunTheme(dark = dark) { Box(Modifier.width(320.dp)) { MessageQueuePanel(state(), intents::add) } } } - repeat(2) { - rule.onAllNodesWithContentDescription(context.getString(R.string.queue_more))[0].performClick() - rule.onNodeWithText(context.getString(R.string.queue_move_up)).assertIsNotEnabled() - rule.onNodeWithText(context.getString(R.string.queue_move_down)).performClick() - assertEquals(RemoteSessionIntent.MoveQueuedMessage("a", "c"), intents.last()) - rule.runOnIdle { dark = false } - } - } - - @Test fun longPressDragCommitsOnceAtRelease() { - val intents = mutableListOf() - rule.setContent { OpenBitFunTheme(dark = true) { Box(Modifier.width(320.dp)) { MessageQueuePanel(state(), intents::add) } } } - val handles = rule.onAllNodesWithContentDescription(context.getString(R.string.queue_reorder)) - val offset = handles[0].fetchSemanticsNode().boundsInRoot.center.y - handles[2].fetchSemanticsNode().boundsInRoot.center.y - 10f - handles[2].performTouchInput { - down(center); advanceEventTime(650); moveBy(Offset(0f, offset), delayMillis = 120) - } - rule.runOnIdle { assertTrue(intents.isEmpty()) } - handles[2].performTouchInput { up() } - rule.runOnIdle { assertEquals(listOf(RemoteSessionIntent.MoveQueuedMessage("c", "a")), intents) } - } - - @Test fun hostRevisionChangeCancelsAnActiveDragAndLegacyHostsHaveNoHandle() { - var current by mutableStateOf(state()) - val intents = mutableListOf() - rule.setContent { OpenBitFunTheme(dark = false) { MessageQueuePanel(current, intents::add) } } - val handles = rule.onAllNodesWithContentDescription(context.getString(R.string.queue_reorder)) - handles[0].performTouchInput { down(center); advanceEventTime(650); moveBy(Offset(0f, 100f), delayMillis = 120) } - rule.runOnIdle { current = current.copy(revisionKey = "e:2") } - handles[0].performTouchInput { up() } - rule.runOnIdle { assertTrue(intents.isEmpty()); current = current.copy(supportsReorder = false) } - rule.onAllNodesWithContentDescription(context.getString(R.string.queue_reorder)).assertCountEquals(0) - rule.onAllNodesWithContentDescription(context.getString(R.string.queue_more))[0].performClick() - rule.onNodeWithText(context.getString(R.string.queue_unsupported)).assertExists() - rule.onNodeWithText(context.getString(R.string.queue_move_down)).assertIsNotEnabled() - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileDesignPreviewVisualTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileDesignPreviewVisualTest.kt deleted file mode 100644 index a38db10650..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileDesignPreviewVisualTest.kt +++ /dev/null @@ -1,180 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.ui.ExperimentalComposeUiApi -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.graphics.toPixelMap -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.captureToImage -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.preview.MOBILE_DESIGN_GALLERY_PLATFORM_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_DESIGN_GALLERY_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MobileDesignGallery -import com.openbitfun.mobile.app.ui.preview.generated.MobilePreviewScenario -import com.openbitfun.mobile.app.ui.preview.generated.MobilePreviewScenarios -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignColors -import com.openbitfun.mobile.app.R -import kotlin.math.abs -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class MobileDesignPreviewVisualTest { - @get:Rule - val composeRule = createComposeRule() - - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - - @Test - fun connectedConversationScenarioExposesStableSemanticsAndPixels() { - composeRule.setContent { - MobileDesignGallery(MobilePreviewScenarios.ConnectedConversation, dark = false) - } - assertGallerySemantics(MobilePreviewScenarios.ConnectedConversation) - val gallery = composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_TEST_TAG) - .captureToImage() - assertNonBlankAndVaried(gallery) - } - - @Test - fun streamingDarkScenarioExposesStableSemanticsAndPixels() { - composeRule.setContent { - MobileDesignGallery(MobilePreviewScenarios.StreamingDark, dark = true) - } - assertGallerySemantics(MobilePreviewScenarios.StreamingDark) - val gallery = composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_TEST_TAG) - .captureToImage() - assertNonBlankAndVaried(gallery) - } - - @Test - fun reconnectingWideScenarioExposesStableSemanticsAndPixels() { - composeRule.setContent { - MobileDesignGallery(MobilePreviewScenarios.ReconnectingWide, dark = false) - } - assertGallerySemantics(MobilePreviewScenarios.ReconnectingWide) - assertNonBlankAndVaried( - composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_TEST_TAG).captureToImage() - ) - } - - @Test - fun darkGalleryIsDarkerThanLightGallery() { - var scenario by mutableStateOf(MobilePreviewScenarios.ConnectedConversation) - composeRule.setContent { - MobileDesignGallery(scenario, dark = scenario.appearance == "dark") - } - val lightGallery = composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_TEST_TAG) - .captureToImage() - - composeRule.runOnIdle { scenario = MobilePreviewScenarios.StreamingDark } - composeRule.waitForIdle() - val darkGallery = composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_TEST_TAG) - .captureToImage() - - assertNonBlankAndVaried(lightGallery) - assertNonBlankAndVaried(darkGallery) - assertTrue( - "Light gallery should be brighter than dark gallery", - meanLuminance(lightGallery) > meanLuminance(darkGallery), - ) - } - - @Test - fun lightThemeBackgroundProbeMatchesContract() { - assertBackgroundProbe(dark = false, expected = MobileDesignColors.Light.PageBg) - } - - @Test - fun darkThemeBackgroundProbeMatchesContract() { - assertBackgroundProbe(dark = true, expected = MobileDesignColors.Dark.PageBg) - } - - private fun assertGallerySemantics(scenario: MobilePreviewScenario) { - composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(MOBILE_DESIGN_GALLERY_PLATFORM_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText("${scenario.viewportWidth} × ${scenario.viewportHeight}") - .assertIsDisplayed() - composeRule.onNodeWithText(scenario.headerTitle).assertIsDisplayed() - composeRule.onNodeWithText(scenario.headerSubtitle).assertIsDisplayed() - scenario.messages.forEach { message -> - composeRule.onNodeWithText(message.text).assertIsDisplayed() - } - if (scenario.composerDraft.isEmpty()) { - composeRule.onNodeWithText(scenario.composerPlaceholder).assertIsDisplayed() - } else { - composeRule.onNodeWithText(scenario.composerDraft).assertIsDisplayed() - } - if (scenario == MobilePreviewScenarios.StreamingDark) { - composeRule.onNodeWithContentDescription(targetContext.getString(R.string.message_send)) - .assertIsDisplayed().assertIsEnabled() - } - } - - @OptIn(ExperimentalTestApi::class, ExperimentalComposeUiApi::class) - private fun assertBackgroundProbe(dark: Boolean, expected: androidx.compose.ui.graphics.Color) { - composeRule.setContent { - OpenBitFunTheme(dark = dark) { - Box( - Modifier - .fillMaxSize() - .background(MaterialTheme.colorScheme.background) - .testTag("token-probe"), - ) - } - } - val image = composeRule.onNodeWithTag("token-probe").captureToImage() - val actual = image.toPixelMap()[image.width / 2, image.height / 2].toArgb() - val expectedArgb = expected.toArgb() - assertTrue( - "Theme background pixel differs: expected $expectedArgb, actual $actual", - channelDistance(actual, expectedArgb) <= 4, - ) - } - - private fun assertNonBlankAndVaried(image: ImageBitmap) { - assertTrue("Captured gallery must have pixels", image.width > 0 && image.height > 0) - val samples = sampledArgb(image) - assertTrue("Captured gallery must contain visual variation", samples.distinct().size > 1) - } - - private fun sampledArgb(image: ImageBitmap): List { - val map = image.toPixelMap() - return (0 until 8).flatMap { row -> - (0 until 8).map { column -> - val x = column * (image.width - 1) / 7 - val y = row * (image.height - 1) / 7 - map[x, y].toArgb() - } - } - } - - private fun meanLuminance(image: ImageBitmap): Double = sampledArgb(image).map { argb -> - val red = (argb shr 16) and 0xff - val green = (argb shr 8) and 0xff - val blue = argb and 0xff - 0.2126 * red + 0.7152 * green + 0.0722 * blue - }.average() - - private fun channelDistance(first: Int, second: Int): Int = maxOf( - abs(((first shr 16) and 0xff) - ((second shr 16) and 0xff)), - abs(((first shr 8) and 0xff) - ((second shr 8) and 0xff)), - abs((first and 0xff) - (second and 0xff)), - ) -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileParityTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileParityTest.kt deleted file mode 100644 index badfcd64e5..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileParityTest.kt +++ /dev/null @@ -1,169 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.chat.* -import com.openbitfun.mobile.app.ui.chat.tool.* -import com.openbitfun.mobile.app.ui.miniapps.BuiltinMiniAppBridge -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.* -import org.json.JSONObject -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test - -class MobileParityTest { - @get:Rule val rule = createComposeRule() - - @Test fun runningRemoteDraftSendsInsteadOfStopping() { - var sent = 0 - var stopped = 0 - rule.setContent { - OpenBitFunTheme(dark = true) { - ComposerBar(draft = "Add tests", images = emptyList(), busy = false, streaming = true, - phase = ConnectionPhase.CONNECTED, model = null, capabilities = ChatComposerCapabilities.RemoteChat, - placeholder = "Message", onDraftChange = {}, onRemoveImage = {}, onAttach = {}, onVoice = {}, - onSend = { sent++ }, onStop = { stopped++ }, onOpenModels = {}, onSelectModel = {}, modifier = Modifier) - } - } - rule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).performClick() - assertEquals(1, sent) - assertEquals(0, stopped) - } - - @Test fun unsupportedPlanIsVisibleButCannotExecute() { - val context = InstrumentationRegistry.getInstrumentation().targetContext - rule.setContent { - OpenBitFunTheme(dark = false) { - ToolStatusRow(plan(), true, {}, {}, {}, {}, {}, { _, _ -> }, Modifier) - } - } - rule.onNodeWithText(context.getString(R.string.plan_build)).assertIsNotEnabled() - rule.onNodeWithText(context.getString(R.string.plan_unsupported)).assertExists() - } - - @Test fun supportedPlanOpensItsRemoteFileAndDispatchesBuild() { - var opened = "" - var built = "" - val context = InstrumentationRegistry.getInstrumentation().targetContext - rule.setContent { - OpenBitFunTheme(dark = false) { - CompositionLocalProvider(LocalPlanActions provides PlanActions(true, true, { built = it.path })) { - ToolStatusRow(plan(), true, {}, {}, {}, {}, {}, { path, _ -> opened = path }, Modifier) - } - } - } - rule.onNodeWithText(context.getString(R.string.plan_view)).performClick() - rule.onNodeWithText(context.getString(R.string.plan_build)).performClick() - assertEquals("/repo/review.plan.md", opened) - assertEquals(opened, built) - } - - @Test fun miniAppStorageSurvivesHostRecreationAndRetainsCorruption() { - // Isolate the test namespace while retaining the target process's writable storage context. - val context = object : android.content.ContextWrapper(InstrumentationRegistry.getInstrumentation().targetContext) { - override fun getSharedPreferences(name: String, mode: Int) = super.getSharedPreferences("parity-test-$name", mode) - } - val preferences = context.getSharedPreferences("miniapps-builtin-gomoku", 0) - preferences.edit().clear().commit() - var reply = JSONObject() - fun bridge() = BuiltinMiniAppBridge(context, "builtin-gomoku") { reply = JSONObject(it) } - bridge().request("""{"id":"set","method":"storage.set","params":{"key":"stats","value":{"wins":3}}}""") - assertFalse(reply.toString(), reply.has("error")) - bridge().request("""{"id":"get","method":"storage.get","params":{"key":"stats"}}""") - assertEquals(3, reply.getJSONObject("result").getInt("wins")) - bridge().request("""{"id":"bad-key","method":"storage.get","params":{"key":"regex-state"}}""") - assertTrue(reply.has("error")) - preferences.edit().putString("stats", "unparseable").commit() - bridge().request("""{"id":"get","method":"storage.get","params":{"key":"stats"}}""") - assertTrue(reply.has("error")) - assertEquals("unparseable", preferences.getString("stats", null)) - preferences.edit().clear().commit() - } - - @Test fun preparedAttachmentsSurviveNewStoresAndStayDeviceScoped() { - val context = InstrumentationRegistry.getInstrumentation().targetContext - val directory = java.io.File(context.cacheDir, "attachment-test-${java.util.UUID.randomUUID()}") - val first = com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel() - lateinit var draft: com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel.AttachmentDraft - rule.runOnIdle { draft = first.forSession("device-a/session", directory) } - rule.waitUntil(5_000) { !draft.loading.value } - val image = ComposerImage("one", "data:image/png;base64,AAAA", "image/png") - rule.runOnIdle { draft.images.value = listOf(image) } - rule.waitUntil(5_000) { !draft.saving.value } - assertFalse(draft.failed.value) - // No shared ViewModelStore or in-memory state: this reads the durable record. - val restored = com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel() - lateinit var reloaded: com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel.AttachmentDraft - lateinit var other: com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel.AttachmentDraft - rule.runOnIdle { - reloaded = restored.forSession("device-a/session", directory) - other = restored.forSession("device-b/session", directory) - } - rule.waitUntil(5_000) { !reloaded.loading.value && !other.loading.value } - assertEquals(listOf(image), reloaded.images.value) - assertTrue(other.images.value.isEmpty()) - // Forward-compatible unknown fields and the original shape without a version. - val file = directory.listFiles()!!.single() - file.writeText(JSONObject(file.readText()).apply { remove("version"); put("future", true) }.toString()) - val legacy = com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel() - rule.runOnIdle { reloaded = legacy.forSession("device-a/session", directory) } - rule.waitUntil(5_000) { !reloaded.loading.value } - assertEquals(listOf(image), reloaded.images.value) - // Unreadable records remain on disk and must not be overwritten by an empty draft. - file.writeText("unparseable") - val corrupt = com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel() - rule.runOnIdle { reloaded = corrupt.forSession("device-a/session", directory) } - rule.waitUntil(5_000) { !reloaded.loading.value } - assertTrue(reloaded.failed.value) - rule.runOnIdle { reloaded.images.value = emptyList() } - assertEquals("unparseable", file.readText()) - directory.deleteRecursively() - } - - @Test fun gomokuAllocatesVisibleViewport() = captureOfflineMiniApp(0) - @Test fun regexAllocatesVisibleViewport() = captureOfflineMiniApp(1) - @Test fun divinationAllocatesVisibleViewport() = captureOfflineMiniApp(2) - - private fun captureOfflineMiniApp(index: Int) { - val instrumentation = InstrumentationRegistry.getInstrumentation() - val context = instrumentation.targetContext - val locale = if (context.resources.configuration.locales[0].language == "zh") "zh-CN" else "en-US" - val catalog = org.json.JSONArray(context.assets.open("miniapps/catalog.json").bufferedReader().use { it.readText() }) - rule.setContent { OpenBitFunTheme(dark = false) { com.openbitfun.mobile.app.ui.miniapps.MiniAppsButton() } } - rule.onNodeWithText(context.getString(R.string.miniapps_title)).performClick() - run { - val app = catalog.getJSONObject(index) - val title = app.getJSONObject("locales").getJSONObject(locale).getString("name") - rule.onNodeWithText(title).performClick() - lateinit var web: android.webkit.WebView - androidx.test.espresso.Espresso.onView(androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom(android.webkit.WebView::class.java)) - .check { view, error -> - if (error != null) throw error - web = view as android.webkit.WebView - assertTrue(web.width > 0 && web.height > 0) - } - val ready = java.util.concurrent.atomic.AtomicBoolean(false) - rule.waitUntil(15_000) { - instrumentation.runOnMainSync { - web.evaluateJavascript("document.querySelector('iframe').dataset.loaded === 'true' && document.querySelector('iframe').clientHeight > 0") { - ready.set(it == "true") - } - } - ready.get() - } - rule.onNodeWithContentDescription(context.getString(R.string.miniapps_back)).performClick() - } - } - - private fun plan() = ToolCard("plan", "Write", ToolPhase.COMPLETED, ToolKind.DOCUMENT, ToolOperation.UNKNOWN, - "review.plan.md", "/repo/review.plan.md", "review.plan.md", "", "", null, emptySet()) -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobilePreviewStatesVisualTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobilePreviewStatesVisualTest.kt deleted file mode 100644 index ab6e79f760..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobilePreviewStatesVisualTest.kt +++ /dev/null @@ -1,142 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.graphics.toPixelMap -import androidx.compose.ui.test.assertHeightIsEqualTo -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertWidthIsEqualTo -import androidx.compose.ui.test.captureToImage -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextInput -import androidx.compose.ui.unit.dp -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.COMPOSER_INPUT_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.COMPOSER_SEND_TEST_TAG -import com.openbitfun.mobile.app.ui.chat.MODEL_CONTROL_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_CIRCLE_BACK_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_CIRCLE_MORE_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_CIRCLE_SIDEBAR_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_CIRCLE_STATES_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_COMPOSER_ATTACHMENTS_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_COMPOSER_FOCUSED_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_MODAL_BUSY_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_MODAL_ERROR_ACTION_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_MODAL_ERROR_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MOBILE_PREVIEW_MODAL_ERROR_TEXT_TEST_TAG -import com.openbitfun.mobile.app.ui.preview.MobilePreviewCircleStates -import com.openbitfun.mobile.app.ui.preview.MobilePreviewComposerAttachments -import com.openbitfun.mobile.app.ui.preview.MobilePreviewComposerFocused -import com.openbitfun.mobile.app.ui.preview.MobilePreviewModalBusy -import com.openbitfun.mobile.app.ui.preview.MobilePreviewModalError -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class MobilePreviewStatesVisualTest { - @get:Rule - val composeRule = createComposeRule() - - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - - @Test - fun focusedComposerExpandsToExposeModelControl() { - composeRule.setContent { MobilePreviewComposerFocused() } - composeRule.onNodeWithTag(MOBILE_PREVIEW_COMPOSER_FOCUSED_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(COMPOSER_INPUT_TEST_TAG) - .assertIsDisplayed() - .performTextInput("hello") - composeRule.onNodeWithTag(MODEL_CONTROL_TEST_TAG).assertIsDisplayed() - } - - @Test - fun attachmentComposerShowsFallbackAttachmentSurfaceAndSend() { - composeRule.setContent { MobilePreviewComposerAttachments() } - composeRule.onNodeWithTag(MOBILE_PREVIEW_COMPOSER_ATTACHMENTS_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText(targetContext.getString(R.string.chat_image)).assertIsDisplayed() - composeRule.onNodeWithTag(COMPOSER_SEND_TEST_TAG).assertIsDisplayed() - } - - @Test - fun busyModalShowsItsWorkingCopy() { - composeRule.setContent { MobilePreviewModalBusy() } - composeRule.onNodeWithTag(MOBILE_PREVIEW_MODAL_BUSY_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText("Working…").assertIsDisplayed() - composeRule.onNodeWithText("Please wait while the request finishes.").assertIsDisplayed() - } - - @Test - fun errorModalExposesRecoverySemantics() { - composeRule.setContent { MobilePreviewModalError() } - composeRule.onNodeWithTag(MOBILE_PREVIEW_MODAL_ERROR_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(MOBILE_PREVIEW_MODAL_ERROR_TEXT_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(MOBILE_PREVIEW_MODAL_ERROR_ACTION_TEST_TAG).assertIsDisplayed() - } - - @Test - fun circleStatesHaveStableTouchTargetsAndMoreActionIsSafe() { - composeRule.setContent { MobilePreviewCircleStates() } - composeRule.onNodeWithTag(MOBILE_PREVIEW_CIRCLE_STATES_TEST_TAG).assertIsDisplayed() - // The shared control_touch_size contract is 48dp on all three platforms. - listOf( - MOBILE_PREVIEW_CIRCLE_SIDEBAR_TEST_TAG, - MOBILE_PREVIEW_CIRCLE_MORE_TEST_TAG, - MOBILE_PREVIEW_CIRCLE_BACK_TEST_TAG, - ).forEach { tag -> - composeRule.onNodeWithTag(tag) - .assertIsDisplayed() - .assertWidthIsEqualTo(48.dp) - .assertHeightIsEqualTo(48.dp) - } - composeRule.onNodeWithContentDescription("More actions").performClick() - composeRule.onNodeWithTag(MOBILE_PREVIEW_CIRCLE_MORE_TEST_TAG).assertIsDisplayed() - } - - @Test - fun darkModalStateProducesNonBlankCapturedPixels() { - composeRule.setContent { MobilePreviewModalError(dark = true) } - val image = composeRule.onNodeWithTag(MOBILE_PREVIEW_MODAL_ERROR_TEST_TAG).captureToImage() - val pixelMap = image.toPixelMap() - val center = pixelMap[image.width / 2, image.height / 2].toArgb() - assertTrue( - "Dark modal capture must have a non-transparent center", - (center ushr 24) != 0, - ) - assertTrue( - "Dark modal capture must be dark-themed", - meanLuminance(sampledArgb(image)) < 128.0, - ) - val maxLuminance = (0 until image.height).maxOf { y -> - (0 until image.width).maxOf { x -> argbLuminance(pixelMap[x, y].toArgb()) } - } - assertTrue( - "Dark modal capture must contain drawn light-on-dark content", - maxLuminance > 128.0, - ) - } - - private fun sampledArgb(image: ImageBitmap): List { - val map = image.toPixelMap() - return (0 until 8).flatMap { row -> - (0 until 8).map { column -> - val x = column * (image.width - 1) / 7 - val y = row * (image.height - 1) / 7 - map[x, y].toArgb() - } - } - } - - private fun argbLuminance(argb: Int): Double { - val red = (argb shr 16) and 0xff - val green = (argb shr 8) and 0xff - val blue = argb and 0xff - return 0.2126 * red + 0.7152 * green + 0.0722 * blue - } - - private fun meanLuminance(samples: List): Double = samples.map(::argbLuminance).average() -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileScreenTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileScreenTest.kt deleted file mode 100644 index f57f70aa37..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MobileScreenTest.kt +++ /dev/null @@ -1,294 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.assertIsNotDisplayed -import androidx.compose.ui.test.hasClickAction -import androidx.compose.ui.test.hasText -import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule -import androidx.compose.ui.test.onAllNodesWithTag -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextInput -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.account.ACCOUNT_SETTINGS_DEVICES_TEST_TAG -import com.openbitfun.mobile.app.ui.account.ACCOUNT_SETTINGS_SIGN_IN_TEST_TAG -import com.openbitfun.mobile.app.ui.account.ACCOUNT_SETTINGS_SIGN_OUT_TEST_TAG -import com.openbitfun.mobile.app.ui.remote.CONNECT_ACCOUNT_DEVICE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.SETTINGS_CLOSE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.SETTINGS_MODEL_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.PERMISSION_SECTION_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.SETTINGS_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_ACCOUNT_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_KEY_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_LOCAL_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_MODEL_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_PROBE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_SAVE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_SERVICE_URL_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.SETTINGS_PROFILE_TEST_TAG -import com.openbitfun.mobile.app.ui.shell.MENU_TEST_TAG -import com.openbitfun.mobile.app.ui.shell.sidebar.SIDEBAR_CODE_TEST_TAG -import com.openbitfun.mobile.app.ui.shell.sidebar.SIDEBAR_REMOTE_SESSION_TEST_TAG -import com.openbitfun.mobile.app.ui.shell.sidebar.SIDEBAR_SETTINGS_TEST_TAG -import com.openbitfun.mobile.app.ui.shell.sidebar.SIDEBAR_TEST_TAG -import org.junit.Assume.assumeTrue -import org.junit.Rule -import org.junit.Test - -/** Covers the Android-to-feature seam without requiring a relay or credentials. */ -class MobileScreenTest { - @get:Rule - val composeRule = createAndroidComposeRule() - - private fun text(resource: Int): String = InstrumentationRegistry.getInstrumentation().targetContext.getString(resource) - - @Test - fun welcomeOrDrawerExposesNavigationEntries() { - if (!hasDrawerEntry()) { - composeRule.onNodeWithText(text(R.string.welcome_login)).assertIsDisplayed() - composeRule.onNodeWithText(text(R.string.miniapps_title)).performClick() - composeRule.onNodeWithContentDescription(text(R.string.miniapps_back)).assertIsDisplayed().performClick() - composeRule.onNodeWithText(text(R.string.welcome_login)).assertIsDisplayed() - return - } - composeRule.onNodeWithTag(SIDEBAR_TEST_TAG).assertIsNotDisplayed() - - openDrawer() - composeRule.onNodeWithTag(SIDEBAR_TEST_TAG).assertIsDisplayed() - // The recent list holds general-chat sessions, and a session is only - // stored once something has been sent to it — so a device that has never - // chatted shows the empty state rather than a blank row. - composeRule.onNodeWithText(text(R.string.sidebar_recent_empty)).assertIsDisplayed() - - composeRule.onNodeWithTag(SIDEBAR_CODE_TEST_TAG).performClick() - - // A signed-in drawer reaches desktops only through the account's device - // picker; there is no scan or pairing-link step behind it any more. - waitForTag(CONNECT_ACCOUNT_DEVICE_TEST_TAG) - composeRule.onNodeWithTag(SIDEBAR_TEST_TAG).assertIsNotDisplayed() - } - - /** - * The account has to be reachable, and the drawer has to get out of its way. - * - * Worth an instrumentation test because the account was once reachable only - * from a footer that the signed-in drawer replaces, which left a signed-in - * user with no way back to it at all. The rule that a sheet closes whatever - * opened it lives in `AppShellState`; this is what it looks like on a phone. - * - * Both footers are walked because a device that has signed in once stays - * signed in: pinning the test to the signed-out door would mean it only - * passes on a fresh install, which is the one state the regression it - * guards against cannot happen in. - */ - @Test - fun accountEntryWorksFromWelcomeOrDrawer() { - if (!hasDrawerEntry()) { - composeRule.onNodeWithText(text(R.string.welcome_login)).performClick() - composeRule.onNode(hasText(text(R.string.account_login_title)) and hasClickAction()).assertIsDisplayed() - return - } - openDrawer() - composeRule.onNodeWithTag(SIDEBAR_TEST_TAG).assertIsDisplayed() - - val signedOut = composeRule.onAllNodesWithText(text(R.string.account_login_title)) - .fetchSemanticsNodes() - .isNotEmpty() - if (signedOut) { - composeRule.onNodeWithText(text(R.string.account_login_title)).performClick() - waitForText(text(R.string.account_login_title)) - } else { - // The account is embedded in settings: the gear is the way to it, - // and the page itself shows who is signed in, the devices, and sign - // out, without another page behind a row. - composeRule.onNodeWithTag(SIDEBAR_SETTINGS_TEST_TAG).performClick() - waitForTag(SETTINGS_PROFILE_TEST_TAG) - composeRule.onNodeWithTag(ACCOUNT_SETTINGS_DEVICES_TEST_TAG).assertExists() - composeRule.onNodeWithTag(ACCOUNT_SETTINGS_SIGN_OUT_TEST_TAG).assertExists() - composeRule.onAllNodesWithTag(ACCOUNT_SETTINGS_SIGN_IN_TEST_TAG).assertCountEquals(0) - } - composeRule.onNodeWithTag(SIDEBAR_TEST_TAG).assertIsNotDisplayed() - } - - /** - * The settings page closes by its own button. - * - * The page's body is one long scroll and the sheet does not take a pull-down, - * so a downward drag never dismisses it and this button is the exit that is - * always there. Losing it would strand the page. - */ - @Test - fun theSettingsPageClosesByItsOwnButton() { - openDrawer() - openSettingsFromAuthenticatedDrawerOrSkip() - waitForText(text(R.string.navigation_settings)) - - composeRule.onNodeWithTag(SETTINGS_CLOSE_TEST_TAG).performClick() - - waitForNoText(text(R.string.settings_about_section)) - } - - /** The sidebar gear is the app-settings entry, even over a remote surface. */ - @Test - fun theGearAlwaysOpensRootSettings() { - openDrawer() - openSettingsFromAuthenticatedDrawerOrSkip() - - waitForTag(SETTINGS_TEST_TAG) - composeRule.onNodeWithTag(SETTINGS_MODEL_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(SETTINGS_CLOSE_TEST_TAG).performClick() - waitForNoTag(SETTINGS_TEST_TAG) - - openDrawer() - waitForTag(SIDEBAR_TEST_TAG) - val connectNodes = composeRule.onAllNodesWithTag(SIDEBAR_CODE_TEST_TAG) - .fetchSemanticsNodes() - if (connectNodes.isNotEmpty()) { - composeRule.onNodeWithTag(SIDEBAR_CODE_TEST_TAG).performClick() - } else { - val remoteSessions = composeRule.onAllNodesWithTag(SIDEBAR_REMOTE_SESSION_TEST_TAG) - .fetchSemanticsNodes() - assumeTrue( - "A connected instrumentation device needs at least one remote session", - remoteSessions.isNotEmpty(), - ) - composeRule.onAllNodesWithTag(SIDEBAR_REMOTE_SESSION_TEST_TAG)[0].performClick() - } - waitForTag(MENU_TEST_TAG) - - openDrawer() - waitForTag(SIDEBAR_TEST_TAG) - openSettingsFromAuthenticatedDrawerOrSkip() - - waitForTag(SETTINGS_TEST_TAG) - composeRule.onNodeWithTag(SETTINGS_MODEL_TEST_TAG).assertIsDisplayed() - // One settings page: the permission section is on it whether or not a - // desktop is connected. - composeRule.onNodeWithTag(PERMISSION_SECTION_TEST_TAG).assertExists() - composeRule.onNodeWithTag(SETTINGS_CLOSE_TEST_TAG).performClick() - waitForNoTag(SETTINGS_TEST_TAG) - } - - /** - * The provider editor is the only general-chat path that can be driven - * without a real model endpoint, and it is the one that touches the - * keystore — so it is worth having on a device rather than only in the - * shared store's tests. - */ - @Test - fun modelServiceSheetRefusesAnInvalidApiUrl() { - openGeneralModelService() - composeRule.onNodeWithTag(MODEL_SERVICE_TEST_TAG).assertIsDisplayed() - - // The panel opens on the overview, so the form is one row in. - composeRule.onNodeWithTag(MODEL_SERVICE_LOCAL_TEST_TAG).performClick() - composeRule.onNodeWithTag(MODEL_SERVICE_URL_TEST_TAG).performTextInput("api.example.com") - composeRule.onNodeWithTag(MODEL_SERVICE_MODEL_TEST_TAG).performTextInput("chat-model") - composeRule.onNodeWithTag(MODEL_SERVICE_KEY_TEST_TAG).performTextInput("instrumentation-key") - composeRule.onNodeWithTag(MODEL_SERVICE_SAVE_TEST_TAG).performClick() - - // Refused, and still on the form: the reason has to sit next to the field - // that caused it, which the overview has none of. - composeRule.onNodeWithText(text(R.string.model_service_invalid_url)) - .assertIsDisplayed() - composeRule.onNodeWithTag(MODEL_SERVICE_URL_TEST_TAG).assertIsDisplayed() - } - - /** - * The account section is a row that is always there, saying what it has. - * - * Whether it has anything depends on who is signed in on the device running - * this, so the assertion is that the section exists at all: "nothing synced" - * and "no such feature" look identical to a user unless the row is present to - * tell them apart, which is exactly what this panel used to get wrong by - * omitting the section entirely. - */ - @Test - fun theModelPanelSaysWhatTheAccountHasSynced() { - openGeneralModelService() - - composeRule.onNodeWithText(text(R.string.model_service_account_section)).assertIsDisplayed() - composeRule.onNodeWithTag(MODEL_SERVICE_ACCOUNT_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText(text(R.string.model_service_account_summary)).assertIsDisplayed() - } - - /** - * A probe with nothing to send is refused by the button, not by the endpoint. - * - * Without this the button is live on an empty form, and the first thing a new - * user learns about their provider is a 401 that says nothing about the fact - * that this app never sent a credential — the request was always going to fail - * and the failure describes the wrong thing. - */ - @Test - fun theConnectionTestWaitsForSomethingToAuthenticateWith() { - openGeneralModelService() - composeRule.onNodeWithTag(MODEL_SERVICE_LOCAL_TEST_TAG).performClick() - - composeRule.onNodeWithTag(MODEL_SERVICE_PROBE_TEST_TAG).assertIsNotEnabled() - composeRule.onNodeWithText(text(R.string.model_service_test_needs_key)) - .assertIsDisplayed() - - composeRule.onNodeWithTag(MODEL_SERVICE_KEY_TEST_TAG).performTextInput("instrumentation-key") - - composeRule.onNodeWithTag(MODEL_SERVICE_PROBE_TEST_TAG).assertIsEnabled() - } - - private fun waitForText(text: String, substring: Boolean = false, timeoutMillis: Long = 20_000) { - composeRule.waitUntil(timeoutMillis = timeoutMillis) { - composeRule.onAllNodesWithText(text, substring = substring) - .fetchSemanticsNodes() - .isNotEmpty() - } - } - - /** The other half of [waitForText]: a sheet leaves over an animation, not at once. */ - private fun waitForNoText(text: String, timeoutMillis: Long = 20_000) { - composeRule.waitUntil(timeoutMillis = timeoutMillis) { - composeRule.onAllNodesWithText(text).fetchSemanticsNodes().isEmpty() - } - } - - private fun waitForTag(tag: String, timeoutMillis: Long = 20_000) { - composeRule.waitUntil(timeoutMillis = timeoutMillis) { - composeRule.onAllNodesWithTag(tag).fetchSemanticsNodes().isNotEmpty() - } - } - - private fun waitForNoTag(tag: String, timeoutMillis: Long = 20_000) { - composeRule.waitUntil(timeoutMillis = timeoutMillis) { - composeRule.onAllNodesWithTag(tag).fetchSemanticsNodes().isEmpty() - } - } - - private fun hasDrawerEntry(): Boolean = composeRule.onAllNodesWithTag(MENU_TEST_TAG).fetchSemanticsNodes().isNotEmpty() - - private fun openDrawer() { - assumeTrue("This path requires an authenticated shell; signed-out welcome is covered separately", hasDrawerEntry()) - composeRule.onNodeWithTag(MENU_TEST_TAG).performClick() - } - - private fun openSettingsFromAuthenticatedDrawerOrSkip() { - val settingsNodes = composeRule.onAllNodesWithTag(SIDEBAR_SETTINGS_TEST_TAG) - .fetchSemanticsNodes() - assumeTrue( - "Settings footer is only available when the instrumentation device is signed in", - settingsNodes.isNotEmpty(), - ) - composeRule.onNodeWithTag(SIDEBAR_SETTINGS_TEST_TAG).performClick() - } - - private fun openGeneralModelService() { - openDrawer() - openSettingsFromAuthenticatedDrawerOrSkip() - waitForText(text(R.string.navigation_settings)) - composeRule.onNodeWithTag(SETTINGS_MODEL_TEST_TAG).performClick() - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/NotificationOnboardingTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/NotificationOnboardingTest.kt deleted file mode 100644 index 2cdc588145..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/NotificationOnboardingTest.kt +++ /dev/null @@ -1,72 +0,0 @@ -package com.openbitfun.mobile.app - -import android.content.Context -import android.content.ContextWrapper -import android.content.SharedPreferences -import android.content.pm.PackageManager -import androidx.activity.compose.LocalActivityResultRegistryOwner -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.platform.NotificationOnboarding as OnboardingStore -import com.openbitfun.mobile.app.ui.shell.NotificationOnboarding -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class NotificationOnboardingTest { - @get:Rule val composeRule = createComposeRule() - - @Test fun laterPersistsAndDoesNotRequestSystemPermission() { - val base = InstrumentationRegistry.getInstrumentation().targetContext - val name = "notification_onboarding_test_${System.nanoTime()}" - val context = object : ContextWrapper(base) { - override fun getSharedPreferences(ignored: String, mode: Int): SharedPreferences = - base.getSharedPreferences(name, mode) - override fun checkSelfPermission(permission: String) = PackageManager.PERMISSION_DENIED - } - try { - // Missing keys from an older install remain readable and offer onboarding. - assertTrue(OnboardingStore(context).shouldOffer()) - composeRule.setContent { - val registryOwner = requireNotNull(LocalActivityResultRegistryOwner.current) - CompositionLocalProvider( - LocalContext provides context, - LocalActivityResultRegistryOwner provides registryOwner, - ) { - OpenBitFunTheme(dark = false) { NotificationOnboarding() } - } - } - composeRule.onNodeWithText(context.getString(R.string.notification_onboarding_title)).assertIsDisplayed() - composeRule.onNodeWithText(context.getString(R.string.notification_onboarding_later)).performClick() - composeRule.waitForIdle() - assertFalse(OnboardingStore(context).shouldOffer()) - composeRule.onNodeWithText(context.getString(R.string.notification_onboarding_title)).assertDoesNotExist() - } finally { - base.deleteSharedPreferences(name) - } - } - - @Test fun existingGrantSkipsIntroductionWithoutResettingStoredData() { - val base = InstrumentationRegistry.getInstrumentation().targetContext - val name = "notification_onboarding_test_${System.nanoTime()}" - val context = object : ContextWrapper(base) { - override fun getSharedPreferences(ignored: String, mode: Int): SharedPreferences = - base.getSharedPreferences(name, mode) - override fun checkSelfPermission(permission: String) = PackageManager.PERMISSION_GRANTED - } - try { - context.getSharedPreferences(name, 0).edit().putString("future_field", "retained").commit() - assertFalse(OnboardingStore(context).shouldOffer()) - assertTrue(context.getSharedPreferences(name, 0).contains("future_field")) - } finally { - base.deleteSharedPreferences(name) - } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/PermissionModeCardTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/PermissionModeCardTest.kt deleted file mode 100644 index 2d195e8a94..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/PermissionModeCardTest.kt +++ /dev/null @@ -1,155 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import com.openbitfun.mobile.app.ui.settings.FULL_ACCESS_CONFIRM_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.PERMISSION_SECTION_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.PermissionSection -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.SessionAgentFilter -import com.openbitfun.mobile.core.feature.session.SessionPermissionMode -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class PermissionModeCardTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun knownModesRenderAndSelectingAutoDispatches() { - val intents = mutableListOf() - setPermissionContent( - permissionMode = SessionPermissionMode.ASK, - onIntent = { intents += it }, - ) - - composeRule.onNodeWithText(testString(R.string.permission_ask)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.permission_auto)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.permission_full)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.permission_auto)).performClick() - - assertEquals( - listOf(RemoteSessionIntent.SetPermissionMode(SessionPermissionMode.AUTO)), - intents, - ) - } - - @Test - fun fullAccessRequiresConfirmationAndCanBeCancelled() { - val intents = mutableListOf() - setPermissionContent( - permissionMode = SessionPermissionMode.ASK, - onIntent = { intents += it }, - ) - - composeRule.onNodeWithText(testString(R.string.permission_full)).performClick() - assertTrue(intents.isEmpty()) - composeRule.onNodeWithTag(FULL_ACCESS_CONFIRM_TEST_TAG).assertIsDisplayed() - - composeRule.onNodeWithText(testString(R.string.common_cancel)).performClick() - composeRule.onNodeWithTag(FULL_ACCESS_CONFIRM_TEST_TAG).assertDoesNotExist() - assertTrue(intents.isEmpty()) - - composeRule.onNodeWithText(testString(R.string.permission_full)).performClick() - composeRule.onNodeWithText(testString(R.string.permission_full_confirm_action)).performClick() - assertEquals( - listOf(RemoteSessionIntent.SetPermissionMode(SessionPermissionMode.FULL_ACCESS)), - intents, - ) - } - - @Test - fun unknownModeExplainsFailureDisablesModesAndLeavesRefreshEnabled() { - setPermissionContent(permissionMode = SessionPermissionMode.UNKNOWN) - - composeRule - .onNodeWithText(testString(R.string.permission_unknown)) - .assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.permission_ask)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_auto)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_full)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.account_devices_refresh)).assertIsEnabled() - } - - @Test - fun disconnectedStateExplainsConnectionAndDisablesModes() { - setPermissionContent( - permissionMode = SessionPermissionMode.ASK, - connected = false, - ) - - composeRule - .onNodeWithText(testString(R.string.permission_needs_connection)) - .assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.permission_ask)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_auto)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_full)).assertIsNotEnabled() - } - - @Test - fun withoutAReadySessionTheSectionStaysVisibleButDisabled() { - val intents = mutableListOf() - composeRule.setContent { - OpenBitFunTheme(dark = false) { - PermissionSection( - state = null, - connected = false, - onIntent = { intents += it }, - modifier = Modifier, - ) - } - } - - composeRule.onNodeWithTag(PERMISSION_SECTION_TEST_TAG).assertIsDisplayed() - composeRule - .onNodeWithText(testString(R.string.permission_needs_connection)) - .assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.permission_ask)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_auto)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_full)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.permission_full)).performClick() - composeRule.onNodeWithTag(FULL_ACCESS_CONFIRM_TEST_TAG).assertDoesNotExist() - assertTrue(intents.isEmpty()) - } - - private fun setPermissionContent( - permissionMode: SessionPermissionMode?, - connected: Boolean = true, - onIntent: (RemoteSessionIntent) -> Unit = {}, - ) { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - PermissionSection( - state = readyState(permissionMode), - connected = connected, - onIntent = onIntent, - modifier = Modifier, - ) - } - } - } - - private fun readyState(permissionMode: SessionPermissionMode?) = RemoteSessionUiState.Ready( - sessions = emptyList(), - selectedSessionId = null, - timeline = null, - busy = false, - permissionMode = permissionMode, - permissionModeFailure = null, - query = "", - agentFilter = SessionAgentFilter.ALL, - hasMore = false, - hasMoreMessages = false, - modelCatalog = null, - ) -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/QuestionDraftTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/QuestionDraftTest.kt deleted file mode 100644 index 908c0f3e90..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/QuestionDraftTest.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.ui.chat.PermissionMailboxView -import com.openbitfun.mobile.core.feature.session.* -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.chat.tool.ToolQuestionAnswerPanel -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -class QuestionDraftTest { - @get:Rule val compose = createComposeRule() - - @Test fun mailboxOwnsTheOnlyAnswerFormWhileTranscriptKeepsItsSummary() { - val question = ToolCard("question", "AskUserQuestion", ToolPhase.RUNNING, - ToolKind.QUESTION, ToolOperation.UNKNOWN, "", "", "", "", "", "One answer only", setOf(ToolAction.ANSWER)) - val mailbox = mutableStateOf(PermissionMailboxUiState(emptyList(), false, false, listOf(question))) - compose.setContent { - OpenBitFunTheme(dark = false) { - androidx.compose.runtime.CompositionLocalProvider( - com.openbitfun.mobile.app.ui.chat.tool.LocalPermissionMailbox provides mailbox.value, - ) { - androidx.compose.foundation.layout.Column { - PermissionMailboxView(mailbox.value, "session", 400.dp) {} - com.openbitfun.mobile.app.ui.chat.tool.ToolStatusList( - listOf(question), true, { _, _ -> }, { _, _ -> }, { _, _ -> }, - { _, _ -> }, { _, _ -> }, { _, _ -> }, androidx.compose.ui.Modifier, - ) - } - } - } - } - compose.onAllNodes(hasSetTextAction()).assertCountEquals(1) - compose.onNodeWithTag(com.openbitfun.mobile.app.ui.chat.tool.TOOL_ROW_TEST_TAG).assertExists() - compose.onNode(hasSetTextAction()).performTextReplacement("Single draft") - compose.onNodeWithText("One answer only").assertExists() - compose.runOnIdle { mailbox.value = mailbox.value.copy(questions = emptyList(), ownedToolIds = setOf(question.id)) } - compose.onAllNodes(hasSetTextAction()).assertCountEquals(0) - compose.onNodeWithTag(com.openbitfun.mobile.app.ui.chat.tool.TOOL_ROW_TEST_TAG).assertExists() - // No mailbox authority on a legacy peer: its transcript still provides the answer UI. - compose.runOnIdle { mailbox.value = PermissionMailboxUiState(emptyList(), false, false) } - compose.onAllNodes(hasSetTextAction()).assertCountEquals(1) - } - - @Test fun removingAnEarlierMailboxQuestionPreservesTheRemainingDraft() { - fun question(id: String) = ToolCard(id, "AskUserQuestion", ToolPhase.RUNNING, - ToolKind.QUESTION, ToolOperation.UNKNOWN, "", "", "", "", "", "Question $id", setOf(ToolAction.ANSWER)) - val questions = mutableStateOf(listOf(question("first"), question("second"))) - compose.setContent { - OpenBitFunTheme(dark = false) { - PermissionMailboxView(PermissionMailboxUiState(emptyList(), false, false, questions.value), "session", 700.dp) {} - } - } - compose.onAllNodes(hasSetTextAction())[1].performTextReplacement("Second question draft") - compose.runOnIdle { questions.value = questions.value.drop(1) } - compose.onNode(hasSetTextAction()).assertTextContains("Second question draft") - compose.onNodeWithText("Question first").assertDoesNotExist() - } - - @Test fun answerSurvivesPendingAndFailedSubmissionButNewQuestionStartsEmpty() { - val question = mutableStateOf("question-1") - val enabled = mutableStateOf(true) - val answers = mutableListOf() - compose.setContent { - OpenBitFunTheme(dark = false) { - ToolQuestionAnswerPanel(question.value, "Explain the change", enabled.value) { - answers += it - enabled.value = false - } - } - } - val label = InstrumentationRegistry.getInstrumentation().targetContext.getString(R.string.tool_answer_send) - compose.onNode(hasSetTextAction()).performTextReplacement("Keep this draft") - compose.onNodeWithText(label).performClick() - compose.onNodeWithText("Keep this draft").assertIsNotEnabled() - compose.runOnIdle { enabled.value = true } - compose.onNode(hasSetTextAction()).assertTextContains("Keep this draft") - compose.onNodeWithText(label).performClick() - compose.runOnIdle { - assertEquals(listOf("Keep this draft", "Keep this draft"), answers) - question.value = "question-2" - enabled.value = true - } - compose.onNode(hasSetTextAction()).assertTextContains("") - compose.onNodeWithText(label).assertIsNotEnabled() - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSessionListViewTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSessionListViewTest.kt deleted file mode 100644 index 02ed261f86..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSessionListViewTest.kt +++ /dev/null @@ -1,144 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import com.openbitfun.mobile.app.ui.remote.ChatCreateControl -import com.openbitfun.mobile.app.ui.remote.ProjectCreateControl -import com.openbitfun.mobile.app.ui.remote.RemoteSessionListView -import com.openbitfun.mobile.app.ui.remote.SESSION_CHAT_CREATE_TEST_TAG -import com.openbitfun.mobile.app.ui.remote.SESSION_PROJECT_CREATE_TEST_TAG_PREFIX -import com.openbitfun.mobile.app.ui.remote.SESSION_SEARCH_FIELD_TEST_TAG -import com.openbitfun.mobile.app.ui.remote.SESSION_SEARCH_TOGGLE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.VIEW_SETTINGS_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.VIEW_SETTINGS_TOGGLE_TEST_TAG -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementMode -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -class RemoteSessionListViewTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun remoteListUsesTheCompactSidebarHeader() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - RemoteSessionListView( - state = RemoteSessionUiState.Idle, - workspaceState = RemoteWorkspaceUiState.Idle, - compact = true, - sessionDetailsPlacement = compactPlacement, - viewSettingsPlacement = compactPlacement, - connectionDetails = {}, - onIntent = {}, - onWorkspaceIntent = {}, - onOpen = {}, - onCreate = {}, - modifier = Modifier, - ) - } - } - - composeRule.onNodeWithText(testString(R.string.app_name)).assertIsDisplayed() - composeRule.onNodeWithTag(VIEW_SETTINGS_TOGGLE_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(SESSION_SEARCH_TOGGLE_TEST_TAG).assertIsDisplayed() - composeRule.onAllNodesWithText(testString(R.string.sessions_title)).assertCountEquals(0) - composeRule.onAllNodesWithText(testString(R.string.sessions_filter_all)).assertCountEquals(0) - - composeRule.onNodeWithTag(SESSION_SEARCH_FIELD_TEST_TAG).assertDoesNotExist() - composeRule.onNodeWithTag(SESSION_SEARCH_TOGGLE_TEST_TAG).performClick() - composeRule.onNodeWithTag(SESSION_SEARCH_FIELD_TEST_TAG).assertIsDisplayed() - } - - @Test - fun viewSettingsOpensAsASheetInsteadOfExpandingTheList() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - RemoteSessionListView( - state = RemoteSessionUiState.Ready( - sessions = emptyList(), - selectedSessionId = null, - timeline = null, - busy = false, - permissionMode = null, - permissionModeFailure = null, - query = "", - agentFilter = com.openbitfun.mobile.core.feature.session.SessionAgentFilter.ALL, - hasMore = false, - hasMoreMessages = false, - modelCatalog = null, - ), - workspaceState = RemoteWorkspaceUiState.Idle, - compact = true, - sessionDetailsPlacement = compactPlacement, - viewSettingsPlacement = compactPlacement, - connectionDetails = {}, - onIntent = {}, - onWorkspaceIntent = {}, - onOpen = {}, - onCreate = {}, - modifier = Modifier, - ) - } - } - - composeRule.onNodeWithTag(VIEW_SETTINGS_TEST_TAG).assertDoesNotExist() - composeRule.onNodeWithTag(VIEW_SETTINGS_TOGGLE_TEST_TAG).performClick() - composeRule.onNodeWithTag(VIEW_SETTINGS_TEST_TAG).assertIsDisplayed() - } - - @Test - fun projectCreateUsesAnAnchoredCodeCoworkMenu() { - val open = mutableStateOf(false) - var agentType: String? = null - val path = "/work/openbitfun" - - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ProjectCreateControl( - path = path, - expanded = open.value, - onToggle = { open.value = !open.value }, - onDismiss = { open.value = false }, - onCreateAgent = { agentType = it }, - ) - } - } - - composeRule.onNodeWithTag(SESSION_PROJECT_CREATE_TEST_TAG_PREFIX + path).performClick() - composeRule.onNodeWithText(testString(R.string.sessions_filter_code)).assertIsDisplayed().performClick() - assertEquals("code", agentType) - } - - @Test - fun chatSectionCreateIsASectionAnchoredAction() { - var clicked = false - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ChatCreateControl(onCreate = { clicked = true }) - } - } - - composeRule.onNodeWithTag(SESSION_CHAT_CREATE_TEST_TAG).assertIsDisplayed().performClick() - assertEquals(true, clicked) - } -} - -private val compactPlacement = SettingsPlacement( - mode = SettingsPlacementMode.BOTTOM, - width = 0, - height = 0, - maxHeight = 0, -) diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSettingsSheetTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSettingsSheetTest.kt deleted file mode 100644 index c014e30fc6..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RemoteSettingsSheetTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import com.openbitfun.mobile.app.ui.settings.MODEL_CATALOG_FAILURE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.MODEL_CATALOG_RETRY_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.RemoteSettingsSheet -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.session.ModelCatalogFailure -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.SessionAgentFilter -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class RemoteSettingsSheetTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun transientCatalogFailureShowsAnErrorAndRetryDispatchesTheIntent() { - val intents = mutableListOf() - setSheetContent( - state = readyState(modelCatalogFailure = ModelCatalogFailure.LOAD_FAILED), - onIntent = { intents += it }, - ) - - composeRule - .onNodeWithTag(MODEL_CATALOG_FAILURE_TEST_TAG) - .assertIsDisplayed() - composeRule - .onNodeWithText(testString(R.string.model_catalog_load_failed)) - .assertIsDisplayed() - composeRule - .onNodeWithTag(MODEL_CATALOG_RETRY_TEST_TAG) - .assertIsDisplayed() - .performClick() - - assertEquals( - listOf(RemoteSessionIntent.RefreshModelCatalog), - intents, - ) - } - - @Test - fun unsupportedByPeerIsExplicitAndOffersNoRetry() { - val intents = mutableListOf() - setSheetContent( - state = readyState(modelCatalogFailure = ModelCatalogFailure.UNSUPPORTED_BY_PEER), - onIntent = { intents += it }, - ) - - composeRule - .onNodeWithText( - testString(R.string.model_catalog_unsupported), - ) - .assertIsDisplayed() - composeRule.onNodeWithTag(MODEL_CATALOG_RETRY_TEST_TAG).assertDoesNotExist() - assertTrue(intents.isEmpty()) - } - - private fun setSheetContent( - state: RemoteSessionUiState.Ready, - onIntent: (RemoteSessionIntent) -> Unit = {}, - ) { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - RemoteSettingsSheet( - state = state, - sessionId = "s-code", - onIntent = onIntent, - modifier = Modifier, - ) - } - } - } - - private fun readyState(modelCatalogFailure: ModelCatalogFailure?) = RemoteSessionUiState.Ready( - sessions = emptyList(), - selectedSessionId = "s-code", - timeline = null, - busy = false, - permissionMode = null, - permissionModeFailure = null, - query = "", - agentFilter = SessionAgentFilter.ALL, - hasMore = false, - hasMoreMessages = false, - modelCatalog = null, - modelCatalogFailure = modelCatalogFailure, - draft = "", - ) -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileBrowserTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileBrowserTest.kt deleted file mode 100644 index b7e1303854..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileBrowserTest.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.openbitfun.mobile.app - -import android.graphics.Bitmap -import java.io.File -import androidx.compose.foundation.layout.Column -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.remote.RuntimeFilesDialog -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.workspace.* -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -class RuntimeFileBrowserTest { - @get:Rule val compose = createComposeRule() - private fun text(id: Int) = InstrumentationRegistry.getInstrumentation().targetContext.getString(id) - - @Test fun changingSortResetsAnchorButAppendingPreservesIt() { - val entries = (0 until 80).map { RuntimeFileUiState("/repo/$it", "entry-$it", false) } - val files = RuntimeFilesUiState("/repo", entries, false, null, "", false, false) - val state = mutableStateOf(RemoteWorkspaceUiState.Ready(emptyList(), emptyList(), null, RemoteFilePreviewUiState.None, false, RemoteFileDownloadUiState.None).copy(files = files)) - compose.setContent { - OpenBitFunTheme(dark = false) { RuntimeFilesDialog(state.value, onBack = {}, onIntent = {}) } - } - compose.onNode(hasScrollToIndexAction()).performScrollToIndex(30) - compose.onNodeWithText("entry-30").assertIsDisplayed() - compose.runOnIdle { - state.value = state.value.copy(files = files.copy(entries = entries + RuntimeFileUiState("/repo/80", "entry-80", false))) - } - compose.onNodeWithText("entry-30").assertIsDisplayed() - compose.runOnIdle { - state.value = state.value.copy(files = files.copy(sort = RuntimeFileSort.NAME_DESC, entries = entries.reversed())) - } - compose.onNodeWithText("entry-79").assertIsDisplayed() - compose.runOnIdle { - state.value = state.value.copy(files = files.copy(directory = "/other")) - } - compose.onNodeWithText("entry-0").assertIsDisplayed() - } - - private fun capture(name: String) { - compose.waitForIdle() - val instrumentation = InstrumentationRegistry.getInstrumentation() - val bitmap = instrumentation.uiAutomation.takeScreenshot() - File(instrumentation.targetContext.getExternalFilesDir(null), name).outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } - bitmap.recycle() - } - - @Test fun rowRenameRetainsFailedDraftAndFastRetryClosesForm() { - val files = RuntimeFilesUiState("/repo", listOf(RuntimeFileUiState("/repo/report.md", "report.md", false)), false, null, "", false, false) - val state = mutableStateOf(RemoteWorkspaceUiState.Ready(emptyList(), emptyList(), null, RemoteFilePreviewUiState.None, false, RemoteFileDownloadUiState.None).copy(files = files)) - val intents = mutableListOf() - compose.setContent { - OpenBitFunTheme(dark = false) { - RuntimeFilesDialog(state.value, onBack = {}, onIntent = { intent -> - intents += intent - if (intent is RemoteWorkspaceIntent.RenameFileEntry) { - val current = state.value.files - state.value = state.value.copy(files = current.copy(failed = intents.size == 1, completedOperation = current.completedOperation + 1)) - } - }) - } - } - compose.onAllNodes(hasSetTextAction()).assertCountEquals(0) - capture("file-browser-list.png") - compose.onNodeWithContentDescription(text(R.string.workspace_file_actions)).performClick() - compose.onNodeWithText(text(R.string.session_rename)).performClick() - compose.onNode(hasSetTextAction()).performTextReplacement("renamed.md") - compose.onAllNodesWithText(text(R.string.session_rename)).filter(hasClickAction()).onFirst().performClick() - compose.onNode(hasSetTextAction()).assertTextContains("renamed.md") - compose.onNodeWithText(text(R.string.workspace_files_failed)).assertIsDisplayed() - capture("file-browser-failed-form.png") - compose.runOnIdle { - val intent = intents.single() as RemoteWorkspaceIntent.RenameFileEntry - assertEquals("/repo/report.md", intent.path) - assertEquals("renamed.md", intent.name) - } - compose.onAllNodesWithText(text(R.string.session_rename)).filter(hasClickAction()).onFirst().performClick() - compose.onAllNodes(hasSetTextAction()).assertCountEquals(0) - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileEditorTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileEditorTest.kt deleted file mode 100644 index f145d95b3b..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeFileEditorTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.remote.RuntimeFileEditorDialog -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RuntimeFilesUiState -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class RuntimeFileEditorTest { - @get:Rule val compose = createComposeRule() - private fun text(id: Int) = InstrumentationRegistry.getInstrumentation().targetContext.getString(id) - - @Test fun failedSavePreservesDraftAndCancelledDiscardKeepsEditorOpen() { - val state = mutableStateOf(RuntimeFilesUiState("/repo", emptyList(), false, "/repo/file.md", "original", false, false)) - val intents = mutableListOf() - compose.setContent { - OpenBitFunTheme(dark = false) { - RuntimeFileEditorDialog(state.value) { intents += it } - } - } - compose.onNode(hasSetTextAction()).performTextReplacement("unsaved draft") - compose.onNodeWithText(text(R.string.workspace_save_file)).performClick() - compose.runOnIdle { - assertEquals("unsaved draft", (intents.single() as RemoteWorkspaceIntent.SaveFile).content) - state.value = state.value.copy(failed = true) - } - compose.onNode(hasSetTextAction()).assertTextEquals("unsaved draft") - compose.onNodeWithText(text(R.string.workspace_files_failed)).assertIsDisplayed() - compose.onNodeWithText(text(R.string.common_back)).performClick() - compose.onNodeWithText(text(R.string.workspace_discard_changes)).assertIsDisplayed() - compose.onNodeWithText(text(R.string.common_cancel)).performClick() - compose.onNode(hasSetTextAction()).assertTextEquals("unsaved draft") - compose.runOnIdle { assertEquals(1, intents.size) } - compose.onNodeWithText(text(R.string.common_back)).performClick() - compose.onNodeWithText(text(R.string.workspace_discard)).performClick() - compose.runOnIdle { assertTrue(intents.last() is RemoteWorkspaceIntent.CloseFileEditor) } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeTerminalViewTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeTerminalViewTest.kt deleted file mode 100644 index 67a84bacde..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeTerminalViewTest.kt +++ /dev/null @@ -1,123 +0,0 @@ -package com.openbitfun.mobile.app - -import android.view.KeyEvent -import android.webkit.WebView -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.remote.RuntimeTerminalDialog -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RuntimeTerminalUiState -import java.util.concurrent.CopyOnWriteArrayList -import org.junit.Assert.assertEquals -import org.junit.Assert.assertSame -import org.json.JSONTokener -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicReference -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -class RuntimeTerminalViewTest { - @get:Rule val compose = createComposeRule() - - @Test fun touchingTerminalRoutesNativeKeysToPtyInsteadOfDialogButtons() { - val intents = CopyOnWriteArrayList() - var dismissed = false - compose.setContent { - OpenBitFunTheme(dark = false) { - RuntimeTerminalDialog( - RuntimeTerminalUiState("test-pty", "ready\r\n", false, false), - { intents += it }, - { dismissed = true }, - ) - } - } - compose.waitUntil(10_000) { intents.any { it is RemoteWorkspaceIntent.ResizeTerminal } } - onView(isAssignableFrom(WebView::class.java)).perform(click()).check { view, error -> - if (error != null) throw error - assertTrue("The native WebView must own focus, not only its DOM textarea", view.hasFocus()) - } - val instrumentation = InstrumentationRegistry.getInstrumentation() - instrumentation.sendStringSync("pwd") - instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER) - compose.waitUntil(10_000) { - intents.filterIsInstance().joinToString("") { it.data } == "pwd\r" - } - compose.runOnIdle { - assertFalse(dismissed) - assertFalse(intents.any { it is RemoteWorkspaceIntent.CloseTerminal }) - } - } - - @Test fun switchingThemeKeepsTheNativeTerminalAndItsOutput() { - val dark = mutableStateOf(false) - val intents = CopyOnWriteArrayList() - compose.setContent { - OpenBitFunTheme(dark = dark.value) { - RuntimeTerminalDialog(RuntimeTerminalUiState("theme-pty", "retained output\r\n", false, false), { intents += it }, {}) - } - } - compose.waitUntil(10_000) { intents.any { it is RemoteWorkspaceIntent.ResizeTerminal } } - var terminal: WebView? = null - onView(isAssignableFrom(WebView::class.java)).check { view, error -> - if (error != null) throw error - terminal = view as WebView - } - val webView = requireNotNull(terminal) - fun snapshot(): String { - val result = AtomicReference("") - val completed = CountDownLatch(1) - InstrumentationRegistry.getInstrumentation().runOnMainSync { - webView.evaluateJavascript("JSON.stringify({background:getComputedStyle(document.querySelector('.xterm')).backgroundColor,text:document.querySelector('.xterm-rows').textContent})") { - result.set(JSONTokener(it).nextValue().toString()) - completed.countDown() - } - } - assertTrue("Renderer must answer while changing theme", completed.await(5, TimeUnit.SECONDS)) - return result.get() - } - compose.waitUntil(10_000) { snapshot().contains("retained output") } - val light = snapshot() - compose.runOnIdle { dark.value = true } - compose.waitUntil(10_000) { snapshot() != light } - assertTrue(snapshot().contains("retained output")) - onView(isAssignableFrom(WebView::class.java)).check { view, error -> - if (error != null) throw error - assertSame("A theme update must not recreate the PTY renderer", webView, view) - } - compose.runOnIdle { dark.value = false } - compose.waitUntil(10_000) { snapshot() == light } - assertEquals(light, snapshot()) - assertFalse(intents.any { it is RemoteWorkspaceIntent.CloseTerminal || it is RemoteWorkspaceIntent.ReopenTerminal }) - } - - @Test fun terminalControlsFollowSharedCloseStateAndOfferScopedReopen() { - val intents = CopyOnWriteArrayList() - val state = mutableStateOf(RuntimeTerminalUiState("pty", "", false, false)) - val context = InstrumentationRegistry.getInstrumentation().targetContext - compose.setContent { - OpenBitFunTheme(dark = false) { RuntimeTerminalDialog(state.value, { intents += it }, {}) } - } - compose.onNodeWithText(context.getString(R.string.message_stop)).performClick() - compose.runOnIdle { assertTrue(intents.filterIsInstance().single().data == "\u0003") } - val close = context.getString(R.string.workspace_terminal_close) - compose.onNodeWithText(close).performClick() - compose.runOnIdle { state.value = state.value.copy(busy = true) } - compose.onNodeWithText(close).assertIsNotEnabled() - compose.runOnIdle { state.value = state.value.copy(busy = false, failed = true) } - compose.onNodeWithText(close).assertIsEnabled() - compose.onNodeWithText(context.getString(R.string.workspace_terminal_failed)).assertIsDisplayed() - compose.runOnIdle { state.value = RuntimeTerminalUiState(null, "", false, false) } - compose.onNodeWithText(close).assertDoesNotExist() - compose.onNodeWithText(context.getString(R.string.workspace_open_terminal)).performClick() - compose.runOnIdle { assertTrue(intents.any { it is RemoteWorkspaceIntent.ReopenTerminal }) } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeWorkspacePickerTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeWorkspacePickerTest.kt deleted file mode 100644 index 2c9a1a950b..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/RuntimeWorkspacePickerTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.runtime.mutableStateOf -import androidx.compose.ui.test.* -import androidx.compose.ui.test.junit4.createComposeRule -import androidx.compose.ui.test.junit4.StateRestorationTester -import androidx.test.platform.app.InstrumentationRegistry -import com.openbitfun.mobile.app.ui.remote.RuntimeWorkspacePickerDialog -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.workspace.* -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -class RuntimeWorkspacePickerTest { - @get:Rule val compose = createComposeRule() - - @Test fun recreationRetainsDraftAndDoesNotReplayWorkspaceMutation() { - val restoration = StateRestorationTester(compose) - val state = mutableStateOf(RemoteWorkspaceUiState.Ready(emptyList(), emptyList(), null, - RemoteFilePreviewUiState.None, false, RemoteFileDownloadUiState.None)) - val intents = mutableListOf() - restoration.setContent { - OpenBitFunTheme(dark = true) { - RuntimeWorkspacePickerDialog(state.value, onIntent = { - intents += it - state.value = state.value.copy(busy = true) - }, onDismiss = {}) - } - } - compose.onNode(hasSetTextAction()).performTextReplacement("/workspace/draft") - restoration.emulateSavedInstanceStateRestore() - compose.onNode(hasSetTextAction()).assertTextContains("/workspace/draft") - compose.runOnIdle { assertEquals(0, intents.size) } - val open = InstrumentationRegistry.getInstrumentation().targetContext.getString(R.string.workspace_open_path) - compose.onAllNodesWithText(open).filter(hasClickAction()).onFirst().performClick() - restoration.emulateSavedInstanceStateRestore() - compose.runOnIdle { - assertEquals(1, intents.size) - state.value = state.value.copy(busy = false, loadFailure = true) - } - compose.onNode(hasSetTextAction()).assertTextContains("/workspace/draft") - compose.runOnIdle { assertEquals(1, intents.size) } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/SymbolDrawableTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/SymbolDrawableTest.kt deleted file mode 100644 index 27d393724d..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/SymbolDrawableTest.kt +++ /dev/null @@ -1,57 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.foundation.layout.size -import androidx.compose.material3.Icon -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.unit.dp -import androidx.test.platform.app.InstrumentationRegistry -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test - -/** - * Every glyph the app draws, drawn once. - * - * These are the HarmonyOS `sys.symbol` set redrawn by hand as vectors, and a - * vector with a malformed `pathData` compiles, links, and only then throws — on - * the one screen that happens to use it. Half of them live on surfaces that need - * a paired desktop to reach, so inflating the whole set here is the only check - * that does not depend on which screen someone remembered to open. - */ -class SymbolDrawableTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun everySymbolDrawableInflatesAndDraws() { - val ids = symbolDrawableIds() - // A guard on the guard: were the field scan to come back empty, the test - // would pass while checking nothing at all. - assertTrue("Expected the redrawn symbol set, found ${ids.size}", ids.size >= 40) - - composeRule.setContent { - ids.forEach { (_, id) -> - Icon( - painterResource(id), - contentDescription = null, - modifier = Modifier.size(24.dp), - ) - } - } - composeRule.waitForIdle() - } - - /** Every `R.drawable.ic_symbol_*`, read off the generated class. */ - private fun symbolDrawableIds(): List> { - val context = InstrumentationRegistry.getInstrumentation().targetContext - return R.drawable::class.java.fields - .filter { it.name.startsWith("ic_symbol_") } - .map { it.name to it.getInt(null) } - .onEach { (name, id) -> - assertTrue(name, context.resources.getResourceEntryName(id) == name) - } - .sortedBy { it.first } - } -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/TestStrings.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/TestStrings.kt deleted file mode 100644 index 30387370dd..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/TestStrings.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.test.platform.app.InstrumentationRegistry - -/** Assertions follow the device locale while fixture transcript text remains literal. */ -internal fun testString(resource: Int, vararg arguments: Any): String = - InstrumentationRegistry.getInstrumentation().targetContext.getString(resource, *arguments) diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolConfirmationPanelTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolConfirmationPanelTest.kt deleted file mode 100644 index ee376fafb9..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolConfirmationPanelTest.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextReplacement -import org.junit.Assert.assertEquals -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.hasSetTextAction -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithText -import com.openbitfun.mobile.app.ui.chat.tool.ToolConfirmationPanel -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import org.junit.Rule -import org.junit.Test - -class ToolConfirmationPanelTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun approvalShowsVerdictButtonsWithoutEditableInput() { - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ToolConfirmationPanel( - input = "", - canApprove = true, - canReject = true, - enabled = true, - onApprove = {}, - onReject = {}, - ) - } - } - - composeRule.onNodeWithText(testString(R.string.tool_approve)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_reject)).assertIsDisplayed() - composeRule.onAllNodes(hasSetTextAction()).assertCountEquals(0) - } - @Test - fun invalidEditedInputDisablesApprovalButKeepsRejectionAvailable() { - var rejected = 0 - var approved = 0 - composeRule.setContent { - OpenBitFunTheme(dark = false) { - ToolConfirmationPanel(canApprove = true, canReject = true, enabled = true, input = "{}", - onApprove = { approved++ }, onReject = { rejected++ }) - } - } - composeRule.onAllNodes(hasSetTextAction()).assertCountEquals(0) - composeRule.onNodeWithText(testString(R.string.tool_edit_approval_input)).performClick() - composeRule.onNode(hasSetTextAction()).performTextReplacement("invalid") - composeRule.onNodeWithText(testString(R.string.tool_approve)).assertIsNotEnabled() - composeRule.onNodeWithText(testString(R.string.tool_reject)).performClick() - composeRule.runOnIdle { assertEquals(1, rejected); assertEquals(0, approved) } - composeRule.onNodeWithText(testString(R.string.tool_hide_approval_input)).performClick() - composeRule.onAllNodes(hasSetTextAction()).assertCountEquals(0) - } - -} diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolStatusRowTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolStatusRowTest.kt deleted file mode 100644 index 7e5c737a80..0000000000 --- a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/ToolStatusRowTest.kt +++ /dev/null @@ -1,271 +0,0 @@ -package com.openbitfun.mobile.app - -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.junit4.v2.createComposeRule -import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import com.openbitfun.mobile.app.ui.chat.tool.TOOL_EXPAND_TEST_TAG -import androidx.compose.ui.test.performTextInput -import com.openbitfun.mobile.app.ui.chat.tool.ToolStatusList -import com.openbitfun.mobile.app.ui.chat.tool.ToolStatusRow -import com.openbitfun.mobile.core.feature.session.ToolAction -import com.openbitfun.mobile.core.feature.session.ToolCard -import com.openbitfun.mobile.core.feature.session.ToolKind -import com.openbitfun.mobile.core.feature.session.ToolOperation -import com.openbitfun.mobile.core.feature.session.ToolPhase -import org.junit.Assert.assertEquals -import org.junit.Rule -import org.junit.Test - -/** - * A tool row and the blocking panels that hang off it, ported from - * `ToolStatusList.ets` and `ToolInteractionPanels.ets`. - * - * These need no relay: a row is a pure function of a [ToolCard]. What is worth - * pinning is that a turn waiting on the user cannot be dismissed into a state - * where nothing on screen says so — and that a finished tool says what it did - * rather than only that it is done. - */ -class ToolStatusRowTest { - @get:Rule - val composeRule = createComposeRule() - - @Test - fun approvalOffersBothVerdictsAndReportsTheOneTapped() { - var approved = false - var rejection: String? = null - - composeRule.setContent { - ToolStatusRow( - tool = pendingTool(setOf(ToolAction.APPROVE, ToolAction.REJECT)), - enabled = true, - onApprove = { approved = true }, - onReject = { rejection = it }, - onCancel = {}, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(testString(R.string.tool_approve)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_reject)).performClick() - - assertEquals(false, approved) - // The desktop refuses a rejection without a reason, so the client - // supplies one rather than asking the user to type it. - assertEquals("Rejected from the Android client", rejection) - } - - @Test - fun aQuestionAsksInlineAndOnlySendsOnceAnswered() { - var answer: String? = null - - composeRule.setContent { - ToolStatusRow( - tool = pendingTool(setOf(ToolAction.ANSWER)).copy( - phase = ToolPhase.RUNNING, - question = "Which branch should this land on?", - ), - enabled = true, - onApprove = {}, - onReject = {}, - onCancel = {}, - onAnswer = { answer = it }, - onAnswerStructured = {}, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - // No tap needed to reach it: the panel is the transcript, not a dialog. - composeRule.onNodeWithText("Which branch should this land on?").assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_answer_send)).assertIsNotEnabled() - - composeRule.onNodeWithText(testString(R.string.tool_answer_label)).performTextInput(" main ") - composeRule.onNodeWithText(testString(R.string.tool_answer_send)).assertIsEnabled().performClick() - - assertEquals("main", answer) - } - - @Test - fun aDisconnectedRowShowsItsActionsWithoutOfferingThem() { - var approved = false - - composeRule.setContent { - ToolStatusRow( - tool = pendingTool(setOf(ToolAction.APPROVE, ToolAction.REJECT)), - enabled = false, - onApprove = { approved = true }, - onReject = {}, - onCancel = {}, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - // Kept on screen rather than hidden: the turn is still blocked on this - // tool, and a row that loses its buttons reads as one that resolved. - composeRule.onNodeWithText(testString(R.string.tool_approve)).assertIsNotEnabled() - assertEquals(false, approved) - } - - @Test - fun aRunningToolLeadsWithItsTargetAndOffersOnlyTheStop() { - var cancellation: String? = null - - composeRule.setContent { - ToolStatusRow( - tool = pendingTool(setOf(ToolAction.CANCEL)).copy(phase = ToolPhase.RUNNING), - enabled = true, - onApprove = {}, - onReject = {}, - onCancel = { cancellation = it }, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(testString(R.string.tool_line_running, "README.md")).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.message_stop)).performClick() - - assertEquals("Cancelled from the Android client", cancellation) - } - - @Test - fun aFinishedToolSaysWhatItDidAndHasNothingToActOn() { - composeRule.setContent { - ToolStatusRow( - tool = pendingTool(emptySet()).copy(phase = ToolPhase.COMPLETED), - enabled = true, - onApprove = {}, - onReject = {}, - onCancel = {}, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - // The state is carried by the badge, so the line is free to say the one - // thing a chip reading "Done" never did: which file was edited. - composeRule.onNodeWithText(testString(R.string.tool_line_target, testString(R.string.tool_op_edit_file), "README.md")).assertIsDisplayed() - composeRule.onNodeWithTag(TOOL_EXPAND_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_approve)).assertDoesNotExist() - composeRule.onNodeWithText(testString(R.string.tool_answer_label)).assertDoesNotExist() - } - - @Test - fun aCompletedEmptyPreviewStillExpandsWithChevronFeedback() { - composeRule.setContent { - ToolStatusRow( - tool = readTool("a", "One.kt"), - enabled = true, - onApprove = {}, - onReject = {}, - onCancel = {}, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithTag(TOOL_EXPAND_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithTag(TOOL_EXPAND_TEST_TAG).performClick() - composeRule.onNodeWithTag(TOOL_EXPAND_TEST_TAG).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_line_target, testString(R.string.tool_op_read_file), "One.kt")).assertIsDisplayed() - } - - @Test - fun tappingAFileRowOpensThatFileRatherThanExpandingIt() { - var opened: Pair? = null - - composeRule.setContent { - ToolStatusRow( - tool = pendingTool(emptySet()).copy( - phase = ToolPhase.COMPLETED, - filePath = "docs/README.md", - fileLabel = "README.md", - ), - enabled = true, - onApprove = {}, - onReject = {}, - onCancel = {}, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = { path, label -> opened = path to label }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(testString(R.string.tool_line_target, testString(R.string.tool_op_edit_file), "README.md")).performClick() - - assertEquals("docs/README.md" to "README.md", opened) - } - - @Test - fun consecutiveFinishedLookupsFoldIntoOneLineUntilOpened() { - composeRule.setContent { - ToolStatusList( - tools = listOf(readTool("a", "One.kt"), readTool("b", "Two.kt")), - enabled = true, - onApprove = { _, _ -> }, - onReject = { _, _ -> }, - onCancel = { _, _ -> }, - onAnswer = { _, _ -> }, - onAnswerStructured = { _, _ -> }, - onOpenFile = { _, _ -> }, - modifier = Modifier, - ) - } - - composeRule.onNodeWithText(testString(R.string.tool_group_summary, 2)).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_line_target, testString(R.string.tool_op_read_file), "One.kt")).assertDoesNotExist() - - composeRule.onNodeWithText(testString(R.string.tool_group_summary, 2)).performClick() - - composeRule.onNodeWithText(testString(R.string.tool_line_target, testString(R.string.tool_op_read_file), "One.kt")).assertIsDisplayed() - composeRule.onNodeWithText(testString(R.string.tool_line_target, testString(R.string.tool_op_read_file), "Two.kt")).assertIsDisplayed() - } - - private fun pendingTool(actions: Set): ToolCard = ToolCard( - id = "tool-1", - name = "Edit", - phase = ToolPhase.PENDING_CONFIRMATION, - kind = ToolKind.MUTATE, - operation = ToolOperation.EDIT_FILE, - target = "README.md", - filePath = "", - fileLabel = "", - input = "{\"path\": \"README.md\"}", - output = "", - question = null, - actions = actions, - ) - - private fun readTool(id: String, target: String): ToolCard = ToolCard( - id = id, - name = "Read", - phase = ToolPhase.COMPLETED, - kind = ToolKind.DOCUMENT, - operation = ToolOperation.READ_FILE, - target = target, - filePath = "", - fileLabel = "", - input = "", - output = "", - question = null, - actions = emptySet(), - ) -} diff --git a/src/apps/mobile/android/app/src/debug/AndroidManifest.xml b/src/apps/mobile/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index c96c170e31..0000000000 --- a/src/apps/mobile/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/AndroidManifest.xml b/src/apps/mobile/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index 0bcdcf69e0..0000000000 --- a/src/apps/mobile/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/assets/miniapps/.gitignore b/src/apps/mobile/android/app/src/main/assets/miniapps/.gitignore deleted file mode 100644 index d6b7ef32c8..0000000000 --- a/src/apps/mobile/android/app/src/main/assets/miniapps/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore diff --git a/src/apps/mobile/android/app/src/main/kotlin/.gitkeep b/src/apps/mobile/android/app/src/main/kotlin/.gitkeep deleted file mode 100644 index 8b13789179..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt deleted file mode 100644 index feb0b1119c..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt +++ /dev/null @@ -1,180 +0,0 @@ -package com.openbitfun.mobile.app - -import android.content.Intent -import android.os.Bundle -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import com.openbitfun.mobile.app.ui.shell.StartupBrandReveal -import com.openbitfun.mobile.app.ui.shell.ColdStartHomeTransition -import com.openbitfun.mobile.app.ui.shell.LocalColdStartTarget -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.remember -import androidx.compose.ui.Modifier -import androidx.compose.ui.Alignment -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.layout.positionInRoot -import androidx.compose.ui.semantics.hideFromAccessibility -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.dp -import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent -import androidx.activity.enableEdgeToEdge -import androidx.core.view.WindowCompat -import androidx.compose.foundation.isSystemInDarkTheme -import androidx.compose.runtime.getValue -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.openbitfun.mobile.app.platform.LogcatCoreLog -import com.openbitfun.mobile.app.ui.shell.MobileScreen -import com.openbitfun.mobile.app.platform.StartupRevealPreference -import com.openbitfun.mobile.app.platform.AppLocaleController -import com.openbitfun.mobile.app.ui.preview.MessageQueuePreview -import com.openbitfun.mobile.app.ui.preview.MobileDesignGallery -import com.openbitfun.mobile.app.ui.preview.mobileDesignScenario -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.app.viewmodel.AppSettingsViewModel -import com.openbitfun.mobile.app.viewmodel.AppThemeMode - -class MainActivity : ComponentActivity() { - private var showStartupBrand by mutableStateOf(true) - private var showColdStart by mutableStateOf(false) - private var allowColdStart by mutableStateOf(false) - private var showWelcomeNavigationProtection by mutableStateOf(true) - private var authorizationCallbackPending = false - override fun onCreate(savedInstanceState: Bundle?) { - AppLocaleController.applySaved(this) - super.onCreate(savedInstanceState) - LogcatCoreLog.initialize(applicationContext) - LogcatCoreLog.info("activity onCreate callback=${isAuthorizationCallbackIntent(intent)}") - authorizationCallbackPending = isAuthorizationCallbackIntent(intent) - val coldStartCandidate = !processLaunchClaimed - && !intent.getBooleanExtra(DESIGN_PREVIEW_EXTRA, false) - processLaunchClaimed = true - showStartupBrand = coldStartCandidate && StartupRevealPreference.claim(this) - allowColdStart = coldStartCandidate && !showStartupBrand - enableEdgeToEdge() - @Suppress("DEPRECATION") - if (android.os.Build.VERSION.SDK_INT >= 29) window.isNavigationBarContrastEnforced = false - setContent { - if (intent.getBooleanExtra(DESIGN_PREVIEW_EXTRA, false)) { - if (intent.getStringExtra(DESIGN_SCENARIO_EXTRA) == "message-queue") { - MessageQueuePreview() - return@setContent - } - val scenario = mobileDesignScenario(intent.getStringExtra(DESIGN_SCENARIO_EXTRA)) - MobileDesignGallery(scenario = scenario, dark = scenario.appearance == "dark") - return@setContent - } - val settings: AppSettingsViewModel = viewModel(factory = AppSettingsViewModel.Factory) - val theme by settings.theme.collectAsStateWithLifecycle() - val dark = when (theme) { - AppThemeMode.SYSTEM -> isSystemInDarkTheme() - AppThemeMode.LIGHT -> false - AppThemeMode.DARK -> true - } - OpenBitFunTheme(dark = dark) { - LaunchedEffect(dark, showWelcomeNavigationProtection, showStartupBrand, showColdStart, allowColdStart) { - val welcomeIsVisible = showWelcomeNavigationProtection && - !showStartupBrand && !showColdStart && !allowColdStart - WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightNavigationBars = - !dark && !welcomeIsVisible - } - val target = remember { mutableStateOf(null) } - var origin by remember { mutableStateOf(Offset.Zero) } - Box(Modifier.onGloballyPositioned { origin = it.positionInRoot() }) { - CompositionLocalProvider(LocalColdStartTarget provides target) { - Box(Modifier.semantics { - if (showStartupBrand || showColdStart) hideFromAccessibility() - }) { - MobileScreen(onAccountRestored = { signedIn -> - showWelcomeNavigationProtection = !signedIn - if (allowColdStart) { - allowColdStart = false - showColdStart = signedIn - } - }) - } - } - if (showStartupBrand) StartupBrandReveal { showStartupBrand = false } - val bounds = target.value - if (showColdStart) { - ColdStartHomeTransition(bounds?.translate(-origin)) { showColdStart = false } - } - // Android 15+ makes the gesture/navigation area part of an - // edge-to-edge window. Keep the signed-out welcome dock's - // dark surface behind that area at the Activity root; a - // screen or Scaffold inset cannot paint over the system - // region reliably on all API levels. - if (showWelcomeNavigationProtection && !showStartupBrand && !showColdStart && !allowColdStart) { - Box( - Modifier - .align(Alignment.BottomCenter) - .fillMaxWidth() - // Include the platform's divider inset above - // the gesture area as well as the nav bar. - .height(40.dp) - .background(Color(23, 25, 23)), - ) - } - } - if (!showStartupBrand && !showColdStart && !allowColdStart) { - com.openbitfun.mobile.app.ui.shell.NotificationOnboarding() - } - } - } - } - - override fun onStart() { - super.onStart() - LogcatCoreLog.info("activity onStart callbackPending=$authorizationCallbackPending") - if (!intent.getBooleanExtra(DESIGN_PREVIEW_EXTRA, false)) { - accountModel().setBackground(false) - if (authorizationCallbackPending) { - authorizationCallbackPending = false - accountModel().notifyAuthorizationCallback() - } - } - } - - override fun onNewIntent(intent: android.content.Intent) { - super.onNewIntent(intent) - setIntent(intent) - LogcatCoreLog.info("activity onNewIntent action=${intent.action} callback=${isAuthorizationCallbackIntent(intent)}") - if (isAuthorizationCallbackIntent(intent)) accountModel().notifyAuthorizationCallback() - } - - override fun onStop() { - LogcatCoreLog.info("activity onStop") - showStartupBrand = false - showColdStart = false - allowColdStart = false - if (!intent.getBooleanExtra(DESIGN_PREVIEW_EXTRA, false)) accountModel().setBackground(true) - super.onStop() - } - - private fun accountModel() = androidx.lifecycle.ViewModelProvider(this, - com.openbitfun.mobile.app.viewmodel.AccountViewModel.Factory)[com.openbitfun.mobile.app.viewmodel.AccountViewModel::class.java] - - private fun isAuthorizationCallbackIntent(intent: Intent): Boolean { - val uri = intent.data ?: return false - return intent.action == Intent.ACTION_VIEW && - uri.scheme == "openbitfun" && - uri.authority == "auth" && - uri.path == "/callback" && - uri.query == null && - uri.fragment == null - } - - private companion object { - var processLaunchClaimed = false - const val DESIGN_PREVIEW_EXTRA = "openbitfun.design_preview" - const val DESIGN_SCENARIO_EXTRA = "openbitfun.design_scenario" - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AccountAvatarLoader.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AccountAvatarLoader.kt deleted file mode 100644 index 5acb58b513..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AccountAvatarLoader.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import java.net.HttpURLConnection -import java.net.URI - -internal suspend fun loadAccountAvatar(value: String?): Bitmap? = withContext(Dispatchers.IO) { - val uri = runCatching { URI(value ?: return@withContext null) }.getOrNull() ?: return@withContext null - if (uri.scheme != "https" || uri.host != "avatars.githubusercontent.com") return@withContext null - val connection = uri.toURL().openConnection() as HttpURLConnection - try { - connection.connectTimeout = 10000 - connection.readTimeout = 10000 - connection.instanceFollowRedirects = false - if (connection.responseCode != 200) return@withContext null - connection.inputStream.use { stream -> - val output = java.io.ByteArrayOutputStream() - val buffer = ByteArray(8192) - while (true) { - val count = stream.read(buffer) - if (count < 0) break - if (output.size() + count > 2 * 1024 * 1024) return@withContext null - output.write(buffer, 0, count) - } - val bytes = output.toByteArray() - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) - if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null - val options = BitmapFactory.Options() - while (bounds.outWidth / options.inSampleSize > 256 || bounds.outHeight / options.inSampleSize > 256) options.inSampleSize *= 2 - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) - } - } catch (_: Exception) { null } finally { connection.disconnect() } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AndroidRuntimeUploadSource.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AndroidRuntimeUploadSource.kt deleted file mode 100644 index 7de63caedf..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AndroidRuntimeUploadSource.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.content.ContentResolver -import android.net.Uri -import com.openbitfun.mobile.core.feature.workspace.RuntimeUploadSource -import java.io.FileInputStream -import java.nio.ByteBuffer - -/** A picker-granted local file is a byte source, never a runtime workspace. */ -internal class AndroidRuntimeUploadSource(resolver: ContentResolver, uri: Uri) : RuntimeUploadSource { - private val descriptor = requireNotNull(resolver.openFileDescriptor(uri, "r")) { "Selected file could not be opened" } - private val stream = FileInputStream(descriptor.fileDescriptor) - override val size: Long = descriptor.statSize.also { if (it < 0) { close(); error("Selected provider does not expose a seekable file") } } - override fun read(offset: Long, length: Int): ByteArray { - val buffer = ByteBuffer.allocate(length) - stream.channel.position(offset) - while (buffer.hasRemaining()) { if (stream.channel.read(buffer) < 0) break } - return buffer.array().copyOf(buffer.position()) - } - override fun close() { runCatching { stream.close() }; runCatching { descriptor.close() } } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AppLocaleController.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AppLocaleController.kt deleted file mode 100644 index 443040b7d3..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/AppLocaleController.kt +++ /dev/null @@ -1,78 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.app.Activity -import android.app.LocaleManager -import android.content.Context -import android.content.res.Configuration -import android.os.Build -import android.os.LocaleList -import java.util.Locale - -/** App-owned locales, matching HarmonyOS's two explicit language choices. */ -internal enum class AppLocale(val languageTag: String) { - ENGLISH("en-US"), - SIMPLIFIED_CHINESE("zh-CN"), -} - -/** - * Resolves Android's language token to one of the app-owned locales. - * - * Every `zh*` Android locale intentionally uses Simplified Chinese because - * this app ships only the default and `values-zh` resource catalogs. - */ -internal fun resolveAppLocale(language: String?): AppLocale = - when (language?.trim()?.lowercase(Locale.ROOT)) { - "zh" -> AppLocale.SIMPLIFIED_CHINESE - null, "" -> AppLocale.ENGLISH - else -> AppLocale.ENGLISH - } - -internal object AppLocaleController { - private const val PREFERENCES = "openbitfun_app_settings" - private const val LANGUAGE_KEY = "language" - - fun current(configuration: Configuration): AppLocale { - val language = configuration.locales - .takeIf { !it.isEmpty } - ?.get(0) - ?.language - return resolveAppLocale(language) - } - - fun set(context: Context, locale: AppLocale) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - val manager = context.getSystemService(LocaleManager::class.java) - manager.applicationLocales = LocaleList.forLanguageTags(locale.languageTag) - } else { - context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) - .edit() - .putString(LANGUAGE_KEY, locale.languageTag) - .apply() - applyLegacy(context, locale.languageTag) - (context as? Activity)?.recreate() - } - } - - fun applySaved(context: Context) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - val manager = context.getSystemService(LocaleManager::class.java) - if (manager.applicationLocales.isEmpty) { - manager.applicationLocales = LocaleList.forLanguageTags(DEFAULT_APP_LANGUAGE_TAG) - } - return - } - val tag = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) - .getString(LANGUAGE_KEY, null) - ?: DEFAULT_APP_LANGUAGE_TAG - applyLegacy(context, tag) - } - - private fun applyLegacy(context: Context, languageTag: String) { - val locale = Locale.forLanguageTag(languageTag) - Locale.setDefault(locale) - val configuration = Configuration(context.resources.configuration) - configuration.setLocales(LocaleList(locale)) - @Suppress("DEPRECATION") - context.resources.updateConfiguration(configuration, context.resources.displayMetrics) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt deleted file mode 100644 index 85b520d3ad..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerActivityLauncher.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.content.ActivityNotFoundException -import android.content.Context -import android.util.Log -import android.widget.Toast -import androidx.annotation.StringRes - -/** System media activities are optional, and OEMs may deny access to them. */ -internal fun launchComposerActivity( - context: Context, - @StringRes failureMessage: Int, - launch: () -> Unit, -): Boolean = try { - launch() - true -} catch (_: ActivityNotFoundException) { - Log.w("ComposerActivity", "System media activity is unavailable") - Toast.makeText(context, failureMessage, Toast.LENGTH_LONG).show() - false -} catch (_: SecurityException) { - Log.w("ComposerActivity", "System media activity access was denied") - Toast.makeText(context, failureMessage, Toast.LENGTH_LONG).show() - false -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerImageEncoder.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerImageEncoder.kt deleted file mode 100644 index 130c00e196..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/ComposerImageEncoder.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.content.ContentResolver -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.graphics.ImageDecoder -import android.graphics.Matrix -import android.media.ExifInterface -import android.net.Uri -import android.os.Build -import android.util.Base64 -import com.openbitfun.mobile.core.feature.session.ComposerImage -import java.io.ByteArrayOutputStream -import java.util.UUID -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext - -/** Decode camera formats and orientation on the device before crossing the relay. */ -internal suspend fun prepareComposerImage(resolver: ContentResolver, uri: Uri): ComposerImage = - withContext(Dispatchers.IO) { - val longestSide = 1920 - var bitmap = if (Build.VERSION.SDK_INT >= 28) { - ImageDecoder.decodeBitmap(ImageDecoder.createSource(resolver, uri)) { decoder, info, _ -> - val scale = minOf(1.0, longestSide.toDouble() / maxOf(info.size.width, info.size.height)) - decoder.setTargetSize(maxOf(1, (info.size.width * scale).toInt()), maxOf(1, (info.size.height * scale).toInt())) - decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE - } - } else { - val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } - resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, options) } - require(options.outWidth > 0 && options.outHeight > 0) { "Invalid image" } - options.inSampleSize = 1 - while (maxOf(options.outWidth, options.outHeight) / options.inSampleSize > longestSide) options.inSampleSize *= 2 - options.inJustDecodeBounds = false - val decoded = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, options) } - ?: error("Unable to decode image") - val orientation = resolver.openInputStream(uri)?.use { - ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) - } ?: ExifInterface.ORIENTATION_NORMAL - val matrix = Matrix().apply { - when (orientation) { - ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> setScale(-1f, 1f) - ExifInterface.ORIENTATION_ROTATE_180 -> setRotate(180f) - ExifInterface.ORIENTATION_FLIP_VERTICAL -> setScale(1f, -1f) - ExifInterface.ORIENTATION_TRANSPOSE -> { setRotate(90f); postScale(-1f, 1f) } - ExifInterface.ORIENTATION_ROTATE_90 -> setRotate(90f) - ExifInterface.ORIENTATION_TRANSVERSE -> { setRotate(270f); postScale(-1f, 1f) } - ExifInterface.ORIENTATION_ROTATE_270 -> setRotate(270f) - } - } - Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true).also { - if (it !== decoded) decoded.recycle() - } - } - try { - var quality = 85 - while (true) { - val encoded = ByteArrayOutputStream().use { - check(bitmap.compress(Bitmap.CompressFormat.JPEG, quality, it)) { "Image compression failed" } - it.toByteArray() - } - if (encoded.size <= 1024 * 1024) { - return@withContext ComposerImage( - id = "android-${UUID.randomUUID()}", - dataUrl = "data:image/jpeg;base64," + Base64.encodeToString(encoded, Base64.NO_WRAP), - mimeType = "image/jpeg", - ) - } - if (quality > 45) { quality -= 10; continue } - check(minOf(bitmap.width, bitmap.height) > 64) { "Image exceeds upload limit" } - val smaller = Bitmap.createScaledBitmap(bitmap, maxOf(1, bitmap.width * 3 / 4), maxOf(1, bitmap.height * 3 / 4), true) - bitmap.recycle() - bitmap = smaller - quality = 75 - } - @Suppress("UNREACHABLE_CODE") - error("Image encoding did not complete") - } finally { - bitmap.recycle() - } - } diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/DeviceInstall.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/DeviceInstall.kt deleted file mode 100644 index bbb9142ad6..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/DeviceInstall.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.content.Context -import android.os.Build -import com.openbitfun.mobile.core.feature.account.MobileDeviceIdentity -import java.util.UUID - -private const val PREFS = "openbitfun_install" -private const val KEY_INSTALL_ID = "install_id" - -internal val LEGACY_MOBILE_DEVICE_NAMES: Set = setOf( - "HarmonyOS Phone", - "HarmonyOS Watch", -) - -/** - * The identity this install presents to the desktop. - * - * Deliberately not `ANDROID_ID` or any other hardware-derived value: the desktop - * only needs something stable enough to recognise the same phone twice, and a - * random id per install gives it that without carrying a device fingerprint off - * the phone. Clearing app data intentionally produces a new device. - */ -internal fun Context.deviceIdentity(): MobileDeviceIdentity { - val prefs = getSharedPreferences(PREFS, Context.MODE_PRIVATE) - val existing = prefs.getString(KEY_INSTALL_ID, null) - val installId = existing ?: "android-${UUID.randomUUID()}".also { - prefs.edit().putString(KEY_INSTALL_ID, it).apply() - } - return MobileDeviceIdentity( - installId = installId, - displayName = Build.MODEL.ifBlank { "Android" }, - ) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/GeneratedLocaleContract.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/GeneratedLocaleContract.kt deleted file mode 100644 index c2f3b9f67e..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/GeneratedLocaleContract.kt +++ /dev/null @@ -1,4 +0,0 @@ -// Generated by scripts/generate-i18n-contract.mjs. Do not edit. -package com.openbitfun.mobile.app.platform - -internal const val DEFAULT_APP_LANGUAGE_TAG = "zh-CN" diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/LogcatCoreLog.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/LogcatCoreLog.kt deleted file mode 100644 index 5a0cc66605..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/LogcatCoreLog.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.content.Context -import android.util.Log -import com.openbitfun.mobile.core.feature.CoreLog -import java.io.File - -/** - * Forwards core log lines to Logcat verbatim. - * - * Verbatim is safe by construction: room ids and request ids are truncated - * before they leave the core, and keys, tokens and passwords never reach it. - * If that ever stops being true, the tests next to `PairingStore` fail first. - */ -internal object LogcatCoreLog : CoreLog { - private const val TAG = "OpenBitFunCore" - private const val FILE_NAME = "openbitfun-auth-diagnostics.log" - private const val MAX_FILE_BYTES = 512 * 1024 - private var diagnosticsFiles: List = emptyList() - - /** - * Keeps a small, pullable breadcrumb file for Android compatibility hosts - * where the normal Android log buffer is not exposed through HDC. - */ - fun initialize(context: Context) { - diagnosticsFiles = listOfNotNull( - File(context.filesDir, FILE_NAME), - context.getExternalFilesDir(null)?.let { File(it, FILE_NAME) }, - ).distinctBy { it.absolutePath } - info("diagnostics initialized") - } - - override fun info(message: String) { - Log.i(TAG, message) - append("I", message) - } - - override fun warn(message: String) { - Log.w(TAG, message) - append("W", message) - } - - override fun error(message: String) { - Log.e(TAG, message) - append("E", message) - } - - private fun append(level: String, message: String) { - synchronized(this) { - diagnosticsFiles.forEach { file -> - runCatching { - if (file.length() > MAX_FILE_BYTES) { - file.writeText("diagnostic log rotated\n") - } - file.appendText("${System.currentTimeMillis()} $level $message\n") - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/NotificationOnboarding.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/NotificationOnboarding.kt deleted file mode 100644 index a5926785f4..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/NotificationOnboarding.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.Manifest -import android.content.Context -import android.content.pm.PackageManager -import android.os.Build -import android.app.Activity -import android.content.ContextWrapper - -/** Installation-scoped choice, independent of account and remote task state. */ -internal class NotificationOnboarding(private val context: Context) { - private val preferences = context.getSharedPreferences("notification_onboarding", Context.MODE_PRIVATE) - - fun shouldOffer(): Boolean { - if (Build.VERSION.SDK_INT < 33 || preferences.getBoolean("completed_v1", false)) return false - if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) return false - var owner: Context = context - while (owner is ContextWrapper && owner !is Activity) owner = owner.baseContext - return (owner as? Activity)?.shouldShowRequestPermissionRationale( - Manifest.permission.POST_NOTIFICATIONS, - ) != true - } - - fun complete() { - preferences.edit().putBoolean("completed_v1", true).apply() - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/StartupRevealPreference.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/StartupRevealPreference.kt deleted file mode 100644 index f19d150fcd..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/StartupRevealPreference.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.content.Context - -/** Installation-local presentation state; account changes and upgrades do not reset it. */ -internal object StartupRevealPreference { - @Synchronized - fun claim(context: Context): Boolean { - val preferences = context.getSharedPreferences("startup_presentation", Context.MODE_PRIVATE) - if (preferences.getBoolean("brand_reveal_shown", false)) return false - // Claim before playback, including when the first reveal is interrupted. - preferences.edit().putBoolean("brand_reveal_shown", true).apply() - return true - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/TaskCompletionNotifier.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/TaskCompletionNotifier.kt deleted file mode 100644 index ff725265ad..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/TaskCompletionNotifier.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.Manifest -import android.app.Notification -import android.app.NotificationChannel -import android.app.NotificationManager -import android.app.PendingIntent -import android.content.Context -import android.content.Intent -import android.content.pm.PackageManager -import android.os.Build -import com.openbitfun.mobile.app.MainActivity -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.TaskCompletionPolicy - -/** Best-effort notification while this controller remains alive; execution belongs to the host. */ -internal class TaskCompletionNotifier(private val context: Context) { - private val policy = TaskCompletionPolicy() - fun setBackground(value: Boolean) { policy.setBackground(value) } - fun reset() { policy.reset() } - fun observe(state: RemoteSessionUiState, target: String) { - val completed = policy.observe(state, target) ?: return - if (Build.VERSION.SDK_INT >= 33 && context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return - val manager = context.getSystemService(NotificationManager::class.java) - manager.createNotificationChannel(NotificationChannel("task_completion", context.getString(R.string.task_completed_title), NotificationManager.IMPORTANCE_DEFAULT)) - val open = PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) - val notification = Notification.Builder(context, "task_completion") - .setSmallIcon(R.drawable.ic_symbol_checkmark_circle_fill) - .setContentTitle(context.getString(R.string.task_completed_title)) - .setContentText(context.getString(R.string.task_completed_body)) - .setContentIntent(open).setAutoCancel(true).build() - manager.notify((completed.target + completed.sessionId + completed.turnId).hashCode(), notification) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/WindowMetrics.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/WindowMetrics.kt deleted file mode 100644 index bbad7443ee..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/platform/WindowMetrics.kt +++ /dev/null @@ -1,206 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import android.app.Activity -import android.content.Context -import android.content.ContextWrapper -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalWindowInfo -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.window.layout.FoldingFeature -import androidx.window.layout.WindowInfoTracker -import com.openbitfun.mobile.core.feature.layout.ConversationLayoutPolicy -import com.openbitfun.mobile.core.feature.layout.HorizontalWindowCrease -import com.openbitfun.mobile.core.feature.layout.WindowCrease -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.map - -/** - * The window as the layout policies measure it. - * - * @param widthDp the window's own width, not the display's: a freeform or split - * window is narrower than the screen it sits on, and the layout follows the - * window. - * Fold APIs are projected into semantic facts here so shared code never imports - * Android WindowManager types. - */ -internal data class WindowMetrics( - val widthDp: Int, - val heightDp: Int, - val wideViewportMatched: Boolean, - val isFolded: Boolean, - val isExpandedFoldable: Boolean, - val isHoverLayout: Boolean, - val creases: List, - val horizontalCreases: List, -) - -internal enum class FoldState { - FLAT, - HALF_OPENED, - UNKNOWN, -} - -internal data class FoldFeatureFacts( - val state: FoldState, - val isHorizontal: Boolean, -) - -internal data class FoldFacts( - val hasFoldingFeature: Boolean, - val halfOpened: Boolean, - val flatOpened: Boolean, - val isFolded: Boolean, - val isExpandedFoldable: Boolean, - val hoverCandidate: Boolean, -) - -internal fun reduceFoldFacts( - hasHingeSensor: Boolean, - features: List, -): FoldFacts { - val hasFoldingFeature = features.isNotEmpty() - val halfOpened = features.any { it.state == FoldState.HALF_OPENED } - val flatOpened = hasFoldingFeature && features.all { it.state == FoldState.FLAT } - return FoldFacts( - hasFoldingFeature = hasFoldingFeature, - halfOpened = halfOpened, - flatOpened = flatOpened, - isFolded = hasHingeSensor && !hasFoldingFeature, - isExpandedFoldable = flatOpened, - hoverCandidate = - features.all { it.state != FoldState.UNKNOWN } && - features.any { - it.isHorizontal && it.state == FoldState.HALF_OPENED - }, - ) -} - -private data class AndroidFoldInfo( - val creases: List, - val horizontalCreases: List, - val foldFacts: FoldFacts, -) - -/** - * Reads the current window and the hinges crossing it. - * - * Vertical creases feed the master/detail policy; horizontal creases feed the - * hover/operate-region modal policy. Both are reduced to their leading edge and - * thickness here, so shared code never imports Android WindowManager types or - * has to know what a pixel is on this device. - */ -@Composable -internal fun rememberWindowMetrics(): WindowMetrics { - val context = LocalContext.current - val density = LocalDensity.current - val containerSize = LocalWindowInfo.current.containerSize - val widthDp = with(density) { containerSize.width.toDp().value.toInt() } - val heightDp = with(density) { containerSize.height.toDp().value.toInt() } - val hasHingeSensor = remember(context) { - context.packageManager.hasSystemFeature(FEATURE_SENSOR_HINGE_ANGLE) - } - //卓易通在鸿蒙上会向 Android 兼容层暴露一个“垂直折痕”,但它不是 - //Android WindowManager 的真实折叠区域。把它当成铰链会把普通宽屏窗口 - //错误拆成左右两套页面。通过鸿蒙系统文件管理器包识别兼容层;普通 - //Android 平板和真实 Android 折叠屏不会安装这个包,因此保持原行为。 - val isHarmonyCompatibilityLayer = remember(context) { - context.packageManager.hasPackage("com.huawei.hmos.filemanager") - } - - val activity = remember(context) { context.findActivity() } - // No activity means no window to track — a @Preview, or a composable hosted - // somewhere that has no fold to report anyway. - val foldInfoFlow = remember(activity, density) { - if (activity == null) { - flowOf(AndroidFoldInfo(emptyList(), emptyList(), reduceFoldFacts(false, emptyList()))) - } else { - WindowInfoTracker.getOrCreate(activity) - .windowLayoutInfo(activity) - .map { info -> - val features = info.displayFeatures.filterIsInstance() - val foldFacts = reduceFoldFacts( - hasHingeSensor = hasHingeSensor, - features = features.map { feature -> - FoldFeatureFacts( - state = when (feature.state) { - FoldingFeature.State.HALF_OPENED -> FoldState.HALF_OPENED - FoldingFeature.State.FLAT -> FoldState.FLAT - else -> FoldState.UNKNOWN - }, - isHorizontal = feature.orientation == FoldingFeature.Orientation.HORIZONTAL, - ) - }, - ) - AndroidFoldInfo( - creases = features - .filter { it.orientation == FoldingFeature.Orientation.VERTICAL } - .map { feature -> - with(density) { - WindowCrease( - left = feature.bounds.left.toDp().value.toInt(), - width = feature.bounds.width().toDp().value.toInt(), - ) - } - }, - horizontalCreases = features - .filter { it.orientation == FoldingFeature.Orientation.HORIZONTAL } - .map { feature -> - with(density) { - HorizontalWindowCrease( - top = feature.bounds.top.toDp().value.toInt(), - height = feature.bounds.height().toDp().value.toInt(), - ) - } - }, - foldFacts = foldFacts, - ) - } - } - } - val reportedFoldInfo by foldInfoFlow.collectAsStateWithLifecycle( - AndroidFoldInfo(emptyList(), emptyList(), reduceFoldFacts(false, emptyList())), - ) - val foldInfo = if (isHarmonyCompatibilityLayer) { - AndroidFoldInfo(emptyList(), emptyList(), reduceFoldFacts(false, emptyList())) - } else { - reportedFoldInfo - } - - return WindowMetrics( - widthDp = widthDp, - heightDp = heightDp, - wideViewportMatched = widthDp >= ConversationLayoutPolicy.MD_MIN_WIDTH, - isFolded = foldInfo.foldFacts.isFolded, - isExpandedFoldable = foldInfo.foldFacts.isExpandedFoldable, - isHoverLayout = ConversationLayoutPolicy.useHoverOperate( - foldInfo.foldFacts.hoverCandidate, - widthDp, - heightDp, - ), - creases = foldInfo.creases, - horizontalCreases = foldInfo.horizontalCreases, - ) -} - -private const val FEATURE_SENSOR_HINGE_ANGLE = "android.hardware.sensor.hinge_angle" - -private fun android.content.pm.PackageManager.hasPackage(packageName: String): Boolean = - try { - getApplicationInfo(packageName, 0) - true - } catch (_: android.content.pm.PackageManager.NameNotFoundException) { - false - } - -private fun Context.findActivity(): Activity? { - var current: Context? = this - while (current is ContextWrapper) { - if (current is Activity) return current - current = current.baseContext - } - return null -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt deleted file mode 100644 index e75d6d8c1f..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/AppShellState.kt +++ /dev/null @@ -1,276 +0,0 @@ -package com.openbitfun.mobile.app.state - -import androidx.compose.runtime.Composable -import androidx.compose.runtime.Stable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.Saver -import androidx.compose.runtime.saveable.listSaver -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue - -/** - * What the content area shows. - * - * Only two, because the shell moved settings and the account onto sheets the - * way `AppShell.ets` binds them — a sheet is not a destination, so neither can - * displace the conversation the user was reading. - */ -internal enum class MobileSurface { - REMOTE, -} - -/** - * The shell's own navigation and overlay state, ported from - * `pages/state/AppShellState.ets`. - * - * The transitions live here rather than in the composable for the reason the - * source keeps them in a class: "opening the account closes settings" is a rule - * about the shell, and a rule spread across the call sites that trigger it is a - * rule each new call site can get wrong. The view reads the properties and calls - * the verbs; nothing outside sets a field. - */ -@Stable -internal class AppShellState( - surface: MobileSurface, - showSettings: Boolean, - showAccount: Boolean, - accountReturnsToSettings: Boolean, - searchOpen: Boolean, - sidebarQuery: String, - remoteSessionId: String? = null, - remoteCreating: Boolean = false, - remoteConnectOpen: Boolean = false, - pendingRemoteSessionId: String? = null, -) { - internal var surface: MobileSurface by mutableStateOf(surface) - private set - - internal var showSettings: Boolean by mutableStateOf(showSettings) - private set - - /** Whether closing the account lands back on the page that opened it. */ - private var accountReturnsToSettings: Boolean by mutableStateOf(accountReturnsToSettings) - - internal var showAccount: Boolean by mutableStateOf(showAccount) - private set - - internal var searchOpen: Boolean by mutableStateOf(searchOpen) - private set - - internal var sidebarQuery: String by mutableStateOf(sidebarQuery) - private set - - internal var remoteSessionId: String? by mutableStateOf(remoteSessionId) - private set - - internal var pendingRemoteSessionId: String? by mutableStateOf(pendingRemoteSessionId) - private set - - private var pendingRemoteSessionObservedBusy = false - - internal var remoteCreating: Boolean by mutableStateOf(remoteCreating) - private set - - internal var remoteConnectOpen: Boolean by mutableStateOf(remoteConnectOpen) - private set - - internal fun closeRemoteConnect() { - remoteConnectOpen = false - } - - internal fun show(next: MobileSurface) { - surface = next - } - - internal fun openRemoteSession(sessionId: String) { - closeRemoteConnect() - surface = MobileSurface.REMOTE - remoteCreating = false - remoteSessionId = sessionId - pendingRemoteSessionId = sessionId - pendingRemoteSessionObservedBusy = false - } - - internal fun observeRemoteSessionOpen(sessionId: String, selectedSessionId: String?, busy: Boolean) { - if (pendingRemoteSessionId != sessionId) return - when { - selectedSessionId == sessionId -> completeRemoteSessionOpen(sessionId) - busy -> pendingRemoteSessionObservedBusy = true - pendingRemoteSessionObservedBusy -> completeRemoteSessionOpen(sessionId) - } - } - - private fun completeRemoteSessionOpen(sessionId: String) { - if (pendingRemoteSessionId != sessionId) return - pendingRemoteSessionId = null - pendingRemoteSessionObservedBusy = false - } - - internal fun createRemoteSession() { - closeRemoteConnect() - surface = MobileSurface.REMOTE - remoteCreating = true - remoteSessionId = null - pendingRemoteSessionId = null - pendingRemoteSessionObservedBusy = false - } - - internal fun closeRemoteSession() { - closeRemoteConnect() - remoteCreating = false - remoteSessionId = null - pendingRemoteSessionId = null - pendingRemoteSessionObservedBusy = false - } - - /** - * Opens the account-device picker on the remote surface. - * - * The only way to reach a desktop is through the signed-in account, so the - * caller decides between this and [openAccount] by whether an account is - * ready; the sheet itself never offers another way in. - */ - internal fun openRemoteConnect() { - remoteConnectOpen = true - surface = MobileSurface.REMOTE - remoteCreating = false - remoteSessionId = null - pendingRemoteSessionId = null - pendingRemoteSessionObservedBusy = false - } - - /** - * Opens the one settings page. The sidebar gear and the remote home header - * both land here: there is no separate remote-control settings page. - */ - internal fun openSettings() { - showSettings = true - } - - internal fun dismissSettings() { - showSettings = false - } - - /** - * The account lives inside the settings page (the way `SettingsSheet.ets` - * embeds `AccountProfilePanel`), so a signed-in account is shown by opening - * settings. Only a signed-out user gets a separate step: the login sheet. - * - * One sheet at a time: login replaces settings rather than stacking on it, and - * whether settings asked for it is remembered — the source's - * `accountReturnMode` — so cancelling puts that page back. - */ - internal fun openAccount(signedIn: Boolean) { - if (signedIn) { - if (!showSettings) openSettings() - return - } - accountReturnsToSettings = showSettings - showSettings = false - showAccount = true - } - - /** - * Login finished: the account now shows inside settings, so the user lands - * there whether or not settings sent them. - */ - internal fun completeLogin() { - if (!showAccount) return - showAccount = false - accountReturnsToSettings = false - openSettings() - } - - internal fun dismissAccount() { - showAccount = false - if (accountReturnsToSettings) { - accountReturnsToSettings = false - showSettings = true - } - } - - internal fun search(query: String) { - sidebarQuery = query - } - - /** Closing the field clears it, so reopening it never resumes an old search. */ - internal fun toggleSearch() { - searchOpen = !searchOpen - if (!searchOpen) sidebarQuery = "" - } - - internal companion object { - private const val SETTINGS_PAGE_PLACEHOLDER = "GENERAL" - - // Enums are not saveable, so the surface crosses as its name — a stable - // identifier, unlike an ordinal, if a case is ever inserted. - val Saver: Saver = listSaver( - save = { - listOf( - it.surface.name, - it.showSettings, - // Index 2 held the settings page, when there were two - // (GENERAL and REMOTE). There is one now; the slot keeps - // the name every build can read so positions line up. - SETTINGS_PAGE_PLACEHOLDER, - it.showAccount, - it.accountReturnsToSettings, - it.searchOpen, - it.sidebarQuery, - it.remoteSessionId, - it.remoteCreating, - // Index 9 held a retired connection-overlay request. It - // stays a placeholder so the positions older builds wrote - // still line up with what [restore] reads. - false, - it.remoteConnectOpen, - it.pendingRemoteSessionId, - ) - }, - restore = { - AppShellState( - surface = MobileSurface.REMOTE, - showSettings = it[1] as Boolean, - // Index 2 is ignored: an old "REMOTE" and "GENERAL" both - // restore to the single settings page. - showAccount = it[3] as Boolean, - accountReturnsToSettings = it[4] as Boolean, - searchOpen = it[5] as Boolean, - sidebarQuery = it[6] as String, - remoteSessionId = it.getOrNull(7) as String?, - remoteCreating = it.getOrNull(8) as? Boolean ?: false, - // A state saved before index 10 existed only knew the - // retired connection-overlay request, which opened the - // account device sheet. - remoteConnectOpen = it.getOrNull(10) as? Boolean - ?: (it.getOrNull(9) as? Boolean ?: false), - pendingRemoteSessionId = it.getOrNull(11) as? String?, - ) - }, - ) - } -} - -internal fun resolveRoutedRemoteSessionId( - pendingSessionId: String?, - requestedSessionId: String?, - committedSessionIds: Set, - selectedSessionId: String?, -): String? = pendingSessionId - ?: requestedSessionId?.takeIf { it in committedSessionIds || it == selectedSessionId } - ?: selectedSessionId - -@Composable -internal fun rememberAppShellState(): AppShellState = rememberSaveable(saver = AppShellState.Saver) { - AppShellState( - surface = MobileSurface.REMOTE, - showSettings = false, - showAccount = false, - accountReturnsToSettings = false, - searchOpen = false, - sidebarQuery = "", - remoteSessionId = null, - remoteCreating = false, - ) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/SessionViewSettings.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/SessionViewSettings.kt deleted file mode 100644 index b31f84a4b4..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/state/SessionViewSettings.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.openbitfun.mobile.app.state - -import androidx.compose.runtime.saveable.Saver -import androidx.compose.runtime.saveable.listSaver -import com.openbitfun.mobile.core.feature.session.SessionAgentGroup -import com.openbitfun.mobile.core.feature.session.SessionGroupMode -import com.openbitfun.mobile.core.feature.session.SessionListOptions - -/** - * How the user wants the session list drawn, ported from the state - * `RemoteSurfaceHost.ets` keeps for `ConversationViewSettings`. - * - * It is view state, not session state: nothing here reaches the desktop, and - * losing it on sign-out costs nothing. It survives rotation via [Saver] and - * nothing more, which is also all the source keeps. - */ -internal data class SessionViewSettings( - val groupMode: SessionGroupMode, - val workspaceFilter: String, - val agentFilter: SessionAgentGroup?, - val statusFilter: String, - val showWorkspace: Boolean, - val showUpdated: Boolean, - val showStatus: Boolean, -) { - fun options(query: String): SessionListOptions = SessionListOptions( - groupMode = groupMode, - query = query, - workspaceFilter = workspaceFilter, - agentFilter = agentFilter, - statusFilter = statusFilter, - ) - - companion object { - /** Same defaults as the source: grouped by project, nothing filtered, no metadata. */ - val Default: SessionViewSettings = SessionViewSettings( - groupMode = SessionGroupMode.PROJECT, - workspaceFilter = "", - agentFilter = null, - statusFilter = "", - showWorkspace = false, - showUpdated = false, - showStatus = false, - ) - - // Enums are not saveable, so both go across as their names — stable - // identifiers, unlike ordinals, if a case is ever inserted. - val Saver: Saver = listSaver( - save = { - listOf( - it.groupMode.name, - it.workspaceFilter, - it.agentFilter?.name.orEmpty(), - it.statusFilter, - it.showWorkspace, - it.showUpdated, - it.showStatus, - ) - }, - restore = { - SessionViewSettings( - groupMode = SessionGroupMode.valueOf(it[0] as String), - workspaceFilter = it[1] as String, - agentFilter = (it[2] as String).takeIf { name -> name.isNotEmpty() } - ?.let { name -> SessionAgentGroup.valueOf(name) }, - statusFilter = it[3] as String, - showWorkspace = it[4] as Boolean, - showUpdated = it[5] as Boolean, - showStatus = it[6] as Boolean, - ) - }, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountLoginScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountLoginScreen.kt deleted file mode 100644 index 49acd5dba8..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountLoginScreen.kt +++ /dev/null @@ -1,144 +0,0 @@ -package com.openbitfun.mobile.app.ui.account - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.openbitfun.mobile.app.ui.common.ConnectionSheetHeader -import com.openbitfun.mobile.app.ui.common.ConnectionSheetFooter -import com.openbitfun.mobile.app.ui.common.connectionSheetTextStyle -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.viewmodel.AccountViewModel -import com.openbitfun.mobile.core.feature.account.AccountFailureReason -import com.openbitfun.mobile.core.feature.account.AccountIntent -import com.openbitfun.mobile.core.feature.account.AccountUiState -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry - -/** - * The login step, and only that. A signed-in account is shown inside every - * settings page (see [AccountSettingsIdentityCard]), so once login lands the - * shell closes this sheet and puts the user on settings; the spinner covers the - * moment between the callback and that hand-off. - */ -@Composable -internal fun AccountLoginScreen( - modifier: Modifier, - onBack: () -> Unit = {}, - viewModel: AccountViewModel = viewModel(factory = AccountViewModel.Factory), -) { - val state by viewModel.state.collectAsStateWithLifecycle() - when (val current = state) { - AccountUiState.Idle, AccountUiState.Restoring, is AccountUiState.Ready -> - Box(modifier.fillMaxWidth().heightIn(min = MobileDesignGeometry.LoginSheetBodyMinHeight), contentAlignment = Alignment.Center) { - CircularProgressIndicator() - } - AccountUiState.SigningIn, AccountUiState.SignedOut, is AccountUiState.Authorizing, is AccountUiState.Failed -> AccountLoginPage( - state = current, - onBack = onBack, - onLogin = { viewModel.dispatch(AccountIntent.Login) }, - modifier = modifier, - ) - } -} - -@Composable -internal fun AccountLoginPage( - state: AccountUiState, - onBack: () -> Unit, - onLogin: () -> Unit, - modifier: Modifier, - openAuthorization: ((String) -> Unit)? = null, -) { - val busy = state is AccountUiState.SigningIn || state is AccountUiState.Authorizing - val locale = androidx.compose.ui.platform.LocalConfiguration.current.locales[0].toLanguageTag() - val authorizationUrl = (state as? AccountUiState.Authorizing)?.authorizationUrl?.let { value -> - val uri = android.net.Uri.parse(value) - if (uri.scheme == "https" && uri.host == "auth.openbitfun.com") { - uri.buildUpon() - .appendQueryParameter("locale", locale) - .appendQueryParameter("returnTo", "openbitfun://auth/callback") - .build().toString() - } else value - } - val uriHandler = androidx.compose.ui.platform.LocalUriHandler.current - var launchedAuthorizationUrl by rememberSaveable { mutableStateOf(null) } - var launchFailed by rememberSaveable(authorizationUrl) { mutableStateOf(false) } - val launchAuthorization = { - authorizationUrl?.let { url -> - launchedAuthorizationUrl = url - launchFailed = runCatching { - if (openAuthorization != null) openAuthorization(url) else uriHandler.openUri(url) - }.isFailure - } - Unit - } - LaunchedEffect(authorizationUrl) { - if (authorizationUrl == null) launchedAuthorizationUrl = null - else if (launchedAuthorizationUrl != authorizationUrl) launchAuthorization() - } - val canSubmit = !busy || launchFailed - Column(modifier.fillMaxWidth()) { - ConnectionSheetHeader(onBack, uniformGlyph = true) - Box(Modifier.weight(1f, fill = false).fillMaxWidth(), contentAlignment = Alignment.TopCenter) { - Column( - modifier = Modifier.fillMaxWidth().verticalScroll(rememberScrollState()) - .padding(horizontal = 20.dp).heightIn(min = MobileDesignGeometry.LoginSheetBodyMinHeight), - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Text(stringResource(R.string.account_login_title), - style = MaterialTheme.typography.displayMedium.connectionSheetTextStyle(), textAlign = TextAlign.Center) - Text(stringResource(R.string.account_login_body), - style = MaterialTheme.typography.bodyMedium.connectionSheetTextStyle(), - color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, - modifier = Modifier.padding(top = 8.dp)) - if (launchFailed) { - Text(stringResource(R.string.account_authorization_open_failed), color = MaterialTheme.colorScheme.error, - style = MaterialTheme.typography.bodySmall.connectionSheetTextStyle(), modifier = Modifier.padding(top = 12.dp)) - } - (state as? AccountUiState.Failed)?.let { failure -> - Text(stringResource(failure.reason.messageRes()), color = MaterialTheme.colorScheme.error, - style = MaterialTheme.typography.bodySmall.connectionSheetTextStyle(), modifier = Modifier.padding(top = 12.dp)) - } - } - } - ConnectionSheetFooter( - label = stringResource(when { - launchFailed -> R.string.sessions_retry - busy -> R.string.account_signing_in - else -> R.string.account_login_title - }), - primary = true, elevated = false, enabled = canSubmit, - onClick = { if (launchFailed) launchAuthorization() else onLogin() }, - ) - } -} - -internal fun AccountFailureReason.messageRes(): Int = when (this) { - AccountFailureReason.INVALID_CREDENTIALS -> R.string.account_invalid_credentials - AccountFailureReason.AUTHENTICATION -> R.string.account_authentication - AccountFailureReason.RATE_LIMITED -> R.string.account_rate_limited - AccountFailureReason.RELAY_UNAVAILABLE -> R.string.account_relay_unavailable - AccountFailureReason.NETWORK -> R.string.account_network - AccountFailureReason.TIMEOUT -> R.string.account_timeout - AccountFailureReason.MALFORMED_RESPONSE -> R.string.account_malformed_response - AccountFailureReason.SECURE_STORAGE -> R.string.account_secure_storage -} 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 deleted file mode 100644 index cd0373d350..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountProfileCards.kt +++ /dev/null @@ -1,342 +0,0 @@ -package com.openbitfun.mobile.app.ui.account - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.defaultMinSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.produceState -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.platform.loadAccountAvatar -import com.openbitfun.mobile.app.ui.settings.SettingsCard -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.account.AccountUiState - -internal const val ACCOUNT_SETTINGS_SIGN_IN_TEST_TAG: String = "account-settings-sign-in" -internal const val ACCOUNT_SETTINGS_DEVICES_TEST_TAG: String = "account-settings-devices" -internal const val ACCOUNT_SETTINGS_REFRESH_TEST_TAG: String = "account-settings-refresh" -internal const val ACCOUNT_SETTINGS_SIGN_OUT_TEST_TAG: String = "account-settings-sign-out" - -internal fun accountSettingsDeviceTestTag(deviceId: String): String = "account-settings-device-$deviceId" - -/* - * The account, embedded in every settings page the way `SettingsSheet.ets` - * embeds `AccountProfilePanel` with `embeddedInSettings: true`: identity at the - * top, the account's devices in the middle, sign out at the bottom. There is no - * separate profile page to open any more; the only separate step left is the - * login sheet, which a signed-out identity card leads to. - */ - -/** Who is signed in, or, when nobody is, the door to signing in. */ -@Composable -internal fun AccountSettingsIdentityCard( - account: AccountUiState.Ready?, - onSignIn: () -> Unit, - modifier: Modifier, -) { - Column(modifier = modifier.fillMaxWidth()) { - AccountSectionTitle(stringResource(R.string.settings_account), Modifier.padding(bottom = 8.dp)) - SettingsCard( - modifier = Modifier, - radius = MobileDesignGeometry.SettingsCompactCardRadius, - bordered = false, - ) { - val signInLabel = stringResource(R.string.sidebar_sign_in) - Row( - modifier = Modifier - .fillMaxWidth() - .then( - if (account == null) { - Modifier - .clickable(role = Role.Button, onClick = onSignIn) - .semantics(mergeDescendants = true) { contentDescription = signInLabel } - .testTag(ACCOUNT_SETTINGS_SIGN_IN_TEST_TAG) - } else { - Modifier - }, - ) - .defaultMinSize(minHeight = 76.dp) - .padding(horizontal = 18.dp, vertical = 14.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - AccountAvatar(46, account?.avatarUrl) - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - account?.username?.ifBlank { account.userId } - ?: stringResource(R.string.settings_account_signed_out), - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - account?.userId ?: signInLabel, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - if (account != null) { - Text( - stringResource(R.string.remote_settings_account_signed_in), - style = MaterialTheme.typography.bodySmall, - color = openBitFunColors.statusSuccess, - ) - } else { - Icon( - painterResource(R.drawable.ic_symbol_chevron_right), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - } - } - } -} - -/** - * The account's desktops, picked in place. Selecting one is the same command the - * sidebar and the connect sheet send; the caller decides where the user lands. - */ -@Composable -internal fun AccountSettingsDevicesSection( - account: AccountUiState.Ready?, - onRefresh: () -> Unit, - onSelect: (String) -> Unit, - modifier: Modifier, -) { - Column(modifier = modifier.fillMaxWidth()) { - Row( - modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - AccountSectionTitle(stringResource(R.string.settings_devices_section), Modifier.weight(1f)) - if (account != null) { - val refreshLabel = stringResource(R.string.account_devices_refresh) - Surface( - onClick = onRefresh, - enabled = !account.refreshing, - shape = CircleShape, - color = MaterialTheme.colorScheme.surface, - modifier = Modifier - .size(36.dp) - .semantics { contentDescription = refreshLabel } - .testTag(ACCOUNT_SETTINGS_REFRESH_TEST_TAG), - ) { - Box(contentAlignment = Alignment.Center) { - if (account.refreshing) { - CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp)) - } else { - Icon( - painterResource(R.drawable.ic_symbol_arrow_clockwise), - contentDescription = null, - modifier = Modifier.size(18.dp), - ) - } - } - } - } - } - SettingsCard( - modifier = Modifier.testTag(ACCOUNT_SETTINGS_DEVICES_TEST_TAG), - radius = MobileDesignGeometry.SettingsCompactCardRadius, - bordered = false, - ) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 18.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - when { - account == null -> DevicesNote(stringResource(R.string.account_devices_sign_in_required)) - account.devices.isEmpty() && account.refreshing -> - DevicesNote(stringResource(R.string.account_devices_loading)) - else -> { - account.refreshFailure?.let { reason -> - Text( - stringResource(reason.messageRes()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - if (account.devices.isEmpty()) { - DevicesNote(stringResource(R.string.account_devices_empty)) - } - account.devices.forEach { device -> - val selected = device.id == account.selectedDeviceId - val reconnectable = selected && !device.online - Row( - modifier = Modifier - .fillMaxWidth() - .defaultMinSize(minHeight = 54.dp) - .clip(RoundedCornerShape(10.dp)) - .clickable( - enabled = device.online || reconnectable, - role = Role.Button, - onClick = { onSelect(device.id) }, - ) - .testTag(accountSettingsDeviceTestTag(device.id)), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Icon( - painterResource(R.drawable.ic_symbol_desktop), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(24.dp), - ) - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - device.displayName, - fontSize = 15.sp, - fontWeight = FontWeight.Medium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - stringResource( - when { - selected && device.online -> R.string.account_device_current_control - device.online -> R.string.account_online - else -> R.string.account_offline - }, - ), - fontSize = 13.sp, - color = if (device.online) { - openBitFunColors.statusSuccess - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - ) - } - when { - reconnectable -> DeviceActionChip(stringResource(R.string.remote_settings_reconnect)) - device.online && !selected -> DeviceActionChip(stringResource(R.string.account_connect)) - } - } - } - } - } - } - } - } -} - -/** Sign out, set apart and in the danger colour as `LogoutAction()` is. */ -@Composable -internal fun AccountSettingsSignOutRow(onSignOut: () -> Unit, modifier: Modifier) { - Column(modifier = modifier.fillMaxWidth()) { - HorizontalDivider(Modifier.padding(bottom = 12.dp), color = MaterialTheme.colorScheme.outlineVariant) - Row( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(MobileDesignGeometry.SettingsCompactCardRadius)) - .clickable(role = Role.Button, onClick = onSignOut) - .defaultMinSize(minHeight = 56.dp) - .padding(horizontal = 18.dp) - .testTag(ACCOUNT_SETTINGS_SIGN_OUT_TEST_TAG), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(14.dp), - ) { - Icon( - painterResource(R.drawable.ic_symbol_arrow_right_and_square), - contentDescription = null, - tint = MaterialTheme.colorScheme.error, - modifier = Modifier.size(22.dp), - ) - Text( - stringResource(R.string.account_sign_out), - fontSize = 17.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.error, - ) - } - } -} - -@Composable -private fun AccountSectionTitle(text: String, modifier: Modifier) { - Text( - text, - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = modifier.padding(start = 12.dp), - ) -} - -@Composable -private fun DevicesNote(text: String) { - Text( - text, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp), - ) -} - -@Composable -private fun DeviceActionChip(label: String) { - Surface(color = MaterialTheme.colorScheme.surfaceVariant, shape = RoundedCornerShape(14.dp)) { - Text(label, fontSize = 14.sp, modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)) - } -} - -@Composable -internal fun AccountAvatar(size: Int, url: String? = null) { - val bitmap by produceState(null, url) { - value = null - value = loadAccountAvatar(url) - } - Box( - Modifier.size(size.dp).clip(CircleShape).background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - val loaded = bitmap - if (loaded != null) { - androidx.compose.foundation.Image( - bitmap = loaded.asImageBitmap(), - contentDescription = null, - contentScale = ContentScale.Crop, - modifier = Modifier.size(size.dp), - ) - } else { - Icon( - painterResource(R.drawable.ic_symbol_person), - contentDescription = null, - modifier = Modifier.size((size * 0.52f).dp), - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt deleted file mode 100644 index 0e33b988e0..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatMessageBubble.kt +++ /dev/null @@ -1,187 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.message.ChatMessageRetryAction -import com.openbitfun.mobile.app.ui.chat.message.ChatTypingDots -import com.openbitfun.mobile.app.ui.chat.message.ChatUserMessageBubble -import com.openbitfun.mobile.app.ui.chat.message.MessageBlockCallbacks -import com.openbitfun.mobile.app.ui.chat.message.MessageBlockList -import com.openbitfun.mobile.app.ui.chat.message.MessageImageGallery -import com.openbitfun.mobile.app.ui.chat.message.ThinkingBlock -import com.openbitfun.mobile.app.ui.chat.tool.ToolStatusList -import com.openbitfun.mobile.core.feature.session.ConversationRow -import com.openbitfun.mobile.core.feature.session.QuestionAnswer -import com.openbitfun.mobile.core.feature.session.ConversationRowKind -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState - -internal const val BUBBLE_TEST_TAG: String = "chat-bubble" - -/** - * One turn, ported from `pages/components/ChatMessageBubble.ets`. - * - * The user's own words sit right and tinted; the agent's sit left on the plain - * surface, because an agent turn can be long and reversed contrast is tiring to - * read. Reasoning and tools hang off the agent side only. - */ -@Composable -internal fun ChatMessageBubble( - row: ConversationRow, - enabled: Boolean, - onApproveTool: (String, String?) -> Unit, - onRejectTool: (String, String) -> Unit, - onCancelTool: (String, String) -> Unit, - onAnswerTool: (String, String) -> Unit, - onAnswerToolStructured: (String, List) -> Unit, - onRetry: (ConversationRow) -> Unit, - onOpenLink: (String, String) -> Unit, - /** The file the preview surface is showing, so its card can say so. */ - previewingRemotePath: String, - previewLoading: Boolean, - download: RemoteFileDownloadUiState = RemoteFileDownloadUiState.None, - onDownloadFile: (String, String) -> Unit = { _, _ -> }, - downloadEnabled: Boolean = true, - modifier: Modifier, -) { - val fromUser = row.kind == ConversationRowKind.USER - Column( - modifier = modifier - .fillMaxWidth() - .padding( - top = if (fromUser) 8.dp else 2.dp, - bottom = if (fromUser) 12.dp else 10.dp, - ) - .testTag(BUBBLE_TEST_TAG), - horizontalAlignment = if (fromUser) Alignment.End else Alignment.Start, - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - if (fromUser) { - ChatUserMessageBubble(row.text, row.images, Modifier) - } else { - AssistantContent( - row = row, - callbacks = MessageBlockCallbacks( - enabled = enabled, - onApproveTool = onApproveTool, - onRejectTool = onRejectTool, - onCancelTool = onCancelTool, - onAnswerTool = onAnswerTool, - onAnswerToolStructured = onAnswerToolStructured, - onOpenLink = onOpenLink, - previewingRemotePath = previewingRemotePath, - previewLoading = previewLoading, - download = download, - onDownloadFile = onDownloadFile, - downloadEnabled = downloadEnabled, - ), - ) - MessageImageGallery(images = row.images, userStyle = false) - } - - row.timestampMs?.let { timestamp -> - val locale = LocalConfiguration.current.locales[0] - Text( - java.text.DateFormat.getDateTimeInstance( - java.text.DateFormat.SHORT, java.text.DateFormat.SHORT, locale, - ).format(java.util.Date(timestamp)), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.testTag("chat-message-timestamp"), - ) - } - - // Two mutually exclusive footnotes about delivery: nothing has arrived - // yet, or the send was refused. - when { - row.showRetry -> ChatMessageRetryAction( - fromUser = fromUser, - enabled = enabled, - onRetry = { onRetry(row) }, - modifier = Modifier, - ) - - row.typing -> ChatTypingDots(Modifier) - } - } -} - -/** - * The agent's side, drawn either as the ordered turn the agent produced or, when - * it produced no such structure, as the plain answer it is. - * - * The fork is the shared layer's: [ConversationRow.blocks] is populated only for - * turns whose ordering carries meaning, and it already contains everything the - * flat fields would have shown. - */ -@Composable -private fun AssistantContent(row: ConversationRow, callbacks: MessageBlockCallbacks) { - if (row.blocks.isNotEmpty()) { - MessageBlockList(row.blocks, callbacks, Modifier) - return - } - - row.thinking?.let { ThinkingBlock(it, row.streaming, row.id) } - if (row.text.isNotEmpty()) { - // No bubble on this side, matching `ChatMessageChrome.ets`: an agent - // turn carries headings, lists and code cards, and a rounded tint - // around all of that reads as one quoted lump. - MarkdownContent( - text = row.text, - onOpenLink = callbacks.onOpenLink, - modifier = Modifier, - streaming = row.streaming, - ) - FileReferenceCards( - text = row.text, - previewingRemotePath = callbacks.previewingRemotePath, - previewLoading = callbacks.previewLoading, - download = callbacks.download, - onOpen = callbacks.onOpenLink, - onDownload = callbacks.onDownloadFile, - downloadEnabled = callbacks.downloadEnabled, - modifier = Modifier, - ) - } - if (row.tools.isNotEmpty()) { - ToolStatusList( - tools = row.tools, - enabled = callbacks.enabled, - onApprove = callbacks.onApproveTool, - onReject = callbacks.onRejectTool, - onCancel = callbacks.onCancelTool, - onAnswer = callbacks.onAnswerTool, - onAnswerStructured = callbacks.onAnswerToolStructured, - onOpenFile = callbacks.onOpenLink, - modifier = Modifier, - ) - } -} - -/** The invitation shown when a session has no messages at all. */ -@Composable -internal fun ConversationEmptyState(modifier: Modifier) { - Column( - modifier = modifier.fillMaxWidth().padding(vertical = 32.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text(stringResource(R.string.chat_empty_title), style = MaterialTheme.typography.titleMedium) - Text( - stringResource(R.string.chat_empty_hint), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatStatusBar.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatStatusBar.kt deleted file mode 100644 index fd85ad166f..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ChatStatusBar.kt +++ /dev/null @@ -1,121 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.role -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.common.chatStatusBarCopy -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.ConnectionStatusPresenter -import com.openbitfun.mobile.core.feature.connection.ConnectionTone - -internal const val CHAT_STATUS_BAR_TEST_TAG: String = "chat-status-bar" -internal const val CHAT_STATUS_DOT_TEST_TAG: String = "chat-status-dot" -internal const val CHAT_STATUS_STOP_TEST_TAG: String = "chat-status-stop" - -/** The relay state strip between the conversation header and transcript. */ -@Composable -internal fun ChatStatusBar( - phase: ConnectionPhase, - canStop: Boolean, - onStop: () -> Unit, - modifier: Modifier = Modifier, -) { - val line = MaterialTheme.colorScheme.outlineVariant - val copy = phase.chatStatusBarCopy(canStop) - val title = stringResource(copy.title) - val detail = stringResource(copy.detail) - val stopLabel = stringResource(R.string.message_stop) - val statusLabel = if (detail != title) "$title · $detail" else title - val statusColor = when (ConnectionStatusPresenter.tone(phase)) { - ConnectionTone.OK -> openBitFunColors.statusSuccess - ConnectionTone.BUSY -> MaterialTheme.colorScheme.onSurfaceVariant - ConnectionTone.ERROR -> MaterialTheme.colorScheme.error - ConnectionTone.MUTED -> MaterialTheme.colorScheme.onSurfaceVariant - } - Row( - modifier = modifier - .testTag(CHAT_STATUS_BAR_TEST_TAG) - .fillMaxWidth() - .height(48.dp) - .drawBehind { - val stroke = 1.dp.toPx() - drawLine(line, start = androidx.compose.ui.geometry.Offset.Zero, end = androidx.compose.ui.geometry.Offset(size.width, 0f), strokeWidth = stroke) - drawLine(line, start = androidx.compose.ui.geometry.Offset(0f, size.height), end = androidx.compose.ui.geometry.Offset(size.width, size.height), strokeWidth = stroke) - } - .padding(horizontal = 24.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (canStop) Spacer(Modifier.width(68.dp)) - Row( - modifier = Modifier.weight(1f), - horizontalArrangement = if (canStop) Arrangement.Center else Arrangement.Start, - verticalAlignment = Alignment.CenterVertically, - ) { - Box( - Modifier - .testTag(CHAT_STATUS_DOT_TEST_TAG) - .size(8.dp) - .background(statusColor, CircleShape), - ) - Spacer(Modifier.width(7.dp)) - Text( - statusLabel, - fontSize = 13.sp, - color = if (canStop) MaterialTheme.colorScheme.onSurfaceVariant else statusColor, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - if (canStop) { - Box( - modifier = Modifier - .width(68.dp) - .height(34.dp) - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(17.dp)) - .clickable(role = Role.Button, onClick = onStop) - .semantics { - contentDescription = stopLabel - role = Role.Button - } - .testTag(CHAT_STATUS_STOP_TEST_TAG), - contentAlignment = Alignment.Center, - ) { - Text( - stopLabel, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - ) - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt deleted file mode 100644 index e4020c7513..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt +++ /dev/null @@ -1,870 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.core.animateDpAsState -import androidx.compose.animation.core.tween -import androidx.compose.animation.expandHorizontally -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut -import androidx.compose.animation.shrinkHorizontally -import androidx.compose.animation.slideInVertically -import androidx.compose.animation.slideOutVertically -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.Image -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.lazy.LazyRow -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Icon -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.rememberModalBottomSheetState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.draw.clip -import androidx.compose.ui.focus.onFocusChanged -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.role -import androidx.compose.ui.semantics.selected -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.OpenBitFunEaseOut -import com.openbitfun.mobile.app.ui.theme.MotionQuickMillis -import com.openbitfun.mobile.app.ui.theme.MotionStructureMillis -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignBreakpoints -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ChatComposerPolicy -import com.openbitfun.mobile.core.feature.session.ComposerImage -import com.openbitfun.mobile.core.feature.session.ComposerPrimaryAction -import com.openbitfun.mobile.core.feature.session.ModelOption -import com.openbitfun.mobile.core.feature.session.ModelRole - -internal const val COMPOSER_TEST_TAG: String = "composer" -internal const val COMPOSER_INPUT_TEST_TAG: String = "composer-input" -internal const val COMPOSER_SEND_TEST_TAG: String = "composer-send" -internal const val MODEL_CONTROL_TEST_TAG: String = "composer-model-control" -internal const val MODEL_SELECTOR_TEST_TAG: String = "composer-model-selector" -internal const val MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX: String = "composer-model-option:" - -/** The relay refuses more than this, and refusing here is a better error. */ -internal const val MAX_COMPOSER_IMAGES: Int = 4 - -internal fun composerIsWide(screenWidthDp: Int): Boolean = - screenWidthDp >= MobileDesignBreakpoints.Wide - -// The measurements come straight from `ComposerBar.ets`, which sizes the bar in -// vp — the same unit as dp. Naming them keeps the two files diffable. -private val ActionSize = MobileDesignGeometry.ComposerActionSize -private val InputHeight = MobileDesignGeometry.ComposerInputHeight -private val ExpandedInputHeight = MobileDesignGeometry.ComposerExpandedInputHeight -private val CollapsedBarHeight = MobileDesignGeometry.ComposerCollapsedHeight -private val ExpandedInputRowHeight = MobileDesignGeometry.ComposerExpandedInputRowHeight -private val ExpandedActionRowHeight = MobileDesignGeometry.ComposerExpandedActionRowHeight - -/** - * The input bar, ported from `pages/components/ComposerBar.ets`. - * - * It is a floating pill rather than a docked band, and it has two forms: a - * one-line row while the user is elsewhere, and a taller one — field on its own - * row, controls beneath — once they are writing. Both are [ChatComposerPolicy]'s - * call rather than this file's, along with which single action the round button - * on the right is offering. The two clients must agree on all of it: a message - * refused after the fact reads as a lost message. - * - * [capabilities] is what lets general chat reuse the bar unchanged: it has no - * desktop to wait for and no attachment pipeline, and hiding those controls is - * the difference between the two surfaces, not a second widget. - * - * There is no in-app listening state here, unlike HarmonyOS: Android dictation - * is a system activity that draws its own listening UI on top of this one. - */ -@Composable -internal fun ComposerBar( - draft: String, - images: List, - busy: Boolean, - /** The draft may be edited while a newly opened session is hydrating. */ - inputEnabled: Boolean = !busy, - streaming: Boolean, - phase: ConnectionPhase, - model: ModelOption?, - modelOptions: List = emptyList(), - /** - * Whether the model catalog command failed and left no selectable models. - * When true the bar still offers the model control so the settings sheet can - * explain the failure and offer Retry, instead of silently dropping the - * control and hiding the only route to that explanation. - */ - modelCatalogFailed: Boolean = false, - capabilities: ChatComposerCapabilities, - /** - * What the empty field says. Every surface asks for something different — - * a message into an open session, or the first instruction of a session - * that does not exist yet — and the source gives each its own wording. - */ - placeholder: String, - onDraftChange: (String) -> Unit, - promptSuggestion: String? = null, - queueAttached: Boolean = false, - onRemoveImage: (String) -> Unit, - onAttach: () -> Unit, - onVoice: () -> Unit, - onSend: () -> Unit, - onStop: () -> Unit, - onOpenModels: () -> Unit, - onSelectModel: (String) -> Unit = {}, - modifier: Modifier, -) { - val inputFocusRequester = remember { FocusRequester() } - var modelSelectorOpen by remember { mutableStateOf(false) } - var focused by remember { mutableStateOf(false) } - val expanded = ChatComposerPolicy.isExpanded( - text = draft, - inputFocused = focused, - // Android has no quick-action panel — the add button opens the system - // photo picker directly — and the model list is a sheet that covers the - // bar rather than a popover anchored to it. - quickActionsOpen = false, - modelSelectorOpen = modelSelectorOpen, - ) - val action = ChatComposerPolicy.primaryAction( - text = draft, - attachmentCount = images.size, - busy = busy, - streaming = streaming, - requiresRemoteConnection = capabilities.requiresRemoteConnection, - phase = phase, - showVoiceInput = capabilities.showVoiceInput, - ) - val structureSpec = tween( - durationMillis = MotionStructureMillis, - easing = OpenBitFunEaseOut, - ) - val radius by animateDpAsState( - if (expanded || images.isNotEmpty()) { - MobileDesignGeometry.ComposerExpandedRadius - } else { - MobileDesignGeometry.ComposerCollapsedRadius - }, - structureSpec, - label = "composer-radius", - ) - val contentTopPadding by animateDpAsState( - if (expanded) 4.dp else 0.dp, - structureSpec, - label = "composer-top-padding", - ) - val contentBottomPadding by animateDpAsState( - if (expanded) 2.dp else 0.dp, - structureSpec, - label = "composer-bottom-padding", - ) - val inputRowHeight by animateDpAsState( - if (expanded) ExpandedInputRowHeight else CollapsedBarHeight, - structureSpec, - label = "composer-input-row-height", - ) - val actionSpacing by animateDpAsState( - if (expanded) 0.dp else 5.dp, - structureSpec, - label = "composer-action-spacing", - ) - val actionRowOffset = with(LocalDensity.current) { 8.dp.roundToPx() } - val actionEnter = fadeIn(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) + - slideInVertically(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) { actionRowOffset } - val actionExit = fadeOut(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) + - slideOutVertically(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) { actionRowOffset } - val compactControlEnter = fadeIn(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) + - expandHorizontally(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) - val compactControlExit = fadeOut(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) + - shrinkHorizontally(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) - - Column( - modifier = modifier - .fillMaxWidth() - .padding( - start = MobileDesignGeometry.ConversationOverlaySideInset, - end = MobileDesignGeometry.ConversationOverlaySideInset, - top = if (queueAttached) 0.dp else 8.dp, - bottom = 14.dp, - ) - .testTag(COMPOSER_TEST_TAG), - ) { - if (!promptSuggestion.isNullOrEmpty() && draft.isEmpty() && !busy && !streaming && inputEnabled && - phase == ConnectionPhase.CONNECTED) { - val acceptLabel = stringResource(R.string.prompt_suggestion_accept) - TextButton( - onClick = { - onDraftChange(promptSuggestion) - inputFocusRequester.requestFocus() - }, - modifier = Modifier.fillMaxWidth() - .heightIn(min = MobileDesignGeometry.ControlTouchSize) - .testTag("composer-prompt-suggestion") - .semantics { contentDescription = "$acceptLabel: $promptSuggestion" }, - ) { - Text(promptSuggestion, style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth()) - } - } - Surface( - shape = RoundedCornerShape(radius), - color = MaterialTheme.colorScheme.surface, - shadowElevation = 2.dp, - modifier = Modifier.fillMaxWidth(), - ) { - Column( - verticalArrangement = Arrangement.spacedBy(2.dp), - modifier = Modifier.padding( - PaddingValues( - start = 8.dp, - end = 8.dp, - top = contentTopPadding, - bottom = contentBottomPadding, - ), - ), - ) { - if (capabilities.supportsAttachments && images.isNotEmpty()) { - AttachmentStrip( - images = images, - enabled = !busy, - onRemove = onRemoveImage, - modifier = Modifier.padding(top = 6.dp), - ) - } - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(actionSpacing), - modifier = Modifier - .fillMaxWidth() - .heightIn(min = inputRowHeight), - ) { - // While expanded both side controls move to the row below, - // so the field gets the full width for what is being typed. - AnimatedVisibility( - visible = !expanded && capabilities.supportsAttachments && capabilities.showAddButton, - enter = compactControlEnter, - exit = compactControlExit, - ) { - AddButton( - enabled = !busy && images.size < MAX_COMPOSER_IMAGES, - onClick = onAttach, - ) - } - ComposerField( - draft = draft, - enabled = inputEnabled, - expanded = expanded, - placeholder = placeholder, - onDraftChange = onDraftChange, - onFocusChange = { focused = it }, - modifier = Modifier.weight(1f).focusRequester(inputFocusRequester), - ) - AnimatedVisibility( - visible = !expanded, - enter = compactControlEnter, - exit = compactControlExit, - ) { - PrimaryActionButton( - action = action, - stopEnabled = ChatComposerPolicy.canStop(streaming, capabilities.requiresRemoteConnection, phase), - onVoice = onVoice, - onSend = onSend, - onStop = onStop, - ) - } - } - - AnimatedVisibility( - visible = expanded, - enter = actionEnter, - exit = actionExit, - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier - .fillMaxWidth() - .height(ExpandedActionRowHeight) - .padding(start = 2.dp), - ) { - if (capabilities.supportsAttachments && capabilities.showAddButton) { - AddButton( - enabled = !busy && images.size < MAX_COMPOSER_IMAGES, - onClick = onAttach, - ) - } - // The model belongs to the session, but it is chosen - // here: it is the one setting a user changes mid-turn. - if (model != null || modelOptions.isNotEmpty() || modelCatalogFailed) { - ModelControl( - model = model, - enabled = !busy, - modelOptions = modelOptions, - onClick = { - if (modelOptions.isEmpty()) onOpenModels() else modelSelectorOpen = true - }, - onSelectModel = { id -> - onSelectModel(id) - modelSelectorOpen = false - }, - selectorOpen = modelSelectorOpen, - onSelectorDismiss = { modelSelectorOpen = false }, - ) - } - Box(modifier = Modifier.weight(1f)) - if (capabilities.showVoiceInput && (draft.isNotBlank() || images.isNotEmpty())) { - PrimaryActionButton(action = if (busy) ComposerPrimaryAction.VOICE_BLOCKED else ComposerPrimaryAction.VOICE, onVoice = onVoice, onSend = onSend, onStop = onStop, testTag = "composer-voice") - } - PrimaryActionButton( - action = action, - onVoice = onVoice, - onSend = onSend, - onStop = onStop, - ) - } - } - } - } - } -} - -/** - * The field itself: a bare text field on the pill's own background. - * - * A Material `OutlinedTextField` would draw a second border and a floating label - * inside a shape that is already the input, which is why the placeholder is - * hand-drawn here. - */ -@Composable -private fun ComposerField( - draft: String, - enabled: Boolean, - expanded: Boolean, - placeholder: String, - onDraftChange: (String) -> Unit, - onFocusChange: (Boolean) -> Unit, - modifier: Modifier, -) { - val colors = MaterialTheme.colorScheme - BasicTextField( - value = draft, - onValueChange = onDraftChange, - enabled = enabled, - // Collapsed the bar is one line tall, so the field must not grow past - // it; expanded it stops at four and scrolls, as the other client does. - maxLines = if (expanded) 4 else 1, - textStyle = MaterialTheme.typography.bodyLarge.copy(color = colors.onSurface), - cursorBrush = SolidColor(colors.onSurface), - modifier = modifier - .heightIn(min = if (expanded) ExpandedInputHeight else InputHeight) - .onFocusChanged { onFocusChange(it.isFocused) } - .testTag(COMPOSER_INPUT_TEST_TAG), - decorationBox = { field -> - Box( - contentAlignment = Alignment.CenterStart, - modifier = Modifier.padding( - start = 4.dp, - end = 4.dp, - top = if (expanded) 10.dp else 9.dp, - bottom = if (expanded) 8.dp else 9.dp, - ), - ) { - if (draft.isEmpty()) { - Text( - placeholder, - style = MaterialTheme.typography.bodyLarge, - color = colors.onSurfaceVariant, - ) - } - // Focus expands the same editor. At rest, render a one-line - // preview so overflow cannot scroll sideways or lose the draft. - Box(Modifier.alpha(if (!expanded && draft.isNotEmpty()) 0f else 1f)) { field() } - if (!expanded && draft.isNotEmpty()) Text( - draft, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - style = MaterialTheme.typography.bodyLarge, - color = colors.onSurface, - modifier = Modifier.fillMaxWidth().clearAndSetSemantics {}, - ) - } - }, - ) -} - -/** The attachment control: a plain glyph, sized to match the primary action. */ -@Composable -private fun AddButton(enabled: Boolean, onClick: () -> Unit) { - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .size(ActionSize) - .clip(CircleShape) - .clickable(role = Role.Button, enabled = enabled, onClick = onClick), - ) { - Icon( - painterResource(R.drawable.ic_symbol_plus), - contentDescription = stringResource(R.string.message_attach_image), - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(22.dp).alpha(if (enabled) 1f else DimmedAlpha), - ) - } -} - -/** - * The current model, as a label the user can press rather than a chip. - * - * It only exists in the expanded form, matching the other client: a model swap - * is something you do while writing the message it applies to. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun ModelControl( - model: ModelOption?, - enabled: Boolean, - modelOptions: List, - onClick: () -> Unit, - onSelectModel: (String) -> Unit, - selectorOpen: Boolean, - onSelectorDismiss: () -> Unit, -) { - val label = stringResource(R.string.models_title) - val displayModel = model ?: modelOptions.firstOrNull { it.selected } - val displayLabel = displayModel?.let { modelOptionTitle(it) } ?: label - val wide = composerIsWide(LocalConfiguration.current.screenWidthDp) - Box { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - modifier = Modifier - .heightIn(min = MobileDesignGeometry.ComposerActionSize) - .widthIn(max = 220.dp) - .clip(RoundedCornerShape(9.dp)) - .clickable(enabled = enabled, onClick = onClick) - .padding(horizontal = 4.dp) - .testTag(MODEL_CONTROL_TEST_TAG) - .semantics { - contentDescription = "$label · $displayLabel" - role = Role.Button - }, - ) { - Text( - displayLabel, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Icon( - painterResource( - if (selectorOpen) R.drawable.ic_symbol_chevron_up - else R.drawable.ic_symbol_chevron_down, - ), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(14.dp).alpha(0.68f), - ) - } - if (wide) { - DropdownMenu( - expanded = selectorOpen, - onDismissRequest = onSelectorDismiss, - modifier = Modifier.width(MobileDesignGeometry.ComposerModelSelectorWidth), - shape = RoundedCornerShape(MobileDesignGeometry.ComposerModelSelectorRadius), - containerColor = MaterialTheme.colorScheme.surfaceContainerLow, - tonalElevation = 0.dp, - shadowElevation = MobileDesignGeometry.PopoverShadowRadius, - border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - ) { - ModelSelectorContent( - options = modelOptions, - onSelect = onSelectModel, - compact = true, - onDismiss = onSelectorDismiss, - ) - } - } - } - if (!wide && selectorOpen) { - ModalBottomSheet( - onDismissRequest = onSelectorDismiss, - sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), - containerColor = MaterialTheme.colorScheme.surface, - shape = RoundedCornerShape( - topStart = MobileDesignGeometry.SelectionTopRadius, - topEnd = MobileDesignGeometry.SelectionTopRadius, - ), - dragHandle = null, - ) { - ModelSelectorContent( - options = modelOptions, - onSelect = onSelectModel, - compact = false, - onDismiss = onSelectorDismiss, - ) - } - } -} - -@Composable -private fun ModelSelectorContent( - options: List, - onSelect: (String) -> Unit, - compact: Boolean, - onDismiss: () -> Unit, -) { - val selectorOptions = remember(options) { - options.filter { it.role != null } + - options.filter { it.role == null && it.selected } + - options.filter { it.role == null && !it.selected } - } - val visibleRows = selectorOptions.size.coerceAtMost(7) - val listHeight = if (visibleRows == 0) { - MobileDesignGeometry.ComposerModelSelectorRowHeight - } else { - MobileDesignGeometry.ComposerModelSelectorRowHeight * visibleRows + - MobileDesignGeometry.ComposerModelSelectorRowGap * (visibleRows - 1) - } - Column( - verticalArrangement = Arrangement.spacedBy(10.dp), - modifier = Modifier - .fillMaxWidth() - // Material's anchored menu reserves 8dp vertically around its - // content. Add only the remaining 2dp there so both the popover - // and the sheet expose the HarmonyOS 10dp inner inset. - .padding(horizontal = 10.dp, vertical = if (compact) 2.dp else 10.dp) - .testTag(MODEL_SELECTOR_TEST_TAG), - ) { - if (!compact) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().heightIn(min = MobileDesignGeometry.SelectionCloseSize), - ) { - Text( - stringResource(R.string.model_selector_title), - fontSize = MaterialTheme.typography.labelLarge.fontSize, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.weight(1f), - ) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .size(MobileDesignGeometry.SelectionCloseSize) - .clip(CircleShape) - .clickable(role = Role.Button, onClick = onDismiss), - ) { - Icon( - painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(15.dp), - ) - } - } - } - if (selectorOptions.isEmpty()) { - Text( - stringResource(R.string.model_selector_empty), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .heightIn(min = MobileDesignGeometry.ComposerModelSelectorRowHeight) - .padding(horizontal = 10.dp, vertical = 14.dp), - ) - } else { - Column( - verticalArrangement = Arrangement.spacedBy( - MobileDesignGeometry.ComposerModelSelectorRowGap, - ), - modifier = Modifier - .fillMaxWidth() - .height(listHeight) - .verticalScroll(rememberScrollState()), - ) { - selectorOptions.forEachIndexed { index, option -> - if (index > 0 && option.role == null && selectorOptions[index - 1].role != null) { - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - } - val title = modelOptionTitle(option) - val subtitle = modelOptionSubtitle(option) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - modifier = Modifier - .fillMaxWidth() - .heightIn(min = MobileDesignGeometry.ComposerModelSelectorRowHeight) - .clip( - RoundedCornerShape( - MobileDesignGeometry.ComposerModelSelectorRowRadius, - ), - ) - .background( - if (option.selected) MaterialTheme.colorScheme.surfaceVariant - else openBitFunColors.transparent, - ) - .clickable { onSelect(option.id) } - .semantics { - contentDescription = - "$title · $subtitle" - role = Role.Button - selected = option.selected - } - .padding(horizontal = 10.dp, vertical = 8.dp) - .testTag(MODEL_SELECTOR_OPTION_TEST_TAG_PREFIX + option.id), - ) { - Box( - contentAlignment = Alignment.Center, - modifier = Modifier.size(20.dp), - ) { - if (option.selected) { - Icon( - painterResource(R.drawable.ic_symbol_checkmark_circle), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(16.dp), - ) - } - } - Column( - verticalArrangement = Arrangement.spacedBy(2.dp), - modifier = Modifier.weight(1f), - ) { - Text( - title, - fontSize = MaterialTheme.typography.labelLarge.fontSize, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - subtitle, - fontSize = MaterialTheme.typography.bodySmall.fontSize, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - option.roles.forEach { role -> - Text( - stringResource(if (role == ModelRole.PRIMARY) R.string.model_role_primary else R.string.model_role_fast), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(4.dp)) - .padding(horizontal = 6.dp, vertical = 1.dp), - ) - } - } - } - } - } - } -} - -@Composable -internal fun modelOptionTitle(option: ModelOption): String = when (option.role) { - ModelRole.PRIMARY -> stringResource(R.string.model_primary) - ModelRole.FAST -> stringResource(R.string.model_fast) - null -> option.primaryLabel -} - -@Composable -internal fun modelOptionSubtitle(option: ModelOption): String = - if (option.fallsBackToPrimary) stringResource(R.string.model_fast_fallback) else option.secondaryLabel - -/** What a control that is offered but not usable right now looks like. */ -private const val DimmedAlpha: Float = 0.38f - -/** - * One slot, never two actions. - * - * Which action it holds is [ChatComposerPolicy.primaryAction]'s decision; this - * only draws it. Stop is the one state with a filled background, because it is - * the one state where pressing the button undoes something. - */ -@Composable -private fun PrimaryActionButton( - action: ComposerPrimaryAction, - stopEnabled: Boolean = true, - onVoice: () -> Unit, - onSend: () -> Unit, - onStop: () -> Unit, - testTag: String = COMPOSER_SEND_TEST_TAG, -) { - val colors = MaterialTheme.colorScheme - val enabled = (action == ComposerPrimaryAction.STOP && stopEnabled) || - action == ComposerPrimaryAction.SEND || - action == ComposerPrimaryAction.VOICE - val description = when (action) { - ComposerPrimaryAction.STOP -> R.string.message_stop - ComposerPrimaryAction.VOICE, ComposerPrimaryAction.VOICE_BLOCKED -> - R.string.message_voice_input - else -> R.string.message_send - } - val actionDescription = stringResource(description) - - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .size(ActionSize) - .clip(CircleShape) - - .clickable(enabled = enabled) { - when (action) { - ComposerPrimaryAction.STOP -> onStop() - ComposerPrimaryAction.SEND -> onSend() - ComposerPrimaryAction.VOICE -> onVoice() - else -> Unit - } - } - .semantics { - contentDescription = actionDescription - role = Role.Button - } - .testTag(testTag), - ) { - if (action == ComposerPrimaryAction.SEND || action == ComposerPrimaryAction.STOP) { - Box(Modifier.size(32.dp).clip(CircleShape).background(colors.primary)) - } - when (action) { - // The same neutral primary disc as send, matching the reference composer. - ComposerPrimaryAction.STOP -> Box( - modifier = Modifier - .size(10.dp) - .clip(RoundedCornerShape(3.dp)) - .background(colors.onPrimary), - ) - - ComposerPrimaryAction.VOICE, ComposerPrimaryAction.VOICE_BLOCKED -> Icon( - painterResource(R.drawable.ic_symbol_mic), - contentDescription = null, - tint = colors.onSurface, - modifier = Modifier.size(22.dp).alpha( - if (action == ComposerPrimaryAction.VOICE) 1f else DimmedAlpha, - ), - ) - - else -> Icon( - painterResource(R.drawable.ic_symbol_arrow_up), - contentDescription = null, - tint = if (action == ComposerPrimaryAction.SEND) colors.onPrimary else colors.onSurfaceVariant, - modifier = Modifier.size(20.dp).alpha( - if (action == ComposerPrimaryAction.SEND) 1f else DimmedAlpha, - ), - ) - } - } -} - -/** - * The pending attachments, each with its own remove control. - * - * A count alone was not enough: the picker can only add, so without a per-image - * remove the only way to drop a wrong photo was to send it. - */ -@Composable -private fun AttachmentStrip( - images: List, - enabled: Boolean, - onRemove: (String) -> Unit, - modifier: Modifier, -) { - LazyRow( - modifier = modifier.height(64.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - contentPadding = PaddingValues(end = 4.dp), - ) { - items(images, key = { it.id }) { image -> - Box(modifier = Modifier.size(64.dp)) { - val bitmap = rememberInlineImage(image.dataUrl) - if (bitmap != null) { - Image( - bitmap = bitmap.asImageBitmap(), - contentDescription = null, - contentScale = ContentScale.Crop, - modifier = Modifier.size(64.dp).clip(RoundedCornerShape(14.dp)), - ) - } else { - Surface( - color = MaterialTheme.colorScheme.surfaceVariant, - shape = RoundedCornerShape(14.dp), - modifier = Modifier.size(64.dp), - ) { - Text( - stringResource(R.string.chat_image), - style = MaterialTheme.typography.labelSmall, - modifier = Modifier.padding(4.dp), - ) - } - } - // Media controls sit over arbitrary photo content, so their - // scrim is a dedicated mobile design token. - val removeLabel = stringResource(R.string.message_remove_image) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier - .align(Alignment.TopEnd) - .size(32.dp) - .clip(CircleShape) - .background(openBitFunColors.mediaScrim) - .clickable(role = Role.Button, enabled = enabled) { onRemove(image.id) } - .semantics { contentDescription = removeLabel }, - ) { - Text( - "×", - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onPrimary, - ) - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt deleted file mode 100644 index 4bb2062a83..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerVoiceInput.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import android.app.Activity -import android.content.Intent -import android.speech.RecognizerIntent -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.platform.LocalContext -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.platform.launchComposerActivity - -/** Dictation belongs to the session that launched it, including across recreation. */ -@Composable -internal fun rememberComposerVoiceInput(owner: String, onText: (String) -> Unit): () -> Unit { - val context = LocalContext.current - var pendingOwner by rememberSaveable { mutableStateOf(null) } - val currentOwner by rememberUpdatedState(owner) - val receiveText by rememberUpdatedState(onText) - val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - val target = pendingOwner - pendingOwner = null - if (target == currentOwner && result.resultCode == Activity.RESULT_OK) { - val text = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)?.firstOrNull().orEmpty() - if (text.isNotBlank()) receiveText(text) - } - } - return { - pendingOwner = owner - if (!launchComposerActivity(context, R.string.chat_voice_input_unavailable) { - launcher.launch(Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { - putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) - }) - }) { - pendingOwner = null - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationHeader.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationHeader.kt deleted file mode 100644 index 975595e791..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationHeader.kt +++ /dev/null @@ -1,307 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.common.CircleControl -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignTypography - -internal const val CONVERSATION_TITLE_TEST_TAG: String = "conversation-title" -internal const val CONVERSATION_MENU_TEST_TAG: String = "conversation-menu" -internal const val CONVERSATION_RENAME_TEST_TAG: String = "conversation-rename" - -/** - * The bar above a transcript, ported from `pages/components/RemoteChatHeader.ets`. - * - * Two lines, centred: the session's own title over where it is running. The - * second line is not decoration — the same list is reachable through a paired - * desktop and through an account device, and only this line says which one is - * answering. - * - * Renaming happens here rather than only in the session list because the title - * a session deserves is usually obvious after reading it, not before. Tapping - * the title opens the editor in place, as the source does. - * - * @param canStop whether a turn is running. The source's header popover is the - * only place it offers to stop from, and this keeps that. - */ -@Composable -internal fun ConversationHeader( - title: String, - contextTitle: String, - canStop: Boolean, - enabled: Boolean, - onBack: () -> Unit, - onOpenSidebar: (() -> Unit)? = null, - onRename: (String) -> Unit, - onStop: () -> Unit, - onShowUploadedFiles: () -> Unit = {}, - modifier: Modifier, -) { - // Keyed on the title so a rename landing from the desktop closes the editor - // rather than leaving the old text sitting in it. - var editing by rememberSaveable(title) { mutableStateOf(false) } - var draft by rememberSaveable(title) { mutableStateOf(title) } - var menuOpen by rememberSaveable { mutableStateOf(false) } - - val hasSubtitle = contextTitle.isNotBlank() - - Column(modifier = modifier.fillMaxWidth()) { - Row( - modifier = Modifier - .fillMaxWidth() - .height( - MobileDesignGeometry.ConversationHeaderHeight, - ) - .padding(horizontal = MobileDesignGeometry.ContentGutter, vertical = 8.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (onOpenSidebar != null) { - CircleControl( - icon = R.drawable.ic_symbol_menu_lines, - glyphSize = 22, - contentDescription = stringResource(R.string.shell_open_sidebar), - onClick = onOpenSidebar, - modifier = Modifier.testTag(CONVERSATION_BACK_TEST_TAG), - ) - } else { - CircleControl( - icon = R.drawable.ic_symbol_chevron_left_wide, - glyphSize = 20, - glyphWidth = 15, - glyphHeight = 23, - contentDescription = stringResource(R.string.conversation_back), - onClick = onBack, - modifier = Modifier.testTag(CONVERSATION_BACK_TEST_TAG), - ) - } - - Column( - modifier = Modifier.weight(1f), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(3.dp), - ) { - Text( - title.ifBlank { stringResource(R.string.conversation_title_default) }, - style = if (hasSubtitle) MobileDesignTypography.ConversationHeaderTitle - else MobileDesignTypography.TitleMedium, - color = MaterialTheme.colorScheme.onSurface, - textAlign = TextAlign.Center, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier - .testTag(CONVERSATION_TITLE_TEST_TAG) - .clickable(enabled = enabled) { - // The title and actions are mutually exclusive surfaces. - menuOpen = false - // Opening the editor re-seeds the draft from the - // committed title; re-tapping the title while the - // editor is already open must not throw the user's - // in-progress text away. - if (!editing) draft = title - editing = true - }, - ) - if (hasSubtitle) { - Text( - contextTitle, - fontSize = 14.sp, - lineHeight = 18.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - - Box { - CircleControl( - icon = R.drawable.ic_symbol_ellipsis, - glyphSize = 20, - glyphWidth = 23, - glyphHeight = 7, - contentDescription = stringResource(R.string.session_actions), - onClick = { - // The editor and the menu are two answers to the same - // tap target area; opening one closes the other. - editing = false - menuOpen = !menuOpen - }, - modifier = Modifier.testTag(CONVERSATION_MENU_TEST_TAG), - ) - OpenBitFunHeaderActionMenu( - expanded = menuOpen, - onDismiss = { menuOpen = false }, - sectionTitle = stringResource(R.string.session_section), - actions = buildList { - add( - OpenBitFunHeaderAction( - icon = R.drawable.ic_symbol_cloud, - label = stringResource(R.string.session_uploaded_files), - onClick = onShowUploadedFiles, - ), - ) - if (canStop) { - add( - OpenBitFunHeaderAction( - icon = R.drawable.ic_symbol_gearshape, - label = stringResource(R.string.message_stop), - onClick = onStop, - dividerBefore = true, - ), - ) - } - }, - ) - } - } - - if (editing) { - TitleEditor( - draft = draft, - enabled = enabled, - onDraftChange = { draft = it }, - onSave = { - onRename(draft.trim()) - editing = false - }, - onCancel = { editing = false }, - ) - } - } -} - -/** Rename in place: a field and the two verdicts, as the source's row is. */ -@Composable -internal fun TitleEditor( - draft: String, - enabled: Boolean, - onDraftChange: (String) -> Unit, - onSave: () -> Unit, - onCancel: () -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding( - start = MobileDesignGeometry.ContentGutter, - end = MobileDesignGeometry.ContentGutter, - top = 10.dp, - bottom = 8.dp, - ), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - val fieldShape = RoundedCornerShape(14.dp) - BasicTextField( - value = draft, - onValueChange = onDraftChange, - singleLine = true, - enabled = enabled, - textStyle = MaterialTheme.typography.bodyMedium.copy( - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurface, - ), - cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), - decorationBox = { inner -> - Box(contentAlignment = Alignment.CenterStart) { - if (draft.isEmpty()) { - Text( - stringResource(R.string.session_rename_label), - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - inner() - } - }, - modifier = Modifier - .weight(1f) - .height(42.dp) - .clip(fieldShape) - .background(MaterialTheme.colorScheme.surface) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant, fieldShape) - .padding(horizontal = 12.dp) - .testTag(CONVERSATION_RENAME_TEST_TAG), - ) - val saveEnabled = enabled && draft.isNotBlank() - EditorButton( - label = stringResource(R.string.session_rename_confirm), - primary = true, - enabled = saveEnabled, - onClick = onSave, - ) - EditorButton( - label = stringResource(R.string.common_cancel), - primary = false, - enabled = true, - onClick = onCancel, - ) - } -} - -@Composable -private fun EditorButton( - label: String, - primary: Boolean, - enabled: Boolean, - onClick: () -> Unit, -) { - val shape = RoundedCornerShape(14.dp) - Box( - modifier = Modifier - .width(52.dp) - .height(42.dp) - .clip(shape) - .background( - if (primary && enabled) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.surfaceVariant, - ) - .clickable(enabled = enabled, onClick = onClick), - contentAlignment = Alignment.Center, - ) { - Text( - label, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = if (primary && enabled) { - MaterialTheme.colorScheme.onPrimary - } else { - MaterialTheme.colorScheme.onSurface - }, - maxLines = 1, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationTimelineView.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationTimelineView.kt deleted file mode 100644 index bc758afddd..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationTimelineView.kt +++ /dev/null @@ -1,286 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import com.openbitfun.mobile.core.feature.session.HistoryLoadState - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.offset -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.interaction.DragInteraction -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.derivedStateOf -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.ConversationRow -import com.openbitfun.mobile.core.feature.session.QuestionAnswer -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import kotlinx.coroutines.flow.distinctUntilChanged - -/** Pure decisions for keeping a forward timeline at its visual tail. */ -internal object ConversationScrollPolicy { - fun shouldStickToBottom( - currentlySticking: Boolean, - isAtBottom: Boolean, - isScrollInProgress: Boolean, - ): Boolean = when { - isScrollInProgress -> false - isAtBottom -> true - else -> currentlySticking - } - - fun shouldScrollToBottom(stickToBottom: Boolean, hasRows: Boolean): Boolean = - stickToBottom && hasRows - - /** - * The LazyColumn puts one leading header in front of the messages when the - * transcript has an older page to load or has not been confirmed by the - * host yet, so the real tail is one past [rowCount] instead of - * `rowCount - 1`. - */ - fun lastItemIndex(rowCount: Int, hasLeadingItem: Boolean): Int = - if (hasLeadingItem) rowCount else (rowCount - 1).coerceAtLeast(0) -} - -/** One automatic page per deliberate drag; layout and bounce cannot re-arm it. */ -internal class HistoryPageArrivalTracker { - private var consumed = true - fun beginGesture() { consumed = false } - fun arrived(atStart: Boolean): Boolean { - if (!atStart || consumed) return false - consumed = true - return true - } - fun cancelArrival() { consumed = true } -} - -/** Timeline renderer over feature-owned presentation rows; session routing stays above it. */ -@Composable -internal fun ConversationTimelineView( - rows: List, - hasMoreMessages: Boolean, - /** - * The rows on screen are this device's stored copy rather than the host's - * transcript: a reopened session shows them at once, and the host has not - * answered for it yet. See `ChatTranscriptOrigin`. - */ - transcriptUnconfirmed: Boolean = false, - onLoadOlder: () -> Unit, - enabled: Boolean, - onApproveTool: (String, String?) -> Unit, - onRejectTool: (String, String) -> Unit, - onCancelTool: (String, String) -> Unit, - onAnswerTool: (String, String) -> Unit, - onAnswerToolStructured: (String, List) -> Unit, - onRetry: (ConversationRow) -> Unit, - onOpenFile: (String, String) -> Unit, - previewingRemotePath: String, - previewLoading: Boolean, - download: RemoteFileDownloadUiState, - onDownloadFile: (String, String) -> Unit, - downloadEnabled: Boolean, - modifier: Modifier, - historyLoadState: HistoryLoadState = HistoryLoadState.IDLE, - /** - * How much of the pane the floating header and composer cover. The list - * runs the full height behind them, so without these the first and last - * messages would sit under a capsule and never come out from under it. - */ - topInset: Dp = 0.dp, - bottomInset: Dp = 0.dp, -) { - val listState = rememberLazyListState() - var stickToBottom by rememberSaveable { mutableStateOf(true) } - val atBottom by remember(listState) { derivedStateOf { !listState.canScrollForward } } - // One header slot holds both leading rows, so the scroll policy counts an - // item, not a row. - val hasLeadingItem = hasMoreMessages || transcriptUnconfirmed - - val historyArrival = remember { HistoryPageArrivalTracker() } - var userDragging by remember { mutableStateOf(false) } - LaunchedEffect(listState.interactionSource) { - listState.interactionSource.interactions.collect { interaction -> - when (interaction) { - is DragInteraction.Start -> { historyArrival.beginGesture(); userDragging = true; stickToBottom = false } - is DragInteraction.Stop, is DragInteraction.Cancel -> userDragging = false - } - } - } - LaunchedEffect(listState) { - snapshotFlow { userDragging to listState.canScrollForward } - .collect { (dragging, canScrollForward) -> - stickToBottom = ConversationScrollPolicy.shouldStickToBottom( - currentlySticking = stickToBottom, - isAtBottom = !canScrollForward, - isScrollInProgress = dragging, - ) - } - } - LaunchedEffect(rows, stickToBottom, hasLeadingItem) { - if (ConversationScrollPolicy.shouldScrollToBottom(stickToBottom, rows.isNotEmpty())) { - // A large offset positions the item's bottom at the viewport tail directly; - // unlike scrollToItem(index), it does not briefly expose the item's top. - listState.scrollToItem( - ConversationScrollPolicy.lastItemIndex(rows.size, hasLeadingItem), - scrollOffset = Int.MAX_VALUE, - ) - } - } - - // Reaching the start of the loaded transcript asks for the next page by - // itself; the header stays as the loading and retry state. Busy gestures - // are consumed so completion cannot silently queue another page. - val canRequestOlder by rememberUpdatedState( - enabled && hasMoreMessages && historyLoadState != HistoryLoadState.LOADING - && historyLoadState != HistoryLoadState.FAILED, - ) - val requestOlder by rememberUpdatedState { - stickToBottom = false - onLoadOlder() - } - LaunchedEffect(listState, hasMoreMessages) { - // Index zero is the "load older messages" header, so seeing it is the - // reader standing at the start of what is loaded. Following the tail is - // excluded: a first page that does not fill the pane is at the start - // without the reader having gone there, and asking from there would - // fight the initial tail scroll. - snapshotFlow { userDragging && listState.firstVisibleItemIndex == 0 && !stickToBottom } - .distinctUntilChanged() - .collect { readerReachedStart -> - if (!historyArrival.arrived(readerReachedStart)) return@collect - if (canRequestOlder) requestOlder() - } - } - - Box(modifier = modifier) { - LazyColumn( - state = listState, - modifier = Modifier.fillMaxSize().testTag(CONVERSATION_LIST_TEST_TAG), - contentPadding = PaddingValues( - start = 20.dp, - end = 20.dp, - top = topInset, - bottom = if (bottomInset > 0.dp) bottomInset else 12.dp, - ), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - if (hasLeadingItem) { - item(key = "load-older-messages") { - Column(modifier = Modifier.fillMaxWidth()) { - if (transcriptUnconfirmed) { - // These rows stop where this device's last write stopped, - // inside the turn that was running when the app went away. - // Say the rest is on its way instead of letting a - // half-finished turn read as the session. - Row( - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), - horizontalArrangement = Arrangement.Center, - verticalAlignment = Alignment.CenterVertically, - ) { - CircularProgressIndicator( - modifier = Modifier.size(16.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(modifier = Modifier.width(7.dp)) - Text( - text = stringResource(R.string.chat_transcript_syncing), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - if (hasMoreMessages) { - Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { - TextButton( - onClick = { historyArrival.cancelArrival(); stickToBottom = false; onLoadOlder() }, - enabled = enabled && historyLoadState != HistoryLoadState.LOADING, - colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant), - ) { - Text(stringResource(when (historyLoadState) { - HistoryLoadState.LOADING -> R.string.chat_loading_older_messages - HistoryLoadState.FAILED -> R.string.chat_load_older_failed - else -> R.string.chat_load_older_messages - })) - } - } - } - } - } - } - val currentUser = rows.lastOrNull { it.kind == com.openbitfun.mobile.core.feature.session.ConversationRowKind.USER } - items(rows, key = { if (it === currentUser) "current-user" else "message:${it.id}" }) { row -> - ChatMessageBubble( - row = row, - enabled = enabled, - onApproveTool = onApproveTool, - onRejectTool = onRejectTool, - onCancelTool = onCancelTool, - onAnswerTool = onAnswerTool, - onAnswerToolStructured = onAnswerToolStructured, - onRetry = onRetry, - onOpenLink = onOpenFile, - previewingRemotePath = previewingRemotePath, - previewLoading = previewLoading, - download = download, - onDownloadFile = onDownloadFile, - downloadEnabled = downloadEnabled, - modifier = Modifier, - ) - } - } - if (!atBottom) { - Surface( - onClick = { stickToBottom = true }, - shape = CircleShape, - color = MaterialTheme.colorScheme.surface, - shadowElevation = 5.dp, - tonalElevation = 1.dp, - // Sits above the floating composer rather than behind it. - modifier = Modifier.align(Alignment.BottomCenter) - .offset(y = -(bottomInset + 4.dp)) - .size(42.dp), - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - painterResource(R.drawable.ic_symbol_chevron_down), - contentDescription = stringResource(R.string.chat_scroll_to_bottom), - modifier = Modifier.size(18.dp), - ) - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt deleted file mode 100644 index 3190c9ff2d..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt +++ /dev/null @@ -1,629 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.foundation.gestures.awaitEachGesture -import androidx.compose.foundation.gestures.awaitFirstDown -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.foundation.Image -import androidx.compose.foundation.border -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.navigationBars -import androidx.compose.foundation.layout.ime -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.size -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.ui.Alignment -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.text.font.FontFamily -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignTypography -import android.widget.Toast -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.PickVisualMediaRequest -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.background -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Brush -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.key -import androidx.compose.runtime.rememberUpdatedState -import kotlinx.coroutines.launch -import com.openbitfun.mobile.app.platform.prepareComposerImage -import com.openbitfun.mobile.app.platform.launchComposerActivity -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalFocusManager -import androidx.compose.ui.platform.LocalSoftwareKeyboardController -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.Dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.settings.RemoteSettingsSheet -import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ComposerImage -import com.openbitfun.mobile.core.feature.session.ConversationRow -import com.openbitfun.mobile.core.feature.session.ConversationRowKind -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent.AnswerStructuredQuestion -import com.openbitfun.mobile.core.feature.session.QuestionAnswer -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.conversationRows -import com.openbitfun.mobile.core.feature.session.modelOptions -import com.openbitfun.mobile.core.feature.session.selectedModelOption -import com.openbitfun.mobile.core.feature.session.transcriptUnconfirmed -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState - -internal const val CONVERSATION_TEST_TAG: String = "conversation" -internal const val CONVERSATION_BACK_TEST_TAG: String = "conversation-back" -internal const val CONVERSATION_LOADING_TEST_TAG: String = "conversation-loading" - -/** - * Grace before a conversation open is announced as a wait, and how long that - * announcement may stand. A cached transcript normally arrives inside the - * grace period, and swapping it for a skeleton and back reads as a stall - * rather than as speed. The cap is the other end: a transcript that never - * lands would otherwise leave the skeleton standing for the rest of the - * session, and a placeholder that outlives its subject reads as a hang. - * Matched to HarmonyOS's `DeferredLoadingGate` and iOS's open gate. - */ -private const val CONVERSATION_LOADING_DELAY_MS: Long = 140 -private const val CONVERSATION_LOADING_MAX_VISIBLE_MS: Long = 20_000 - -/** - * The transcript itself, tagged so a test can scroll it to a row. - * - * Separate from [CONVERSATION_TEST_TAG] because that one sits on the whole - * surface, header and composer included, and it is not the scrollable. - */ -internal const val CONVERSATION_LIST_TEST_TAG: String = "conversation-list" - -/** - * Joins a dictated fragment onto whatever the composer already holds. - * - * Uses the shared policy to preserve existing whitespace and avoid inserting - * spaces between CJK fragments. - */ -internal fun mergeComposerDraft(existing: String, spoken: String): String = - com.openbitfun.mobile.core.feature.session.VoiceDraftPolicy.merge(existing, spoken) - -/** - * One open session: the transcript and the composer, ported from - * `pages/components/ConversationSurface.ets`. - * - * The transcript is a lazy list and the composer is pinned below it, so a - * long session never pushes the input off screen. That is also why this surface - * replaces the session list rather than sitting under it — the list's own scroll - * cannot contain a lazy list. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun ConversationView( - state: RemoteSessionUiState.Ready, - phase: ConnectionPhase, - settingsPlacement: SettingsPlacement, - onBack: () -> Unit, - onOpenSidebar: (() -> Unit)? = null, - onIntent: (RemoteSessionIntent) -> Unit, - /** - * Where this transcript is running — a desktop name, or the brand and the - * branch. Built by `ConversationHeaderPresenter` at the call site, because - * only the screen knows whether it reached this session through the - * selected account device. - */ - contextTitle: String, - /** A file the agent named, taken from a markdown link. Path, then label. */ - onOpenFile: (String, String) -> Unit, - /** - * The file the preview surface currently holds, normalised, and whether it - * is still arriving. Passed as two scalars rather than the workspace state: - * this screen is about the transcript, and the only thing it needs from the - * preview is which of its own file cards is the one on screen. - */ - previewingRemotePath: String, - previewLoading: Boolean, - download: RemoteFileDownloadUiState, - onDownloadFile: (String, String) -> Unit, - modifier: Modifier, - hostCapabilities: List = emptyList(), - attachmentOwner: String = "", -) { - val timeline = state.timeline?.takeIf { it.sessionId == state.selectedSessionId } - var loadingVisible by remember(attachmentOwner, state.selectedSessionId) { mutableStateOf(false) } - LaunchedEffect(state.selectedSessionId, timeline == null) { - loadingVisible = false - if (timeline == null) { - kotlinx.coroutines.delay(CONVERSATION_LOADING_DELAY_MS) - loadingVisible = true - kotlinx.coroutines.delay(CONVERSATION_LOADING_MAX_VISIBLE_MS) - loadingVisible = false - } - } - val activeTurn = timeline?.activeTurn - val sessionId = state.selectedSessionId.orEmpty() - val rows = remember(timeline) { timeline?.conversationRows().orEmpty() } - val visibleRows = remember(rows) { rows.filter { it.kind != ConversationRowKind.EMPTY } } - val uploadedFileCount = rows.sumOf { it.images.size } - // Resolved here rather than inside the click: a Toast is raised from a - // callback, and reading resources off `LocalContext` there reads them - // without the composition's configuration. - val uploadedFilesMessage = if (uploadedFileCount > 0) { - stringResource(R.string.session_uploaded_files_count, uploadedFileCount) - } else { - stringResource(R.string.session_uploaded_files_empty) - } - // The remote composer's single source of truth is the store's draft. Typing, - // voice, and send all round-trip through `state.draft` so a half-written - // message survives session switches and process restarts via DraftStore. - var submittedDraft by rememberSaveable(attachmentOwner, state.selectedSessionId) { mutableStateOf(null) } - val draft = if (submittedDraft == state.draft) "" else state.draft - val focusManager = LocalFocusManager.current - val keyboard = LocalSoftwareKeyboardController.current - // Only the submitted draft is hidden while awaiting acknowledgement. Failure restores it; - // subsequent typing belongs to the new draft and must never be cleared by the old send. - LaunchedEffect(state.busy, state.lastSentMessage) { - if (!state.busy) submittedDraft = null - } - val attachments: com.openbitfun.mobile.app.viewmodel.ComposerAttachmentsViewModel = - androidx.lifecycle.viewmodel.compose.viewModel() - val context = LocalContext.current - val attachmentKey = org.json.JSONArray(listOf(attachmentOwner, sessionId)).toString() - val attachmentDraft = remember(attachmentKey, attachments) { - attachments.forSession(attachmentKey, java.io.File(context.noBackupFilesDir, "composer-attachments")) - } - var images by attachmentDraft.images - val attachmentsBlocked = attachmentDraft.loading.value || attachmentDraft.saving.value || attachmentDraft.failed.value - LaunchedEffect(attachmentKey, state.lastSentMessage, attachmentDraft.loading.value) { - state.lastSentMessage?.takeIf { it.sessionId == sessionId }?.let { sent -> - images = images.filterNot { it.id in sent.imageIds } - } - } - var showSettings by rememberSaveable(sessionId) { mutableStateOf(false) } - val pickerScope = rememberCoroutineScope() - val currentAttachmentKey by rememberUpdatedState(attachmentKey) - var preparingImage by remember(attachmentKey) { mutableStateOf(false) } - var pickerOwner by rememberSaveable { mutableStateOf(null) } - val importPhotos: (List) -> Unit = { uris -> - val belongsToCurrentTarget = pickerOwner == attachmentKey - pickerOwner = null - if (belongsToCurrentTarget && uris.isNotEmpty() && images.size < MAX_COMPOSER_IMAGES) { - val targetSession = attachmentKey - preparingImage = true - pickerScope.launch { - try { - for (uri in uris.take(MAX_COMPOSER_IMAGES - images.size)) { - val prepared = prepareComposerImage(context.contentResolver, uri) - if (currentAttachmentKey == targetSession && images.size < MAX_COMPOSER_IMAGES) { - images = images + prepared - } - } - } catch (cancelled: kotlinx.coroutines.CancellationException) { - throw cancelled - } catch (_: Exception) { - if (currentAttachmentKey == targetSession) { - Toast.makeText(context, R.string.chat_image_prepare_failed, Toast.LENGTH_LONG).show() - } - } finally { - if (currentAttachmentKey == targetSession) preparingImage = false - } - } - } - } - - val photoPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(MAX_COMPOSER_IMAGES), importPhotos) - val singlePhotoPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> - if (uri != null) importPhotos(listOf(uri)) - } - - val voiceInput = rememberComposerVoiceInput(attachmentKey) { text -> - onIntent(RemoteSessionIntent.UpdateDraft(mergeComposerDraft(state.draft, text))) - } - - androidx.compose.runtime.CompositionLocalProvider( - com.openbitfun.mobile.app.ui.chat.tool.LocalPermissionMailbox provides state.permissionMailbox, - com.openbitfun.mobile.app.ui.chat.tool.LocalPlanActions provides com.openbitfun.mobile.app.ui.chat.tool.PlanActions( - supported = "plan_build_v1" in hostCapabilities, - enabled = !state.busy && activeTurn == null && phase == ConnectionPhase.CONNECTED, - build = { plan -> onIntent(RemoteSessionIntent.BuildPlan(sessionId, plan.path, plan.name)) }, - ), - ) { - androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) { - val mailboxMaxHeight = maxHeight * 0.4f - // How much of the pane the two floating layers cover, measured rather - // than assumed: the composer grows with multiline text and attachments, - // and the mailbox appears without warning. The transcript runs the full - // height behind them and borrows these as its content insets, so a - // stale number would leave the first or last message under a capsule. - var topInset by remember { mutableStateOf(0.dp) } - var bottomInset by remember { mutableStateOf(0.dp) } - val density = LocalDensity.current - // Scaffold already lifts the pane above the keyboard. Navigation only - // belongs to this layer when the keyboard is absent. - val navigationBottom = with(density) { - if (WindowInsets.ime.getBottom(this) > 0) 0.dp else WindowInsets.navigationBars.getBottom(this).toDp() - } - Box(modifier = Modifier.fillMaxSize().testTag(CONVERSATION_TEST_TAG)) { - if (timeline == null) { - Box(Modifier.fillMaxSize()) { - if (loadingVisible) ConversationLoadingState( - Modifier.fillMaxSize().padding(top = topInset, bottom = bottomInset), - ) - } - } else if (visibleRows.isEmpty() && !state.hasMoreMessages) { - ConversationEmptyState(modifier = Modifier.fillMaxSize()) - } else { - key(attachmentOwner, sessionId) { - ConversationTimelineViewHost( - state = state, - sessionId = sessionId, - visibleRows = visibleRows, - images = images, - phase = phase, - previewingRemotePath = previewingRemotePath, - previewLoading = previewLoading, - download = download, - onDownloadFile = onDownloadFile, - onOpenFile = onOpenFile, - onIntent = onIntent, - topInset = topInset, - bottomInset = bottomInset, - ) - } - } - - Column( - modifier = Modifier - .align(Alignment.TopCenter) - .fillMaxWidth() - .onSizeChanged { topInset = with(density) { it.height.toDp() } }, - ) { - Column(modifier = Modifier.fillMaxWidth().background(overlayFill())) { - ConversationHeader( - title = state.sessions.firstOrNull { it.id == sessionId }?.title.orEmpty(), - contextTitle = contextTitle, - canStop = activeTurn != null && phase == ConnectionPhase.CONNECTED, - enabled = !state.busy && sessionId.isNotEmpty(), - onBack = onBack, - onOpenSidebar = onOpenSidebar, - onRename = { title -> - onIntent(RemoteSessionIntent.RenameSession(sessionId, title)) - }, - onShowUploadedFiles = { - Toast.makeText(context, uploadedFilesMessage, Toast.LENGTH_SHORT).show() - }, - onStop = { - onIntent(RemoteSessionIntent.CancelTurn(sessionId, activeTurn?.turnId)) - }, - modifier = Modifier, - ) - - key(sessionId) { PermissionMailboxView(state.permissionMailbox, sessionId, mailboxMaxHeight, onIntent) } - } - ConversationTopEdgeFade() - } - - Column( - modifier = Modifier - .align(Alignment.BottomCenter) - .fillMaxWidth() - .onSizeChanged { bottomInset = with(density) { it.height.toDp() } } - // The fade covers the whole layer, not just a strip above - // it: the transcript runs behind the composer, so anything - // short of that leaves a line of text sitting crisp and - // legible beside the pill after it has already faded out - // higher up. - .background(bottomOverlayFade()) - .padding(bottom = navigationBottom), - ) { - if (attachmentDraft.failed.value) { - TextButton(onClick = { attachmentDraft.retry() }) { - Text(stringResource(R.string.chat_attachment_recovery_failed)) - } - } - val queueMatchesSession = state.messageQueue.sessionId == state.selectedSessionId - if (queueMatchesSession) MessageQueuePanel(state.messageQueue, onIntent) - ComposerBar( - queueAttached = queueMatchesSession && (state.messageQueue.items.isNotEmpty() || state.messageQueue.failure != null), - draft = draft, - images = images, - // An empty session id would send nowhere, so it reads as busy. - busy = state.busy || preparingImage || attachmentsBlocked || sessionId.isEmpty(), - // Session hydration must not make the draft field require - // repeated taps. Sending and attachment actions remain - // guarded by `busy`; typing can start as soon as a session - // has been selected and the draft survives hydration. - inputEnabled = sessionId.isNotEmpty() && !preparingImage && !attachmentsBlocked, - streaming = activeTurn != null, - phase = phase, - model = timeline?.selectedModelOption(stringResource(R.string.models_unnamed)), - modelOptions = timeline?.modelOptions(stringResource(R.string.models_unnamed)) ?: emptyList(), - modelCatalogFailed = state.modelCatalogFailure != null, - capabilities = ChatComposerCapabilities.RemoteChat, - placeholder = stringResource(R.string.message_input_label), - promptSuggestion = state.promptSuggestion, - onDraftChange = { - submittedDraft = null - onIntent(RemoteSessionIntent.UpdateDraft(it)) - }, - onRemoveImage = { id -> images = images.filterNot { it.id == id } }, - onOpenModels = { showSettings = true }, - onSelectModel = { modelId -> - onIntent(RemoteSessionIntent.SelectModel(sessionId, modelId)) - }, - modifier = Modifier, - onAttach = { - pickerOwner = attachmentKey - val remaining = MAX_COMPOSER_IMAGES - images.size - if (!launchComposerActivity(context, R.string.chat_photo_picker_unavailable) { - if (remaining == 1) singlePhotoPicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) - else if (remaining > 1) photoPicker.launch( - PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly, maxItems = remaining), - ) - }) pickerOwner = null - }, - onVoice = voiceInput, - onSend = { - submittedDraft = draft - keyboard?.hide() - focusManager.clearFocus(force = true) - onIntent( - RemoteSessionIntent.SendMessage( - sessionId, - draft, - images.takeIf { it.isNotEmpty() }, - ), - ) - }, - onStop = { - onIntent(RemoteSessionIntent.CancelTurn(sessionId, activeTurn?.turnId)) - }, - ) - } - } - } - - } - - if (showSettings) { - AdaptiveModalSurface( - visible = true, - placement = settingsPlacement, - onDismissRequest = { showSettings = false }, - ) { surfaceModifier -> - RemoteSettingsSheet( - state = state, - sessionId = sessionId, - onIntent = onIntent, - modifier = surfaceModifier.padding(16.dp), - ) - } - } -} - -/** - * The timeline call is long enough that inlining it under the floating layout - * buried the layout itself. Nothing here is new behaviour; it is the same call - * with the measured insets handed through. - */ -@Composable -private fun ConversationTimelineViewHost( - state: RemoteSessionUiState.Ready, - sessionId: String, - visibleRows: List, - images: List, - phase: ConnectionPhase, - previewingRemotePath: String, - previewLoading: Boolean, - download: RemoteFileDownloadUiState, - onDownloadFile: (String, String) -> Unit, - onOpenFile: (String, String) -> Unit, - onIntent: (RemoteSessionIntent) -> Unit, - topInset: Dp, - bottomInset: Dp, -) { - ConversationTimelineView( - rows = visibleRows, - hasMoreMessages = state.hasMoreMessages, - transcriptUnconfirmed = state.timeline - ?.takeIf { it.sessionId == state.selectedSessionId } - ?.transcriptUnconfirmed() == true, - historyLoadState = state.historyLoadState, - onLoadOlder = { onIntent(RemoteSessionIntent.LoadOlderMessages) }, - enabled = !state.busy, - onApproveTool = { toolId, updatedInput -> - onIntent(RemoteSessionIntent.ApproveTool(sessionId, toolId, updatedInput)) - }, - onRejectTool = { toolId, reason -> - onIntent(RemoteSessionIntent.RejectTool(sessionId, toolId, reason)) - }, - onCancelTool = { toolId, reason -> - onIntent(RemoteSessionIntent.CancelTool(sessionId, toolId, reason)) - }, - onAnswerTool = { toolId, answer -> - onIntent(RemoteSessionIntent.AnswerQuestion(sessionId, toolId, answer)) - }, - onAnswerToolStructured = { toolId, answers -> - onIntent(AnswerStructuredQuestion(sessionId, toolId, answers)) - }, - onRetry = { row -> - val retryImages = row.images.map { image -> - images.firstOrNull { it.dataUrl == image.dataUrl } ?: ComposerImage( - id = image.name, - dataUrl = image.dataUrl, - mimeType = image.dataUrl.substringAfter("data:").substringBefore(';'), - ) - } - onIntent(RemoteSessionIntent.SendMessage(sessionId, row.text, retryImages)) - }, - onOpenFile = onOpenFile, - previewingRemotePath = previewingRemotePath, - previewLoading = previewLoading, - download = download, - onDownloadFile = onDownloadFile, - downloadEnabled = !state.busy && phase == ConnectionPhase.CONNECTED, - modifier = Modifier.fillMaxSize(), - topInset = topInset, - bottomInset = bottomInset, - ) -} - -/** - * Softens where the transcript meets a floating layer. Without it a line of - * text is cut in half at the capsule's edge and reads as clipped rather than as - * continuing underneath. - */ -/** - * The floor under the bottom layer: transparent where the transcript is still - * fully readable, settling into the page colour by the time it reaches the - * composer. Matches the gradient HarmonyOS paints behind the same layer. - */ -@Composable -private fun bottomOverlayFade(): Brush = Brush.verticalGradient( - // The page colour at zero alpha rather than a bare transparent: a gradient - // run to plain transparent interpolates through grey and leaves a smudge - // over the transcript. - 0f to overlayFill().copy(alpha = 0f), - 0.45f to overlayFill(), - 1f to overlayFill(), -) - -/** - * Carries the header's opaque band down into the transcript, so a line of text - * is not cut in half at its edge. The bottom layer needs no strip of its own — - * its whole background is [bottomOverlayFade]. - */ -@Composable -private fun ConversationTopEdgeFade() { - val page = MaterialTheme.colorScheme.background - Box( - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.ConversationEdgeFadeHeight) - .background(Brush.verticalGradient(listOf(page, page.copy(alpha = 0f)))), - ) -} - -/** - * The floor under the top layer. Compose has no first-party backdrop blur, so - * where iOS and HarmonyOS put a material this puts a near-opaque page colour: - * the transcript still passes behind it, and the header stays readable over - * whatever is passing. - */ -@Composable -private fun overlayFill(): Color = MaterialTheme.colorScheme.background.copy(alpha = 0.94f) - -@Composable -private fun ConversationLoadingState(modifier: Modifier) { - Column(modifier.testTag(CONVERSATION_LOADING_TEST_TAG).padding(horizontal = 22.dp, vertical = 28.dp), - verticalArrangement = Arrangement.spacedBy(18.dp)) { - listOf(0.72f to 78, 0.46f to 42, 0.84f to 112).forEachIndexed { index, (width, height) -> - Box(Modifier.fillMaxWidth(), contentAlignment = if (index == 1) androidx.compose.ui.Alignment.CenterEnd else androidx.compose.ui.Alignment.CenterStart) { - Column(Modifier.fillMaxWidth(width).height(height.dp) - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(10.dp)).padding(14.dp), - verticalArrangement = Arrangement.spacedBy(7.dp)) { - listOf(0.74f, 0.92f, 0.58f).forEach { fraction -> - Box(Modifier.fillMaxWidth(fraction).height(6.dp) - .background(MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(3.dp))) - } - } - } - } - } -} - -@Composable -internal fun PermissionMailboxView(state: com.openbitfun.mobile.core.feature.session.PermissionMailboxUiState, sessionId: String, maxHeight: androidx.compose.ui.unit.Dp, onIntent: (RemoteSessionIntent) -> Unit) { - if (!state.failed && state.requests.isEmpty() && state.questions.isEmpty()) return - Column(Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(MobileDesignGeometry.ApprovalCardGap)) { - if (state.failed) Text(stringResource(R.string.permission_mailbox_failed)) - if (state.failed) androidx.compose.material3.TextButton(onClick = { onIntent(RemoteSessionIntent.RefreshPermissionMailbox) }) { - Text(stringResource(R.string.sessions_retry)) - } - state.questions.forEach { question -> - androidx.compose.runtime.key(sessionId, question.id) { - Column(Modifier.fillMaxWidth().pointerInput(question.id) { - awaitEachGesture { awaitFirstDown(requireUnconsumed = false); onIntent(RemoteSessionIntent.StartQuestionInteraction(question.id)) } - }) { - if (question.questions.isNotEmpty()) { - com.openbitfun.mobile.app.ui.chat.tool.ToolStructuredQuestionPanel( - toolId = question.id, questions = question.questions, enabled = !state.busy, - onSubmit = { answers -> onIntent(RemoteSessionIntent.AnswerStructuredQuestion(sessionId, question.id, answers)) }) - } else { - com.openbitfun.mobile.app.ui.chat.tool.ToolQuestionAnswerPanel( - toolId = question.id, prompt = question.question ?: stringResource(R.string.tool_question_default), enabled = !state.busy, - onSubmit = { answer -> onIntent(RemoteSessionIntent.AnswerQuestion(sessionId, question.id, answer)) }) - } - } - } - } - state.requests.forEach { request -> - androidx.compose.runtime.key(sessionId, request.requestId) { - var edit by rememberSaveable { mutableStateOf(false) } - var input by rememberSaveable { mutableStateOf("{}") } - val valid = !edit || runCatching { org.json.JSONObject(input) }.isSuccess - Column(Modifier.fillMaxWidth() - .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(MobileDesignGeometry.ApprovalCardRadius)) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(MobileDesignGeometry.ApprovalCardRadius)) - .padding(MobileDesignGeometry.ApprovalCardPadding), - verticalArrangement = Arrangement.spacedBy(MobileDesignGeometry.ApprovalCardGap)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Image(painterResource(R.drawable.approval_shield), contentDescription = null, modifier = Modifier.size(16.dp)) - Text(request.source.ifBlank { request.action }, modifier = Modifier.weight(1f), style = MobileDesignTypography.BodySmall) - TextButton(onClick = { edit = !edit }, enabled = !state.busy, - modifier = Modifier.height(32.dp), contentPadding = PaddingValues(horizontal = 8.dp)) { - Text(stringResource(if (edit) R.string.tool_hide_approval_input else R.string.tool_edit_approval_input), style = MobileDesignTypography.LabelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - if (request.source.isNotBlank() && !request.source.equals(request.action, ignoreCase = true)) { - Text(request.action, style = MobileDesignTypography.BodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - if (request.resources.isNotEmpty()) { - Text(request.resources.joinToString("\n"), style = MobileDesignTypography.LabelSmall.copy(fontFamily = FontFamily.Monospace), - modifier = Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp)).padding(10.dp)) - } - if (edit) androidx.compose.material3.OutlinedTextField(value = input, onValueChange = { input = it }, enabled = !state.busy, - isError = !valid, modifier = Modifier.fillMaxWidth().heightIn(max = 120.dp), textStyle = MobileDesignTypography.LabelSmall.copy(fontFamily = FontFamily.Monospace)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { - Button(onClick = { onIntent(RemoteSessionIntent.RespondPermission(request.requestId, false, null)) }, enabled = !state.busy, - shape = RoundedCornerShape(MobileDesignGeometry.ApprovalActionRadius), - colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.surfaceVariant, contentColor = MaterialTheme.colorScheme.onSurface), - modifier = Modifier.height(MobileDesignGeometry.ApprovalActionHeight)) { Text(stringResource(R.string.tool_reject), style = MobileDesignTypography.LabelMedium) } - Button(onClick = { onIntent(RemoteSessionIntent.RespondPermission(request.requestId, true, if (edit) input else null)) }, enabled = !state.busy && valid, - shape = RoundedCornerShape(MobileDesignGeometry.ApprovalActionRadius), modifier = Modifier.height(MobileDesignGeometry.ApprovalActionHeight)) { - Text(stringResource(R.string.tool_approve), style = MobileDesignTypography.LabelMedium) - } - } - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/FileReferenceCards.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/FileReferenceCards.kt deleted file mode 100644 index 87390dc75f..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/FileReferenceCards.kt +++ /dev/null @@ -1,222 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.MessageFileReference -import com.openbitfun.mobile.core.feature.session.MessageFileReferenceProjector -import com.openbitfun.mobile.core.feature.workspace.FilePreviewFormat -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState - -internal const val FILE_REFERENCE_CARD_TEST_TAG: String = "file-reference-card" -internal const val FILE_DOWNLOAD_ACTION_TEST_TAG: String = "file-download-action" - -/** - * The files an agent turn named, as cards under the turn — ported from - * `MessageFileCards` in `pages/components/ChatMessageContent.ets`. - * - * The same paths are already tappable inside the prose. These exist because on a - * phone a link inside a justified paragraph is a small target next to other - * small targets, and because the projection dedupes: a turn that mentions one - * file four times gets one card, not four links to hunt through. - * - * Preview and download both use the displayed session's file channel. Source - * references are preserved for the owning remote host to resolve. - */ -@Composable -internal fun FileReferenceCards( - text: String, - previewingRemotePath: String, - previewLoading: Boolean, - download: RemoteFileDownloadUiState = RemoteFileDownloadUiState.None, - onOpen: (String, String) -> Unit, - onDownload: (String, String) -> Unit = { _, _ -> }, - downloadEnabled: Boolean = true, - modifier: Modifier, -) { - // Projecting is a markdown parse; a streaming turn recomposes on every - // chunk, so it is keyed on the text rather than run each time. - val references = remember(text) { MessageFileReferenceProjector.project(text) } - if (references.isEmpty()) return - - Column( - modifier = modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - references.forEach { reference -> - val open = reference.remotePath == previewingRemotePath - val downloadState = download.forReference(reference.reference, reference.remotePath) - FileReferenceCard( - reference = reference, - selected = open, - loading = open && previewLoading, - onOpen = { onOpen(reference.reference, reference.label) }, - download = downloadState, - onDownload = { onDownload(reference.reference, reference.label) }, - downloadEnabled = downloadEnabled, - ) - } - } -} - -@Composable -private fun FileReferenceCard( - reference: MessageFileReference, - selected: Boolean, - loading: Boolean, - download: RemoteFileDownloadUiState, - onOpen: () -> Unit, - onDownload: () -> Unit, - downloadEnabled: Boolean, -) { - Surface( - shape = RoundedCornerShape(14.dp), - color = if (selected) { - MaterialTheme.colorScheme.secondaryContainer - } else { - MaterialTheme.colorScheme.surface - }, - border = BorderStroke( - width = 1.dp, - color = if (selected) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.outlineVariant - }, - ), - modifier = Modifier.fillMaxWidth().testTag(FILE_REFERENCE_CARD_TEST_TAG), - ) { - Row( - modifier = Modifier.padding(12.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - modifier = Modifier.weight(1f).height(44.dp).clickable(onClick = onOpen), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Box( - modifier = Modifier - .size(34.dp) - .clip(RoundedCornerShape(12.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - if (loading) { - CircularProgressIndicator(modifier = Modifier.size(17.dp), strokeWidth = 2.dp) - } else { - Icon( - painterResource(R.drawable.ic_symbol_doc_text), - contentDescription = null, - modifier = Modifier.size(18.dp), - ) - } - } - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(3.dp), - ) { - Text( - reference.label, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - download.statusText(), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.primary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - val actionEnabled = downloadEnabled && - download !is RemoteFileDownloadUiState.Loading && - download !is RemoteFileDownloadUiState.AwaitingSave - Box( - modifier = Modifier.size(44.dp).testTag(FILE_DOWNLOAD_ACTION_TEST_TAG) - .alpha(if (actionEnabled) 1f else 0.55f) - .clip(RoundedCornerShape(12.dp)).clickable( - enabled = actionEnabled, - onClick = onDownload, - ), - contentAlignment = Alignment.Center, - ) { - if (download is RemoteFileDownloadUiState.Loading || - download is RemoteFileDownloadUiState.AwaitingSave - ) { - CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) - } else { - Icon( - painterResource(R.drawable.ic_symbol_arrow_down_to_line), - contentDescription = stringResource(R.string.file_download), - modifier = Modifier.size(19.dp), - ) - } - } - } - } -} - -/** Also read by the file preview pane's status band, which says it the same way. */ -@Composable -internal fun RemoteFileDownloadUiState.statusText(): String = when (this) { - RemoteFileDownloadUiState.None -> stringResource(R.string.file_reference_desktop) - is RemoteFileDownloadUiState.Loading -> if (totalBytes > 0) { - stringResource( - R.string.file_downloading_progress, - FilePreviewFormat.bytes(downloadedBytes), - FilePreviewFormat.bytes(totalBytes), - ) - } else { - stringResource(R.string.file_downloading) - } - is RemoteFileDownloadUiState.AwaitingSave -> stringResource(R.string.file_saving) - is RemoteFileDownloadUiState.Saved -> stringResource(R.string.common_done) - is RemoteFileDownloadUiState.Failed -> stringResource(R.string.file_download_failed) -} - -internal fun RemoteFileDownloadUiState.forReference( - reference: String, - remotePath: String, -): RemoteFileDownloadUiState { - val target = when (this) { - RemoteFileDownloadUiState.None -> return this - is RemoteFileDownloadUiState.Loading -> target - is RemoteFileDownloadUiState.AwaitingSave -> target - is RemoteFileDownloadUiState.Saved -> target - is RemoteFileDownloadUiState.Failed -> target - } - return if (target.path == reference || target.remotePath == remotePath) this else RemoteFileDownloadUiState.None -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt deleted file mode 100644 index 807de15be5..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/GeneralChatScreen.kt +++ /dev/null @@ -1,480 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.widget.Toast -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.PickVisualMediaRequest -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.clickable -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.platform.launchComposerActivity -import com.openbitfun.mobile.app.platform.prepareComposerImage -import com.openbitfun.mobile.app.ui.common.CircleControl -import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface -import com.openbitfun.mobile.app.ui.settings.ModelServiceScreen -import com.openbitfun.mobile.app.viewmodel.GeneralChatViewModel -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatFailureReason -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatIntent -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ConversationRowKind -import com.openbitfun.mobile.core.feature.session.ModelOption -import com.openbitfun.mobile.core.feature.session.conversationRows -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.launch - -internal const val GENERAL_CHAT_TEST_TAG: String = "general-chat" -// Keep the shell-level automation id while the control is now owned by the -// surface header rather than by a platform TopAppBar. -internal const val GENERAL_CHAT_SIDEBAR_TEST_TAG: String = "shell-menu" -internal const val GENERAL_CHAT_MENU_TEST_TAG: String = "general-chat-menu" -internal const val GENERAL_CHAT_MODEL_TEST_TAG: String = "general-chat-model" - -/** - * The general-chat surface, the counterpart of `ConversationView` for a - * conversation that has no desktop behind it. - * - * It renders the same rows through the same bubbles and the same composer as the - * remote session: both surfaces project the same shared timeline, and letting - * them diverge visually is how the two clients drift apart. What differs is the - * header menu — rename and delete are this store's own operations — and - * the composer's capabilities. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun GeneralChatScreen( - modifier: Modifier, - modelServicePlacement: SettingsPlacement, - onOpenSidebar: (() -> Unit)? = null, - viewModel: GeneralChatViewModel = viewModel(factory = GeneralChatViewModel.Factory), -) { - val state by viewModel.state.collectAsStateWithLifecycle() - val rows = remember(state.timeline) { state.timeline.conversationRows() } - val listState = rememberLazyListState() - val context = LocalContext.current - var menuOpen by rememberSaveable { mutableStateOf(false) } - var showModelService by rememberSaveable { mutableStateOf(false) } - var renaming by rememberSaveable { mutableStateOf(false) } - - val untitled = stringResource(R.string.sidebar_untitled) - val userLabel = stringResource(R.string.general_chat_role_user) - val assistantLabel = stringResource(R.string.general_chat_role_assistant) - val localModelSource = stringResource(R.string.model_selector_local) - val accountModelSource = stringResource(R.string.model_selector_account) - val title = state.sessions.firstOrNull { it.id == state.sessionId } - ?.title - ?.takeIf(String::isNotBlank) - ?: stringResource(R.string.app_name) - var renameDraft by rememberSaveable(title) { mutableStateOf(title) } - val visibleRows = remember(rows) { rows.filter { it.kind != ConversationRowKind.EMPTY } } - val uploadedFileCount = visibleRows.sumOf { it.images.size } - // Read in composition, not in the menu callback -- see `ConversationView`. - val uploadedFilesMessage = if (uploadedFileCount > 0) { - stringResource(R.string.session_uploaded_files_count, uploadedFileCount) - } else { - stringResource(R.string.session_uploaded_files_empty) - } - val composerModels = remember( - state.models, - state.activeModelId, - localModelSource, - accountModelSource, - ) { - state.models.map { model -> - ModelOption( - id = model.id, - primaryLabel = model.label, - secondaryLabel = when (model.source) { - com.openbitfun.mobile.core.feature.generalchat.GeneralChatModelSource.LOCAL -> - localModelSource - com.openbitfun.mobile.core.feature.generalchat.GeneralChatModelSource.ACCOUNT -> - accountModelSource - }, - selected = model.id == state.activeModelId, - ) - } - } - - val voiceInput = rememberComposerVoiceInput(state.sessionId) { text -> - viewModel.dispatch(GeneralChatIntent.UpdateDraft(listOf(state.draft.trim(), text.trim()).filter(String::isNotEmpty).joinToString(" "))) - } - val pickerScope = rememberCoroutineScope() - val currentState by rememberUpdatedState(state) - var pickerOwner by rememberSaveable { mutableStateOf(null) } - var preparingImage by remember(state.sessionId) { mutableStateOf(false) } - val photoPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> - val target = pickerOwner - pickerOwner = null - if (uri != null && target == state.sessionId && state.images.size < MAX_COMPOSER_IMAGES) { - preparingImage = true - pickerScope.launch { - try { - val prepared = prepareComposerImage(context.contentResolver, uri) - val latest = currentState - if (latest.sessionId == target && latest.images.size < MAX_COMPOSER_IMAGES) { - viewModel.dispatch(GeneralChatIntent.SetImages(latest.images + prepared)) - } - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - if (currentState.sessionId == target) { - Toast.makeText(context, R.string.chat_image_prepare_failed, Toast.LENGTH_LONG).show() - } - } finally { - if (currentState.sessionId == target) preparingImage = false - } - } - } - } - - // An export's share sheet is raised by `MobileScreen`, which is mounted - // whichever surface is showing: the drawer can export a conversation this - // screen is not on, and two consumers would raise two choosers. - LaunchedEffect(rows.size) { - if (rows.isNotEmpty()) listState.animateScrollToItem(rows.lastIndex) - } - - Column(modifier = modifier.fillMaxSize().testTag(GENERAL_CHAT_TEST_TAG)) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry.ConversationHeaderHeight) - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (onOpenSidebar != null) { - CircleControl( - icon = R.drawable.ic_symbol_menu_lines, - glyphSize = 22, - contentDescription = stringResource(R.string.shell_open_sidebar), - onClick = onOpenSidebar, - modifier = Modifier.testTag(GENERAL_CHAT_SIDEBAR_TEST_TAG), - ) - } else { - Box(Modifier.size(44.dp)) - } - Text( - title, - style = MaterialTheme.typography.titleMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier - .weight(1f) - .padding(horizontal = 8.dp) - .clickable(enabled = state.sessions.any { it.id == state.sessionId }) { - renameDraft = title - renaming = true - }, - textAlign = TextAlign.Center, - ) - if (visibleRows.isNotEmpty()) { - Box { - // The same box `ConversationHeader` gives the glyph: this - // header is the general-chat face of the one HarmonyOS - // draws for every conversation, so the dots are the source's - // 23x7 rather than a square that would fit them smaller. - CircleControl( - icon = R.drawable.ic_symbol_ellipsis, - glyphSize = 20, - glyphWidth = 23, - glyphHeight = 7, - contentDescription = stringResource(R.string.general_chat_menu), - onClick = { menuOpen = true }, - modifier = Modifier.testTag(GENERAL_CHAT_MENU_TEST_TAG), - ) - // Every session mutation remains disabled until a stored - // conversation exists; the shared menu only changes the - // presentation, not that capability rule. - val stored = state.sessions.any { it.id == state.sessionId } - val current = state.sessions.firstOrNull { it.id == state.sessionId } - val archived = current?.status.equals(ARCHIVED, ignoreCase = true) - OpenBitFunHeaderActionMenu( - expanded = menuOpen, - onDismiss = { menuOpen = false }, - sectionTitle = stringResource(R.string.session_section), - actions = listOf( - OpenBitFunHeaderAction( - icon = R.drawable.ic_symbol_checkmark_circle, - label = stringResource( - if (current?.pinned == true) R.string.session_unpin - else R.string.session_pin, - ), - enabled = stored, - selected = current?.pinned == true, - onClick = { - viewModel.dispatch( - GeneralChatIntent.PinSession( - state.sessionId, - current?.pinned != true, - ), - ) - }, - ), - OpenBitFunHeaderAction( - icon = R.drawable.ic_symbol_cloud, - label = stringResource(R.string.session_uploaded_files), - onClick = { - Toast - .makeText(context, uploadedFilesMessage, Toast.LENGTH_SHORT) - .show() - }, - ), - OpenBitFunHeaderAction( - icon = R.drawable.ic_symbol_folder, - label = stringResource( - if (archived) R.string.session_unarchive else R.string.session_archive, - ), - enabled = stored, - dividerBefore = true, - onClick = { - viewModel.dispatch(GeneralChatIntent.ArchiveSession(state.sessionId, !archived)) - }, - ), - OpenBitFunHeaderAction( - icon = R.drawable.ic_symbol_gearshape, - label = stringResource(R.string.session_delete), - enabled = stored, - onClick = { - viewModel.dispatch(GeneralChatIntent.DeleteSession(state.sessionId)) - }, - ), - ), - ) - } - } else { - Box(Modifier.size(44.dp)) - } - } - - if (renaming) { - TitleEditor( - draft = renameDraft, - enabled = !state.busy, - onDraftChange = { renameDraft = it }, - onSave = { - viewModel.dispatch(GeneralChatIntent.RenameSession(state.sessionId, renameDraft.trim())) - renaming = false - }, - onCancel = { renaming = false }, - ) - } - - if (visibleRows.isEmpty()) { - Box( - modifier = Modifier.weight(1f).fillMaxWidth(), - contentAlignment = Alignment.Center, - ) { - if (!state.configured) { - Text( - stringResource(R.string.general_chat_unconfigured), - fontSize = 17.sp, - lineHeight = 24.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - modifier = Modifier.padding(horizontal = 24.dp), - ) - } - } - } else { - LazyColumn( - state = listState, - modifier = Modifier.weight(1f).fillMaxWidth(), - contentPadding = PaddingValues(start = 20.dp, end = 20.dp, bottom = 12.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - items(visibleRows, key = { it.id }) { row -> - ChatMessageBubble( - row = row, - enabled = !state.busy, - // General chat has no tools: the provider stream carries - // text only, so no row can ever ask for an approval. - onApproveTool = { _, _ -> }, - onRejectTool = { _, _ -> }, - onCancelTool = { _, _ -> }, - onAnswerTool = { _, _ -> }, - onAnswerToolStructured = { _, _ -> }, - onRetry = { row -> - viewModel.dispatch(GeneralChatIntent.UpdateDraft(row.text)) - viewModel.dispatch(GeneralChatIntent.Send) - }, - // No desktop behind this surface, so a link to a file has - // nothing to open — only a web address goes anywhere, and - // it leaves the app. Anything else is left as plain text. - onOpenLink = { url, _ -> openWebLink(context, url) }, - // No preview surface here either, so no card is ever the - // open one; the projector only matches `computer://`, so - // a general-chat turn produces no cards to mark anyway. - previewingRemotePath = "", - previewLoading = false, - download = com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState.None, - onDownloadFile = { _, _ -> }, - downloadEnabled = false, - modifier = Modifier, - ) - } - } - } - - state.failure?.let { failure -> - Text( - stringResource(failure.messageRes()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), - ) - } - - ComposerBar( - draft = state.draft, - images = state.images, - busy = state.busy || preparingImage, - inputEnabled = !state.busy && !preparingImage, - streaming = state.timeline.activeTurn != null, - // Never consulted: general chat's capabilities do not require a - // desktop, so the phase cannot gate the send. - phase = ConnectionPhase.DISCONNECTED, - model = composerModels.firstOrNull { it.selected }, - modelOptions = composerModels, - capabilities = ChatComposerCapabilities.GeneralChat, - placeholder = stringResource(R.string.message_input_label), - onDraftChange = { viewModel.dispatch(GeneralChatIntent.UpdateDraft(it)) }, - onRemoveImage = { id -> - viewModel.dispatch(GeneralChatIntent.SetImages(state.images.filterNot { it.id == id })) - }, - onAttach = { - pickerOwner = state.sessionId - if (!launchComposerActivity(context, R.string.chat_photo_picker_unavailable) { - photoPicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) - }) pickerOwner = null - }, - onOpenModels = { showModelService = true }, - onSelectModel = { viewModel.dispatch(GeneralChatIntent.SelectModel(it)) }, - onSend = { viewModel.dispatch(GeneralChatIntent.Send) }, - onStop = { viewModel.dispatch(GeneralChatIntent.Cancel) }, - modifier = Modifier, - onVoice = voiceInput, - ) - } - - if (showModelService) { - val dismissModelService = { - showModelService = false - viewModel.dispatch(GeneralChatIntent.ClearConfigFailure) - viewModel.dispatch(GeneralChatIntent.ClearConnectionTest) - } - AdaptiveModalSurface( - visible = true, - placement = modelServicePlacement, - onDismissRequest = dismissModelService, - ) { surfaceModifier -> - ModelServiceScreen( - config = state.config, - models = state.models, - activeModelId = state.activeModelId, - failure = state.configFailure, - connectionTest = state.connectionTest, - onIntent = viewModel::dispatch, - onSave = { intent -> - viewModel.dispatch(intent) - // Read back rather than waiting for recomposition: dispatch - // is synchronous, and a refused save must keep the form up - // with the reason next to the field that caused it. - viewModel.state.value.configFailure == null - }, - onClose = dismissModelService, - modifier = surfaceModifier, - ) - } - } - -} - -/** Shown above the transcript rather than instead of it: an unconfigured provider - * does not hide a conversation the user can still read back. */ -@Composable -private fun UnconfiguredNotice(onConfigure: () -> Unit) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text( - stringResource(R.string.general_chat_setup_hint), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - TextButton(onClick = onConfigure) { - Text(stringResource(R.string.general_chat_setup)) - } - } -} - -/** - * Hands a link to whatever the phone opens web addresses with. - * - * Only `http` and `https`: everything else a model can write into a link — a - * path, a `file:` url, an intent scheme — either points at a machine this app - * cannot reach or is a way to aim this app's own components from text a server - * sent. A device with no browser at all is the remaining failure, and doing - * nothing is the right answer there too. - */ -private fun openWebLink(context: Context, url: String) { - val uri = runCatching { Uri.parse(url) }.getOrNull() ?: return - if (uri.scheme?.lowercase() !in setOf("http", "https")) return - runCatching { - context.startActivity(Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - } -} - -internal fun GeneralChatFailureReason.messageRes(): Int = when (this) { - GeneralChatFailureReason.UNCONFIGURED -> R.string.general_chat_unconfigured - GeneralChatFailureReason.AUTHENTICATION -> R.string.general_chat_authentication - GeneralChatFailureReason.RATE_LIMITED -> R.string.general_chat_rate_limited - GeneralChatFailureReason.SERVICE_UNAVAILABLE -> R.string.general_chat_service_unavailable - GeneralChatFailureReason.INVALID_RESPONSE -> R.string.general_chat_invalid_response - GeneralChatFailureReason.NETWORK -> R.string.general_chat_network -} - -/** The status the store writes for a filed-away conversation. */ -private const val ARCHIVED = "archived" diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt deleted file mode 100644 index bf1b70a435..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/InlineImage.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.util.Base64 - -/** - * Decodes one of the relay's inline `data:` URLs. - * - * Both the transcript and the composer show the same attachments, and neither - * may fetch anything: an image that is not carried inline is not ours to load, - * so a URL of any other shape decodes to null and the caller shows a caption. - */ -internal fun decodeInlineImage(dataUrl: String): Bitmap? { - if (!dataUrl.startsWith("data:", ignoreCase = true)) return null - val metadata = dataUrl.substringBefore(',') - if (!metadata.split(';').any { it.equals("base64", ignoreCase = true) }) return null - val payload = dataUrl.substringAfter(',', "") - if (payload.isEmpty()) return null - return runCatching { - val bytes = Base64.decode(payload, Base64.DEFAULT) - // The encoded size says nothing about decoded pixel memory. History may - // contain full-resolution photos from another client; these are thumbnails. - val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) - if (options.outWidth <= 0 || options.outHeight <= 0) return null - options.inSampleSize = 1 - while (maxOf(options.outWidth, options.outHeight) / options.inSampleSize > 512) { - options.inSampleSize *= 2 - } - options.inJustDecodeBounds = false - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) - }.getOrNull() -} - -/** Pure projection work belongs off the Compose/UI thread. Key changes cancel - * the old delivery, so a reused row cannot receive another message's bitmap. */ -@androidx.compose.runtime.Composable -internal fun rememberInlineImage(dataUrl: String): Bitmap? { - val state = androidx.compose.runtime.produceState(null, dataUrl) { - value = null - value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) { - decodeInlineImage(dataUrl) - } - } - return state.value -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt deleted file mode 100644 index b2a198140c..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MarkdownContent.kt +++ /dev/null @@ -1,358 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import android.content.ClipData -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.IntrinsicSize -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.ClipEntry -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalClipboard -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.rememberTextMeasurer -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.LinkAnnotation -import androidx.compose.ui.text.SpanStyle -import androidx.compose.ui.text.TextLinkStyles -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontStyle -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextDecoration -import androidx.compose.ui.text.withLink -import androidx.compose.ui.text.withStyle -import androidx.compose.ui.unit.TextUnit -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.markdown.MarkdownBlock -import com.openbitfun.mobile.core.feature.markdown.MarkdownInline -import com.openbitfun.mobile.core.feature.markdown.MarkdownListItem -import com.openbitfun.mobile.core.feature.markdown.MarkdownParser -import kotlinx.coroutines.launch - -internal const val MARKDOWN_TEST_TAG: String = "markdown" - - -/** - * An agent turn as marked-up text, ported from `pages/components/MarkdownContent.ets`. - * - * The agent writes markdown whether or not the client renders it, so the choice - * was never "markdown or plain text" — it was "rendered, or the asterisks and - * backticks shown raw". HarmonyOS has rendered it from the start; this is the - * Android half. - * - * Parsing is [MarkdownParser] in `core-feature`, already shared and already - * tested — nothing about *what* a line means is decided here. What this file - * owns is only how each block looks, and it keeps HarmonyOS's sizes so the two - * clients scan the same. There is no [com.openbitfun.mobile.core.feature.markdown.MarkdownParseCache] - * on this side: `remember(text)` is the cache Compose already has, and the ArkTS - * class exists because its `build()` re-runs without one. - */ -@Composable -internal fun MarkdownContent( - text: String, - onOpenLink: (String, String) -> Unit, - modifier: Modifier, - streaming: Boolean = false, -) { - val blocks = remember(text) { MarkdownParser.parse(text) } - Column( - modifier = modifier.fillMaxWidth().testTag(MARKDOWN_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(5.dp), - ) { - blocks.forEach { block -> - MarkdownBlockView( - block = block, - onOpenLink = onOpenLink, - copyFullText = if (streaming) text else null, - ) - } - } -} - -@Composable -private fun MarkdownBlockView( - block: MarkdownBlock, - onOpenLink: (String, String) -> Unit, - copyFullText: String?, -) { - val colors = MaterialTheme.colorScheme - when (block.type) { - "code" -> CodeBlock( - language = block.language, - body = block.text, - copyFullText = copyFullText, - ) - - "heading" -> InlineText( - inlines = block.inlines, - fontSize = headingFontSize(block.level), - lineHeight = headingLineHeight(block.level), - color = colors.onSurface, - bold = true, - onOpenLink = onOpenLink, - ) - - // A rule down the left rather than an indent: an indent alone is what a - // nested list looks like, and the two blocks read differently. - "quote" -> Row(modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) { - Box(Modifier.width(2.dp).fillMaxHeight().background(colors.outlineVariant)) - Spacer(Modifier.width(9.dp)) - InlineText( - inlines = block.inlines, - fontSize = MaterialTheme.typography.bodyLarge.fontSize, - lineHeight = MaterialTheme.typography.bodyLarge.lineHeight, - color = colors.onSurfaceVariant, - bold = false, - onOpenLink = onOpenLink, - ) - } - - "list" -> MarkdownList(items = block.items, onOpenLink = onOpenLink) - - "table" -> ScrollingMonospaceCard(body = block.text, header = null) - - "divider" -> Box(Modifier.fillMaxWidth().height(1.dp).background(colors.outlineVariant)) - - else -> InlineText( - inlines = block.inlines, - fontSize = MaterialTheme.typography.bodyLarge.fontSize, - lineHeight = MaterialTheme.typography.bodyLarge.lineHeight, - color = colors.onSurface, - bold = false, - onOpenLink = onOpenLink, - ) - } -} - -/** - * One run of text, with its emphasis and its links. - * - * [bold] is the heading case, and it is carried by the paragraph style rather - * than stamped onto every span: an italic or a link inside a heading is still a - * heading, so only the spans that add something set a weight of their own. - */ -@Composable -private fun InlineText( - inlines: List, - fontSize: TextUnit, - lineHeight: TextUnit, - color: Color, - bold: Boolean, - onOpenLink: (String, String) -> Unit, -) { - val linkColor = MaterialTheme.colorScheme.tertiary - Text( - text = annotatedInlines(inlines = inlines, linkColor = linkColor, onOpenLink = onOpenLink), - fontSize = fontSize, - lineHeight = lineHeight, - color = color, - fontWeight = if (bold) FontWeight.Bold else FontWeight.Normal, - modifier = Modifier.fillMaxWidth(), - ) -} - -@Composable -private fun annotatedInlines( - inlines: List, - linkColor: Color, - onOpenLink: (String, String) -> Unit, -): AnnotatedString = buildAnnotatedString { - inlines.forEach { inline -> - when (inline.type) { - "strong" -> withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(inline.text) } - - "emphasis" -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { append(inline.text) } - - "delete" -> withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) { append(inline.text) } - - "code" -> withStyle(SpanStyle(fontFamily = FontFamily.Monospace)) { append(inline.text) } - - // A link in an agent turn is nearly always a file it just touched, - // so the tap goes to the same preview a file card would open — not - // out to a browser. - "link" -> withLink( - LinkAnnotation.Clickable( - tag = inline.url, - styles = TextLinkStyles( - style = SpanStyle( - color = linkColor, - textDecoration = TextDecoration.Underline, - ), - ), - ) { onOpenLink(inline.url, inline.text) }, - ) { append(inline.text) } - - else -> append(inline.text) - } - } -} - -/** - * The markers share a measured column so wrapped lines line up under the - * text rather than under the bullet. - */ -@Composable -private fun MarkdownList(items: List, onOpenLink: (String, String) -> Unit) { - val measurer = rememberTextMeasurer() - val density = LocalDensity.current - val style = MaterialTheme.typography.bodyLarge - val markerWidth = remember(items, style, density, measurer) { - with(density) { - items.maxOfOrNull { measurer.measure(it.marker, style, softWrap = false).size.width } - ?.toDp()?.coerceAtLeast(20.dp) ?: 20.dp - } - } - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - items.forEach { item -> - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(7.dp), - verticalAlignment = Alignment.Top, - ) { - Text( - item.marker, - fontSize = MaterialTheme.typography.bodyLarge.fontSize, - lineHeight = MaterialTheme.typography.bodyLarge.lineHeight, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.End, - modifier = Modifier.width(markerWidth), - softWrap = false, - maxLines = 1, - ) - Box(Modifier.weight(1f)) { - InlineText( - inlines = item.inlines, - fontSize = MaterialTheme.typography.bodyLarge.fontSize, - lineHeight = MaterialTheme.typography.bodyLarge.lineHeight, - color = MaterialTheme.colorScheme.onSurface, - bold = false, - onOpenLink = onOpenLink, - ) - } - } - } - } -} - -/** - * A fenced block, with the language it declared and a way to take it. - * - * Copy matters more here than anywhere else on the screen: a command the agent - * wrote is meant to be run, and retyping it is how a typo gets into a shell. - */ -@Composable -private fun CodeBlock(language: String, body: String, copyFullText: String?) { - val copyBody = copyFullText ?: body - val clipboard = LocalClipboard.current - val scope = rememberCoroutineScope() - val copyLabel = stringResource(R.string.chat_copy) - ScrollingMonospaceCard( - body = body, - header = { - Row(modifier = Modifier.fillMaxWidth()) { - Text( - language.ifBlank { "code" }, - fontSize = MaterialTheme.typography.labelSmall.fontSize, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.weight(1f), - ) - Text( - copyLabel, - fontSize = MaterialTheme.typography.labelSmall.fontSize, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.clickableText { - scope.launch { - clipboard.setClipEntry( - ClipEntry(ClipData.newPlainText(copyLabel, copyBody)), - ) - } - }, - ) - } - }, - ) -} - -/** - * Code and tables are the two blocks that must not be re-wrapped: a broken line - * of code is a different line of code, and a wrapped table stops being a table. - * Both scroll sideways inside their own card instead. - */ -@Composable -private fun ScrollingMonospaceCard(body: String, header: (@Composable () -> Unit)?) { - Surface( - color = MaterialTheme.colorScheme.surfaceVariant, - shape = RoundedCornerShape(12.dp), - border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - modifier = Modifier.fillMaxWidth(), - ) { - Column( - modifier = Modifier.padding(horizontal = 9.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(7.dp), - ) { - header?.invoke() - val scroll = rememberScrollState() - Box(Modifier.fillMaxWidth().horizontalScroll(scroll)) { - Text( - body, - fontSize = MaterialTheme.typography.labelSmall.fontSize, - lineHeight = MaterialTheme.typography.labelSmall.lineHeight, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurface, - softWrap = false, - // Fills the card when the content is narrower than it, so a - // one-word block is still a full-width card. - modifier = Modifier.widthIn(min = 1.dp), - ) - } - } - } -} - -/** A tap target on a label, without a button's padding or ripple bounds. */ -private fun Modifier.clickableText(onClick: () -> Unit): Modifier = - clickable(onClick = onClick).padding(start = 8.dp) - -@Composable -private fun headingFontSize(level: Int): TextUnit = when { - level <= 1 -> MaterialTheme.typography.headlineSmall.fontSize - level == 2 -> MaterialTheme.typography.titleMedium.fontSize - else -> MaterialTheme.typography.bodyLarge.fontSize -} - -@Composable -private fun headingLineHeight(level: Int): TextUnit = when { - level <= 1 -> MaterialTheme.typography.headlineSmall.lineHeight - level == 2 -> MaterialTheme.typography.titleMedium.lineHeight - else -> MaterialTheme.typography.bodyLarge.lineHeight -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt deleted file mode 100644 index 754e89f2e2..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt +++ /dev/null @@ -1,141 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.background -import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.* -import androidx.compose.runtime.* -import androidx.compose.ui.Alignment -import androidx.compose.ui.draw.drawWithContent -import androidx.compose.ui.zIndex -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.boundsInRoot -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.CustomAccessibilityAction -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.customActions -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.session.MessageQueueFailure -import com.openbitfun.mobile.core.feature.session.MessageQueueUiState -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent - -/** Host receipts stay authoritative; a gesture submits one move only on release. */ -@Composable -internal fun MessageQueuePanel(state: MessageQueueUiState, onIntent: (RemoteSessionIntent) -> Unit) { - if (state.items.isEmpty() && state.failure == null) return - var expanded by remember(state.sessionId) { mutableStateOf(true) } - var menuId by remember(state.sessionId) { mutableStateOf(null) } - var dragging by remember(state.sessionId) { mutableStateOf(null) } - var displacement by remember { mutableFloatStateOf(0f) } - var destination by remember { mutableStateOf(null) } - var dragBounds by remember { mutableStateOf>(emptyMap()) } - val bounds = remember { mutableMapOf() } - val queued = state.items.filter { it.status == "queued" }.map { it.id } - val enabled = state.supportsReorder && !state.busy && state.failure == null - val latestIntent by rememberUpdatedState(onIntent) - val moveUp = stringResource(R.string.queue_move_up) - val moveDown = stringResource(R.string.queue_move_down) - val handleLabel = stringResource(R.string.queue_reorder) - LaunchedEffect(state.revisionKey, state.busy, state.failure) { dragging = null; displacement = 0f } - Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp)) { - TextButton(onClick = { expanded = !expanded }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant), contentPadding = PaddingValues(horizontal = 8.dp)) { - Text(stringResource(R.string.queue_title, state.items.size), style = MaterialTheme.typography.labelMedium) - Icon(painterResource(if (expanded) R.drawable.ic_symbol_chevron_down else R.drawable.ic_symbol_chevron_up), null, Modifier.size(14.dp)) - } - if (state.failure != null) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text(stringResource(if (state.failure == MessageQueueFailure.UNSUPPORTED) R.string.queue_unsupported else R.string.queue_refresh_required), Modifier.weight(1f), style = MaterialTheme.typography.bodySmall) - TextButton(onClick = { onIntent(RemoteSessionIntent.RefreshMessageQueue) }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !state.busy) { Text(stringResource(R.string.queue_refresh)) } - } - } - if (expanded) Column(Modifier.heightIn(max = 192.dp).verticalScroll(rememberScrollState())) { - state.items.forEach { item -> - key(item.id) { - val index = queued.indexOf(item.id) - val canMove = enabled && index >= 0 && queued.size > 1 - val ink = MaterialTheme.colorScheme.onSurfaceVariant - val marker = MaterialTheme.colorScheme.primary - Column(Modifier.onGloballyPositioned { bounds[item.id] = it.boundsInRoot() } - .graphicsLayer { if (dragging == item.id) translationY = displacement } - .zIndex(if (dragging == item.id) 1f else 0f) - .background(if (dragging == item.id) MaterialTheme.colorScheme.surfaceContainer else openBitFunColors.transparent) - .drawWithContent { - drawContent() - if (dragging != null && dragging != item.id) { - val y = if (destination == item.id) 0f - else if (destination == null && item.id == queued.lastOrNull { it != dragging }) size.height - else null - if (y != null) drawLine(marker, Offset(0f, y), Offset(size.width, y), 1.dp.toPx()) - } - } - .semantics { - customActions = if (canMove) listOfNotNull( - if (index > 0) CustomAccessibilityAction(moveUp) { onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued[index - 1])); true } else null, - if (index < queued.lastIndex) CustomAccessibilityAction(moveDown) { onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued.getOrNull(index + 2))); true } else null, - ) else emptyList() - }) { - HorizontalDivider(Modifier.padding(horizontal = 8.dp), color = MaterialTheme.colorScheme.outlineVariant) - Row(Modifier.fillMaxWidth().heightIn(min = 48.dp), verticalAlignment = Alignment.Top) { - if (state.supportsReorder) IconButton(onClick = { menuId = item.id }, enabled = canMove, - modifier = Modifier.size(width = 48.dp, height = 48.dp).pointerInput(item.id, queued, enabled, state.revisionKey) { - if (canMove) detectDragGesturesAfterLongPress( - onDragStart = { dragBounds = bounds.toMap(); dragging = item.id; displacement = 0f; destination = queued.getOrNull(index + 1) }, - onDragCancel = { dragging = null; displacement = 0f }, - onDragEnd = { - if (dragging == item.id && destination != queued.getOrNull(index + 1)) latestIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, destination)) - dragging = null; displacement = 0f - }, - onDrag = { change, amount -> - change.consume(); displacement += amount.y - val center = (dragBounds[item.id]?.center?.y ?: 0f) + displacement - destination = queued.firstOrNull { it != item.id && center < (dragBounds[it]?.center?.y ?: Float.MAX_VALUE) } - }, - ) - }) { - Canvas(Modifier.size(14.dp).semantics { contentDescription = handleLabel }) { - for (line in 1..3) drawLine(ink, Offset(1f, size.height * line / 4), Offset(size.width - 1f, size.height * line / 4), strokeWidth = 1.5.dp.toPx()) - } - } - Column(Modifier.weight(1f).padding(vertical = 14.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text(item.text, Modifier.weight(1f, fill = false), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) - if (item.attachmentCount > 0) Text(stringResource(R.string.queue_attachments, item.attachmentCount), style = MaterialTheme.typography.labelSmall, color = ink) - } - if (item.status != "queued") Text(stringResource(R.string.queue_waiting), style = MaterialTheme.typography.bodySmall, color = ink) - } - IconButton(onClick = { onIntent(RemoteSessionIntent.PromoteQueuedMessage(item.id)) }, enabled = !state.busy && state.failure == null && item.status in listOf("queued", "blocked")) { - Icon(painterResource(R.drawable.ic_symbol_arrow_up), stringResource(R.string.queue_send_now), Modifier.size(16.dp)) - } - Box { - IconButton(onClick = { menuId = item.id }) { Icon(painterResource(R.drawable.ic_symbol_ellipsis), stringResource(R.string.queue_more), Modifier.size(16.dp)) } - DropdownMenu(expanded = menuId == item.id, onDismissRequest = { menuId = null }) { - DropdownMenuItem(text = { Text(item.text) }, onClick = {}, enabled = false) - if (!state.supportsReorder) DropdownMenuItem(text = { Text(stringResource(R.string.queue_unsupported)) }, onClick = {}, enabled = false) - DropdownMenuItem(text = { Text(moveUp) }, enabled = canMove && index > 0, - onClick = { menuId = null; onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued[index - 1])) }) - DropdownMenuItem(text = { Text(moveDown) }, enabled = canMove && index < queued.lastIndex, - onClick = { menuId = null; onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued.getOrNull(index + 2))) }) - DropdownMenuItem(text = { Text(stringResource(R.string.queue_remove)) }, enabled = !state.busy && state.failure == null && item.status in listOf("queued", "blocked"), - onClick = { menuId = null; onIntent(RemoteSessionIntent.CancelQueuedMessage(item.id)) }) - } - } - } - } - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/OpenBitFunHeaderActionMenu.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/OpenBitFunHeaderActionMenu.kt deleted file mode 100644 index 57a46d6b17..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/OpenBitFunHeaderActionMenu.kt +++ /dev/null @@ -1,231 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import androidx.annotation.DrawableRes -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.core.MutableTransitionState -import androidx.compose.animation.core.tween -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut -import androidx.compose.animation.slideIn -import androidx.compose.animation.slideOut -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.draw.clip -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import androidx.compose.ui.window.Popup -import androidx.compose.ui.window.PopupPositionProvider -import androidx.compose.ui.window.PopupProperties -import com.openbitfun.mobile.app.ui.theme.OpenBitFunEaseOut -import com.openbitfun.mobile.app.ui.theme.MotionQuickMillis -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -internal const val HEADER_ACTION_MENU_TEST_TAG: String = "header-action-menu" - -/** One row in the fixed-width header menu shared by local and remote chat. */ -internal data class OpenBitFunHeaderAction( - @DrawableRes val icon: Int, - val label: String, - val onClick: () -> Unit, - val enabled: Boolean = true, - val selected: Boolean = false, - val destructive: Boolean = false, - val dividerBefore: Boolean = false, - val testTag: String? = null, -) - -/** - * The compact floating menu used by the HarmonyOS conversation header. - * - * Material's default menu is intentionally not used as-is: its narrow shape, - * missing section label, and text-only rows made local and remote headers read - * like different products. The actions remain platform-owned; this component - * owns only the shared presentation contract. - */ -@Composable -internal fun OpenBitFunHeaderActionMenu( - expanded: Boolean, - onDismiss: () -> Unit, - sectionTitle: String, - actions: List, - modifier: Modifier = Modifier, -) { - val visibility = remember { MutableTransitionState(false) } - visibility.targetState = expanded - val density = LocalDensity.current - val targetSpace = with(density) { 8.dp.roundToPx() } - val motionOffset = with(density) { 8.dp.roundToPx() } - val positionProvider = remember(targetSpace) { HeaderMenuPositionProvider(targetSpace) } - if (visibility.currentState || visibility.targetState) { - Popup( - popupPositionProvider = positionProvider, - onDismissRequest = onDismiss, - properties = PopupProperties( - focusable = true, - dismissOnBackPress = true, - dismissOnClickOutside = true, - clippingEnabled = true, - ), - ) { - AnimatedVisibility( - visibleState = visibility, - enter = fadeIn(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) + - slideIn( - animationSpec = tween(MotionQuickMillis, easing = OpenBitFunEaseOut), - initialOffset = { IntOffset(motionOffset, -motionOffset) }, - ), - exit = fadeOut(tween(MotionQuickMillis, easing = OpenBitFunEaseOut)) + - slideOut( - animationSpec = tween(MotionQuickMillis, easing = OpenBitFunEaseOut), - targetOffset = { IntOffset(motionOffset, -motionOffset) }, - ), - ) { - Surface( - modifier = modifier - .testTag(HEADER_ACTION_MENU_TEST_TAG) - .width(MobileDesignGeometry.PopoverWidth) - .clip(RoundedCornerShape(MobileDesignGeometry.PopoverRadius)) - .border( - BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - RoundedCornerShape(MobileDesignGeometry.PopoverRadius), - ), - shape = RoundedCornerShape(MobileDesignGeometry.PopoverRadius), - color = MaterialTheme.colorScheme.surfaceContainerLow, - tonalElevation = 0.dp, - shadowElevation = MobileDesignGeometry.PopoverShadowRadius, - ) { - Column( - Modifier.padding( - horizontal = MobileDesignGeometry.PopoverPadding, - vertical = MobileDesignGeometry.PopoverVerticalPadding, - ), - ) { - Box( - modifier = Modifier.fillMaxWidth().height(28.dp).padding(start = 8.dp), - contentAlignment = Alignment.CenterStart, - ) { - Text( - sectionTitle, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - actions.forEachIndexed { index, action -> - if (index > 0 && shouldDivide(actions[index - 1], action)) { - HorizontalDivider( - color = MaterialTheme.colorScheme.outlineVariant, - modifier = Modifier.padding(vertical = 8.dp), - ) - } - HeaderActionRow(action, onDismiss) - } - } - } - } - } - } -} - -private class HeaderMenuPositionProvider( - private val targetSpace: Int, -) : PopupPositionProvider { - override fun calculatePosition( - anchorBounds: IntRect, - windowSize: IntSize, - layoutDirection: LayoutDirection, - popupContentSize: IntSize, - ): IntOffset { - val x = (anchorBounds.right - popupContentSize.width) - .coerceIn(0, (windowSize.width - popupContentSize.width).coerceAtLeast(0)) - val below = anchorBounds.bottom + targetSpace - val y = if (below + popupContentSize.height <= windowSize.height) { - below - } else { - (anchorBounds.top - targetSpace - popupContentSize.height).coerceAtLeast(0) - } - return IntOffset(x, y) - } -} - -private fun shouldDivide(previous: OpenBitFunHeaderAction, current: OpenBitFunHeaderAction): Boolean = - current.dividerBefore || - (previous.label.contains("model", ignoreCase = true) && - !current.label.contains("model", ignoreCase = true)) - -@Composable -private fun HeaderActionRow(action: OpenBitFunHeaderAction, onDismiss: () -> Unit) { - val contentColor = when { - !action.enabled -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.42f) - action.destructive -> MaterialTheme.colorScheme.error - else -> MaterialTheme.colorScheme.onSurface - } - Row( - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.PopoverActionHeight) - .clip(RoundedCornerShape(10.dp)) - .background( - if (action.selected) MaterialTheme.colorScheme.surfaceVariant - else openBitFunColors.transparent, - ) - .clickable(enabled = action.enabled) { - action.onClick() - onDismiss() - } - .alpha(if (action.enabled) 1f else 0.42f) - .padding(horizontal = 8.dp) - .then(action.testTag?.let { Modifier.testTag(it) } ?: Modifier), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Box(Modifier.size(23.dp), contentAlignment = Alignment.Center) { - Icon( - painterResource(action.icon), - contentDescription = null, - tint = if (action.destructive) MaterialTheme.colorScheme.error else - MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(20.dp), - ) - } - Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) { - Text( - action.label, - color = contentColor, - fontSize = 15.sp, - maxLines = 1, - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ChatMessageChrome.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ChatMessageChrome.kt deleted file mode 100644 index 0d04738ff5..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ChatMessageChrome.kt +++ /dev/null @@ -1,239 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.message - -import androidx.compose.animation.core.LinearEasing -import androidx.compose.animation.core.RepeatMode -import androidx.compose.animation.core.StartOffset -import androidx.compose.animation.core.animateFloat -import androidx.compose.animation.core.infiniteRepeatable -import androidx.compose.animation.core.keyframes -import androidx.compose.animation.core.rememberInfiniteTransition -import androidx.compose.foundation.Image -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.rememberInlineImage -import com.openbitfun.mobile.app.ui.chat.tool.PillButton -import com.openbitfun.mobile.core.feature.session.ConversationImage - -internal const val TYPING_DOTS_TEST_TAG: String = "chat-typing-dots" - -/** One dot lit at a time, at the pace of `ChatTypingDots` in `ChatMessageChrome.ets`. */ -private const val DOT_COUNT = 3 -private const val FADE_MS = 180 -private const val HOLD_MS = 360 -private const val CYCLE_MS = HOLD_MS * DOT_COUNT -private const val DOT_DIM = 0.34f -private const val DOT_BRIGHT = 1f - -/** - * The agent has the turn but has not said anything yet, ported from - * `ChatTypingDots` in `pages/components/ChatMessageChrome.ets`. - * - * Dots rather than the word "Replying…": the wait is usually a second or two, - * and a caption that appears and disappears in that time is read as an event. - * Once any token arrives this goes away — the arriving text says the same thing. - */ -@Composable -internal fun ChatTypingDots(modifier: Modifier) { - val transition = rememberInfiniteTransition(label = "typing") - Row( - modifier = modifier.height(24.dp).testTag(TYPING_DOTS_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(5.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - repeat(DOT_COUNT) { index -> - val alpha by transition.animateFloat( - initialValue = DOT_DIM, - targetValue = DOT_DIM, - animationSpec = infiniteRepeatable( - animation = keyframes { - durationMillis = CYCLE_MS - DOT_DIM at 0 using LinearEasing - DOT_BRIGHT at FADE_MS using LinearEasing - DOT_BRIGHT at HOLD_MS using LinearEasing - DOT_DIM at HOLD_MS + FADE_MS using LinearEasing - }, - repeatMode = RepeatMode.Restart, - // Each dot runs the same pulse a beat later than the one - // before it, which is what makes the row read as travelling. - initialStartOffset = StartOffset(index * HOLD_MS), - ), - label = "typing-dot-$index", - ) - Box( - modifier = Modifier - .size(6.dp) - .alpha(alpha) - .background(MaterialTheme.colorScheme.onSurfaceVariant, CircleShape), - ) - } - } -} - -/** - * The user's own words, ported from `ChatUserMessageBubble`. - * - * Images go inside the bubble rather than above it: they were part of the same - * message, and floating them outside reads as a second, separate send. - */ -@Composable -internal fun ChatUserMessageBubble( - text: String, - images: List, - modifier: Modifier, -) { - val visibleText = text.trim().takeUnless { - it == "(empty message)" || it == "(空消息)" - }.orEmpty() - // Capped rather than full width so a short question does not read as a - // paragraph, and so the two sides of the exchange are distinguishable at a - // glance before either is read. - BoxWithConstraints(modifier.fillMaxWidth()) { - Surface( - color = MaterialTheme.colorScheme.surfaceVariant, - shape = RoundedCornerShape(18.dp), - modifier = Modifier.widthIn(max = maxWidth * 0.7f).align(Alignment.CenterEnd), - ) { - Column( - modifier = Modifier.padding(10.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - MessageImageGallery(images = images, userStyle = true) - if (visibleText.isNotEmpty()) { - Text( - visibleText, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - ) - } - } - } - } -} - -/** - * What went wrong and the one thing to do about it, ported from - * `ChatMessageRetryAction`. - * - * The wording differs by side because the failures differ: the user's message - * never left the device, while the agent's reply started and stopped partway. - * Saying "not delivered" under half an answer would be describing the wrong - * event. - */ -@Composable -internal fun ChatMessageRetryAction( - fromUser: Boolean, - enabled: Boolean, - onRetry: () -> Unit, - modifier: Modifier, -) { - Row( - modifier = modifier, - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - ChatCaption( - stringResource( - if (fromUser) R.string.chat_send_failed else R.string.chat_reply_interrupted, - ), - error = true, - ) - PillButton( - label = stringResource(R.string.chat_retry), - primary = true, - enabled = enabled, - compact = true, - onClick = onRetry, - modifier = Modifier, - ) - } -} - -@Composable -internal fun MessageImageGallery( - images: List, - userStyle: Boolean, -) { - if (images.isEmpty()) return - val perRow = if (userStyle) 2 else 3 - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - images.chunked(perRow).forEach { imageRow -> - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - imageRow.forEach { image -> ChatAttachedImage(image, userStyle) } - } - } - } -} - -@Composable -internal fun ChatAttachedImage(image: ConversationImage, userStyle: Boolean = false) { - // Anything the relay did not carry inline shows as a name rather than a - // broken frame; see [decodeInlineImage]. - val bitmap = rememberInlineImage(image.dataUrl) - val imageSize = if (userStyle) 112.dp else 92.dp - val shape = RoundedCornerShape(if (userStyle) 12.dp else 14.dp) - if (bitmap != null) { - Image( - bitmap = bitmap.asImageBitmap(), - contentDescription = image.name, - contentScale = ContentScale.Crop, - modifier = Modifier - .size(imageSize) - .clip(shape) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant, shape), - ) - } else { - Surface( - shape = shape, - color = MaterialTheme.colorScheme.surfaceVariant, - border = androidx.compose.foundation.BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - modifier = Modifier.size(imageSize), - ) { - Box(Modifier.padding(8.dp), contentAlignment = Alignment.Center) { - ChatCaption(image.name.ifBlank { stringResource(R.string.chat_image) }, error = false) - } - } - } -} - -@Composable -internal fun ChatCaption(text: String, error: Boolean) { - Text( - text, - style = MaterialTheme.typography.labelSmall, - color = if (error) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - ) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/MessageBlockList.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/MessageBlockList.kt deleted file mode 100644 index c833398d88..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/MessageBlockList.kt +++ /dev/null @@ -1,314 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.message - -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.selection.toggleable -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.key -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.FileReferenceCards -import com.openbitfun.mobile.app.ui.chat.MarkdownContent -import com.openbitfun.mobile.app.ui.chat.tool.ToolStatusList -import com.openbitfun.mobile.app.ui.chat.tool.ToolDisclosure -import com.openbitfun.mobile.app.ui.chat.tool.LocalToolDisclosure -import com.openbitfun.mobile.core.feature.session.MessageBlock -import com.openbitfun.mobile.core.feature.session.QuestionAnswer -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState - -internal const val SUBAGENT_GROUP_TEST_TAG: String = "subagent-group" - -/** What the app has to be handed to draw any block, gathered so nesting stays cheap. */ -internal data class MessageBlockCallbacks( - val enabled: Boolean, - val onApproveTool: (String, String?) -> Unit, - val onRejectTool: (String, String) -> Unit, - val onCancelTool: (String, String) -> Unit, - val onAnswerTool: (String, String) -> Unit, - val onAnswerToolStructured: (String, List) -> Unit, - val onOpenLink: (String, String) -> Unit, - /** The file the preview surface is showing, so its card can say so. */ - val previewingRemotePath: String, - val previewLoading: Boolean, - val download: RemoteFileDownloadUiState, - val onDownloadFile: (String, String) -> Unit, - val downloadEnabled: Boolean, -) - -/** - * An agent turn in the order it happened, ported from `structuredGroups` in - * `pages/components/ChatMessageBubble.ets`. - * - * The alternative — all the prose, then all the tools — is what this replaces, - * and it misrepresented every turn that worked in steps: the agent appeared to - * have explained the whole job before touching any of it. - */ -@Composable -internal fun MessageBlockList( - blocks: List, - callbacks: MessageBlockCallbacks, - modifier: Modifier, -) { - val selectedTool = rememberSaveable { mutableStateOf(null) } - val disclosure = remember { ToolDisclosure(selectedTool) } - CompositionLocalProvider(LocalToolDisclosure provides disclosure) { - Column( - modifier = modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - val groups = remember(blocks) { processGroups(blocks) } - groups.forEach { group -> - key(group.id) { - var expanded by rememberSaveable { mutableStateOf(false) } - if (group.summarized) { - Row(Modifier.fillMaxWidth().height(32.dp).clickable { expanded = !expanded }, - verticalAlignment = Alignment.CenterVertically) { - Text(stringResource(R.string.tool_group_summary, group.tools.size), - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.weight(1f)) - androidx.compose.material3.Icon(androidx.compose.ui.res.painterResource( - if (expanded) R.drawable.ic_symbol_chevron_down else R.drawable.ic_symbol_chevron_right), - contentDescription = null, modifier = Modifier.width(16.dp)) - } - } - if (!group.summarized || expanded) group.blocks.forEach { block -> - key(block.id) { MessageBlockView(block, callbacks) } - } - } - } - } - } -} - -@Composable -private fun MessageBlockView(block: MessageBlock, callbacks: MessageBlockCallbacks) { - when (block) { - is MessageBlock.Text -> { - MarkdownContent( - text = block.text, - onOpenLink = callbacks.onOpenLink, - modifier = Modifier, - streaming = block.streaming, - ) - FileReferenceCards( - text = block.text, - previewingRemotePath = callbacks.previewingRemotePath, - previewLoading = callbacks.previewLoading, - download = callbacks.download, - onOpen = callbacks.onOpenLink, - onDownload = callbacks.onDownloadFile, - downloadEnabled = callbacks.downloadEnabled, - modifier = Modifier, - ) - } - - is MessageBlock.Thinking -> ThinkingBlock(block.text, block.streaming, block.id) - - is MessageBlock.Tools -> ToolStatusList( - tools = block.tools, - enabled = callbacks.enabled, - onApprove = callbacks.onApproveTool, - onReject = callbacks.onRejectTool, - onCancel = callbacks.onCancelTool, - onAnswer = callbacks.onAnswerTool, - onAnswerStructured = callbacks.onAnswerToolStructured, - onOpenFile = callbacks.onOpenLink, - modifier = Modifier, - ) - - is MessageBlock.Subagent -> SubagentGroup(block, callbacks) - } -} - -/** - * A subagent's turn boxed inside the one that started it, ported from - * `SubagentGroup`. - * - * The box and the left rule down its children exist to answer one question the - * flat list could not: which of these tools did *this* agent run, and which did - * the one it handed the job to. - */ -@Composable -private fun SubagentGroup(block: MessageBlock.Subagent, callbacks: MessageBlockCallbacks) { - var expanded by rememberSaveable(block.id) { mutableStateOf(false) } - val children = remember(block.children, block.running) { subagentChildren(block) } - val hasDetails = children.isNotEmpty() || block.text.isNotBlank() - val outline = MaterialTheme.colorScheme.outlineVariant - Column( - modifier = Modifier - .fillMaxWidth() - .testTag(SUBAGENT_GROUP_TEST_TAG) - .border(1.dp, outline, RoundedCornerShape(12.dp)) - .padding(horizontal = 10.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .semantics(mergeDescendants = true) {} - .toggleable( - value = expanded, - role = Role.Button, - enabled = hasDetails, - onValueChange = { expanded = it }, - ), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (hasDetails) androidx.compose.material3.Icon( - painter = androidx.compose.ui.res.painterResource( - if (expanded) R.drawable.ic_symbol_chevron_down else R.drawable.ic_symbol_chevron_right, - ), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.width(18.dp), - ) - Text( - block.title.ifEmpty { stringResource(R.string.chat_subagent) }, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.weight(1f), - maxLines = 1, - overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, - ) - Text(stringResource(when { - subagentFailed(block.status) -> R.string.tool_phase_failed - block.running -> R.string.tool_phase_running - else -> R.string.tool_phase_completed - }), style = MaterialTheme.typography.labelSmall, - color = if (subagentFailed(block.status)) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) - } - if (expanded && hasDetails) { - Column( - modifier = Modifier - .fillMaxWidth() - .drawBehind { - drawLine( - color = outline, - start = Offset.Zero, - end = Offset(0f, size.height), - strokeWidth = 1.dp.toPx(), - ) - } - .padding(start = 12.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - if (children.isEmpty() && block.text.isNotBlank()) { - Text( - subagentPreview(block.text), - maxLines = 4, - overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, - fontSize = 14.sp, - lineHeight = 21.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - children.forEach { child -> key(child.id) { - if (child is MessageBlock.Text) { - Text(stringResource(R.string.chat_subagent_output), style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(subagentPreview(child.text), maxLines = 4, - overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } else MessageBlockView(child, callbacks) - } } - } - } - } -} - -/** - * Reasoning, collapsed to its label by default: it is usually longer than the - * answer, and scrolling past it to reach the answer is the wrong default. - * - * Reasoning that is still being written opens itself, because at that moment it - * is the only part of the turn there is to read. - */ -@Composable -internal fun ThinkingBlock(thinking: String, streaming: Boolean, stateKey: String) { - var expanded by rememberSaveable(stateKey) { mutableStateOf(streaming) } - var userToggled by rememberSaveable(stateKey) { mutableStateOf(false) } - LaunchedEffect(streaming) { - expanded = if (streaming) { - if (userToggled) expanded else true - } else { - userToggled = false - false - } - } - Column( - modifier = Modifier.fillMaxWidth().padding(start = 2.dp, end = 2.dp, top = 2.dp, bottom = if (expanded) 8.dp else 2.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(32.dp) - .clickable(enabled = thinking.isNotBlank()) { - if (streaming) userToggled = true - expanded = !expanded - }, - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (streaming) { - ChatTypingDots(Modifier.width(22.dp)) - } else { - androidx.compose.material3.Icon( - painter = androidx.compose.ui.res.painterResource( - if (expanded) R.drawable.ic_symbol_chevron_down else R.drawable.ic_symbol_chevron_right, - ), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.width(16.dp), - ) - } - Text( - stringResource( - if (streaming) R.string.chat_thinking_in_progress else R.string.chat_thinking_complete, - ), - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.weight(1f), - ) - } - if (expanded) { - Text( - thinking, - fontSize = 14.sp, - lineHeight = 21.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ProcessPresentation.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ProcessPresentation.kt deleted file mode 100644 index 278540ed47..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/message/ProcessPresentation.kt +++ /dev/null @@ -1,57 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.message - -import com.openbitfun.mobile.core.feature.session.MessageBlock - -/** Native grouping over the shared core's foldability facts; never cross prose or task boundaries. */ -internal data class ProcessGroup(val blocks: List) { - val id: String get() = blocks.first().id - val tools get() = blocks.filterIsInstance().flatMap { it.tools } - val summarized: Boolean get() = tools.size >= 2 && tools.all { it.foldIntoSummary } -} - -internal fun processGroups(blocks: List): List { - val result = mutableListOf() - val pending = mutableListOf() - fun flush() { if (pending.isNotEmpty()) { result += ProcessGroup(pending.toList()); pending.clear() } } - blocks.forEach { block -> - when (block) { - is MessageBlock.Thinking -> { - val previous = pending.lastOrNull() as? MessageBlock.Thinking - if (previous == null) pending += block else { - pending[pending.lastIndex] = previous.copy(text = previous.text + "\n\n" + block.text, - streaming = previous.streaming || block.streaming) - } - } - is MessageBlock.Tools -> block.tools.forEach { tool -> - val leaf = MessageBlock.Tools("tool:${tool.id}", listOf(tool)) - if (tool.foldIntoSummary) pending += leaf else { flush(); result += ProcessGroup(listOf(leaf)) } - } - else -> { flush(); result += ProcessGroup(listOf(block)) } - } - } - flush() - return result -} - -internal fun subagentChildren(block: MessageBlock.Subagent): List { - val visible = block.children.flatMap { child -> - when (child) { - is MessageBlock.Thinking -> if (child.text.isBlank()) emptyList() else listOf(child) - is MessageBlock.Text -> if (child.text.isBlank()) emptyList() else listOf(child) - is MessageBlock.Tools -> child.tools.map { MessageBlock.Tools("subtask-tool:${it.id}", listOf(it)) } - else -> listOf(child) - } - } - return visible.mapIndexed { index, child -> - if (child is MessageBlock.Thinking) child.copy(streaming = block.running && index == visible.lastIndex) else child - } -} - -internal fun subagentFailed(status: String): Boolean = status.lowercase() in - setOf("failed", "error", "timeout", "cancelled", "canceled", "rejected") - -internal fun subagentPreview(text: String): String { - val trimmed = text.trim() - val count = trimmed.codePointCount(0, trimmed.length) - return if (count <= 320) trimmed else trimmed.substring(0, trimmed.offsetByCodePoints(0, 320)).trimEnd() + "…" -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt deleted file mode 100644 index d6dd1b0197..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolGlyph.kt +++ /dev/null @@ -1,140 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.tool - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.ToolCard -import com.openbitfun.mobile.core.feature.session.ToolKind -import com.openbitfun.mobile.core.feature.session.ToolPhase - -/** - * The badge a tool row leads with, ported from `ToolStatusIcon` in - * `pages/components/ToolStatusList.ets` and the glyph set in `ToolGlyphs.ets`. - * - * Two marks in one: what the tool does, which is constant, and how it is going, - * which is not. The second is drawn only while it is worth a glance — a tool - * that finished the way tools usually do says so by having nothing pinned to it. - */ -@Composable -internal fun ToolStatusIcon(tool: ToolCard, modifier: Modifier) { - Box(modifier = modifier.size(20.dp), contentAlignment = Alignment.TopStart) { - Box( - modifier = Modifier - .size(18.dp) - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(5.dp)) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(5.dp)), - contentAlignment = Alignment.Center, - ) { - Icon( - painter = painterResource(kindIcon(tool.kind)), - contentDescription = null, - tint = kindTint(tool.kind), - modifier = Modifier.size(12.dp), - ) - } - statusMark(tool.phase)?.let { mark -> - Box( - modifier = Modifier - .align(Alignment.BottomEnd) - .size(10.dp) - .background(MaterialTheme.colorScheme.onSurfaceVariant, CircleShape) - .border(1.dp, MaterialTheme.colorScheme.surface, CircleShape), - contentAlignment = Alignment.Center, - ) { - // A character rather than an icon, as in the source: at ten - // pixels across, a drawn glyph turns to mud and a bold `!` or - // `?` still reads. - Text( - text = mark, - fontSize = 7.sp, - lineHeight = 8.sp, - fontWeight = FontWeight.Bold, - textAlign = TextAlign.Center, - color = MaterialTheme.colorScheme.surface, - ) - } - } - } -} - -/** - * The badge for a folded group, which stands for several tools at once: the one - * thing they all were when they agree, and a stack when they do not. - */ -@Composable -internal fun ToolSummaryIcon(readCount: Int, searchCount: Int, modifier: Modifier) { - val icon = when { - searchCount > 0 && readCount == 0 -> R.drawable.ic_symbol_magnifyingglass - readCount > 0 && searchCount == 0 -> R.drawable.ic_symbol_doc_text - else -> R.drawable.ic_symbol_rectangle_stack - } - Box( - modifier = modifier - .size(18.dp) - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(5.dp)), - contentAlignment = Alignment.Center, - ) { - Icon( - painter = painterResource(icon), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(12.dp), - ) - } -} - -@DrawableRes -private fun kindIcon(kind: ToolKind): Int = when (kind) { - ToolKind.QUESTION -> R.drawable.ic_symbol_questionmark_circle - ToolKind.TODO -> R.drawable.ic_symbol_list_checkmark - ToolKind.TASK -> R.drawable.ic_symbol_person - ToolKind.GIT -> R.drawable.ic_symbol_arrow_triangle_merge - ToolKind.DELETE -> R.drawable.ic_symbol_trash - ToolKind.DIFF -> R.drawable.ic_symbol_doc_text_badge_magnifyingglass - // Patch and command share a glyph in the source: both of them are, in the - // end, something the desktop ran. - ToolKind.PATCH, ToolKind.COMMAND -> R.drawable.ic_symbol_code_square - ToolKind.CREATE -> R.drawable.ic_symbol_doc_text_badge_arrow_up - ToolKind.MUTATE -> R.drawable.ic_symbol_square_and_pencil - ToolKind.FOLDER -> R.drawable.ic_symbol_folder - ToolKind.DOCUMENT -> R.drawable.ic_symbol_doc_text - ToolKind.SEARCH -> R.drawable.ic_symbol_magnifyingglass - ToolKind.WEB -> R.drawable.ic_symbol_link - ToolKind.GENERIC -> R.drawable.ic_symbol_wrench_and_screwdriver -} - -/** - * Two families are tinted away from the default: what removes something, and - * what adds it. The rest are one weight, because a column where every icon is a - * colour is a column where none of them is a signal. - */ -@Composable -private fun kindTint(kind: ToolKind): Color = when (kind) { - ToolKind.DELETE -> MaterialTheme.colorScheme.error - ToolKind.TODO, ToolKind.CREATE -> MaterialTheme.colorScheme.tertiary - else -> MaterialTheme.colorScheme.onSurfaceVariant -} - -private fun statusMark(phase: ToolPhase): String? = when (phase) { - ToolPhase.PENDING_CONFIRMATION -> "?" - ToolPhase.RUNNING -> "•" - ToolPhase.CANCELLED -> "×" - ToolPhase.COMPLETED, ToolPhase.FAILED, ToolPhase.WAITING -> null -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanels.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanels.kt deleted file mode 100644 index d5809004f7..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanels.kt +++ /dev/null @@ -1,295 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.tool - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.selection.toggleable -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.RadioButton -import androidx.compose.material3.TextButton -import androidx.compose.material3.Text -import androidx.compose.material3.Checkbox -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.session.QuestionAnswer -import com.openbitfun.mobile.core.feature.session.QuestionAnswerValue -import com.openbitfun.mobile.core.feature.session.QuestionOption -import com.openbitfun.mobile.core.feature.session.ToolQuestion - -/** Compact approval actions; rejection remains available while JSON edits are invalid. */ -@Composable -internal fun ToolConfirmationPanel( - canApprove: Boolean, - canReject: Boolean, - enabled: Boolean, - input: String, - onApprove: (String?) -> Unit, - onReject: () -> Unit, -) { - var editing by rememberSaveable(input) { mutableStateOf(false) } - var editedInput by rememberSaveable(input) { mutableStateOf(input.ifBlank { "{}" }) } - val valid = !editing || runCatching { org.json.JSONObject(editedInput) }.isSuccess - Column(verticalArrangement = Arrangement.spacedBy(MobileDesignGeometry.ApprovalCardGap)) { - if (canApprove) { - TextButton(onClick = { editing = !editing }, enabled = enabled) { Text(stringResource(if (editing) R.string.tool_hide_approval_input else R.string.tool_edit_approval_input)) } - if (editing) OutlinedTextField(enabled = enabled, value = editedInput, onValueChange = { editedInput = it }, isError = !valid, label = { Text(stringResource(R.string.tool_input)) }, modifier = Modifier.fillMaxWidth()) - } - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MobileDesignGeometry.ApprovalCardGap, androidx.compose.ui.Alignment.End), - ) { - if (canReject) { - Button( - onClick = onReject, - enabled = enabled, - shape = RoundedCornerShape(MobileDesignGeometry.ApprovalActionRadius), - colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, - contentColor = MaterialTheme.colorScheme.onSurface), - contentPadding = PaddingValues(horizontal = 16.dp), - modifier = Modifier.height(MobileDesignGeometry.ApprovalActionHeight), - ) { Text(stringResource(R.string.tool_reject)) } - } - if (canApprove) { - Button( - onClick = { if (valid) onApprove(if (editing) editedInput else null) }, - enabled = enabled && valid, - shape = RoundedCornerShape(MobileDesignGeometry.ApprovalActionRadius), - contentPadding = PaddingValues(horizontal = 16.dp), - modifier = Modifier.height(MobileDesignGeometry.ApprovalActionHeight), - ) { Text(stringResource(R.string.tool_approve)) } - } - } - } -} - -/** - * The agent's question and its answer box, ported from - * `ToolQuestionAnswerPanel` in `pages/components/ToolInteractionPanels.ets`. - * - * Inline rather than the dialog this used to be. The turn does not move until - * the question is answered, so the box belongs in the transcript beside the - * question it answers — a dialog can be dismissed, which leaves the turn stuck - * with nothing on screen saying why. - */ -@Composable -internal fun ToolQuestionAnswerPanel( - toolId: String, - prompt: String, - enabled: Boolean, - onSubmit: (String) -> Unit, -) { - // Keyed on the tool: a new question is a new blank box, and the answer to - // the one before it should not be sitting in it. - var answer by remember(toolId) { mutableStateOf("") } - val canSubmit = enabled && toolId.isNotEmpty() && answer.isNotBlank() - - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(prompt, style = MaterialTheme.typography.bodyMedium) - OutlinedTextField( - value = answer, - onValueChange = { answer = it }, - label = { Text(stringResource(R.string.tool_answer_label)) }, - // Multi-line, as the source's `TextArea` is: an answer to an agent is - // prose, and the send action is the button rather than the return key. - minLines = 3, - maxLines = 6, - enabled = enabled, - modifier = Modifier.fillMaxWidth(), - ) - PillButton( - label = stringResource(R.string.tool_answer_send), - primary = true, - enabled = canSubmit, - compact = false, - onClick = { - onSubmit(answer.trim()) - // Keep the draft until the authoritative question leaves the UI. - }, - modifier = Modifier.fillMaxWidth(), - ) - } -} - -internal fun isOtherOption(label: String, otherLabel: String): Boolean { - val normalizedLabel = label.trim() - return normalizedLabel.equals("other", ignoreCase = true) || - normalizedLabel.equals(otherLabel.trim(), ignoreCase = true) || - normalizedLabel == "其他" -} - -internal fun effectiveOptions( - question: ToolQuestion, - otherLabel: String, -): List = question.options + if ( - question.options.none { isOtherOption(it.label, otherLabel) } -) { - listOf(QuestionOption(otherLabel, null)) -} else { - emptyList() -} - -internal fun buildStructuredAnswers( - questions: List, - selectedByIndex: Map>, - customByIndex: Map, - otherLabel: String, -): List = questions.map { question -> - val selected = selectedByIndex[question.index].orEmpty() - val custom = customByIndex[question.index].orEmpty().trim() - val effectiveOptions = effectiveOptions(question, otherLabel) - val values = effectiveOptions.map { it.label }.filter { it in selected }.map { label -> - if (isOtherOption(label, otherLabel)) custom else label - } - if (question.multiSelect) { - QuestionAnswer(question.index, QuestionAnswerValue.Choice(values)) - } else { - QuestionAnswer(question.index, QuestionAnswerValue.Text(values.firstOrNull().orEmpty())) - } -} - -@Composable -internal fun ToolStructuredQuestionPanel( - toolId: String, - questions: List, - enabled: Boolean, - onSubmit: (List) -> Unit, -) { - val otherLabel = stringResource(R.string.tool_option_other) - var selectedByIndex by remember(toolId) { mutableStateOf>>(emptyMap()) } - var customByIndex by remember(toolId) { mutableStateOf>(emptyMap()) } - val answers = buildStructuredAnswers(questions, selectedByIndex, customByIndex, otherLabel) - val canSubmit = enabled && toolId.isNotEmpty() && questions.all { question -> - val selected = selectedByIndex[question.index].orEmpty() - selected.isNotEmpty() && (!selected.any { isOtherOption(it, otherLabel) } || customByIndex[question.index].orEmpty().isNotBlank()) - } - - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - questions.forEach { question -> - val selected = selectedByIndex[question.index].orEmpty() - Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - if (question.header.isNotBlank()) { - Text(question.header, style = MaterialTheme.typography.labelLarge) - } - Text(question.question, style = MaterialTheme.typography.bodyMedium) - val options = effectiveOptions(question, otherLabel) - options.forEach { option -> - val checked = option.label in selected - Column( - modifier = Modifier.fillMaxWidth().toggleable( - value = checked, - enabled = enabled, - role = if (question.multiSelect) androidx.compose.ui.semantics.Role.Checkbox else androidx.compose.ui.semantics.Role.RadioButton, - onValueChange = { - selectedByIndex = selectedByIndex.toMutableMap().apply { - this[question.index] = if (question.multiSelect) { - if (checked) selected - option.label else selected + option.label - } else { - setOf(option.label) - } - } - }, - ).padding(vertical = 2.dp), - ) { - Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { - if (question.multiSelect) Checkbox(checked, null, enabled = enabled) - else RadioButton(checked, null, enabled = enabled) - Text(option.label, style = MaterialTheme.typography.bodyMedium) - } - option.description?.takeIf(String::isNotBlank)?.let { - Text(it, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(start = 48.dp)) - } - } - if (isOtherOption(option.label, otherLabel) && checked) { - OutlinedTextField( - value = customByIndex[question.index].orEmpty(), - onValueChange = { customByIndex = customByIndex + (question.index to it) }, - label = { Text(stringResource(R.string.tool_answer_label)) }, - enabled = enabled, - modifier = Modifier.fillMaxWidth().padding(start = 48.dp), - ) - } - } - } - } - PillButton( - label = stringResource(R.string.tool_answer_send), - primary = true, - enabled = canSubmit, - compact = false, - onClick = { onSubmit(answers) }, - modifier = Modifier.fillMaxWidth(), - ) - } -} - -/** - * The source draws every tool action as a 32-high rounded capsule, filled for - * the affirmative one and outlined for the rest. This is that shape. - * - * [compact] is the one that rides inside a tool row rather than under it, so it - * has to fit the row's own height instead of setting it. - */ -@Composable -internal fun PillButton( - label: String, - primary: Boolean, - enabled: Boolean, - compact: Boolean, - onClick: () -> Unit, - modifier: Modifier, -) { - val shape = RoundedCornerShape(percent = 50) - val padding = if (compact) { - PaddingValues(horizontal = 12.dp, vertical = 0.dp) - } else { - ButtonDefaults.ContentPadding - } - val sized = modifier.heightIn(min = if (compact) 28.dp else 36.dp) - val content: @Composable () -> Unit = { - Text( - label, - style = if (compact) { - MaterialTheme.typography.labelMedium - } else { - MaterialTheme.typography.labelLarge - }, - maxLines = 1, - ) - } - if (primary) { - Button( - onClick = onClick, - enabled = enabled, - shape = shape, - contentPadding = padding, - modifier = sized, - ) { content() } - } else { - OutlinedButton( - onClick = onClick, - enabled = enabled, - shape = shape, - contentPadding = padding, - modifier = sized, - ) { content() } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt deleted file mode 100644 index b80f4f5ea3..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolStatusList.kt +++ /dev/null @@ -1,520 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.tool - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.staticCompositionLocalOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import org.json.JSONObject -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.ToolAction -import com.openbitfun.mobile.core.feature.session.ToolCard -import com.openbitfun.mobile.core.feature.session.QuestionAnswer -import com.openbitfun.mobile.core.feature.session.ToolOperation -import com.openbitfun.mobile.core.feature.session.ToolPhase -import com.openbitfun.mobile.core.feature.session.ToolRow -import com.openbitfun.mobile.core.feature.session.collapseToolRows -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -/** Anything the desktop must be told about a rejection needs a reason; this is ours. */ -internal data class PlanActions( - val supported: Boolean = false, - val enabled: Boolean = false, - val build: (com.openbitfun.mobile.core.feature.session.PlanToolDescriptor) -> Unit = {}, -) -internal val LocalPlanActions = androidx.compose.runtime.staticCompositionLocalOf { PlanActions() } - -internal class ToolDisclosure(selectedState: MutableState) { - var selected by selectedState -} -internal val LocalToolDisclosure = staticCompositionLocalOf { null } -internal val LocalPermissionMailbox = staticCompositionLocalOf { null } - -private const val REJECT_REASON = "Rejected from the Android client" -private const val CANCEL_REASON = "Cancelled from the Android client" - -internal const val TOOL_ROW_TEST_TAG: String = "tool-row" -internal const val TOOL_GROUP_TEST_TAG: String = "tool-group" -internal const val TOOL_EXPAND_TEST_TAG: String = "tool-expand" - -/** The indent that lines a row's detail up under its label rather than its icon. */ -private val DETAIL_INDENT = 28.dp - -/** - * The tools a turn ran, ported from `pages/components/ToolStatusList.ets`. - * - * A line each, not a card each: a turn can run a dozen tools, and a dozen filled - * boxes between two paragraphs is a wall rather than a trace. Weight is spent - * only where something is unresolved — a failure, or a tool that cannot go on - * until the user answers it — and consecutive finished lookups fold into one - * line, because six `Read`s in a row say the same thing six times. - */ -@Composable -internal fun ToolStatusList( - tools: List, - enabled: Boolean, - onApprove: (String, String?) -> Unit, - onReject: (String, String) -> Unit, - onCancel: (String, String) -> Unit, - onAnswer: (String, String) -> Unit, - onAnswerStructured: (String, List) -> Unit, - onOpenFile: (String, String) -> Unit, - modifier: Modifier, -) { - val rows = remember(tools) { collapseToolRows(tools) } - Column( - modifier = modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - rows.forEach { row -> - when (row) { - is ToolRow.Single -> ToolStatusRow( - tool = row.tool, - enabled = enabled, - onApprove = { input -> onApprove(row.tool.id, input) }, - onReject = { reason -> onReject(row.tool.id, reason) }, - onCancel = { reason -> onCancel(row.tool.id, reason) }, - onAnswer = { answer -> onAnswer(row.tool.id, answer) }, - onAnswerStructured = { answers -> onAnswerStructured(row.tool.id, answers) }, - onOpenFile = onOpenFile, - modifier = Modifier, - ) - - is ToolRow.Collapsed -> CollapsedToolGroup( - group = row, - enabled = enabled, - onOpenFile = onOpenFile, - modifier = Modifier, - ) - } - } - } -} - -/** - * Several finished lookups behind one line, opened by tapping it. - * - * Expanding keeps the summary on screen above the tools it stands for, so the - * column does not appear to grow out of nothing. - */ -@Composable -private fun CollapsedToolGroup( - group: ToolRow.Collapsed, - enabled: Boolean, - onOpenFile: (String, String) -> Unit, - modifier: Modifier, -) { - var expanded by remember(group.id) { mutableStateOf(false) } - Column( - modifier = modifier.fillMaxWidth().testTag(TOOL_GROUP_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth().heightIn(min = 28.dp).clickable { expanded = !expanded }, - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - ToolSummaryIcon(group.readCount, group.searchCount, Modifier) - Text( - stringResource(R.string.tool_group_summary, group.tools.size), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - Chevron( - if (expanded) { - R.drawable.ic_symbol_chevron_up - } else { - R.drawable.ic_symbol_chevron_down - }, - ) - } - if (expanded) { - group.tools.forEach { tool -> - ToolStatusRow( - tool = tool, - enabled = enabled, - // Nothing in a folded group is still actionable; that is what - // made it foldable. - onApprove = {}, - onReject = {}, - onCancel = {}, - onAnswer = {}, - onAnswerStructured = {}, - onOpenFile = onOpenFile, - modifier = Modifier, - ) - } - } - } -} - -/** - * One tool, ported from `ToolRow` in `pages/components/ToolStatusList.ets`. - * - * The label is the whole row when nothing is pending: a line naming what was - * done and to what. It becomes a link when the tool worked on a file, because - * the file is what the user would go looking for next. - */ -@Composable -internal fun ToolStatusRow( - tool: ToolCard, - enabled: Boolean, - onApprove: (String?) -> Unit, - onReject: (String) -> Unit, - onCancel: (String) -> Unit, - onAnswer: (String) -> Unit, - onAnswerStructured: (List) -> Unit, - onOpenFile: (String, String) -> Unit, - modifier: Modifier, -) { - val plan = tool.plan - if (plan != null) { - val actions = LocalPlanActions.current - Column(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(14.dp)).padding(14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(plan.name.ifBlank { stringResource(R.string.plan_title) }, style = MaterialTheme.typography.titleSmall) - if (plan.overview.isNotBlank()) Text(plan.overview, style = MaterialTheme.typography.bodySmall) - androidx.compose.material3.TextButton(onClick = { onOpenFile(plan.path, plan.name) }, enabled = enabled && plan.path.isNotBlank()) { - Text(stringResource(R.string.plan_view)) - } - androidx.compose.material3.Button(onClick = { actions.build(plan) }, enabled = actions.supported && actions.enabled && tool.phase == ToolPhase.COMPLETED && plan.path.isNotBlank()) { - Text(stringResource(R.string.plan_build)) - } - if (!actions.supported) Text(stringResource(R.string.plan_unsupported), style = MaterialTheme.typography.bodySmall) - else if (!actions.enabled) Text(stringResource(R.string.plan_wait), style = MaterialTheme.typography.bodySmall) - } - return - } - if (tool.kind == com.openbitfun.mobile.core.feature.session.ToolKind.TODO || - tool.operation == ToolOperation.UPDATE_TODOS || tool.name.equals("TodoWrite", ignoreCase = true)) { - TodoToolCard(tool = tool, enabled = enabled, modifier = modifier) - return - } - var localExpanded by rememberSaveable(tool.id) { mutableStateOf(false) } - val disclosure = LocalToolDisclosure.current - val expanded = disclosure?.let { it.selected == tool.id } ?: localExpanded - val toggle = { - if (disclosure == null) localExpanded = !localExpanded - else disclosure.selected = if (expanded) null else tool.id - } - val transcriptActions = if (LocalPermissionMailbox.current?.ownsToolInteraction(tool.id) == true) { - tool.actions - setOf(ToolAction.ANSWER, ToolAction.APPROVE, ToolAction.REJECT) - - (if (ToolAction.ANSWER in tool.actions) setOf(ToolAction.CANCEL) else emptySet()) - } else tool.actions - val blocking = transcriptActions.isNotEmpty() - val emphasized = expanded || blocking - val canExpand = tool.expandable - val openable = tool.filePath.isNotEmpty() - - Column( - modifier = modifier - .fillMaxWidth() - .testTag(TOOL_ROW_TEST_TAG) - .background( - color = if (emphasized) { - MaterialTheme.colorScheme.surfaceVariant - } else { - openBitFunColors.transparent - }, - shape = RoundedCornerShape(if (emphasized) 14.dp else 8.dp), - ) - .border( - width = if (emphasized) 1.dp else 0.dp, - color = if (emphasized) MaterialTheme.colorScheme.outlineVariant else openBitFunColors.transparent, - shape = RoundedCornerShape(if (emphasized) 14.dp else 8.dp), - ) - .padding( - horizontal = if (emphasized) 10.dp else 0.dp, - vertical = if (emphasized) 6.dp else 0.dp, - ), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth().heightIn(min = 28.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - ToolStatusIcon(tool, Modifier) - Text( - toolLineLabel(tool), - style = MaterialTheme.typography.bodySmall, - color = when { - openable -> MaterialTheme.colorScheme.primary - else -> MaterialTheme.colorScheme.onSurfaceVariant - }, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier - .weight(1f) - .clickable(enabled = openable || canExpand) { - if (openable) { - onOpenFile(tool.filePath, tool.fileLabel) - } else { - toggle() - } - }, - ) - if (canExpand) { - Box( - modifier = Modifier - .size(width = 32.dp, height = 28.dp) - .testTag(TOOL_EXPAND_TEST_TAG) - .clickable { toggle() }, - contentAlignment = Alignment.Center, - ) { - Chevron( - if (expanded) { - R.drawable.ic_symbol_chevron_down - } else { - R.drawable.ic_symbol_chevron_right - }, - ) - } - } - } - - if (expanded) { - if (tool.input.isNotEmpty()) { - ToolDetail(stringResource(R.string.tool_input), tool.input, false) - } - if (tool.output.isNotEmpty()) { - val failed = tool.phase == ToolPhase.FAILED - ToolDetail( - stringResource(if (failed) R.string.tool_error else R.string.tool_output), - tool.output, - failed, - ) - } - } - - if (ToolAction.APPROVE in transcriptActions || ToolAction.REJECT in transcriptActions) { - ToolConfirmationPanel( - input = tool.input, - canApprove = ToolAction.APPROVE in transcriptActions, - canReject = ToolAction.REJECT in transcriptActions, - enabled = enabled, - onApprove = onApprove, - onReject = { onReject(REJECT_REASON) }, - ) - } - - if (ToolAction.ANSWER in transcriptActions) { - if (tool.questions.isNotEmpty()) { - ToolStructuredQuestionPanel( - toolId = tool.id, - questions = tool.questions, - enabled = enabled, - onSubmit = onAnswerStructured, - ) - } else { - ToolQuestionAnswerPanel( - toolId = tool.id, - // The agent did not always send a prompt to quote, so we ask in ours. - prompt = tool.question ?: stringResource(R.string.tool_question_default), - enabled = enabled, - onSubmit = onAnswer, - ) - } - } - - if (ToolAction.CANCEL in transcriptActions) { - Row( - modifier = Modifier.fillMaxWidth().padding(start = DETAIL_INDENT), - horizontalArrangement = Arrangement.End, - ) { - PillButton( - label = stringResource(R.string.tool_cancel), - primary = false, - enabled = enabled, - compact = true, - onClick = { onCancel(CANCEL_REASON) }, - modifier = Modifier, - ) - } - } - } -} - - -private data class TodoItem(val content: String, val status: String) - -private fun parseTodoItems(value: String): List = runCatching { - val root = JSONObject(value) - val todos = root.optJSONArray("todos") ?: return@runCatching emptyList() - buildList { - for (index in 0 until todos.length()) { - val item = todos.optJSONObject(index) ?: continue - val content = item.optString("content").trim() - if (content.isNotEmpty()) add(TodoItem(content, item.optString("status", "pending"))) - } - } -}.getOrDefault(emptyList()) - -@Composable -private fun TodoToolCard(tool: ToolCard, enabled: Boolean, modifier: Modifier) { - var expanded by rememberSaveable(tool.id) { mutableStateOf(tool.phase != ToolPhase.COMPLETED) } - val items = remember(tool.input, tool.output) { - parseTodoItems(tool.input).ifEmpty { parseTodoItems(tool.output) } - } - val done = items.count { it.status.equals("completed", true) } - val title = stringResource(R.string.tool_op_update_todos) - val active = items.firstOrNull { it.status.equals("in_progress", true) } - ?: items.firstOrNull { it.status.equals("pending", true) } - val summary = when { - items.isEmpty() -> tool.target.ifBlank { stringResource(R.string.tool_todo_fallback) } - done == items.size -> stringResource(R.string.tool_todo_all_completed) - else -> active?.content ?: items.first().content - } - Column( - modifier = modifier.fillMaxWidth() - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(16.dp)) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(16.dp)) - .padding(horizontal = 12.dp, vertical = 10.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth().clickable { expanded = !expanded }, - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(9.dp), - ) { - ToolStatusIcon(tool, Modifier) - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text(title, style = MaterialTheme.typography.bodyMedium, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold) - Text(summary, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, overflow = TextOverflow.Ellipsis) - } - if (items.isNotEmpty()) Text("$done/${items.size}", style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - Chevron(if (expanded) R.drawable.ic_symbol_chevron_down else R.drawable.ic_symbol_chevron_right) - } - if (expanded && items.isNotEmpty()) { - Column(Modifier.fillMaxWidth().padding(start = 29.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Box(Modifier.fillMaxWidth().height(2.dp).background(MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(2.dp))) { - Box(Modifier.fillMaxWidth(done.toFloat() / items.size.toFloat()).height(2.dp).background(MaterialTheme.colorScheme.onSurfaceVariant, RoundedCornerShape(2.dp))) - } - items.forEach { item -> - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.Top) { - Text(if (item.status.equals("completed", true)) "✓" else if (item.status.equals("cancelled", true)) "×" else if (item.status.equals("in_progress", true)) "•" else "○", - color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(item.content, style = MaterialTheme.typography.bodySmall, - color = if (item.status.equals("in_progress", true)) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant) - } - } - } - } - if (expanded && items.isEmpty() && tool.output.isNotBlank()) { - ToolDetail(stringResource(R.string.tool_output), tool.output, tool.phase == ToolPhase.FAILED) - } - } -} - -/** - * The row's one line, ported from `toolLineLabel`. - * - * What it leads with is what the reader wants first, and that changes with the - * state: a running tool leads with the thing it is working on, and anything - * waiting on the user with the fact that it is. Failures remain in the details. - */ -@Composable -private fun toolLineLabel(tool: ToolCard): String { - val operation = operationLabel(tool) - val target = tool.target - return when { - tool.phase == ToolPhase.RUNNING -> - stringResource(R.string.tool_line_running, target.ifEmpty { operation }) - - tool.phase == ToolPhase.PENDING_CONFIRMATION || ToolAction.ANSWER in tool.actions -> - join(stringResource(R.string.tool_phase_pending), operation) - - tool.phase == ToolPhase.WAITING -> join(stringResource(R.string.tool_phase_waiting), operation) - else -> join(operation, target) - } -} - -@Composable -private fun join(head: String, tail: String): String = - if (tail.isEmpty()) head else stringResource(R.string.tool_line_target, head, tail) - -/** What the tool is doing, or its own name when this client cannot tell. */ -@Composable -private fun operationLabel(tool: ToolCard): String { - val label = when (tool.operation) { - ToolOperation.UPDATE_TODOS -> R.string.tool_op_update_todos - ToolOperation.START_TASK -> R.string.tool_op_start_task - ToolOperation.READ_FILE -> R.string.tool_op_read_file - ToolOperation.WRITE_FILE -> R.string.tool_op_write_file - ToolOperation.DELETE_FILE -> R.string.tool_op_delete_file - ToolOperation.VIEW_DIFF -> R.string.tool_op_view_diff - ToolOperation.EDIT_FILE -> R.string.tool_op_edit_file - ToolOperation.RUN_COMMAND -> R.string.tool_op_run_command - ToolOperation.SEARCH_WEB -> R.string.tool_op_search_web - ToolOperation.OPEN_WEB -> R.string.tool_op_open_web - ToolOperation.SEARCH_CODE -> R.string.tool_op_search_code - ToolOperation.ASK_CONFIRMATION -> R.string.tool_op_ask_confirmation - ToolOperation.UNKNOWN -> null - } - return label?.let { stringResource(it) } ?: tool.name.ifBlank { stringResource(R.string.tool_unknown) } -} - -@Composable -private fun Chevron(@DrawableRes icon: Int) { - Icon( - painter = painterResource(icon), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(14.dp), - ) -} - -@Composable -private fun ToolDetail(label: String, body: String, isError: Boolean) { - Column(modifier = Modifier.fillMaxWidth().padding(start = DETAIL_INDENT)) { - Text( - label, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - body, - style = MaterialTheme.typography.bodySmall, - color = if (isError) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - // Capped the way the source caps it: a tool that printed a file - // should not push the answer the user is reading off the screen. - maxLines = 5, - overflow = TextOverflow.Ellipsis, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/AdaptiveModalSurface.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/AdaptiveModalSurface.kt deleted file mode 100644 index f55ed7b6a4..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/AdaptiveModalSurface.kt +++ /dev/null @@ -1,161 +0,0 @@ -package com.openbitfun.mobile.app.ui.common - -import androidx.compose.foundation.background -import androidx.compose.foundation.gestures.detectTapGestures -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.statusBars -import androidx.compose.foundation.layout.asPaddingValues -import androidx.compose.material3.BottomSheetDefaults -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalWindowInfo -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.safeDrawingPadding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.Surface -import androidx.compose.material3.rememberModalBottomSheetState -import androidx.compose.ui.platform.LocalView -import androidx.compose.ui.window.DialogWindowProvider -import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Dialog -import androidx.compose.ui.window.DialogProperties -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementMode - -/** - * Native modal lifecycle around the shared mobile overlay visual contract. - * - * Compact and hover windows keep Material's modal sheet semantics. A side - * placement uses a full-window Dialog so back handling, focus containment and - * accessibility isolation remain native while the surface docks to the - * physical trailing region selected by the shared policy. - * - * @param draggable whether the compact sheet follows a pull-down. A page whose - * body is itself a scroll should say no: the same pull-down then means both - * "scroll the body" and "drag the sheet away", so a gesture the user meant as - * scrolling can move the surface or dismiss the page. Such a page still closes - * through its own close button, the back action, and a tap on the scrim. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun AdaptiveModalSurface( - visible: Boolean, - placement: SettingsPlacement, - onDismissRequest: () -> Unit, - edgeToEdgeContent: Boolean = false, - fitContent: Boolean = false, - draggable: Boolean = true, - content: @Composable (Modifier) -> Unit, -) { - if (!visible) return - - // Scrim and sheet hit interception must not merge labels into extra clickable - // accessibility nodes. Close buttons and the native back action remain available. - if (fitContent) { - Dialog(onDismissRequest = onDismissRequest, - properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { - val window = (LocalView.current.parent as? DialogWindowProvider)?.window - SideEffect { - window?.setDimAmount(0f) - // The account sheet is edge-to-edge. Some Android-compatible - // hosts otherwise leave the dialog's default white navigation - // bar below the rounded surface as a visible strip. - window?.navigationBarColor = android.graphics.Color.TRANSPARENT - if (android.os.Build.VERSION.SDK_INT >= 29) { - window?.isNavigationBarContrastEnforced = false - } - } - Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.scrim) - .pointerInput(onDismissRequest) { detectTapGestures(onTap = { onDismissRequest() }) } - .safeDrawingPadding().imePadding().padding(MobileDesignGeometry.LoginSheetOuterMargin), - contentAlignment = Alignment.BottomCenter) { - Surface(modifier = Modifier.widthIn(max = MobileDesignGeometry.LoginSheetMaxWidth).fillMaxWidth() - .pointerInput(Unit) { detectTapGestures(onTap = {}) }, - shape = RoundedCornerShape(MobileDesignGeometry.SheetTopRadius), - color = MaterialTheme.colorScheme.background) { - content(Modifier.fillMaxWidth()) - } - } - } - return - } - - if (placement.mode == SettingsPlacementMode.SIDE) { - Dialog( - onDismissRequest = onDismissRequest, - properties = DialogProperties( - dismissOnBackPress = true, - dismissOnClickOutside = true, - usePlatformDefaultWidth = false, - decorFitsSystemWindows = false, - ), - ) { - Box( - modifier = Modifier - .fillMaxSize() - .background(MaterialTheme.colorScheme.scrim) - .pointerInput(onDismissRequest) { detectTapGestures(onTap = { onDismissRequest() }) } - .safeDrawingPadding() - .imePadding(), - contentAlignment = Alignment.CenterEnd, - ) { - Surface( - color = MaterialTheme.colorScheme.background, - shape = RoundedCornerShape(MobileDesignGeometry.SheetSideRadius), - shadowElevation = MobileDesignGeometry.PopoverShadowRadius, - modifier = Modifier - .width(placement.width.dp) - .height(placement.height.dp) - .pointerInput(Unit) { detectTapGestures(onTap = {}) }, - ) { - content(Modifier.fillMaxSize()) - } - } - } - return - } - - val height = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.height.toDp() } - val topInset = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() - ModalBottomSheet( - onDismissRequest = onDismissRequest, - sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), - containerColor = MaterialTheme.colorScheme.background, - shape = RoundedCornerShape( - topStart = MobileDesignGeometry.SheetTopRadius, - topEnd = MobileDesignGeometry.SheetTopRadius, - ), - dragHandle = null, - sheetGesturesEnabled = draggable, - contentWindowInsets = { if (edgeToEdgeContent) WindowInsets(0) else BottomSheetDefaults.windowInsets }, - ) { - val modifier = if (fitContent) { - Modifier.fillMaxWidth().heightIn(max = (height - topInset - 8.dp).coerceAtLeast(0.dp)) - } else if (edgeToEdgeContent && placement.mode != SettingsPlacementMode.FOLD_OPERATE) { - Modifier.fillMaxWidth().height((height - topInset - 8.dp).coerceAtLeast(0.dp)) - } else if (placement.mode == SettingsPlacementMode.FOLD_OPERATE && placement.height > 0) { - Modifier.fillMaxWidth().height(placement.height.dp) - } else { - Modifier.fillMaxWidth().fillMaxHeight(0.94f) - } - content(modifier) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/CircleControl.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/CircleControl.kt deleted file mode 100644 index 49176117f7..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/CircleControl.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.openbitfun.mobile.app.ui.common - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry - -/** - * The floating round control the source draws on a page rather than on a bar. - * - * `RemoteChatHeader.ets` and `RemoteCreateSessionView.ets` both open with one of - * these in the top-left, which is what keeps whatever is centred — a title, or - * nothing at all — the subject of the screen instead of one of three equal - * things in a row. Shared rather than copied so the two screens cannot drift - * apart by a dp. - * - * @param glyphWidth and [glyphHeight] are the box the glyph is *fitted* into, - * matching HarmonyOS' `TemplateIcon`, which fits its asset with - * `ImageFit.Contain`. Neither one is the drawn size on its own: a drawable is - * scaled by the smaller of the two ratios and stays centred. Passing the - * source's non-square numbers to a drawable that keeps this set's square 24x24 - * viewport therefore shrinks the whole glyph to the shorter side — a 23x7 box - * draws a 24x24 vector at 7x7. Give the glyph its own aspect in the drawable, - * as `ic_symbol_ellipsis` and `ic_symbol_chevron_left_wide` do, or pass a - * square box. - */ -@Composable -internal fun CircleControl( - @DrawableRes icon: Int, - glyphSize: Int, - glyphWidth: Int = glyphSize, - glyphHeight: Int = glyphSize, - contentDescription: String, - onClick: () -> Unit, - modifier: Modifier, -) { - Surface( - onClick = onClick, - shape = CircleShape, - color = MaterialTheme.colorScheme.surface, - - shadowElevation = 1.dp, - modifier = modifier.size(MobileDesignGeometry.ControlTouchSize), - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - painterResource(icon), - contentDescription = contentDescription, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(width = glyphWidth.dp, height = glyphHeight.dp), - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionLabels.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionLabels.kt deleted file mode 100644 index 3384ef9311..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionLabels.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.openbitfun.mobile.app.ui.common - -import androidx.annotation.StringRes -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.ConnectionStatusLabel -import com.openbitfun.mobile.core.feature.connection.ConnectionStatusPresenter - -/** Android resource adapter for the platform-neutral connection presentation. */ -internal fun ConnectionPhase.labelRes(): Int = when (ConnectionStatusPresenter.label(this)) { - ConnectionStatusLabel.CONNECTED -> R.string.connection_connected - ConnectionStatusLabel.RECONNECTING -> R.string.connection_reconnecting - ConnectionStatusLabel.CONNECTING -> R.string.connection_connecting - ConnectionStatusLabel.ERROR -> R.string.connection_error - ConnectionStatusLabel.DISCONNECTED -> R.string.connection_disconnected - ConnectionStatusLabel.WAITING -> R.string.connection_waiting -} - -/** Resource keys for HarmonyOS' conversation status-strip title and detail. */ -internal data class ChatStatusBarCopy( - @StringRes val title: Int, - @StringRes val detail: Int, -) - -internal fun ConnectionPhase.chatStatusBarCopy(canStop: Boolean): ChatStatusBarCopy { - val title = when { - canStop -> R.string.chat_status_executing - this == ConnectionPhase.FAILED -> R.string.connection_error - this == ConnectionPhase.RECONNECTING -> R.string.chat_status_restoring_connection - else -> R.string.chat_status_messages_synced - } - val detail = when { - canStop -> title - this == ConnectionPhase.RECONNECTING -> R.string.connection_reconnecting_desktop - this == ConnectionPhase.FAILED -> R.string.connection_unavailable_reconnect - this == ConnectionPhase.DISCONNECTED -> R.string.connection_desktop_disconnected - else -> labelRes() - } - return ChatStatusBarCopy(title, detail) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionSheetChrome.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionSheetChrome.kt deleted file mode 100644 index 3369e22fb0..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/common/ConnectionSheetChrome.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.openbitfun.mobile.app.ui.common - -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.* -import androidx.compose.runtime.Composable -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry - -@Composable -internal fun ConnectionSheetHeader(onClose: () -> Unit) = ConnectionSheetHeader(onClose, false) - -@Composable -internal fun ConnectionSheetHeader(onClose: () -> Unit, uniformGlyph: Boolean) { - Box(Modifier.fillMaxWidth().height(MobileDesignGeometry.SheetHeaderHeight).padding(end = 8.dp)) { - IconButton(onClick = onClose, modifier = Modifier.align(Alignment.CenterEnd) - .size(MobileDesignGeometry.ControlTouchSize)) { - if (uniformGlyph) { - val ink = MaterialTheme.colorScheme.onSurface - val closeLabel = stringResource(R.string.common_close) - androidx.compose.foundation.Canvas(Modifier.size(18.dp).semantics { contentDescription = closeLabel }) { - drawLine(ink, androidx.compose.ui.geometry.Offset(2.dp.toPx(), 2.dp.toPx()), - androidx.compose.ui.geometry.Offset(16.dp.toPx(), 16.dp.toPx()), 1.5.dp.toPx(), androidx.compose.ui.graphics.StrokeCap.Round) - drawLine(ink, androidx.compose.ui.geometry.Offset(16.dp.toPx(), 2.dp.toPx()), - androidx.compose.ui.geometry.Offset(2.dp.toPx(), 16.dp.toPx()), 1.5.dp.toPx(), androidx.compose.ui.graphics.StrokeCap.Round) - } - } else Icon(painterResource(R.drawable.ic_symbol_xmark), stringResource(R.string.common_close), - modifier = Modifier.size(18.dp)) - } - } -} - -@Composable -internal fun ConnectionSheetFooter(label: String, primary: Boolean = false, enabled: Boolean = true, - modifier: Modifier = Modifier, elevated: Boolean = true, onClick: () -> Unit) { - Box(modifier.fillMaxWidth().padding(start = MobileDesignGeometry.SheetHorizontalPadding, - end = MobileDesignGeometry.SheetHorizontalPadding, top = 10.dp, bottom = 24.dp), - contentAlignment = Alignment.Center) { - Button(onClick = onClick, enabled = enabled, - modifier = Modifier.widthIn(max = 520.dp).fillMaxWidth().height(MobileDesignGeometry.SheetActionHeight), - shape = RoundedCornerShape(24.dp), - border = if (primary) null else BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - colors = ButtonDefaults.buttonColors( - containerColor = if (primary) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface, - contentColor = if (primary) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface), - elevation = ButtonDefaults.buttonElevation(defaultElevation = if (elevated) 3.dp else 0.dp)) { - Text(label, style = MaterialTheme.typography.labelLarge.connectionSheetTextStyle()) - } - } -} - -// These sheet roles reserve their full contract line box, including for CJK fallback fonts. -internal fun androidx.compose.ui.text.TextStyle.connectionSheetTextStyle() = copy( - platformStyle = androidx.compose.ui.text.PlatformTextStyle(includeFontPadding = false), - lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle( - alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center, - trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both, - mode = androidx.compose.ui.text.style.LineHeightStyle.Mode.Tight, - ), -) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/miniapps/MiniApps.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/miniapps/MiniApps.kt deleted file mode 100644 index 4f2d7cc36e..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/miniapps/MiniApps.kt +++ /dev/null @@ -1,255 +0,0 @@ -package com.openbitfun.mobile.app.ui.miniapps - -import android.annotation.SuppressLint -import android.content.ClipData -import android.content.ClipboardManager -import android.content.Context -import android.webkit.JavascriptInterface -import android.webkit.WebResourceRequest -import android.webkit.WebResourceResponse -import android.webkit.WebView -import android.webkit.WebViewClient -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.Image -import androidx.compose.foundation.clickable -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.lazy.grid.GridCells -import androidx.compose.foundation.lazy.grid.LazyVerticalGrid -import androidx.compose.foundation.lazy.grid.items -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.ui.Alignment -import androidx.compose.ui.draw.clip -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow - -import androidx.compose.material3.* -import androidx.compose.runtime.* -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalView -import androidx.compose.ui.graphics.luminance -import androidx.compose.ui.window.DialogWindowProvider -import androidx.core.view.WindowCompat -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import androidx.compose.ui.viewinterop.AndroidView -import androidx.compose.ui.window.Dialog -import androidx.compose.ui.window.DialogProperties -import com.openbitfun.mobile.app.R -import org.json.JSONObject -import java.io.ByteArrayInputStream - -/** Local, bundled tools remain available without an account or a connected host. */ -@Composable -internal fun MiniAppsButton( - sidebar: Boolean = false, - contentColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.primary, -) { - var open by rememberSaveable { mutableStateOf(false) } - if (sidebar) { - Row(Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp).heightIn(min = 48.dp) - .clip(RoundedCornerShape(12.dp)).clickable { open = true } - .padding(start = 4.dp, end = 8.dp).testTag("sidebar-miniapps"), - horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically) { - Icon(painterResource(R.drawable.ic_symbol_square_grid_2x2), contentDescription = null, modifier = Modifier.size(24.dp)) - Text(stringResource(R.string.miniapps_title), style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium) - } - } else TextButton( - onClick = { open = true }, - modifier = Modifier.fillMaxWidth().height(44.dp), - contentPadding = PaddingValues(0.dp), - colors = ButtonDefaults.textButtonColors(contentColor = contentColor), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.Center, - verticalAlignment = Alignment.CenterVertically, - ) { - Text(stringResource(R.string.miniapps_title)) - Icon( - painter = painterResource(R.drawable.ic_symbol_chevron_right), - contentDescription = null, - modifier = Modifier.padding(start = 5.dp).size(16.dp), - ) - } - } - if (open) MiniAppsDialog { open = false } -} - -@Composable -private fun MiniAppsDialog(onClose: () -> Unit) { - val context = LocalContext.current - val locale = if (LocalConfiguration.current.locales[0].language == "zh") "zh-CN" else "en-US" - var selected by rememberSaveable { mutableStateOf(null) } - var retry by remember { mutableIntStateOf(0) } - val catalog = remember(retry) { - runCatching { - val array = org.json.JSONArray(context.assets.open("miniapps/catalog.json").bufferedReader().use { it.readText() }) - (0 until array.length()).map(array::getJSONObject) - } - } - Dialog(onDismissRequest = { if (selected != null) selected = null else onClose() }, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { - val window = (LocalView.current.parent as? DialogWindowProvider)?.window - val lightBackground = MaterialTheme.colorScheme.surface.luminance() > 0.5f - SideEffect { - window?.let { - WindowCompat.getInsetsController(it, it.decorView).apply { - isAppearanceLightStatusBars = lightBackground - isAppearanceLightNavigationBars = lightBackground - } - } - } - Surface(Modifier.fillMaxSize()) { - Column(Modifier.fillMaxSize().systemBarsPadding()) { - val selectedCopy = catalog.getOrNull()?.firstOrNull { it.getString("id") == selected } - ?.getJSONObject("locales")?.optJSONObject(locale) - Row(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = { if (selected != null) selected = null else onClose() }, modifier = Modifier.size(48.dp)) { - Icon(painterResource(R.drawable.ic_symbol_chevron_left), stringResource(R.string.miniapps_back)) - } - Text(selectedCopy?.getString("name") ?: stringResource(R.string.miniapps_title), - modifier = Modifier.weight(1f), textAlign = TextAlign.Center, - style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, - maxLines = 1, overflow = TextOverflow.Ellipsis) - Spacer(Modifier.width(48.dp)) - } - if (selected == null) { - BoxWithConstraints(Modifier.fillMaxWidth().weight(1f), contentAlignment = Alignment.TopCenter) { - val columns = if (maxWidth >= 600.dp) 3 else 2 - Column(Modifier.widthIn(max = 1000.dp).fillMaxWidth().padding(horizontal = 16.dp)) { - Row(Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 20.dp), verticalAlignment = Alignment.CenterVertically) { - Text(stringResource(R.string.miniapps_all), modifier = Modifier - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(24.dp)) - .padding(horizontal = 16.dp, vertical = 10.dp), style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.weight(1f)) - Text(stringResource(R.string.miniapps_offline), style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } - if (catalog.isFailure) { - Text(stringResource(R.string.miniapps_load_failed)) - TextButton(onClick = { retry++ }) { Text(stringResource(R.string.account_devices_retry)) } - } else LazyVerticalGrid(columns = GridCells.Fixed(columns), - horizontalArrangement = Arrangement.spacedBy(14.dp), verticalArrangement = Arrangement.spacedBy(20.dp), - contentPadding = PaddingValues(bottom = 24.dp), modifier = Modifier.testTag("miniapps-gallery")) { - items(catalog.getOrDefault(emptyList()), key = { it.getString("id") }) { app -> - val id = app.getString("id") - val copy = app.getJSONObject("locales").optJSONObject(locale) - ?: app.getJSONObject("locales").getJSONObject("en-US") - Column(Modifier.fillMaxWidth().clickable { selected = id }.testTag("miniapp:$id"), - verticalArrangement = Arrangement.spacedBy(10.dp)) { - val preview = when (id) { - "builtin-gomoku" -> R.drawable.miniapp_gomoku_preview - "builtin-regex-playground" -> R.drawable.miniapp_regex_preview - else -> R.drawable.miniapp_divination_preview - } - Image(painterResource(preview), contentDescription = copy.getString("description"), - contentScale = ContentScale.Crop, modifier = Modifier.fillMaxWidth().aspectRatio(1f) - .clip(RoundedCornerShape(24.dp)) - .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(24.dp))) - Text(copy.getString("name"), style = MaterialTheme.typography.titleSmall, - maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 4.dp)) - } - } - } - } - } - } else { - key(selected, locale) { MiniAppWebView(selected!!, locale, Modifier.weight(1f)) } - } - } - } - } -} - -@SuppressLint("SetJavaScriptEnabled") -@Composable -private fun MiniAppWebView(appId: String, locale: String, modifier: Modifier) { - AndroidView(modifier = modifier.fillMaxWidth(), factory = { context -> - WebView(context).apply { - // A wrap-content WebView gives a percentage-height iframe a zero-height viewport. - layoutParams = android.view.ViewGroup.LayoutParams( - android.view.ViewGroup.LayoutParams.MATCH_PARENT, - android.view.ViewGroup.LayoutParams.MATCH_PARENT, - ) - settings.javaScriptEnabled = true - settings.allowFileAccess = false - settings.allowContentAccess = false - settings.setSupportMultipleWindows(false) - webViewClient = object : WebViewClient() { - override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { - return request.url.scheme !in setOf("blob", "about") - } - override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? { - // Blob frames contain only bundled bytes. No app can request a network resource. - if (request.url.scheme == "blob" || request.url.scheme == "data") return null - return WebResourceResponse("text/plain", "UTF-8", ByteArrayInputStream(ByteArray(0))) - } - } - addJavascriptInterface(BuiltinMiniAppBridge(context, appId) { reply -> - post { evaluateJavascript("window.__miniappReply($reply)", null) } - }, "miniappNative") - val html = context.assets.open("miniapps/$appId.$locale.html").bufferedReader().use { it.readText() } - loadDataWithBaseURL("https://miniapp.local/", html, "text/html", "UTF-8", null) - } - }, onRelease = { view -> - view.removeJavascriptInterface("miniappNative") - view.stopLoading() - view.destroy() - }) -} - -/** Per-app key allowlist; unparseable persisted JSON is retained and reported, never reset. */ -internal class BuiltinMiniAppBridge(private val context: Context, private val appId: String, private val reply: (String) -> Unit) { - @JavascriptInterface - @Synchronized - fun request(raw: String) { - val request = runCatching { JSONObject(raw) }.getOrNull() ?: return - val id = request.optString("id") - if (id.isEmpty()) return - val response = JSONObject().put("id", id) - try { - val params = request.getJSONObject("params") - val method = request.getString("method") - val key = params.optString("key") - val allowedKey = when (appId) { - "builtin-gomoku" -> "stats" - "builtin-regex-playground" -> "regex-state" - "builtin-daily-divination" -> "lastReading" - else -> error("Unsupported MiniApp") - } - val result = when (method) { - "clipboard.writeText" -> { - val text = params.getString("text") - android.os.Handler(context.mainLooper).post { - (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText("", text)) - } - JSONObject.NULL - } - "storage.get", "storage.set" -> { - require(key == allowedKey) { "Unsupported storage key" } - val store = context.getSharedPreferences("miniapps-$appId", Context.MODE_PRIVATE) - if (method == "storage.get") { - store.getString(key, null)?.let { JSONObject(it).get("value") } ?: JSONObject.NULL - } else { - val encoded = JSONObject().put("value", params.opt("value") ?: JSONObject.NULL).toString() - // Store an envelope so scalar/null values retain valid JSON too. - check(store.edit().putString(key, encoded).commit()) { "Unable to save MiniApp data" } - JSONObject.NULL - } - } - else -> error("Unsupported capability") - } - response.put("result", result) - } catch (error: Exception) { - response.put("error", JSONObject().put("message", error.message ?: "MiniApp operation failed")) - } - reply(response.toString()) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt deleted file mode 100644 index 3dd686f8d8..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.openbitfun.mobile.app.ui.preview - -import androidx.compose.foundation.layout.* -import androidx.compose.material3.* -import androidx.compose.runtime.* -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.ui.chat.MessageQueuePanel -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.session.* - -/** Isolated native review surface. The production panel uses simulated host replies. */ -@Composable -internal fun MessageQueuePreview() { - var dark by remember { mutableStateOf(true) } - var narrow by remember { mutableStateOf(true) } - var revision by remember { mutableIntStateOf(1) } - var items by remember { mutableStateOf(listOf( - QueuedMessageUiState("first", "Review the queue layout", 1, "queued", null), - QueuedMessageUiState("second", "Check long messages and attachment spacing", 2, "queued", null), - QueuedMessageUiState("third", "Run the focused tests", 0, "queued", null), - )) } - OpenBitFunTheme(dark = dark) { - Surface(Modifier.fillMaxSize()) { - Column(Modifier.fillMaxSize().safeDrawingPadding(), verticalArrangement = Arrangement.Center) { - Row(Modifier.padding(horizontal = 12.dp)) { - TextButton(onClick = { dark = !dark }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant)) { Text("Light / Dark") } - TextButton(onClick = { narrow = !narrow }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant)) { Text("Resize") } - } - Text("Queue · Native component preview", Modifier.padding(20.dp), style = MaterialTheme.typography.titleMedium) - Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { - Box(if (narrow) Modifier.width(320.dp) else Modifier.fillMaxWidth()) { - MessageQueuePanel(MessageQueueUiState("preview", true, true, "preview:$revision", items, false, null)) { intent -> - when (intent) { - is RemoteSessionIntent.MoveQueuedMessage -> { - val item = items.firstOrNull { it.id == intent.id } - if (item != null) { - val next = items.filterNot { it.id == intent.id }.toMutableList() - next.add(intent.beforeId?.let { id -> next.indexOfFirst { it.id == id } }?.coerceAtLeast(0) ?: next.size, item) - items = next; revision++ - } - } - is RemoteSessionIntent.CancelQueuedMessage -> { items = items.filterNot { it.id == intent.id }; revision++ } - is RemoteSessionIntent.PromoteQueuedMessage -> { items = items.filterNot { it.id == intent.id }; revision++ } - else -> Unit - } - } - } - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobileDesignGallery.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobileDesignGallery.kt deleted file mode 100644 index fd66d1731f..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobileDesignGallery.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.openbitfun.mobile.app.ui.preview - -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.statusBarsPadding -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.ui.chat.ComposerBar -import com.openbitfun.mobile.app.ui.chat.ConversationHeader -import com.openbitfun.mobile.app.ui.preview.generated.MobilePreviewMessage -import com.openbitfun.mobile.app.ui.preview.generated.MobilePreviewScenario -import com.openbitfun.mobile.app.ui.preview.generated.MobilePreviewScenarios -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ModelOption - -/** - * Stable preview semantics: the gallery root, platform label, and message timeline - * are tagged so visual-parity instrumentation can locate each region. - */ -internal const val MOBILE_DESIGN_GALLERY_TEST_TAG: String = "mobile-design-gallery" -internal const val MOBILE_DESIGN_GALLERY_PLATFORM_TEST_TAG: String = "mobile-design-gallery-platform" -internal const val MOBILE_DESIGN_GALLERY_TIMELINE_TEST_TAG: String = "mobile-design-gallery-timeline" - -@Composable -internal fun MobileDesignGallery(scenario: MobilePreviewScenario, dark: Boolean) { - OpenBitFunTheme(dark = dark) { - Column( - modifier = Modifier - .fillMaxSize() - .statusBarsPadding() - .navigationBarsPadding() - .background(MaterialTheme.colorScheme.background) - .testTag(MOBILE_DESIGN_GALLERY_TEST_TAG), - ) { - PlatformLabel(scenario) - ConversationHeader( - title = scenario.headerTitle, - contextTitle = scenario.headerSubtitle, - canStop = scenario.streaming, - enabled = true, - onBack = {}, - onOpenSidebar = {}, - onRename = {}, - onStop = {}, - modifier = Modifier.background(MaterialTheme.colorScheme.background), - ) - Column( - verticalArrangement = Arrangement.spacedBy(MobileDesignGeometry.MessageSpacing), - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .testTag(MOBILE_DESIGN_GALLERY_TIMELINE_TEST_TAG) - .padding( - horizontal = MobileDesignGeometry.ContentGutter, - vertical = MobileDesignGeometry.TimelineTopPadding, - ), - ) { - scenario.messages.forEach { message -> PreviewMessageBubble(message) } - } - ComposerBar( - draft = scenario.composerDraft, - images = emptyList(), - busy = false, - streaming = scenario.streaming, - phase = if (scenario.connectionPhase == "reconnecting") { - ConnectionPhase.RECONNECTING - } else { - ConnectionPhase.CONNECTED - }, - model = null, - modelOptions = emptyList(), - capabilities = ChatComposerCapabilities.RemoteChat, - placeholder = scenario.composerPlaceholder, - onDraftChange = {}, - onRemoveImage = {}, - onAttach = {}, - onVoice = {}, - onSend = {}, - onStop = {}, - onOpenModels = {}, - modifier = Modifier, - ) - } - } -} - -internal fun mobileDesignScenario(id: String?): MobilePreviewScenario = when (id) { - MobilePreviewScenarios.StreamingDark.id -> MobilePreviewScenarios.StreamingDark - MobilePreviewScenarios.NarrowMultiline.id -> MobilePreviewScenarios.NarrowMultiline - MobilePreviewScenarios.FoldContext.id -> MobilePreviewScenarios.FoldContext - MobilePreviewScenarios.LongReading.id -> MobilePreviewScenarios.LongReading - MobilePreviewScenarios.ReconnectingWide.id -> MobilePreviewScenarios.ReconnectingWide - else -> MobilePreviewScenarios.ConnectedConversation -} - -@Composable -private fun PlatformLabel(scenario: MobilePreviewScenario) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.ConnectionStripHeight) - .border(1.dp, MaterialTheme.colorScheme.outlineVariant) - .padding(horizontal = MobileDesignGeometry.ContentGutter) - .testTag(MOBILE_DESIGN_GALLERY_PLATFORM_TEST_TAG), - ) { - Text("Android", style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface) - Text( - "NATIVE", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(10.dp)) - .padding(horizontal = 8.dp, vertical = 4.dp), - ) - Spacer(Modifier.weight(1f)) - Text( - "${scenario.viewportWidth} × ${scenario.viewportHeight}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -@Composable -private fun PreviewMessageBubble(message: MobilePreviewMessage) { - if (message.role == "user") { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { - com.openbitfun.mobile.app.ui.chat.message.ChatUserMessageBubble(message.text, emptyList(), Modifier) - } - } else { - Text(message.text, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.fillMaxWidth()) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobilePreviewStates.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobilePreviewStates.kt deleted file mode 100644 index 5d89d0f8be..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MobilePreviewStates.kt +++ /dev/null @@ -1,189 +0,0 @@ -package com.openbitfun.mobile.app.ui.preview - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.unit.dp -import androidx.compose.ui.tooling.preview.Preview -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.ComposerBar -import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface -import com.openbitfun.mobile.app.ui.common.CircleControl -import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementPolicy -import com.openbitfun.mobile.core.feature.layout.SettingsSheetKind -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.ComposerImage -import com.openbitfun.mobile.core.feature.session.ModelOption - -internal const val MOBILE_PREVIEW_COMPOSER_FOCUSED_TEST_TAG: String = "mobile-preview-composer-focused" -internal const val MOBILE_PREVIEW_COMPOSER_ATTACHMENTS_TEST_TAG: String = "mobile-preview-composer-attachments" -internal const val MOBILE_PREVIEW_MODAL_BUSY_TEST_TAG: String = "mobile-preview-modal-busy" -internal const val MOBILE_PREVIEW_MODAL_ERROR_TEST_TAG: String = "mobile-preview-modal-error" -internal const val MOBILE_PREVIEW_MODAL_ERROR_TEXT_TEST_TAG: String = "mobile-preview-modal-error-text" -internal const val MOBILE_PREVIEW_MODAL_ERROR_ACTION_TEST_TAG: String = "mobile-preview-modal-error-action" -internal const val MOBILE_PREVIEW_CIRCLE_STATES_TEST_TAG: String = "mobile-preview-circle-states" -internal const val MOBILE_PREVIEW_CIRCLE_SIDEBAR_TEST_TAG: String = "mobile-preview-circle-sidebar" -internal const val MOBILE_PREVIEW_CIRCLE_MORE_TEST_TAG: String = "mobile-preview-circle-more" -internal const val MOBILE_PREVIEW_CIRCLE_BACK_TEST_TAG: String = "mobile-preview-circle-back" - -private val PreviewModel = ModelOption("preview-model", "Preview model", "Native model", true) - -@Composable -private fun previewComposer( - draft: String, - images: List, - modifier: Modifier, -) { - ComposerBar( - draft = draft, - images = images, - busy = false, - streaming = false, - phase = ConnectionPhase.CONNECTED, - model = PreviewModel, - capabilities = ChatComposerCapabilities.GeneralChat, - placeholder = "Type a message", - onDraftChange = {}, - onRemoveImage = {}, - onAttach = {}, - onVoice = {}, - onSend = {}, - onStop = {}, - onOpenModels = {}, - modifier = modifier, - ) -} - -@Preview(name = "OpenBitFun Mobile · Composer Focused", showBackground = true) -@Composable -internal fun MobilePreviewComposerFocused(dark: Boolean = false) { - OpenBitFunTheme(dark = dark) { - Column( - modifier = Modifier.fillMaxSize().testTag(MOBILE_PREVIEW_COMPOSER_FOCUSED_TEST_TAG), - ) { - previewComposer( - draft = "Review the current message", - images = emptyList(), - modifier = Modifier.fillMaxWidth(), - ) - } - } -} - -@Preview(name = "OpenBitFun Mobile · Composer Attachments", showBackground = true) -@Composable -internal fun MobilePreviewComposerAttachments(dark: Boolean = false) { - OpenBitFunTheme(dark = dark) { - Column( - modifier = Modifier.fillMaxSize().testTag(MOBILE_PREVIEW_COMPOSER_ATTACHMENTS_TEST_TAG), - ) { - previewComposer( - draft = "", - images = listOf(ComposerImage(id = "preview-1", dataUrl = "", mimeType = "")), - modifier = Modifier.fillMaxWidth(), - ) - } - } -} - -@Preview(name = "OpenBitFun Mobile · Modal Busy", showBackground = true) -@Composable -internal fun MobilePreviewModalBusy(dark: Boolean = false) { - OpenBitFunTheme(dark = dark) { - AdaptiveModalSurface( - visible = true, - placement = SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SETTINGS), - onDismissRequest = {}, - ) { surfaceModifier -> - Column( - modifier = surfaceModifier - .padding(24.dp) - .testTag(MOBILE_PREVIEW_MODAL_BUSY_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text("Working…", style = MaterialTheme.typography.titleMedium) - Text("Please wait while the request finishes.") - } - } - } -} - -@Preview(name = "OpenBitFun Mobile · Modal Error", showBackground = true) -@Composable -internal fun MobilePreviewModalError(dark: Boolean = false) { - OpenBitFunTheme(dark = dark) { - AdaptiveModalSurface( - visible = true, - placement = SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SETTINGS), - onDismissRequest = {}, - ) { surfaceModifier -> - Column( - modifier = surfaceModifier - .padding(24.dp) - .testTag(MOBILE_PREVIEW_MODAL_ERROR_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - "Connection failed", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.testTag(MOBILE_PREVIEW_MODAL_ERROR_TEXT_TEST_TAG), - ) - Text("Try again when the connection is available.") - TextButton( - onClick = {}, - modifier = Modifier.testTag(MOBILE_PREVIEW_MODAL_ERROR_ACTION_TEST_TAG), - ) { - Text("Try again") - } - } - } - } -} - -@Preview(name = "OpenBitFun Mobile · Circle States", showBackground = true) -@Composable -internal fun MobilePreviewCircleStates(dark: Boolean = false) { - OpenBitFunTheme(dark = dark) { - Row( - modifier = Modifier - .fillMaxSize() - .padding(24.dp) - .testTag(MOBILE_PREVIEW_CIRCLE_STATES_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - CircleControl( - icon = R.drawable.ic_symbol_menu_lines, - glyphSize = 22, - contentDescription = "Open sidebar", - onClick = {}, - modifier = Modifier.testTag(MOBILE_PREVIEW_CIRCLE_SIDEBAR_TEST_TAG), - ) - CircleControl( - icon = R.drawable.ic_symbol_ellipsis, - glyphSize = 22, - contentDescription = "More actions", - onClick = {}, - modifier = Modifier.testTag(MOBILE_PREVIEW_CIRCLE_MORE_TEST_TAG), - ) - CircleControl( - icon = R.drawable.ic_symbol_chevron_left, - glyphSize = 22, - contentDescription = "Back", - onClick = {}, - modifier = Modifier.testTag(MOBILE_PREVIEW_CIRCLE_BACK_TEST_TAG), - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/generated/MobilePreviewScenarios.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/generated/MobilePreviewScenarios.kt deleted file mode 100644 index 06a79e4a1e..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/generated/MobilePreviewScenarios.kt +++ /dev/null @@ -1,118 +0,0 @@ -// Generated by scripts/mobile-ui-design-system.mjs. Do not edit. -package com.openbitfun.mobile.app.ui.preview.generated - -internal data class MobilePreviewMessage(val role: String, val text: String) - -internal data class MobilePreviewScenario( - val id: String, - val title: String, - val description: String, - val appearance: String, - val viewportWidth: Int, - val viewportHeight: Int, - val headerTitle: String, - val headerSubtitle: String, - val messages: List, - val composerDraft: String, - val composerPlaceholder: String, - val connectionPhase: String, - val streaming: Boolean, -) - -internal object MobilePreviewScenarios { - val ConnectedConversation = MobilePreviewScenario( - id = "connected-conversation", - title = "Connected conversation", - description = "A remote desktop is answering and the composer is ready.", - appearance = "light", - viewportWidth = 390, - viewportHeight = 844, - headerTitle = "统一移动端设计系统", - headerSubtitle = "DESKTOP-KM3L4UI", - messages = listOf(MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), MobilePreviewMessage("assistant", "可以。共享视觉契约,三端继续使用原生渲染。")), - composerDraft = "", - composerPlaceholder = "向 OpenBitFun 提问", - connectionPhase = "connected", - streaming = false, - ) - - val StreamingDark = MobilePreviewScenario( - id = "streaming-dark", - title = "Streaming in dark mode", - description = "An active turn exercises dark surfaces and the stop action.", - appearance = "dark", - viewportWidth = 390, - viewportHeight = 844, - headerTitle = "跨端视觉校验", - headerSubtitle = "正在由 MacBook Pro 运行", - messages = listOf(MobilePreviewMessage("user", "比较三端的输入框、消息气泡和标题栏。"), MobilePreviewMessage("assistant", "正在生成原生截图,并按相同基线并排展示。")), - composerDraft = "检查深色模式下的边框对比度", - composerPlaceholder = "输入消息", - connectionPhase = "connected", - streaming = true, - ) - - val ReconnectingWide = MobilePreviewScenario( - id = "reconnecting-wide", - title = "Reconnecting on a wide viewport", - description = "A tablet-sized viewport keeps remote blocking states answerable.", - appearance = "light", - viewportWidth = 1024, - viewportHeight = 768, - headerTitle = "远程会话", - headerSubtitle = "正在恢复连接", - messages = listOf(MobilePreviewMessage("assistant", "连接暂时中断。恢复后会从上次游标继续。")), - composerDraft = "", - composerPlaceholder = "等待重新连接", - connectionPhase = "reconnecting", - streaming = false, - ) - - val NarrowMultiline = MobilePreviewScenario( - id = "narrow-multiline", - title = "Narrow phone with a multiline draft", - description = "Narrow phone with a multiline draft", - appearance = "light", - viewportWidth = 360, - viewportHeight = 800, - headerTitle = "检查移动端长标题、正文与控制目标的可读性", - headerSubtitle = "远程开发工作站 · OpenBitFun / feature/mobile-reading", - messages = listOf(MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), MobilePreviewMessage("assistant", "可以。共享视觉契约,三端继续使用原生渲染。")), - composerDraft = "请检查输入框是否能保留多行中文草稿。\n模型选择后内容应继续保留。\n附件与文本应各自成行。", - composerPlaceholder = "向 OpenBitFun 提问", - connectionPhase = "connected", - streaming = false, - ) - - val FoldContext = MobilePreviewScenario( - id = "fold-context", - title = "Foldable with long remote context", - description = "Foldable with long remote context", - appearance = "light", - viewportWidth = 700, - viewportHeight = 840, - headerTitle = "检查移动端长标题、正文与控制目标的可读性", - headerSubtitle = "远程开发工作站 · OpenBitFun / feature/mobile-reading", - messages = listOf(MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), MobilePreviewMessage("assistant", "可以。共享视觉契约,三端继续使用原生渲染。")), - composerDraft = "请保留当前会话与控制目标。", - composerPlaceholder = "向 OpenBitFun 提问", - connectionPhase = "connected", - streaming = false, - ) - - val LongReading = MobilePreviewScenario( - id = "long-reading", - title = "Long reading content", - description = "Long reading content", - appearance = "light", - viewportWidth = 430, - viewportHeight = 932, - headerTitle = "检查移动端长标题、正文与控制目标的可读性", - headerSubtitle = "远程开发工作站 · OpenBitFun / feature/mobile-reading", - messages = listOf(MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), MobilePreviewMessage("assistant", "移动端的阅读层级需要清晰,正文应该舒适地换行,辅助说明保留足够对比度。\n\n当内容变长时,消息区滚动,输入框仍然可以操作。请在系统大字体设置下检查这一场景。")), - composerDraft = "", - composerPlaceholder = "向 OpenBitFun 提问", - connectionPhase = "connected", - streaming = false, - ) -} 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 deleted file mode 100644 index d6e8a979fe..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/ConnectAccountDeviceScreen.kt +++ /dev/null @@ -1,254 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.account.messageRes -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.account.AccountUiState - -internal const val CONNECT_ACCOUNT_DEVICE_TEST_TAG: String = "connect-account-device" -internal const val CONNECT_ACCOUNT_DEVICE_REFRESH_TEST_TAG: String = "connect-account-device-refresh" -internal const val CONNECT_ACCOUNT_DEVICE_ROW_TEST_TAG_PREFIX: String = "connect-account-device-row:" - -/** - * Signed-in landing page for remote control, matching HarmonyOS' - * `ConnectAccountDevicePage`. - * - * A signed-in phone should not fall through to anonymous pairing just because - * no desktop happened to be online when its session was restored. The last - * device snapshot remains useful and refresh is explicit; the account is the - * only way to reach a desktop. - */ -@Composable -internal fun ConnectAccountDeviceScreen( - state: AccountUiState.Ready, - onBack: () -> Unit, - onRefresh: () -> Unit, - onSelect: (String) -> Unit, - modifier: Modifier, -) { - Column( - modifier = modifier - .fillMaxSize() - .testTag(CONNECT_ACCOUNT_DEVICE_TEST_TAG), - ) { - Row( - modifier = Modifier.fillMaxWidth().height(92.dp).padding(start = 28.dp, end = 28.dp, top = 18.dp), - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalAlignment = Alignment.Top, - ) { - Surface( - onClick = onBack, - shape = CircleShape, - color = MaterialTheme.colorScheme.surfaceVariant, - modifier = Modifier.size(48.dp), - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - painterResource(R.drawable.ic_symbol_chevron_left), - contentDescription = stringResource(R.string.common_back), - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(23.dp), - ) - } - } - Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.weight(1f)) { - Text( - stringResource(R.string.connect_account_devices_title), - fontSize = 22.sp, - lineHeight = 28.sp, - fontWeight = FontWeight.Bold, - ) - Text( - stringResource(R.string.connect_account_devices_subtitle), - fontSize = 13.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - Column( - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .verticalScroll(rememberScrollState()) - .padding(start = 28.dp, end = 28.dp, top = 10.dp, bottom = 34.dp), - verticalArrangement = Arrangement.spacedBy(18.dp), - ) { - Text( - stringResource(R.string.connect_account_devices_body), - fontSize = 14.sp, - lineHeight = 21.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - DeviceListCard(state = state, onRefresh = onRefresh, onSelect = onSelect) - } - } -} - -@Composable -private fun DeviceListCard( - state: AccountUiState.Ready, - onRefresh: () -> Unit, - onSelect: (String) -> Unit, -) { - Surface( - shape = RoundedCornerShape(8.dp), - color = MaterialTheme.colorScheme.surface, - border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), - modifier = Modifier.fillMaxWidth(), - ) { - Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { - Row(modifier = Modifier.fillMaxWidth().height(38.dp), verticalAlignment = Alignment.CenterVertically) { - Text( - stringResource(R.string.connect_account_devices_available), - fontSize = 16.sp, - fontWeight = FontWeight.Bold, - ) - Spacer(Modifier.weight(1f)) - if (state.refreshing) { - CircularProgressIndicator( - strokeWidth = 2.dp, - modifier = Modifier.size(16.dp), - ) - } else { - Text( - stringResource( - if (state.refreshFailure == null) { - R.string.account_devices_refresh - } else { - R.string.account_devices_retry - }, - ), - fontSize = 14.sp, - color = if (state.refreshFailure == null) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.error - }, - modifier = Modifier - .clickable(onClick = onRefresh) - .padding(horizontal = 6.dp, vertical = 6.dp) - .testTag(CONNECT_ACCOUNT_DEVICE_REFRESH_TEST_TAG), - ) - } - } - state.refreshFailure?.let { failure -> - Text( - stringResource(failure.messageRes()), - fontSize = 13.sp, - lineHeight = 19.sp, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(bottom = 6.dp), - ) - } - if (state.devices.isEmpty()) { - Box( - modifier = Modifier.fillMaxWidth().height(120.dp), - contentAlignment = Alignment.CenterStart, - ) { - Text( - stringResource(R.string.account_devices_empty), - fontSize = 14.sp, - lineHeight = 20.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } else { - state.devices.forEach { device -> - val selected = device.id == state.selectedDeviceId - val reconnectable = selected && !device.online - Row( - modifier = Modifier - .fillMaxWidth() - .height(60.dp) - .clickable(enabled = device.online || reconnectable, onClick = { onSelect(device.id) }) - .alpha(if (device.online || selected) 1f else 0.64f) - .testTag(CONNECT_ACCOUNT_DEVICE_ROW_TEST_TAG_PREFIX + device.id), - horizontalArrangement = Arrangement.spacedBy(12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_desktop), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(26.dp).alpha(if (device.online || selected) 0.68f else 0.38f), - ) - Column(verticalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.weight(1f)) { - Text( - device.displayName, - fontSize = 15.sp, - fontWeight = FontWeight.Medium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - stringResource( - when { - selected && device.online -> R.string.account_device_current_control - device.online -> R.string.account_online - else -> R.string.account_offline - }, - ), - fontSize = 13.sp, - color = if (device.online) { - openBitFunColors.statusSuccess - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - ) - } - if (reconnectable) { - Surface(color = MaterialTheme.colorScheme.surfaceVariant, shape = RoundedCornerShape(14.dp)) { - Text( - stringResource(R.string.remote_settings_reconnect), - fontSize = 14.sp, - modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp), - ) - } - } else if (device.online && !selected) { - Surface(color = MaterialTheme.colorScheme.surfaceVariant, shape = RoundedCornerShape(14.dp)) { - Text( - stringResource(R.string.account_connect), - fontSize = 14.sp, - modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp), - ) - } - } - } - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt deleted file mode 100644 index 96b982e0f5..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/CreateSessionScreen.kt +++ /dev/null @@ -1,585 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.clickable -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusManager -import androidx.compose.ui.platform.LocalFocusManager -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.core.feature.session.HarnessProfilePolicy -import com.openbitfun.mobile.core.feature.session.HarnessProfile -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.ComposerBar -import com.openbitfun.mobile.app.ui.chat.rememberComposerVoiceInput -import com.openbitfun.mobile.app.ui.common.CircleControl -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.ChatComposerCapabilities -import com.openbitfun.mobile.core.feature.session.CreateSessionPresenter -import com.openbitfun.mobile.core.feature.session.ModelOption -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.createModelOptions -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState - -internal const val CREATE_SESSION_TEST_TAG: String = "create-session" -internal const val CREATE_SESSION_BACK_TEST_TAG: String = "create-session-back" -internal const val CREATE_SESSION_WORKSPACE_TEST_TAG: String = "create-session-workspace" - -internal data class CreateDeviceChoice( - val id: String, - val name: String, - val online: Boolean, - val selected: Boolean, -) - -private enum class CreateSelectionKind { DEVICE, WORKSPACE } - -/** - * [CreateSessionScreen] plus the one thing it cannot decide for itself: when the - * session it asked for exists. - * - * The store answers a successful create by selecting the new session, so the - * signal is that the selection changed from whatever it was when this screen - * opened. Both hosts route on it identically, which is why it lives here rather - * than twice in the screens that mount this. - */ -@Composable -internal fun CreateSessionRoute( - sessionState: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - phase: ConnectionPhase, - deviceId: String, - devices: List, - compact: Boolean, - onDevicePick: (String) -> Unit, - onBack: () -> Unit, - onCreated: (String) -> Unit, - onWorkspaceIntent: (RemoteWorkspaceIntent) -> Unit, - onIntent: (RemoteSessionIntent) -> Unit, - modifier: Modifier, -) { - val ready = sessionState as? RemoteSessionUiState.Ready - val modelOptions = ready?.createModelOptions(stringResource(R.string.models_unnamed)).orEmpty() - val baseline = rememberSaveable { mutableStateOf(ready?.selectedSessionId) } - val created = ready?.selectedSessionId - LaunchedEffect(created) { - // The shared store publishes the new id only after the remote create - // has committed. Do not wait for a non-null timeline here: an empty - // session has no records, and a delayed stream must not strand the - // user on the creation surface. ConversationView owns that loading - // state once the id has been routed. - if (created != null && created != baseline.value) onCreated(created) - } - - CreateSessionScreen( - workspaceState = workspaceState, - phase = phase, - deviceId = deviceId, - devices = devices, - modelOptions = modelOptions, - compact = compact, - onDevicePick = onDevicePick, - // Anything other than a settled list means the store is mid-request or - // has nothing to create against, and either way the send would be lost. - busy = ready?.busy ?: true, - onBack = onBack, - onWorkspaceIntent = onWorkspaceIntent, - onIntent = onIntent, - modifier = modifier, - ) -} - -/** - * The new-session screen, ported from `pages/components/RemoteCreateSessionView.ets`. - * - * It is deliberately almost empty: a way back, one line saying where the work - * will happen, and the composer. The source has no title field and no agent - * picker on this route because both are inferred — the agent follows from the - * workspace ([CreateSessionPresenter.agentType]) and the title is whatever the - * agent renames the session to after reading the first message. - * - * The pencil menu on the session list stays as it is: that is a different, - * faster act — start a Code or Cowork session here in this project — and the - * source keeps both too. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun CreateSessionScreen( - workspaceState: RemoteWorkspaceUiState, - phase: ConnectionPhase, - /** The desktop this would run on. Empty means there is nothing to create on. */ - deviceId: String, - devices: List, - modelOptions: List = emptyList(), - compact: Boolean, - busy: Boolean, - onBack: () -> Unit, - onDevicePick: (String) -> Unit, - onWorkspaceIntent: (RemoteWorkspaceIntent) -> Unit, - onIntent: (RemoteSessionIntent) -> Unit, - modifier: Modifier, -) { - var draft by rememberSaveable { mutableStateOf("") } - var workspacePath by rememberSaveable { mutableStateOf("") } - var workspaceConnectionId by rememberSaveable { mutableStateOf(null) } - var workspaceSshHost by rememberSaveable { mutableStateOf(null) } - // The stable reference; the three fields above are display context once this is set. - var workspaceId by rememberSaveable { mutableStateOf(null) } - var selectedModelId by rememberSaveable { mutableStateOf(null) } - // Not saveable: an open sheet is a finger part-way through a gesture. - var pickerKind by remember { mutableStateOf(null) } - val focusManager = LocalFocusManager.current - var harnessProfile by remember { mutableStateOf(HarnessProfile.STANDARD) } - var harnessMenuOpen by remember { mutableStateOf(false) } - val ready = workspaceState as? RemoteWorkspaceUiState.Ready - LaunchedEffect(modelOptions) { - if (modelOptions.none { it.id == selectedModelId }) { - selectedModelId = modelOptions.firstOrNull { it.selected }?.id ?: modelOptions.firstOrNull()?.id - } - } - val selectedModel = modelOptions.firstOrNull { it.id == selectedModelId } - ?: modelOptions.firstOrNull { it.selected } - ?: modelOptions.firstOrNull() - val selectWorkspace: (WorkspaceChoice?) -> Unit = { workspace -> - workspacePath = workspace?.path.orEmpty() - workspaceConnectionId = workspace?.remoteConnectionId - workspaceSshHost = workspace?.remoteSshHost - workspaceId = workspace?.workspaceId - } - val selectedChoice = WorkspaceChoice(workspacePath, "", workspaceConnectionId, workspaceSshHost, workspaceId) - - val voiceInput = rememberComposerVoiceInput( - org.json.JSONArray(listOf(deviceId, workspaceConnectionId, workspacePath)).toString(), - ) { text -> - draft = listOf(draft.trim(), text.trim()).filter(String::isNotEmpty).joinToString(" ") - } - - Column(modifier = modifier.fillMaxSize().testTag(CREATE_SESSION_TEST_TAG)) { - Row( - modifier = Modifier.fillMaxWidth().height(78.dp).padding(start = 18.dp, top = 14.dp), - verticalAlignment = Alignment.Top, - ) { - CircleControl( - icon = R.drawable.ic_symbol_chevron_left, - glyphSize = 20, - contentDescription = stringResource(R.string.create_back), - onClick = onBack, - modifier = Modifier.testTag(CREATE_SESSION_BACK_TEST_TAG), - ) - } - - // The empty middle is load-bearing in the source: it is what the user - // taps to put the keyboard away without leaving the screen. - DismissFiller(focusManager = focusManager, modifier = Modifier.weight(1f)) - - if (deviceId.isEmpty()) { - Text( - stringResource(R.string.create_no_device), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.fillMaxWidth().padding(horizontal = 28.dp, vertical = 4.dp), - ) - } - - Column(modifier = Modifier.fillMaxWidth()) { - if (!compact && devices.isNotEmpty()) { - Box(modifier = Modifier.fillMaxWidth()) { - ContextRow( - glyph = R.drawable.ic_symbol_desktop, - label = devices.firstOrNull { it.selected }?.name - ?.ifBlank { deviceId } - ?: deviceId, - expanded = pickerKind == CreateSelectionKind.DEVICE, - enabled = !busy, - onClick = { - focusManager.clearFocus() - pickerKind = CreateSelectionKind.DEVICE - }, - modifier = Modifier, - ) - DropdownMenu( - expanded = pickerKind == CreateSelectionKind.DEVICE, - onDismissRequest = { pickerKind = null }, - modifier = Modifier.width(340.dp), - shape = RoundedCornerShape(16.dp), - containerColor = MaterialTheme.colorScheme.surface, - tonalElevation = 0.dp, - shadowElevation = 18.dp, - ) { - DevicePicker( - devices = devices, - onPick = { id -> - pickerKind = null - onDevicePick(id) - }, - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), - ) - } - } - } - - Box(modifier = Modifier.fillMaxWidth()) { - ContextRow( - glyph = if (workspacePath.isEmpty()) { - R.drawable.ic_symbol_message - } else { - R.drawable.ic_symbol_folder - }, - label = when { - workspaceState is RemoteWorkspaceUiState.Loading -> stringResource(R.string.sessions_loading) - workspacePath.isEmpty() -> stringResource(R.string.create_chat) - else -> ready?.workspaces?.firstOrNull { selectedChoice.refersTo(WorkspaceChoice(it.path, it.displayName, it.remoteConnectionId, it.remoteSshHost, it.workspaceId)) }?.displayName.orEmpty() - .ifEmpty { workspacePath } - }, - expanded = pickerKind == CreateSelectionKind.WORKSPACE, - enabled = !busy, - onClick = { - focusManager.clearFocus() - pickerKind = CreateSelectionKind.WORKSPACE - }, - modifier = Modifier.testTag(CREATE_SESSION_WORKSPACE_TEST_TAG), - ) - if (!compact) { - DropdownMenu( - expanded = pickerKind == CreateSelectionKind.WORKSPACE, - onDismissRequest = { pickerKind = null }, - modifier = Modifier.width(340.dp), - shape = RoundedCornerShape(16.dp), - containerColor = MaterialTheme.colorScheme.surface, - tonalElevation = 0.dp, - shadowElevation = 18.dp, - ) { - WorkspacePicker( - workspaces = ready?.workspaces.orEmpty().map { WorkspaceChoice(it.path, it.displayName, it.remoteConnectionId, it.remoteSshHost, it.workspaceId) }, - selected = selectedChoice, - showHeader = false, - onDismiss = { pickerKind = null }, - onPick = { path -> - pickerKind = null - selectWorkspace(path) - }, - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), - ) - } - } - } - } - - if (!workspacePath.isNullOrBlank() && HarnessProfilePolicy.supported(ready?.hostCapabilities.orEmpty())) { - Box { - androidx.compose.material3.TextButton(onClick = { harnessMenuOpen = true }) { HarnessProfileLabel(harnessProfile) } - androidx.compose.material3.DropdownMenu(expanded = harnessMenuOpen, onDismissRequest = { harnessMenuOpen = false }) { - HarnessProfile.entries.forEach { profile -> - androidx.compose.material3.DropdownMenuItem(text = { HarnessProfileLabel(profile) }, onClick = { - harnessProfile = profile - harnessMenuOpen = false - }) - } - } - } - } - ComposerBar( - draft = draft, - images = emptyList(), - busy = busy, - streaming = false, - // No device means the remote genuinely is not reachable, so the send - // dims itself the way it does during a dropout. The field stays - // typable on purpose: the draft is worth keeping until a desktop - // comes back, and the source blocks only the send too. - phase = if (deviceId.isEmpty()) ConnectionPhase.DISCONNECTED else phase, - // There is no session yet, so there is no per-session model to swap. - model = selectedModel, - modelOptions = modelOptions, - capabilities = ChatComposerCapabilities.RemoteCreate, - placeholder = stringResource(R.string.create_placeholder), - onDraftChange = { draft = it }, - onRemoveImage = {}, - onAttach = {}, - onOpenModels = {}, - onSelectModel = { selectedModelId = it }, - onVoice = voiceInput, - onSend = { - if (CreateSessionPresenter.canSubmit(draft, deviceId, busy)) { - onIntent( - RemoteSessionIntent.CreateSession( - agentType = if (workspacePath.isNullOrBlank()) CreateSessionPresenter.agentType(workspacePath) else HarnessProfilePolicy.creationAgent(harnessProfile, ready?.hostCapabilities.orEmpty()), - title = "", - instruction = draft, - modelId = selectedModelId, - workspacePath = workspacePath.takeIf { it.isNotBlank() }, - remoteConnectionId = workspaceConnectionId, - remoteSshHost = workspaceSshHost, - workspaceId = workspaceId?.takeIf { workspacePath.isNotBlank() }, - ), - ) - draft = "" - } - }, - onStop = {}, - modifier = Modifier, - ) - } - - if (compact && pickerKind == CreateSelectionKind.WORKSPACE) { - ModalBottomSheet(onDismissRequest = { pickerKind = null }) { - WorkspacePicker( - workspaces = ready?.workspaces.orEmpty().map { WorkspaceChoice(it.path, it.displayName, it.remoteConnectionId, it.remoteSshHost, it.workspaceId) }, - selected = selectedChoice, - showHeader = true, - onDismiss = { pickerKind = null }, - onPick = { path -> - pickerKind = null - selectWorkspace(path) - }, - modifier = Modifier.fillMaxWidth().padding(bottom = 24.dp), - ) - } - } - -} - -/** What the desktop calls the workspace it keeps its chat sessions in. */ -private const val ASSISTANT_KIND = "assistant" - -/** - * One row of the picker. - * - * The workspace domain type carries a kind and a timestamp the picker has no use - * for, and the app layer cannot see `core-domain` anyway. - */ -private data class WorkspaceChoice(val path: String, val name: String, val remoteConnectionId: String?, val remoteSshHost: String?, val workspaceId: String?) { - /** - * ID-first identity: when both rows carry a workspace ID only the IDs are - * compared; a row from a pre-ID host falls back to the legacy triple. - */ - fun refersTo(other: WorkspaceChoice): Boolean { - val ownId = workspaceId?.takeIf { it.isNotBlank() } - val otherId = other.workspaceId?.takeIf { it.isNotBlank() } - if (ownId != null && otherId != null) return ownId == otherId - return path == other.path && remoteConnectionId == other.remoteConnectionId && remoteSshHost == other.remoteSshHost - } -} - -/** - * The tap target that puts the keyboard away. - * - * No ripple and no role: it is empty space, and an indication here would read as - * a control the user had missed. - */ -@Composable -private fun DismissFiller(focusManager: FocusManager, modifier: Modifier) { - val interaction = remember { MutableInteractionSource() } - Box( - modifier = modifier - .fillMaxWidth() - .clickable( - interactionSource = interaction, - indication = null, - ) { focusManager.clearFocus() }, - ) -} - -/** - * One line saying where the session will run, as the source's `ContextRow` is: - * a glyph for the kind of place, its name, and a chevron because it opens. - */ -@Composable -private fun ContextRow( - @DrawableRes glyph: Int, - label: String, - expanded: Boolean, - enabled: Boolean, - onClick: () -> Unit, - modifier: Modifier, -) { - Row( - modifier = modifier - .fillMaxWidth() - .height(48.dp) - .clickable(enabled = enabled, onClick = onClick) - .padding(horizontal = 28.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Icon( - painterResource(glyph), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(18.dp), - ) - Text( - label, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f, fill = false), - ) - Icon( - painterResource( - if (expanded) R.drawable.ic_symbol_chevron_up - else R.drawable.ic_symbol_chevron_down, - ), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(14.dp), - ) - } -} - -@Composable -private fun DevicePicker( - devices: List, - onPick: (String) -> Unit, - modifier: Modifier, -) { - Column(modifier = modifier) { - devices.forEach { device -> - PickerRow( - title = device.name.ifBlank { device.id }, - subtitle = stringResource(if (device.online) R.string.account_online else R.string.account_offline), - selected = device.selected, - enabled = device.online || device.selected, - onClick = { onPick(device.id) }, - ) - } - } -} - -/** - * Where the session will run: chat, or one of the desktop's recent workspaces. - * - * Chat leads because it is the one option that needs no project, and because - * choosing it is how the user says "just talk to me" rather than "work here". - */ -@Composable -private fun WorkspacePicker( - workspaces: List, - selected: WorkspaceChoice, - showHeader: Boolean, - onDismiss: () -> Unit, - onPick: (WorkspaceChoice?) -> Unit, - modifier: Modifier, -) { - Column(modifier = modifier) { - if (showHeader) { - Row( - modifier = Modifier.fillMaxWidth().height(52.dp).padding(start = 18.dp, end = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.create_workspace_picker), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.weight(1f), - ) - IconButton(onClick = onDismiss, modifier = Modifier.size(44.dp)) { - Icon( - painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - } - } - PickerRow( - title = stringResource(R.string.create_chat), - subtitle = "", - selected = selected.path.isEmpty(), - onClick = { onPick(null) }, - ) - if (workspaces.isEmpty()) { - Text( - stringResource(R.string.create_no_workspaces), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp), - ) - return@Column - } - workspaces.forEach { workspace -> - PickerRow( - title = workspace.name.ifBlank { workspace.path }, - // Two projects can share a name; the path is what tells them - // apart, and it is the only place the user can check. - subtitle = workspace.path, - selected = selected.path.isNotEmpty() && selected.refersTo(workspace), - onClick = { onPick(workspace) }, - ) - } - } -} - -@Composable -private fun PickerRow( - title: String, - subtitle: String, - selected: Boolean, - enabled: Boolean = true, - onClick: () -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .alpha(if (enabled) 1f else 0.55f) - .clickable(enabled = enabled, onClick = onClick) - .padding(horizontal = 24.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Column(modifier = Modifier.weight(1f)) { - Text(title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) - if (subtitle.isNotEmpty()) { - Text( - subtitle, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - if (selected) { - Icon( - painterResource(R.drawable.ic_symbol_checkmark_circle), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(19.dp), - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DeviceToolsDialog.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DeviceToolsDialog.kt deleted file mode 100644 index d1e7df117c..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DeviceToolsDialog.kt +++ /dev/null @@ -1,87 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.layout.* -import androidx.compose.material3.* -import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset -import androidx.compose.runtime.* -import androidx.compose.runtime.saveable.rememberSaveableStateHolder -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.workspace.* - -/** Native navigation only. Location, selected panel and PTY lifetime belong to KMP. */ -@Composable -internal fun DeviceToolsDialog(state: RemoteWorkspaceUiState.Ready, onIntent: (RemoteWorkspaceIntent) -> Unit) { - val tools = state.deviceTools - var choosing by remember { mutableStateOf(false) } - val panels = rememberSaveableStateHolder() - RuntimeFullScreen(stringResource(R.string.device_tools), { onIntent(RemoteWorkspaceIntent.CloseDeviceTools) }) { - Box { - TextButton(enabled = !tools.busy && state.files.file == null, onClick = { choosing = true }, - colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface)) { - Text(state.savedConnections.firstOrNull { it.id == tools.connectionId }?.name ?: stringResource(R.string.workspace_target_device)) - } - DropdownMenu(expanded = choosing, onDismissRequest = { choosing = false }) { - DropdownMenuItem(text = { Text(stringResource(R.string.workspace_target_device)) }, onClick = { - choosing = false; onIntent(RemoteWorkspaceIntent.OpenDeviceTools()) - }) - state.savedConnections.forEach { connection -> - DropdownMenuItem(text = { Text(connection.name) }, onClick = { - choosing = false; onIntent(RemoteWorkspaceIntent.OpenDeviceTools(connectionId = connection.id)) - }) - } - } - } - TabRow( - selectedTabIndex = tools.panel.ordinal, - containerColor = MaterialTheme.colorScheme.surface, - contentColor = MaterialTheme.colorScheme.onSurface, - indicator = { positions -> - TabRowDefaults.SecondaryIndicator( - modifier = Modifier.tabIndicatorOffset(positions[tools.panel.ordinal]), - color = MaterialTheme.colorScheme.onSurface, - ) - }, - ) { - DeviceToolsPanel.entries.forEach { panel -> - Tab( - selected = panel == tools.panel, - enabled = state.files.file == null, - onClick = { onIntent(RemoteWorkspaceIntent.SelectDeviceToolsPanel(panel)) }, - selectedContentColor = MaterialTheme.colorScheme.onSurface, - unselectedContentColor = MaterialTheme.colorScheme.onSurfaceVariant, - text = { Text(stringResource(if (panel == DeviceToolsPanel.FILES) R.string.workspace_browse_files else R.string.workspace_terminal)) }, - ) - } - } - when { - tools.busy -> CircularProgressIndicator(Modifier.padding(16.dp)) - tools.failed -> TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { onIntent(RemoteWorkspaceIntent.OpenDeviceTools(connectionId = tools.connectionId)) }) { - Text(stringResource(R.string.workspace_files_failed)) - } - else -> panels.SaveableStateProvider("${tools.connectionId}:${tools.path}:${tools.panel}") { - when (tools.panel) { - DeviceToolsPanel.FILES -> RuntimeFilesContent(state, onIntent) - DeviceToolsPanel.TERMINAL -> { - val terminal = state.terminal - if (terminal.failed) Text(terminal.errorDetail ?: stringResource(R.string.workspace_terminal_failed), color = MaterialTheme.colorScheme.error) - if (terminal.busy) CircularProgressIndicator(Modifier.padding(12.dp)) - if (terminal.sessionId != null) { - Row { - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !terminal.busy, onClick = { onIntent(RemoteWorkspaceIntent.WriteTerminal("\u0003")) }) { Text(stringResource(R.string.message_stop)) } - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !terminal.busy, onClick = { onIntent(RemoteWorkspaceIntent.CloseTerminal) }) { Text(stringResource(R.string.workspace_terminal_close)) } - } - RuntimeTerminalView(terminal, { onIntent(RemoteWorkspaceIntent.WriteTerminal(it)) }, { cols, rows -> onIntent(RemoteWorkspaceIntent.ResizeTerminal(cols, rows)) }, Modifier.fillMaxWidth().weight(1f)) - } else if (!terminal.busy) { - Box(Modifier.fillMaxWidth().weight(1f), contentAlignment = androidx.compose.ui.Alignment.Center) { - OutlinedButton(colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { onIntent(RemoteWorkspaceIntent.StartDeviceToolsTerminal) }) { Text(stringResource(R.string.workspace_open_terminal)) } - } - } - } - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicy.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicy.kt deleted file mode 100644 index 12ce81e778..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicy.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -/** Preserve the host filename when Android associates its extension with another MIME type. */ -internal fun documentExportMimeType(declared: String, extensionMimeType: String?): String = - if (declared.isNotBlank() && declared.equals(extensionMimeType, ignoreCase = true)) declared - else "application/octet-stream" diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/FilePreviewSurface.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/FilePreviewSurface.kt deleted file mode 100644 index 30b518eb0a..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/FilePreviewSurface.kt +++ /dev/null @@ -1,722 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import android.graphics.BitmapFactory -import androidx.compose.foundation.Image -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.SpanStyle -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.text.withStyle -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.CodeSyntaxColors -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.workspace.CodeSyntaxHighlighter -import com.openbitfun.mobile.core.feature.workspace.CodeSyntaxTokenKind -import com.openbitfun.mobile.core.feature.workspace.FilePreviewFailureKind -import com.openbitfun.mobile.core.feature.workspace.FilePreviewFormat -import com.openbitfun.mobile.app.ui.chat.MarkdownContent -import com.openbitfun.mobile.app.ui.chat.forReference -import com.openbitfun.mobile.app.ui.chat.statusText -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteFilePreviewUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState - -internal const val FILE_PREVIEW_TEST_TAG: String = "file-preview" -internal const val FILE_PREVIEW_HEADER_TEST_TAG: String = "file-preview-header" -internal const val FILE_PREVIEW_REFRESH_TEST_TAG: String = "file-preview-refresh" -internal const val FILE_PREVIEW_DOWNLOAD_TEST_TAG: String = "file-preview-download" -internal const val FILE_PREVIEW_TRUNCATION_TEST_TAG: String = "file-preview-truncation" - -/** - * A file the agent referenced, ported from `pages/components/FilePreviewSurface.ets`. - * - * This is a pane, not a card: HarmonyOS gives the preview its own surface with a - * 68dp header carrying the file's name, its type and size, and the three things - * that can be done to it. The card this used to be had none of that, so the same - * file read as a different feature on the two platforms. - * - * The read is a peek, not an editor: text arrives already capped by the shared - * `FilePreviewPolicy`, so the truncation banner is part of the content rather - * than an error, and it says how much did arrive. Every failure names what went - * wrong and offers Retry only when retrying could work — a file outside the - * workspace will not appear on a second try, and a Retry button there is a lie. - * - * @param remoteAvailable whether the link could still answer. Refresh and - * download are dimmed rather than hidden when it cannot, because the file on - * screen is still readable and hiding the actions would suggest it is not. - */ -@Composable -internal fun FilePreviewSurface( - preview: RemoteFilePreviewUiState, - download: RemoteFileDownloadUiState, - remoteAvailable: Boolean, - onIntent: (RemoteWorkspaceIntent) -> Unit, - modifier: Modifier, -) { - if (preview is RemoteFilePreviewUiState.None) return - val remotePath = preview.remotePath() - - // Opening a different file starts it fitted again: 1:1 is a choice about - // the image being looked at, not a mode the pane stays in. - var actualSize by remember(remotePath) { mutableStateOf(false) } - - Column( - modifier = modifier - .background(MaterialTheme.colorScheme.background) - .testTag(FILE_PREVIEW_TEST_TAG), - ) { - FilePreviewHeader( - preview = preview, - remoteAvailable = remoteAvailable, - canRefresh = remoteAvailable && preview.canBeAskedAgain(), - canDownload = remoteAvailable && !download.isFetching(preview.reference(), remotePath), - actualSize = actualSize, - onToggleActualSize = { actualSize = !actualSize }, - onIntent = onIntent, - ) - DownloadStatusBand(download.forReference(preview.reference(), remotePath)) - when (preview) { - RemoteFilePreviewUiState.None -> Unit - - is RemoteFilePreviewUiState.Loading -> if (remoteAvailable) { - CenteredState(spacing = 12, gutter = 0) { - CircularProgressIndicator( - Modifier.size(28.dp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - stringResource(R.string.file_preview_loading), - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } else { - // A spinner over a dropped link is a promise nothing will keep. - CenteredState(spacing = 10, gutter = 32) { - Text( - stringResource(R.string.file_preview_failed), - fontSize = 17.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - stringResource(R.string.file_preview_offline), - fontSize = 13.sp, - textAlign = TextAlign.Center, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - is RemoteFilePreviewUiState.Text -> { - if (preview.truncated) { - // The banner sits above the text, not under it: it changes - // how the rows below are read, so it has to be read first. - Text( - stringResource( - R.string.file_preview_truncated, - FilePreviewFormat.bytes(preview.loadedBytes), - ), - fontSize = 11.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .background(MaterialTheme.colorScheme.surfaceVariant) - .bottomHairline(MaterialTheme.colorScheme.outlineVariant) - .padding(start = 14.dp, end = 14.dp, top = 7.dp, bottom = 7.dp) - .testTag(FILE_PREVIEW_TRUNCATION_TEST_TAG), - ) - } - if (preview.markdown) { - // Markdown is the one text file the reader wants rendered - // rather than read as source, so it reflows and the line - // gutter is meaningless. HarmonyOS pads it 20/16/20/28. - MarkdownContent( - text = preview.content, - onOpenLink = { reference, label -> - onIntent(RemoteWorkspaceIntent.OpenFile(reference, label, preview.sessionId())) - }, - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .verticalScroll(rememberScrollState()) - .padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 28.dp), - ) - } else { - val code = openBitFunColors.code - // Lexing is linear over the whole file, so it is not something - // to redo on every recomposition — scrolling is exactly when - // that would happen. - val source = remember(preview, code) { - highlightedSource( - content = preview.content, - fileName = preview.name.ifEmpty { preview.target.path }, - lineStart = preview.target.lineStart, - lineEnd = preview.target.lineEnd, - colors = code, - ) - } - // Source lines are not reflowed: a wrapped line number or a - // broken indent makes a diff unreadable, so it scrolls. - // The pane sits on the soft surface the whole way down, as - // HarmonyOS' TextPreview does — source is read against a - // tint, rendered Markdown against the page. - SelectionContainer { - Text( - source, - fontSize = 12.sp, - lineHeight = 19.sp, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurface, - softWrap = false, - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .background(MaterialTheme.colorScheme.surfaceVariant) - .verticalScroll(rememberScrollState()) - .horizontalScroll(rememberScrollState()) - .padding(start = 14.dp, end = 20.dp, top = 14.dp, bottom = 24.dp), - ) - } - } - } - - is RemoteFilePreviewUiState.Image -> { - val decoded by androidx.compose.runtime.produceState>( - initialValue = false to null, key1 = preview.bytes, - ) { - value = false to null - value = true to kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) { - BitmapFactory.decodeByteArray(preview.bytes, 0, preview.bytes.size) - } - } - val bitmap = decoded.second - if (!decoded.first) { - CenteredState(spacing = 12, gutter = 32) { CircularProgressIndicator() } - } else if (bitmap != null) { - Image( - bitmap = bitmap.asImageBitmap(), - contentDescription = preview.name, - contentScale = if (actualSize) ContentScale.None else ContentScale.Fit, - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .background(MaterialTheme.colorScheme.surfaceVariant) - .padding(18.dp) - .then( - if (actualSize) { - Modifier - .verticalScroll(rememberScrollState()) - .horizontalScroll(rememberScrollState()) - } else { - Modifier - } - ), - ) - } else { - // The bytes arrived but this device cannot decode them; - // that is a decode failure, not a transfer failure. - CenteredState(spacing = 12, gutter = 32) { - Text( - stringResource(R.string.file_preview_image_decode_failed), - fontSize = 13.sp, - textAlign = TextAlign.Center, - color = MaterialTheme.colorScheme.error, - ) - } - } - } - - is RemoteFilePreviewUiState.Unsupported -> CenteredState(spacing = 10, gutter = 32) { - Icon( - painterResource(R.drawable.ic_symbol_doc), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(38.dp), - ) - Text( - stringResource(R.string.file_preview_unsupported), - fontSize = 17.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - metadataDetail(preview.mimeType, preview.sizeBytes, remotePath), - fontSize = 13.sp, - textAlign = TextAlign.Center, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - InkPill( - label = stringResource(R.string.file_download), - enabled = remoteAvailable, - onClick = { onIntent(preview.downloadIntent()) }, - ) - } - - is RemoteFilePreviewUiState.Failed -> CenteredState(spacing = 12, gutter = 32) { - Text( - stringResource(R.string.file_preview_failed), - fontSize = 17.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - ) - Text( - stringResource(preview.kind.messageRes()), - fontSize = 13.sp, - lineHeight = 19.sp, - textAlign = TextAlign.Center, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 4, - overflow = TextOverflow.Ellipsis, - ) - if (preview.retryable) { - InkPill( - label = stringResource(R.string.chat_retry), - enabled = remoteAvailable, - onClick = { onIntent(preview.openIntent()) }, - ) - } - } - } - } -} - -/** - * The name, what the file is, and the three things that can be done to it. - * - * Fixed at 68dp with its own hairline: the pane below it scrolls, and a header - * that grew with a long file name would move the actions out from under the - * thumb that was already reaching for them. - */ -@Composable -private fun FilePreviewHeader( - preview: RemoteFilePreviewUiState, - remoteAvailable: Boolean, - canRefresh: Boolean, - canDownload: Boolean, - actualSize: Boolean, - onToggleActualSize: () -> Unit, - onIntent: (RemoteWorkspaceIntent) -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(68.dp) - .background(MaterialTheme.colorScheme.background) - .bottomHairline(MaterialTheme.colorScheme.outlineVariant) - .padding(8.dp) - .testTag(FILE_PREVIEW_HEADER_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - HeaderControl( - icon = R.drawable.ic_symbol_chevron_left, - glyphSize = 22, - contentDescription = stringResource(R.string.common_close), - enabled = true, - onClick = { onIntent(RemoteWorkspaceIntent.DismissPreview) }, - ) - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - Text( - preview.displayName().ifEmpty { stringResource(R.string.file_preview_title) }, - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - headerDetail(preview, remoteAvailable), - fontSize = 11.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - if (preview is RemoteFilePreviewUiState.Image) { - Box( - modifier = Modifier - .size(44.dp) - .clickable(onClick = onToggleActualSize), - contentAlignment = Alignment.Center, - ) { - Text( - "1:1", - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - color = if (actualSize) { - openBitFunColors.code.function - } else { - MaterialTheme.colorScheme.onSurface - }, - ) - } - } - HeaderControl( - icon = R.drawable.ic_symbol_arrow_clockwise, - glyphSize = 20, - contentDescription = stringResource(R.string.common_refresh), - enabled = canRefresh, - onClick = { onIntent(preview.openIntent()) }, - modifier = Modifier.testTag(FILE_PREVIEW_REFRESH_TEST_TAG), - ) - HeaderControl( - icon = R.drawable.ic_symbol_arrow_down_to_line, - glyphSize = 20, - contentDescription = stringResource(R.string.file_download), - enabled = canDownload, - onClick = { onIntent(preview.downloadIntent()) }, - modifier = Modifier.testTag(FILE_PREVIEW_DOWNLOAD_TEST_TAG), - ) - } -} - -/** A 44dp header slot. Dimmed rather than removed when the link cannot answer. */ -@Composable -private fun HeaderControl( - icon: Int, - glyphSize: Int, - contentDescription: String, - enabled: Boolean, - onClick: () -> Unit, - modifier: Modifier = Modifier, -) { - Box( - modifier = modifier - .size(44.dp) - .alpha(if (enabled) 1f else 0.45f) - .clickable(enabled = enabled, onClick = onClick), - contentAlignment = Alignment.Center, - ) { - Icon( - painterResource(icon), - contentDescription = contentDescription, - tint = if (enabled) { - MaterialTheme.colorScheme.onSurface - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - modifier = Modifier.size(glyphSize.dp), - ) - } -} - -/** The 42dp filled action HarmonyOS puts under an empty state. */ -@Composable -private fun InkPill(label: String, enabled: Boolean, onClick: () -> Unit) { - Button( - onClick = onClick, - enabled = enabled, - shape = RoundedCornerShape(21.dp), - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.onSurface, - contentColor = MaterialTheme.colorScheme.surface, - disabledContainerColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.45f), - disabledContentColor = MaterialTheme.colorScheme.surface, - ), - modifier = Modifier.height(42.dp), - ) { Text(label, fontSize = 14.sp) } -} - -/** - * Every empty and failure state centres the same way. - * - * The spacing and gutter are per state rather than shared: HarmonyOS gives the - * loading state no gutter at all, and a wider gap to the states that carry a - * sentence someone has to read. - */ -@Composable -private fun ColumnScope.CenteredState( - spacing: Int, - gutter: Int, - content: @Composable ColumnScope.() -> Unit, -) { - Column( - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .padding(horizontal = gutter.dp), - verticalArrangement = Arrangement.spacedBy(spacing.dp, Alignment.CenterVertically), - horizontalAlignment = Alignment.CenterHorizontally, - content = content, - ) -} - -/** - * How a download of the open file is going, in the band under the header. - * - * Only this file's download: a transfer started from some other card belongs on - * that card, not over the thing being read. - */ -@Composable -private fun DownloadStatusBand(download: RemoteFileDownloadUiState) { - if (download is RemoteFileDownloadUiState.None) return - Text( - download.statusText(), - fontSize = 12.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - modifier = Modifier - .fillMaxWidth() - .background(MaterialTheme.colorScheme.surfaceVariant) - .bottomHairline(MaterialTheme.colorScheme.outlineVariant) - .padding(start = 14.dp, end = 14.dp, top = 8.dp, bottom = 8.dp), - ) -} - -/** - * A 1dp rule on the bottom edge, drawn inside the box. - * - * A `HorizontalDivider` underneath would add its own dp to the 68dp header; - * HarmonyOS' border is part of that height, so this one has to be too. - */ -private fun Modifier.bottomHairline(color: Color): Modifier = drawBehind { - val stroke = 1.dp.toPx() - drawRect(color = color, topLeft = Offset(0f, size.height - stroke), size = Size(size.width, stroke)) -} - -/** - * What the file is, under its name. - * - * Offline outranks everything: it explains why the actions are dimmed and why - * the content may be older than the file on the desktop. - */ -@Composable -private fun headerDetail(preview: RemoteFilePreviewUiState, remoteAvailable: Boolean): String = when { - !remoteAvailable -> stringResource(R.string.file_preview_offline) - preview is RemoteFilePreviewUiState.Loading -> stringResource(R.string.file_preview_loading) - else -> metadataDetail(preview.mimeType(), preview.sizeBytes(), preview.remotePath()) -} - -/** `text/plain · 12 KB`, falling back to whichever half is known. */ -private fun metadataDetail(mimeType: String, sizeBytes: Long, remotePath: String): String { - val size = if (sizeBytes > 0) FilePreviewFormat.bytes(sizeBytes) else "" - if (mimeType.isNotEmpty() && size.isNotEmpty()) return "$mimeType · $size" - return mimeType.ifEmpty { size.ifEmpty { remotePath } } -} - -private fun RemoteFilePreviewUiState.mimeType(): String = when (this) { - RemoteFilePreviewUiState.None, is RemoteFilePreviewUiState.Loading -> "" - is RemoteFilePreviewUiState.Text -> mimeType - is RemoteFilePreviewUiState.Image -> mimeType - is RemoteFilePreviewUiState.Unsupported -> mimeType - is RemoteFilePreviewUiState.Failed -> mimeType -} - -private fun RemoteFilePreviewUiState.sizeBytes(): Long = when (this) { - RemoteFilePreviewUiState.None, is RemoteFilePreviewUiState.Loading -> 0 - is RemoteFilePreviewUiState.Text -> sizeBytes - is RemoteFilePreviewUiState.Image -> sizeBytes - is RemoteFilePreviewUiState.Unsupported -> sizeBytes - is RemoteFilePreviewUiState.Failed -> sizeBytes -} - -/** Refresh re-opens the same reference, which is what HarmonyOS' refresh does. */ -private fun RemoteFilePreviewUiState.openIntent(): RemoteWorkspaceIntent = - RemoteWorkspaceIntent.OpenFile(reference(), label(), sessionId()) - -private fun RemoteFilePreviewUiState.downloadIntent(): RemoteWorkspaceIntent = - RemoteWorkspaceIntent.DownloadFile(reference(), label(), sessionId()) - -/** - * Whether asking the desktop for this file again is a question worth putting - * under the reader's thumb. Mirrors HarmonyOS' `canUseRemoteAction`: a read - * already in flight, a refusal that will not change, or a target that never - * resolved all leave the control visible but dimmed. - */ -private fun RemoteFilePreviewUiState.canBeAskedAgain(): Boolean = when (this) { - RemoteFilePreviewUiState.None -> false - is RemoteFilePreviewUiState.Loading -> false - is RemoteFilePreviewUiState.Failed -> retryable && remotePath().isNotEmpty() - else -> remotePath().isNotEmpty() -} - -/** True while this exact file is the one being fetched. */ -private fun RemoteFileDownloadUiState.isFetching(reference: String, remotePath: String): Boolean { - val target = when (this) { - is RemoteFileDownloadUiState.Loading -> this.target - else -> return false - } - val asked = target.path.ifEmpty { target.remotePath } - return asked.isNotEmpty() && (asked == reference || target.remotePath == remotePath) -} - -private fun RemoteFilePreviewUiState.reference(): String = when (this) { - RemoteFilePreviewUiState.None -> "" - is RemoteFilePreviewUiState.Loading -> target.path.ifEmpty { target.remotePath } - is RemoteFilePreviewUiState.Text -> target.path.ifEmpty { target.remotePath } - is RemoteFilePreviewUiState.Image -> target.path.ifEmpty { target.remotePath } - is RemoteFilePreviewUiState.Unsupported -> target.path.ifEmpty { target.remotePath } - is RemoteFilePreviewUiState.Failed -> target.path.ifEmpty { target.remotePath } -} - -private fun RemoteFilePreviewUiState.remotePath(): String = when (this) { - RemoteFilePreviewUiState.None -> "" - is RemoteFilePreviewUiState.Loading -> target.remotePath - is RemoteFilePreviewUiState.Text -> target.remotePath - is RemoteFilePreviewUiState.Image -> target.remotePath - is RemoteFilePreviewUiState.Unsupported -> target.remotePath - is RemoteFilePreviewUiState.Failed -> target.remotePath -} - -private fun RemoteFilePreviewUiState.sessionId(): String = when (this) { - RemoteFilePreviewUiState.None -> "" - is RemoteFilePreviewUiState.Loading -> target.sessionId - is RemoteFilePreviewUiState.Text -> target.sessionId - is RemoteFilePreviewUiState.Image -> target.sessionId - is RemoteFilePreviewUiState.Unsupported -> target.sessionId - is RemoteFilePreviewUiState.Failed -> target.sessionId -} - -private fun RemoteFilePreviewUiState.label(): String = when (this) { - RemoteFilePreviewUiState.None -> "" - is RemoteFilePreviewUiState.Loading -> target.displayName - is RemoteFilePreviewUiState.Text -> target.displayName - is RemoteFilePreviewUiState.Image -> target.displayName - is RemoteFilePreviewUiState.Unsupported -> target.displayName - is RemoteFilePreviewUiState.Failed -> target.displayName -} - -/** - * Colours the preview and marks the lines the agent's reference named. - * - * The shared [CodeSyntaxHighlighter] decides *what* each run is; this decides - * what that looks like. Plain runs are left unspecified so they inherit the - * card's own text colour rather than pinning a second definition of "ink". - */ -private fun highlightedSource( - content: String, - fileName: String, - lineStart: Int, - lineEnd: Int, - colors: CodeSyntaxColors, -): AnnotatedString = buildAnnotatedString { - for (token in CodeSyntaxHighlighter.tokenize(content, fileName)) { - val style = SpanStyle( - color = token.kind.color(colors), - background = if (isTargetLine(token.lineNumber, lineStart, lineEnd)) { - colors.targetBackground - } else { - Color.Unspecified - }, - ) - withStyle(style) { append(token.text) } - } -} - -private fun CodeSyntaxTokenKind.color(colors: CodeSyntaxColors): Color = when (this) { - CodeSyntaxTokenKind.PLAIN -> Color.Unspecified - CodeSyntaxTokenKind.LINE_NUMBER -> colors.lineNumber - CodeSyntaxTokenKind.KEYWORD -> colors.keyword - CodeSyntaxTokenKind.STRING -> colors.string - CodeSyntaxTokenKind.NUMBER -> colors.number - CodeSyntaxTokenKind.COMMENT -> colors.comment - CodeSyntaxTokenKind.FUNCTION -> colors.function - CodeSyntaxTokenKind.TYPE -> colors.type - CodeSyntaxTokenKind.CONSTANT -> colors.constant - CodeSyntaxTokenKind.PROPERTY -> colors.property -} - -/** - * Line `0` means the file was too big to lex and came back as one block, so - * there is nothing to line the highlight up with — better none than the wrong rows. - */ -private fun isTargetLine(lineNumber: Int, lineStart: Int, lineEnd: Int): Boolean { - if (lineNumber <= 0 || lineStart <= 0) return false - return lineNumber in lineStart..maxOf(lineEnd, lineStart) -} - -/** The desktop's own sentence never reaches here; each reason has our wording. */ -private fun FilePreviewFailureKind.messageRes(): Int = when (this) { - FilePreviewFailureKind.NOT_FOUND -> R.string.file_preview_not_found - FilePreviewFailureKind.UNAVAILABLE -> R.string.file_preview_unavailable - FilePreviewFailureKind.ACCESS_DENIED -> R.string.file_preview_access_denied - FilePreviewFailureKind.TOO_LARGE -> R.string.file_preview_too_large - FilePreviewFailureKind.CONNECTION -> R.string.file_preview_connection - FilePreviewFailureKind.LOAD_FAILED -> R.string.file_preview_failed -} - -private fun RemoteFilePreviewUiState.displayName(): String = when (this) { - RemoteFilePreviewUiState.None -> "" - is RemoteFilePreviewUiState.Loading -> target.displayName - is RemoteFilePreviewUiState.Text -> name - is RemoteFilePreviewUiState.Image -> name - is RemoteFilePreviewUiState.Unsupported -> target.displayName - is RemoteFilePreviewUiState.Failed -> target.displayName -} - -/** - * The file this surface is currently holding, as the remote path the projector - * also produces, so a file card under a turn can mark itself as the open one. - * - * Empty when nothing is open — an empty path matches no card, which is the same - * answer as "none of them" without a nullable travelling down to every bubble. - */ -internal fun RemoteWorkspaceUiState.previewingRemotePath(): String { - val preview = (this as? RemoteWorkspaceUiState.Ready)?.preview ?: return "" - return when (preview) { - RemoteFilePreviewUiState.None -> "" - is RemoteFilePreviewUiState.Loading -> preview.target.remotePath - is RemoteFilePreviewUiState.Text -> preview.target.remotePath - is RemoteFilePreviewUiState.Image -> preview.target.remotePath - is RemoteFilePreviewUiState.Unsupported -> preview.target.remotePath - // A failure still names its file: the card that asked for it should keep - // showing as the selected one while the reason sits above it. - is RemoteFilePreviewUiState.Failed -> preview.target.remotePath - } -} - -/** Whether the open file is still on its way, for the card's spinner. */ -internal fun RemoteWorkspaceUiState.previewLoading(): Boolean = - (this as? RemoteWorkspaceUiState.Ready)?.preview is RemoteFilePreviewUiState.Loading diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/HarnessProfileLabel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/HarnessProfileLabel.kt deleted file mode 100644 index 9bd190c676..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/HarnessProfileLabel.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.HarnessProfile - -@Composable -internal fun HarnessProfileLabel(profile: HarnessProfile) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Row(Modifier.size(22.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterHorizontally)) { - repeat(profile.ordinal + 1) { index -> - Box(Modifier.width(4.dp).height((8 + index * 5).dp).background(MaterialTheme.colorScheme.onSurface, RoundedCornerShape(2.dp))) - } - } - Text(stringResource(when (profile) { - HarnessProfile.MINIMAL -> R.string.harness_minimal - HarnessProfile.STANDARD -> R.string.harness_standard - HarnessProfile.ULTIMATE -> R.string.harness_ultimate - }), style = MaterialTheme.typography.titleSmall) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/PairingScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/PairingScreen.kt deleted file mode 100644 index 940d0ea200..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/PairingScreen.kt +++ /dev/null @@ -1,456 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.layout.widthIn -import androidx.compose.material3.HorizontalDivider -import com.openbitfun.mobile.app.ui.shell.WelcomeBrandFlow -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.session.RecentSessionsPresentation -import com.openbitfun.mobile.core.feature.session.RecentSessionUiState -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Button -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.Alignment -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.ConversationView -import com.openbitfun.mobile.app.ui.common.CircleControl -import com.openbitfun.mobile.app.ui.shell.MENU_TEST_TAG -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.session.ConversationHeaderPresenter -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState - -/** The account-device route: the only way this app reaches a desktop. */ -@Composable -internal fun AccountRemoteScreen( - remoteState: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - deviceId: String, - deviceName: String, - createDevices: List, - accountUsername: String, - attachmentOwner: String = deviceId, - phase: ConnectionPhase, - settingsPlacement: SettingsPlacement, - sessionDetailsPlacement: SettingsPlacement, - viewSettingsPlacement: SettingsPlacement, - onOpenRemoteSettings: () -> Unit, - onCreateDevicePick: (String) -> Unit, - onSessionIntent: (com.openbitfun.mobile.core.feature.session.RemoteSessionIntent) -> Unit, - onWorkspaceIntent: (RemoteWorkspaceIntent) -> Unit, - onOpenSidebar: (() -> Unit)? = null, - compact: Boolean = true, - requestedSessionId: String? = null, - creatingSession: Boolean = false, - onOpenSession: (String) -> Unit = {}, - // CreateSession is already opened by the shared store. Keep its route - // callback separate from the sidebar callback, which also dispatches an - // Open intent for an existing row. - onCreatedSession: (String) -> Unit = onOpenSession, - onCreateSession: () -> Unit = {}, - onRemoteHome: () -> Unit = {}, - modifier: Modifier, -) { - RemoteConnectedScreen( - remoteState = remoteState, - workspaceState = workspaceState, - phase = phase, - settingsPlacement = settingsPlacement, - sessionDetailsPlacement = sessionDetailsPlacement, - viewSettingsPlacement = viewSettingsPlacement, - onOpenRemoteSettings = onOpenRemoteSettings, - deviceId = deviceId, - attachmentOwner = attachmentOwner, - createDevices = createDevices, - desktopName = deviceName, - onCreateDevicePick = onCreateDevicePick, - onSessionIntent = onSessionIntent, - onWorkspaceIntent = onWorkspaceIntent, - onOpenSidebar = onOpenSidebar, - compact = compact, - requestedSessionId = requestedSessionId, - creatingSession = creatingSession, - onOpenSession = onOpenSession, - onCreatedSession = onCreatedSession, - onCreateSession = onCreateSession, - onRemoteHome = onRemoteHome, - connectionDetails = { - AccountDeviceDetails(deviceName = deviceName, accountUsername = accountUsername) - }, - modifier = modifier, - ) -} - -@Composable -private fun RemoteConnectedScreen( - remoteState: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - phase: ConnectionPhase, - settingsPlacement: SettingsPlacement, - sessionDetailsPlacement: SettingsPlacement, - viewSettingsPlacement: SettingsPlacement, - onOpenRemoteSettings: () -> Unit, - deviceId: String, - attachmentOwner: String, - createDevices: List, - desktopName: String, - onCreateDevicePick: (String) -> Unit, - onSessionIntent: (com.openbitfun.mobile.core.feature.session.RemoteSessionIntent) -> Unit, - onWorkspaceIntent: (RemoteWorkspaceIntent) -> Unit, - onOpenSidebar: (() -> Unit)?, - compact: Boolean, - requestedSessionId: String?, - creatingSession: Boolean, - onOpenSession: (String) -> Unit, - onCreatedSession: (String) -> Unit, - onCreateSession: () -> Unit, - onRemoteHome: () -> Unit, - connectionDetails: @Composable () -> Unit, - modifier: Modifier, -) { - val ready = remoteState as? RemoteSessionUiState.Ready - // Route immediately. A previous session snapshot must never stand in for the requested one. - val conversation = requestedSessionId?.takeIf { remoteState !is RemoteSessionUiState.Failed }?.let { requested -> - val matches = ready?.selectedSessionId == requested && ready.timeline?.sessionId == requested - if (matches) ready else RemoteSessionUiState.Ready( - sessions = ready?.sessions.orEmpty(), selectedSessionId = requested, - timeline = null, busy = true, permissionMode = null, permissionModeFailure = null, - query = "", agentFilter = com.openbitfun.mobile.core.feature.session.SessionAgentFilter.ALL, - hasMore = false, hasMoreMessages = false, modelCatalog = null, - ) - } - if (conversation != null) { - ConversationView( - state = conversation, - attachmentOwner = attachmentOwner, - hostCapabilities = (workspaceState as? RemoteWorkspaceUiState.Ready)?.hostCapabilities.orEmpty(), - phase = phase, - settingsPlacement = settingsPlacement, - onBack = onRemoteHome, - onOpenSidebar = onOpenSidebar, - onIntent = onSessionIntent, - contextTitle = ConversationHeaderPresenter.contextTitle( - desktopName = desktopName, - workspaceBranch = (workspaceState as? RemoteWorkspaceUiState.Ready) - ?.selected?.gitBranch.orEmpty(), - ), - onOpenFile = { path, label -> - onWorkspaceIntent( - RemoteWorkspaceIntent.OpenFile( - path, - label, - conversation.selectedSessionId.orEmpty(), - ), - ) - }, - previewingRemotePath = workspaceState.previewingRemotePath(), - previewLoading = workspaceState.previewLoading(), - download = (workspaceState as? RemoteWorkspaceUiState.Ready)?.download - ?: com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState.None, - onDownloadFile = { path, label -> - onWorkspaceIntent( - RemoteWorkspaceIntent.DownloadFile( - path, - label, - conversation.selectedSessionId.orEmpty(), - ), - ) - }, - modifier = modifier, - ) - } else if (requestedSessionId != null && remoteState is RemoteSessionUiState.Failed) { - Column(modifier.fillMaxSize()) { - RemoteShellHeader(onOpenSidebar, desktopName, onOpenRemoteSettings) - Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), - verticalArrangement = Arrangement.Center, - horizontalAlignment = Alignment.CenterHorizontally) { - Text(stringResource(R.string.sessions_failed), color = MaterialTheme.colorScheme.onSurfaceVariant) - TextButton(onClick = { - onSessionIntent(com.openbitfun.mobile.core.feature.session.RemoteSessionIntent.Open(requestedSessionId)) - }) { Text(stringResource(R.string.sessions_retry)) } - TextButton(onClick = onRemoteHome) { Text(stringResource(R.string.conversation_back)) } - } - } - } else if (creatingSession) { - CreateSessionRoute( - sessionState = remoteState, - workspaceState = workspaceState, - phase = phase, - deviceId = deviceId, - devices = createDevices, - compact = compact, - onDevicePick = onCreateDevicePick, - onBack = onRemoteHome, - onCreated = onCreatedSession, - onWorkspaceIntent = onWorkspaceIntent, - onIntent = onSessionIntent, - modifier = modifier, - ) - } else { - RemoteCompactHome( - remoteState = remoteState, - desktopName = desktopName, - onOpenSidebar = onOpenSidebar, - onBrowse = onOpenSidebar, - onOpen = { id -> - onOpenSession(id) - onSessionIntent(com.openbitfun.mobile.core.feature.session.RemoteSessionIntent.Open(id)) - }, - modifier = modifier, - ) - } -} - -@Composable -internal fun RemoteCompactHome( - remoteState: RemoteSessionUiState, - desktopName: String, - onOpenSidebar: (() -> Unit)?, - onBrowse: (() -> Unit)?, - onOpen: (String) -> Unit, - modifier: Modifier = Modifier, -) { - val ready = remoteState as? RemoteSessionUiState.Ready - val sessions = ready?.sessions.orEmpty() - val recent = RecentSessionsPresentation.sessionIds(sessions.map { - RecentSessionUiState(it.id, it.status, it.updatedAt, it.createdAt) - }).mapNotNull { id -> sessions.firstOrNull { it.id == id } } - Column(modifier.fillMaxSize()) { - RemoteShellHeader(onOpenSidebar, desktopName, null) - Column( - Modifier.weight(1f).align(Alignment.CenterHorizontally) - .widthIn(max = MobileDesignGeometry.RecentHomeMaxWidth).fillMaxWidth() - .verticalScroll(rememberScrollState()) - .padding(horizontal = MobileDesignGeometry.RecentHomeGutter, vertical = 24.dp), - ) { - com.openbitfun.mobile.app.ui.shell.ColdStartHomeMark(Modifier.align(Alignment.CenterHorizontally).size(MobileDesignGeometry.RecentHomeMarkSize)) - Text(stringResource(R.string.home_recent_title), fontSize = 25.sp, - fontWeight = FontWeight.Medium, textAlign = androidx.compose.ui.text.style.TextAlign.Center, - modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 32.dp)) - if (remoteState is RemoteSessionUiState.Loading) CircularProgressIndicator(Modifier.size(24.dp)) - if (remoteState is RemoteSessionUiState.Failed) { - Text(stringResource(R.string.sessions_failed), color = MaterialTheme.colorScheme.onSurfaceVariant) - } - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text(stringResource(R.string.home_recent_recent), fontSize = 12.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) - if (onBrowse != null) TextButton( - onClick = onBrowse, - colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), - ) { Text(stringResource(R.string.home_recent_all), fontSize = 12.sp) } - } - recent.forEach { session -> - Column(Modifier.fillMaxWidth().clickable { onOpen(session.id) } - .padding(vertical = MobileDesignGeometry.RecentHomeRowPadding)) { - Text(session.title, fontSize = 15.sp, maxLines = 2) - val workspace = session.workspaceName?.takeIf { it.isNotBlank() } - ?: session.workspacePath.orEmpty().trimEnd('/').substringAfterLast('/') - Text(listOf(desktopName, workspace).filter { it.isNotBlank() }.joinToString(" · "), - fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 6.dp), maxLines = 1) - } - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - } - if (recent.isEmpty() && remoteState !is RemoteSessionUiState.Loading) { - Text(stringResource(if (desktopName.isBlank()) R.string.home_recent_connect else R.string.home_recent_empty), - fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(vertical = 18.dp)) - } - } - } -} - -@Composable -private fun RemoteShellHeader( - onOpenSidebar: (() -> Unit)?, - subtitle: String = "", - onOpenRemoteSettings: (() -> Unit)?, -) { - val hasSubtitle = subtitle.isNotBlank() - Row( - modifier = Modifier - .fillMaxWidth() - .height(if (hasSubtitle) 76.dp else 64.dp) - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - onOpenSidebar?.let { openSidebar -> - CircleControl( - icon = R.drawable.ic_symbol_menu_lines, - glyphSize = 22, - contentDescription = stringResource(R.string.shell_open_sidebar), - onClick = openSidebar, - modifier = Modifier.testTag(MENU_TEST_TAG), - ) - } ?: Box(Modifier.size(44.dp)) - Column( - modifier = Modifier.weight(1f), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(3.dp), - ) { - Text( - stringResource(R.string.app_name), - fontSize = if (hasSubtitle) 18.sp else 17.sp, - fontWeight = FontWeight.Medium, - maxLines = 1, - textAlign = TextAlign.Center, - ) - if (hasSubtitle) { - Text( - subtitle, - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - textAlign = TextAlign.Center, - ) - } - } - if (onOpenRemoteSettings != null) CircleControl( - icon = R.drawable.ic_symbol_gearshape, - glyphSize = 19, - contentDescription = stringResource(R.string.navigation_settings), - onClick = onOpenRemoteSettings, - modifier = Modifier, - ) else Box(Modifier.size(com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry.ControlTouchSize)) - } -} - -@Composable -private fun AccountDeviceDetails(deviceName: String, accountUsername: String) { - Text(stringResource(R.string.paired_title), style = MaterialTheme.typography.headlineSmall) - Text( - stringResource(R.string.account_device_controlling, deviceName), - style = MaterialTheme.typography.bodyMedium, - ) - if (accountUsername.isNotBlank()) { - Text( - stringResource(R.string.paired_user, accountUsername), - style = MaterialTheme.typography.bodyMedium, - ) - } -} - -@Composable -internal fun RemoteWorkspacePanel( - state: RemoteWorkspaceUiState, - sessionId: String, - onIntent: (RemoteWorkspaceIntent) -> Unit, - // False wherever the shell places the preview itself: the file gets a pane - // or the whole page there, and a second copy inline under the list would be - // the same document twice. - showPreview: Boolean = true, -) { - var fileReference by rememberSaveable { mutableStateOf("") } - var directoryDialog by rememberSaveable { mutableStateOf(false) } - var workspacePath by rememberSaveable { mutableStateOf("") } - var savedConnectionId by rememberSaveable { mutableStateOf(null) } - Text(stringResource(R.string.workspace_title), style = MaterialTheme.typography.titleLarge) - when (state) { - RemoteWorkspaceUiState.Idle -> Unit - RemoteWorkspaceUiState.Loading -> CircularProgressIndicator() - is RemoteWorkspaceUiState.Failed -> { - Text(stringResource(R.string.workspace_failed), color = MaterialTheme.colorScheme.error) - TextButton(onClick = { onIntent(RemoteWorkspaceIntent.Load) }) { - Text(stringResource(R.string.sessions_refresh)) - } - } - is RemoteWorkspaceUiState.Ready -> { - if (directoryDialog) RuntimeDirectoryPickerDialog(state.directoryPicker, savedConnectionId, onIntent, { workspacePath = it; directoryDialog = false }, { directoryDialog = false }) - state.selected?.let { selected -> - Text(selected.name, style = MaterialTheme.typography.titleMedium) - if (selected.gitBranch.isNotEmpty()) Text(selected.gitBranch) - } - OutlinedTextField(value = workspacePath, onValueChange = { workspacePath = it }, - label = { Text(stringResource(R.string.workspace_target_path)) }, enabled = !state.busy, - modifier = Modifier.fillMaxWidth()) - TextButton(onClick = { directoryDialog = true; onIntent(RemoteWorkspaceIntent.BrowseWorkspaceDirectories(workspacePath.ifBlank { "/" }, savedConnectionId, false)) }, enabled = !state.busy) { Text(stringResource(R.string.workspace_choose_folder)) } - TextButton(onClick = { savedConnectionId = null }, enabled = !state.busy) { - Text(stringResource(R.string.workspace_target_device)) - } - state.savedConnections.forEach { connection -> - TextButton(onClick = { savedConnectionId = connection.id }, enabled = !state.busy) { - Text((if (savedConnectionId == connection.id) "✓ " else "") + connection.name) - } - } - if (state.savedConnectionsFailure) Text(stringResource(R.string.workspace_connections_failed), color = MaterialTheme.colorScheme.error) - // A hand-typed path has no workspace ID: only the legacy projection can be sent. - TextButton(enabled = !state.busy && workspacePath.isNotBlank(), onClick = { - onIntent(RemoteWorkspaceIntent.SelectWorkspace(workspacePath, savedConnectionId, null)) - }) { Text(stringResource(R.string.workspace_open_path)) } - state.workspaceReferenceFailure?.let { failure -> - Text(stringResource(workspaceReferenceFailureText(failure)), color = MaterialTheme.colorScheme.error) - } - state.workspaces.forEach { workspace -> - TextButton( - onClick = { onIntent(RemoteWorkspaceIntent.SelectWorkspace(workspace.path, workspace.remoteConnectionId, workspace.remoteSshHost, false, workspace.workspaceId)) }, - enabled = !state.busy && !state.isSelected(workspace), - ) { Text(workspace.displayName) } - } - if (state.assistants.isNotEmpty()) { - Text(stringResource(R.string.assistants_title), style = MaterialTheme.typography.titleSmall) - state.assistants.forEach { assistant -> - TextButton( - onClick = { onIntent(RemoteWorkspaceIntent.SelectAssistant(assistant.path, assistant.workspaceId)) }, - enabled = !state.busy && !state.isSelected(assistant), - ) { Text(assistant.name) } - } - } - OutlinedTextField( - value = fileReference, - onValueChange = { fileReference = it }, - label = { Text(stringResource(R.string.file_reference_label)) }, - enabled = !state.busy, - modifier = Modifier.fillMaxWidth(), - ) - Button( - onClick = { - onIntent(RemoteWorkspaceIntent.OpenFile(fileReference, "", sessionId)) - }, - enabled = fileReference.isNotBlank(), - ) { Text(stringResource(R.string.file_preview_open)) } - if (showPreview) { - // The pane sizes itself to the space it is given, and this - // panel is inside a scrolling column with none to give. - FilePreviewSurface( - preview = state.preview, - download = state.download, - remoteAvailable = true, - onIntent = onIntent, - modifier = Modifier.fillMaxWidth().height(360.dp), - ) - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteDownloadSaver.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteDownloadSaver.kt deleted file mode 100644 index 9349ebb690..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteDownloadSaver.kt +++ /dev/null @@ -1,82 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import android.app.Activity -import android.content.Intent -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.platform.LocalContext -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** Hands bytes fetched by KMP to Android's user-selected document destination. */ -@Composable -internal fun RemoteDownloadSaver( - state: RemoteWorkspaceUiState, - onIntent: (RemoteWorkspaceIntent) -> Unit, -) { - val context = LocalContext.current - val scope = rememberCoroutineScope() - val current by rememberUpdatedState((state as? RemoteWorkspaceUiState.Ready)?.download as? RemoteFileDownloadUiState.AwaitingSave) - var pending by remember { mutableStateOf(null) } - val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - val download = pending ?: return@rememberLauncherForActivityResult - pending = null - if (current?.localReference != download.localReference) return@rememberLauncherForActivityResult - val uri = result.data?.data - if (result.resultCode != Activity.RESULT_OK || uri == null) { - onIntent(RemoteWorkspaceIntent.DownloadSaveFailed(download.target.path)) - return@rememberLauncherForActivityResult - } - scope.launch { - val saved = runCatching { - withContext(Dispatchers.IO) { - context.contentResolver.openOutputStream(uri, "wt")?.use { output -> - java.io.File(download.localReference).inputStream().use { input -> - val buffer = ByteArray(64 * 1024) - while (true) { - check(current?.localReference == download.localReference) { "Download target changed" } - val count = input.read(buffer); if (count < 0) break - output.write(buffer, 0, count) - } - } - } ?: error("document destination is unavailable") - } - }.isSuccess - onIntent( - if (saved) RemoteWorkspaceIntent.DownloadSaved(download.target.path) - else RemoteWorkspaceIntent.DownloadSaveFailed(download.target.path), - ) - } - } - val awaiting = (state as? RemoteWorkspaceUiState.Ready)?.download - as? RemoteFileDownloadUiState.AwaitingSave - LaunchedEffect(awaiting?.localReference) { - if (awaiting == null || pending != null) return@LaunchedEffect - pending = awaiting - launcher.launch( - Intent(Intent.ACTION_CREATE_DOCUMENT).apply { - addCategory(Intent.CATEGORY_OPENABLE) - // DocumentsUI appends its MIME extension when it disagrees with - // the supplied filename (for example source.ts -> source.ts.txt). - val extension = awaiting.name.substringAfterLast('.', "").lowercase() - type = documentExportMimeType( - awaiting.mimeType, - android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension), - ) - putExtra(Intent.EXTRA_TITLE, awaiting.name) - }, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteSessionListView.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteSessionListView.kt deleted file mode 100644 index bc63f6d45e..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RemoteSessionListView.kt +++ /dev/null @@ -1,881 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LocalTextStyle -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.layout.boundsInWindow -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.core.feature.session.HarnessProfilePolicy -import com.openbitfun.mobile.core.feature.session.HarnessProfile -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.state.SessionViewSettings -import com.openbitfun.mobile.app.ui.settings.SessionViewSettingsSheet -import com.openbitfun.mobile.app.ui.settings.VIEW_SETTINGS_TOGGLE_TEST_TAG -import com.openbitfun.mobile.app.ui.settings.statusText -import com.openbitfun.mobile.app.ui.shell.sidebar.SidebarCircleButton -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.session.RelativeTime -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.session.RemoteSessionFailureReason -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.SessionActionPolicy -import com.openbitfun.mobile.core.feature.session.SessionActionScope -import com.openbitfun.mobile.core.feature.session.SessionListPresentation -import com.openbitfun.mobile.core.feature.session.SessionListSection -import com.openbitfun.mobile.core.feature.session.SessionTimePresentation -import com.openbitfun.mobile.core.feature.session.SessionWorkspaceContext -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import kotlinx.coroutines.delay -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -internal const val SESSION_LIST_TEST_TAG: String = "session-list" -internal const val SESSION_PROJECTS_TEST_TAG: String = "session-projects" -internal const val SESSION_PROJECT_CREATE_TEST_TAG_PREFIX: String = "session-project-create:" -internal const val SESSION_CHAT_CREATE_TEST_TAG: String = "session-chat-create" -internal const val SESSION_SHOW_MORE_TEST_TAG_PREFIX: String = "session-show-more:" -internal const val SESSION_SEARCH_TOGGLE_TEST_TAG: String = "session-search-toggle" -internal const val SESSION_SEARCH_FIELD_TEST_TAG: String = "session-search-field" - -/** - * The paired desktop's sessions, ported from `pages/components/SessionList.ets`. - * - * Opening a row hands the screen over to [ConversationView]; this surface is - * everything that is *about* sessions rather than inside one. - */ -@Composable -internal fun RemoteSessionListView( - state: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - compact: Boolean, - sessionDetailsPlacement: SettingsPlacement, - viewSettingsPlacement: SettingsPlacement, - connectionDetails: @Composable () -> Unit, - onIntent: (RemoteSessionIntent) -> Unit, - onWorkspaceIntent: (RemoteWorkspaceIntent) -> Unit, - onOpen: (String) -> Unit, - onCreate: () -> Unit, - modifier: Modifier, -) { - Column( - modifier = modifier - .fillMaxSize() - .padding(start = 20.dp, end = 20.dp, top = 4.dp) - .testTag(SESSION_LIST_TEST_TAG), - ) { - RemoteSessionListContent( - state = state, - workspaceState = workspaceState, - compact = compact, - sessionDetailsPlacement = sessionDetailsPlacement, - viewSettingsPlacement = viewSettingsPlacement, - onIntent = onIntent, - onWorkspaceIntent = onWorkspaceIntent, - onOpen = onOpen, - onCreate = onCreate, - connectionDetails = connectionDetails, - workspaceContent = { - RemoteWorkspacePanel( - state = workspaceState, - sessionId = (state as? RemoteSessionUiState.Ready)?.selectedSessionId.orEmpty(), - onIntent = onWorkspaceIntent, - showPreview = false, - ) - }, - ) - } -} - -/** - * The session list itself, without a scroll container of its own. - * - * Kept separate because the account sheet shows the same list under a different - * header, and both callers already own the surface they scroll. - */ -@Composable -@OptIn(ExperimentalMaterial3Api::class) -internal fun RemoteSessionListContent( - state: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - compact: Boolean, - sessionDetailsPlacement: SettingsPlacement, - viewSettingsPlacement: SettingsPlacement, - onIntent: (RemoteSessionIntent) -> Unit, - onWorkspaceIntent: (RemoteWorkspaceIntent) -> Unit, - onOpen: (String) -> Unit, - /** Opens the longer create route, where the first message is written. */ - onCreate: () -> Unit, - connectionDetails: @Composable () -> Unit, - workspaceContent: @Composable () -> Unit, -) { - var search by rememberSaveable { mutableStateOf("") } - var searchOpen by rememberSaveable { mutableStateOf(false) } - var actionsFor by rememberSaveable { mutableStateOf(null) } - var actionAnchor by remember { mutableStateOf(null) } - var detailsFor by rememberSaveable { mutableStateOf(null) } - var viewSettingsOpen by rememberSaveable { mutableStateOf(false) } - var collapsedSectionKeys by rememberSaveable { mutableStateOf>(emptyList()) } - var revealedSectionKeys by rememberSaveable { mutableStateOf>(emptyList()) } - // Not saveable, like the delete confirmation: an open menu is a finger - // half-way through a gesture, not a place to come back to. - // Keyed by the project's identity key, never its path: two open workspaces may share a root. - var projectCreateMenuKey by remember { mutableStateOf(null) } - var viewSettings by rememberSaveable(stateSaver = SessionViewSettings.Saver) { - mutableStateOf(SessionViewSettings.Default) - } - - val ready = state as? RemoteSessionUiState.Ready - LaunchedEffect(ready?.query) { - if (ready != null && ready.query != search) search = ready.query - } - LaunchedEffect(search, searchOpen) { - if (searchOpen && ready != null && search != ready.query) { - delay(250) - onIntent(RemoteSessionIntent.Search(search)) - } - } - val createAssistantSession = { - onIntent(RemoteSessionIntent.CreateSession("Claw")) - } - - Column(modifier = Modifier.fillMaxSize()) { - RemoteSessionListHeader( - onToggleViewSettings = { viewSettingsOpen = true }, - onToggleSearch = { - searchOpen = !searchOpen - if (!searchOpen && search.isNotEmpty()) { - search = "" - onIntent(RemoteSessionIntent.Search("")) - } - }, - ) - if (searchOpen) { - RemoteSessionSearchField( - query = search, - enabled = ready != null, - onQueryChange = { search = it }, - ) - } - Column( - modifier = Modifier - .weight(1f) - .fillMaxWidth() - .verticalScroll(rememberScrollState()) - .padding(bottom = 20.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - connectionDetails() - when (state) { - RemoteSessionUiState.Idle -> Unit - RemoteSessionUiState.Loading -> Text(stringResource(R.string.sessions_loading)) - is RemoteSessionUiState.Failed -> SessionFailure( - state, - onRetry = { onIntent(RemoteSessionIntent.Load) }, - ) - is RemoteSessionUiState.Ready -> { - // The desktop's search is a separate, server-side narrowing; the - // sheet's filters are applied here on what came back, exactly as - // `RemoteSessionList.ets` layers the two. - val workspace = workspaceState.asSessionContext() - val view = remember(state.sessions, workspace, viewSettings) { - SessionListPresentation.view( - sessions = state.sessions, - workspace = workspace, - options = viewSettings.options(query = ""), - nowMs = System.currentTimeMillis(), - ) - } - - val rows = view.sections.flatMap { it.sessions } - if (rows.isEmpty()) { - Text(stringResource(R.string.sessions_empty)) - } else { - val projectCount = view.sections.count { it is SessionListSection.Project } - view.sections.forEachIndexed { index, section -> - if (section is SessionListSection.Project && - view.sections.take(index).none { it is SessionListSection.Project } - ) { - ProjectTreeHeader(projectCount) - } - val sectionKey = sectionKey(section) - val collapsed = sectionKey in collapsedSectionKeys - SectionHeader( - supportsHarnessProfiles = HarnessProfilePolicy.supported((workspaceState as? RemoteWorkspaceUiState.Ready)?.hostCapabilities.orEmpty()), - section = section, - collapsed = collapsed, - createMenuOpen = section is SessionListSection.Project && - projectCreateMenuKey == section.key, - onToggleCreateMenu = if (section is SessionListSection.Project) { - { - projectCreateMenuKey = if (projectCreateMenuKey == section.key) { - null - } else { - section.key - } - } - } else null, - onDismissCreateMenu = { projectCreateMenuKey = null }, - onCreateAgent = if (section is SessionListSection.Project) { - { agentType -> - projectCreateMenuKey = null - // The section already carries the resolved workspace identity: with an - // ID the create is addressed by ID only; a pre-ID row sends its legacy - // triple. The shared store refuses unknown IDs instead of retrying by path. - onIntent(RemoteSessionIntent.CreateSession(agentType, "", "", null, section.path, - section.remoteConnectionId, section.remoteSshHost, section.workspaceId)) - } - } else null, - onCreateAssistant = if (section is SessionListSection.Chat) { - createAssistantSession - } else null, - onToggle = { - collapsedSectionKeys = if (collapsed) { - collapsedSectionKeys - sectionKey - } else { - collapsedSectionKeys + sectionKey - } - }, - ) - val batch = SessionListPresentation.batch( - sessions = section.sessions, - revealedSteps = revealedSectionKeys.count { it == sectionKey }, - ) - if (!collapsed) batch.visible.forEach { session -> - SessionRow( - title = session.title, - status = session.status, - updatedAt = session.updatedAt, - workspace = session.workspaceName - ?: session.workspacePath.orEmpty(), - settings = viewSettings, - projectChild = section is SessionListSection.Project, - selected = session.id == state.selectedSessionId, - // Opening a session is cancellable/supersedable - // in the store; keep rows tappable while the - // previous transcript hydrates. - enabled = true, - onOpen = { - onIntent(RemoteSessionIntent.Open(session.id)) - onOpen(session.id) - }, - onActions = { anchor -> - actionAnchor = anchor - actionsFor = session.id - }, - ) - } - if (!collapsed && batch.nextCount > 0) { - TextButton( - onClick = { - revealedSectionKeys = revealedSectionKeys + sectionKey - }, - modifier = Modifier - .fillMaxWidth() - .testTag(SESSION_SHOW_MORE_TEST_TAG_PREFIX + sectionKey), - ) { - Text(stringResource(R.string.sessions_show_more, batch.nextCount)) - } - } - } - if (state.hasMore) { - TextButton( - onClick = { onIntent(RemoteSessionIntent.LoadMore) }, - enabled = !state.busy, - modifier = Modifier.fillMaxWidth(), - ) { Text(stringResource(R.string.sessions_load_more)) } - } - } - // Looked up by id rather than held as an object: a refresh that - // lands while the sheet is open replaces every row, and holding - // the old copy would show a title the list no longer has. If the - // session is gone entirely the sheet closes with it. - rows.firstOrNull { it.id == actionsFor }?.let { session -> - val capabilities = SessionActionPolicy.resolve( - SessionActionScope.REMOTE, - session.agentType, - state.busy, - ) - val dismissActions = { - actionsFor = null - actionAnchor = null - } - val openDetails = { detailsFor = session.id } - val delete = { onIntent(RemoteSessionIntent.DeleteSession(session.id)) } - if (compact || actionAnchor == null) SessionActionSheet( - title = session.title, - status = session.status, - capabilities = capabilities, - onViewDetails = openDetails, - onDelete = delete, - onDismiss = dismissActions, - ) else SessionActionPopup( - anchorBounds = actionAnchor!!, - title = session.title, - status = session.status, - capabilities = capabilities, - onViewDetails = openDetails, - onDelete = delete, - onDismiss = dismissActions, - ) - } - rows.firstOrNull { it.id == detailsFor }?.let { session -> - SessionDetailsSheet( - title = session.title, - agentType = session.agentType, - status = session.status, - workspaceName = session.workspaceName, - workspacePath = session.workspacePath, - createdAt = session.createdAt, - updatedAt = session.updatedAt, - messageCount = session.messageCount, - placement = sessionDetailsPlacement, - onDismiss = { detailsFor = null }, - ) - } - } - } - workspaceContent() - } - } - - if (viewSettingsOpen && ready != null) { - val workspace = workspaceState.asSessionContext() - com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface( - visible = true, - placement = viewSettingsPlacement, - onDismissRequest = { viewSettingsOpen = false }, - ) { surfaceModifier -> - Column(surfaceModifier.verticalScroll(rememberScrollState())) { - SessionViewSettingsSheet( - settings = viewSettings, - workspaces = remember(ready.sessions, workspace) { - SessionListPresentation.workspaceOptions(ready.sessions, workspace) - }, - agentGroups = remember(ready.sessions, workspace) { - SessionListPresentation.agentGroups(ready.sessions, workspace) - }, - statuses = remember(ready.sessions) { - SessionListPresentation.statusOptions(ready.sessions) - }, - onChange = { viewSettings = it }, - onClose = { viewSettingsOpen = false }, - modifier = Modifier, - ) - } - } - } -} - -@Composable -private fun RemoteSessionListHeader( - onToggleViewSettings: () -> Unit, - onToggleSearch: () -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth().height(50.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.app_name), - fontSize = 20.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onBackground, - modifier = Modifier.weight(1f), - ) - SidebarCircleButton( - icon = R.drawable.ic_symbol_ellipsis, - contentDescription = stringResource(R.string.view_settings_title), - diameter = 38, - onClick = onToggleViewSettings, - modifier = Modifier.testTag(VIEW_SETTINGS_TOGGLE_TEST_TAG), - background = MaterialTheme.colorScheme.surface, - border = MaterialTheme.colorScheme.outlineVariant, - tint = MaterialTheme.colorScheme.onSurface, - ) - SidebarCircleButton( - icon = R.drawable.ic_symbol_magnifyingglass, - contentDescription = stringResource(R.string.sidebar_search), - diameter = 38, - onClick = onToggleSearch, - modifier = Modifier.testTag(SESSION_SEARCH_TOGGLE_TEST_TAG), - background = MaterialTheme.colorScheme.surface, - border = MaterialTheme.colorScheme.outlineVariant, - tint = MaterialTheme.colorScheme.onSurface, - ) - } -} - -@Composable -private fun CompactCreateMenuItem( - label: String, - enabled: Boolean, - onClick: () -> Unit, - modifier: Modifier, -) { - DropdownMenuItem( - text = { - Text(label, fontSize = 15.sp, fontWeight = FontWeight.Medium) - }, - onClick = onClick, - enabled = enabled, - modifier = modifier.height(MobileDesignGeometry.CompactPopoverActionHeight), - ) -} - -@Composable -private fun RemoteSessionSearchField( - query: String, - enabled: Boolean, - onQueryChange: (String) -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(top = 12.dp, bottom = 4.dp) - .height(42.dp) - .clip(RoundedCornerShape(8.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant) - .padding(horizontal = 14.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_magnifyingglass), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(18.dp), - ) - BasicTextField( - value = query, - onValueChange = onQueryChange, - enabled = enabled, - singleLine = true, - textStyle = LocalTextStyle.current.copy( - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurface, - ), - cursorBrush = SolidColor(MaterialTheme.colorScheme.onSurface), - decorationBox = { field -> - Box(contentAlignment = Alignment.CenterStart) { - if (query.isEmpty()) { - Text( - stringResource(R.string.sidebar_search_placeholder), - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - field() - } - }, - modifier = Modifier.fillMaxWidth().testTag(SESSION_SEARCH_FIELD_TEST_TAG), - ) - } -} - -/** - * The selected workspace and the desktop's recents, as the grouping needs them. - * - * A workspace list we have not loaded yet is not an error here: the grouping - * falls back to a single unnamed project, which is what the list looked like - * before any of this existed. - */ -@Composable -private fun RemoteWorkspaceUiState.asSessionContext(): SessionWorkspaceContext { - val ready = this as? RemoteWorkspaceUiState.Ready - return remember(ready) { - SessionWorkspaceContext( - selectedPath = ready?.selected?.path.orEmpty(), - selectedName = ready?.selected?.name.orEmpty(), - selectedKind = ready?.selected?.kind.orEmpty(), - recent = ready?.workspaces.orEmpty(), - selectedWorkspaceId = ready?.selected?.workspaceId, - selectedRemoteConnectionId = ready?.selected?.remoteConnectionId, - selectedRemoteSshHost = ready?.selected?.remoteSshHost, - ) - } -} - -/** One group heading; the project ones are named by the desktop, not by us. */ -@Composable -private fun ProjectTreeHeader(projectCount: Int) { - Row( - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 44.dp) - .testTag(SESSION_PROJECTS_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.sessions_projects), - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - projectCount.toString(), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -/** One collapsible group heading; project ones form the folder tree. */ -@Composable -private fun SectionHeader( - supportsHarnessProfiles: Boolean, - section: SessionListSection, - collapsed: Boolean, - createMenuOpen: Boolean, - onToggleCreateMenu: (() -> Unit)?, - onDismissCreateMenu: () -> Unit, - onCreateAgent: ((String) -> Unit)?, - onCreateAssistant: (() -> Unit)?, - onToggle: () -> Unit, -) { - val label = when (section) { - is SessionListSection.Chat -> stringResource(R.string.session_group_chat) - is SessionListSection.Today -> stringResource(R.string.time_today) - is SessionListSection.Yesterday -> stringResource(R.string.time_yesterday) - is SessionListSection.Earlier -> stringResource(R.string.time_earlier) - is SessionListSection.Project -> - section.name.ifBlank { stringResource(R.string.view_settings_workspace) } - } - Row( - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 42.dp) - .clip(RoundedCornerShape(8.dp)) - .clickable(onClick = onToggle) - .padding(horizontal = if (section is SessionListSection.Project) 4.dp else 0.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (section is SessionListSection.Project) { - Icon( - painterResource(R.drawable.ic_symbol_folder), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(22.dp), - ) - } - Text( - label, - style = MaterialTheme.typography.labelLarge, - color = if (section is SessionListSection.Project) { - MaterialTheme.colorScheme.onSurface - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - if (section is SessionListSection.Project) { - Text( - section.sessions.size.toString(), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - ProjectCreateControl( - supportsHarnessProfiles = supportsHarnessProfiles, - path = section.path, - expanded = createMenuOpen, - onToggle = { onToggleCreateMenu?.invoke() }, - onDismiss = onDismissCreateMenu, - onCreateAgent = { onCreateAgent?.invoke(it) }, - ) - } - if (section is SessionListSection.Chat) { - ChatCreateControl(onCreate = { onCreateAssistant?.invoke() }) - } - Icon( - painterResource( - if (collapsed) R.drawable.ic_symbol_chevron_right - else R.drawable.ic_symbol_chevron_down, - ), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } -} - -@Composable -internal fun ChatCreateControl(onCreate: () -> Unit) { - IconButton( - onClick = onCreate, - modifier = Modifier.size(40.dp).testTag(SESSION_CHAT_CREATE_TEST_TAG), - ) { - Icon( - painterResource(R.drawable.ic_symbol_square_and_pencil), - contentDescription = stringResource(R.string.sidebar_new_chat), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(18.dp), - ) - } -} - -@Composable -internal fun ProjectCreateControl( - supportsHarnessProfiles: Boolean = false, - enabled: Boolean = true, - path: String, - expanded: Boolean, - onToggle: () -> Unit, - onDismiss: () -> Unit, - onCreateAgent: (String) -> Unit, - modesOnly: Boolean = false, - onFiles: (() -> Unit)? = null, - onTerminal: (() -> Unit)? = null, -) { - Box { - IconButton( - onClick = onToggle, - enabled = enabled, - modifier = Modifier - .size(36.dp) - .testTag(SESSION_PROJECT_CREATE_TEST_TAG_PREFIX + path), - ) { - Icon( - painterResource(if (modesOnly || onFiles != null || onTerminal != null) R.drawable.ic_symbol_plus else R.drawable.ic_symbol_square_and_pencil), - contentDescription = stringResource(if (modesOnly || onFiles != null || onTerminal != null) R.string.workspace_actions else R.string.sidebar_new_chat), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(18.dp), - ) - } - DropdownMenu( - expanded = expanded, - onDismissRequest = onDismiss, - modifier = Modifier.width(MobileDesignGeometry.CompactPopoverWidth), - shape = RoundedCornerShape(MobileDesignGeometry.CompactPopoverRadius), - containerColor = MaterialTheme.colorScheme.surface, - tonalElevation = 0.dp, - shadowElevation = 18.dp, - ) { - HarnessProfile.entries.forEach { profile -> - androidx.compose.material3.DropdownMenuItem( - text = { HarnessProfileLabel(profile) }, - onClick = { onCreateAgent(profile.agentType) }, - ) - } - } - } -} - -private fun sectionKey(section: SessionListSection): String = when (section) { - is SessionListSection.Chat -> "chat" - is SessionListSection.Project -> "project:" + section.key - is SessionListSection.Today -> "today" - is SessionListSection.Yesterday -> "yesterday" - is SessionListSection.Earlier -> "earlier" -} - -private const val ASSISTANT_WORKSPACE_KIND = "assistant" - -/** - * One session in the list, from `RemoteSessionList.ets#SessionRow`. - * - * A flat row rather than a filled button: the source paints a background only on - * the session being read, so the list reads as a list with one thing marked in - * it. Every row filled meant the marked one had nowhere left to go, and a column - * of solid blocks buried the metadata line under its own contrast. - * - * Which parts of the metadata appear is the user's choice, and by default none - * of them do — a row is its title until someone asks for more. Each part is - * still conditional on having something to say: a timestamp the desktop did not - * send is left out rather than shown as "unknown", and only `archived` has a - * word of our own, so any other status is passed through as the desktop spelled - * it. The row is shorter when it has only the title, as the source's height is. - * - * Long-pressing opens the same actions the overflow does, which is how the - * source reaches them on a phone. - */ -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun SessionRow( - title: String, - status: String, - updatedAt: String, - workspace: String, - settings: SessionViewSettings, - projectChild: Boolean, - selected: Boolean, - enabled: Boolean, - onOpen: () -> Unit, - onActions: (IntRect) -> Unit, -) { - var anchorBounds by remember { mutableStateOf(IntRect.Zero) } - val now = remember(updatedAt) { System.currentTimeMillis() } - val relative = remember(updatedAt, now) { SessionTimePresentation.relative(updatedAt, now) } - val metadata = listOfNotNull( - workspace.takeIf { settings.showWorkspace && it.isNotBlank() }, - relativeTimeText(relative).takeIf { settings.showUpdated }, - status.takeIf { settings.showStatus && it.isNotBlank() }?.let { statusText(it) }, - ).joinToString(" · ") - - Row( - modifier = Modifier - .fillMaxWidth() - .heightIn(min = if (metadata.isEmpty()) 46.dp else 56.dp) - .clip(RoundedCornerShape(10.dp)) - .background( - if (selected) MaterialTheme.colorScheme.secondaryContainer else openBitFunColors.transparent, - ) - .onGloballyPositioned { coordinates -> - anchorBounds = coordinates.boundsInWindow().toIntRect() - } - .combinedClickable( - enabled = enabled, - onClick = onOpen, - onLongClick = { onActions(anchorBounds) }, - ) - .padding(start = if (projectChild) 28.dp else 10.dp, end = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - title.ifBlank { stringResource(R.string.sidebar_untitled) }, - style = MaterialTheme.typography.bodyLarge, - fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (metadata.isNotEmpty()) { - Text( - metadata, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - // The overflow keeps the destructive actions one deliberate tap away, - // as `SessionMoreButton` does. Two permanent buttons under every row - // made destroying a session as reachable as opening one. - IconButton(onClick = { onActions(anchorBounds) }) { - Icon( - painterResource(R.drawable.ic_symbol_ellipsis), - contentDescription = stringResource(R.string.session_actions), - modifier = Modifier.size(18.dp), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -private fun Rect.toIntRect(): IntRect = IntRect( - left = left.toInt(), - top = top.toInt(), - right = right.toInt(), - bottom = bottom.toInt(), -) - -/** Null when the desktop sent nothing readable — see [SessionRowLabel]. */ -@Composable -internal fun relativeTimeText(relative: RelativeTime): String? = when (relative) { - RelativeTime.Unknown -> null - RelativeTime.JustNow -> stringResource(R.string.time_just_now) - is RelativeTime.MinutesAgo -> stringResource(R.string.time_minutes_ago, relative.minutes) - is RelativeTime.HoursAgo -> stringResource(R.string.time_hours_ago, relative.hours) - is RelativeTime.DaysAgo -> stringResource(R.string.time_days_ago, relative.days) - // A plain ISO date rather than a localized one: it sits beside a status the - // desktop wrote, and a sortable date reads the same in both languages. - is RelativeTime.OnDate -> buildString { - append(relative.year.toString().padStart(4, '0')) - append('-') - append(relative.month.toString().padStart(2, '0')) - append('-') - append(relative.day.toString().padStart(2, '0')) - } -} - -@Composable -private fun SessionFailure(state: RemoteSessionUiState.Failed, onRetry: () -> Unit) { - Column { - Text( - stringResource( - when (state.reason) { - RemoteSessionFailureReason.NO_WORKSPACE -> R.string.sessions_failed_no_workspace - RemoteSessionFailureReason.REMOTE_REJECTED -> R.string.sessions_failed_remote_rejected - RemoteSessionFailureReason.NETWORK -> R.string.sessions_failed_network - RemoteSessionFailureReason.TIMEOUT -> R.string.sessions_failed_timeout - RemoteSessionFailureReason.RATE_LIMITED -> R.string.sessions_failed_rate_limited - RemoteSessionFailureReason.PROTOCOL_MISMATCH -> R.string.sessions_failed_protocol_mismatch - RemoteSessionFailureReason.SESSION_NOT_FOUND -> R.string.sessions_failed_session_not_found - RemoteSessionFailureReason.WORKSPACE_ID_UNSUPPORTED -> R.string.sessions_failed_workspace_id_unsupported - RemoteSessionFailureReason.WORKSPACE_ID_UNKNOWN -> R.string.sessions_failed_workspace_id_unknown - RemoteSessionFailureReason.HOST_STREAM_UNSUPPORTED -> R.string.sessions_failed_host_stream_unsupported - // Exhaustive on purpose rather than an `else`: every reason - // that reaches this screen was raised to say something - // specific, and a new one falling into the generic line is - // the bug this branch exists to prevent. - RemoteSessionFailureReason.TRANSPORT -> R.string.sessions_failed - }, - ), - color = MaterialTheme.colorScheme.error, - ) - // The desktop wrote this sentence; it cannot be translated on this side, - // so it sits under our heading as supporting detail. - state.remoteMessage?.let { detail -> - Text( - detail, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - // Every reason above is retryable in the sense that matters here: the - // request can be made again. Without this the screen is a dead end that - // states a problem and offers nothing, which is how the account path - // stranded a real session behind one bad decode. - TextButton(onClick = onRetry) { Text(stringResource(R.string.sessions_retry)) } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeTerminalView.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeTerminalView.kt deleted file mode 100644 index f6f8c5e9d6..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeTerminalView.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import android.annotation.SuppressLint -import android.webkit.JavascriptInterface -import android.webkit.WebResourceRequest -import android.webkit.WebView -import android.webkit.WebViewClient -import androidx.compose.runtime.* -import androidx.compose.material3.MaterialTheme -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.Modifier -import androidx.compose.ui.viewinterop.AndroidView -import com.openbitfun.mobile.core.feature.workspace.RuntimeTerminalUiState -import org.json.JSONObject - -/** Trusted bundled renderer only; all terminal execution stays in the selected runtime store. */ -@SuppressLint("SetJavaScriptEnabled") -@Composable -internal fun RuntimeTerminalView(state: RuntimeTerminalUiState, onInput: (String) -> Unit, onResize: (Int, Int) -> Unit, modifier: Modifier) { - val background = MaterialTheme.colorScheme.background.toArgb() - val foreground = MaterialTheme.colorScheme.onBackground.toArgb() - val latestInput by rememberUpdatedState(onInput) - val latestResize by rememberUpdatedState(onResize) - var bridge by remember { mutableStateOf(null) } - AndroidView(modifier = modifier, factory = { context -> - WebView(context).apply { - if (context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) WebView.setWebContentsDebuggingEnabled(true) - // Without explicit match-parent params WebView can keep a zero CSS - // viewport even after Compose measures the native view to full height. - layoutParams = android.view.ViewGroup.LayoutParams( - android.view.ViewGroup.LayoutParams.MATCH_PARENT, - android.view.ViewGroup.LayoutParams.MATCH_PARENT, - ) - settings.javaScriptEnabled = true - settings.allowFileAccess = true - settings.allowContentAccess = false - isFocusableInTouchMode = true - // DOM focus alone does not move focus out of the Compose dialog. - // Give WebView native focus before xterm focuses its textarea so - // Android establishes the input connection and routes keys here. - setOnTouchListener { view, event -> - if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) view.requestFocus() - false - } - val adapter = TerminalBridge(this, { latestInput(it) }, { cols, rows -> latestResize(cols, rows) }) - bridge = adapter - addJavascriptInterface(adapter, "OpenBitFunTerminalHost") - webViewClient = object : WebViewClient() { - override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean = request?.url?.toString() != "file:///android_asset/index.html" - override fun onPageFinished(view: WebView?, url: String?) { evaluateJavascript("window.OpenBitFunTerminal.connect()", null) } - } - loadUrl("file:///android_asset/index.html") - } - }, update = { bridge?.updateTheme(background, foreground); bridge?.update(state) }) - DisposableEffect(Unit) { onDispose { bridge?.dispose() } } -} - -private class TerminalBridge(private val view: WebView, private val input: (String) -> Unit, private val resize: (Int, Int) -> Unit) { - private var theme: String? = null - fun updateTheme(background: Int, foreground: Int) { - fun css(color: Int) = "#" + (color and 0xffffff).toString(16).padStart(6, '0') - val next = JSONObject().put("background", css(background)).put("foreground", css(foreground)).put("cursor", css(foreground)).toString() - view.setBackgroundColor(background) - if (next == theme) return - theme = next - renderTheme() - } - private fun renderTheme() { - if (ready && !disposed) theme?.let { view.evaluateJavascript("window.OpenBitFunTerminal.setTheme($it)", null) } - } - private var state: RuntimeTerminalUiState? = null - private var ready = false - private var disposed = false - private var epoch: String? = null - private var revision = -1L - fun update(value: RuntimeTerminalUiState) { state = value; render(false) } - private fun render(force: Boolean) { - val value = state ?: return - val id = value.sessionId ?: return - if (!ready || disposed || (!force && id == epoch && revision == value.revision)) return - val reset = force || id != epoch || value.reset || value.revision != revision + 1 - val frame = JSONObject().put("epoch", id).put("revision", value.revision).put("reset", reset).put("data", if (reset) value.output else value.chunk) - view.evaluateJavascript("window.OpenBitFunTerminal.accept($frame)", null) - epoch = id; revision = value.revision - } - @JavascriptInterface fun postMessage(message: String) { - view.post { - if (disposed) return@post - val event = runCatching { JSONObject(message) }.getOrNull() ?: return@post - when (event.optString("type")) { - "ready" -> { ready = true; renderTheme(); render(true) } - "resync" -> render(true) - "input" -> input(event.optString("data")) - "resize" -> { val cols = event.optInt("cols"); val rows = event.optInt("rows"); if (cols > 0 && rows > 0) resize(cols, rows) } - } - } - } - fun dispose() { disposed = true; view.removeJavascriptInterface("OpenBitFunTerminalHost"); view.destroy() } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspaceDialogs.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspaceDialogs.kt deleted file mode 100644 index 7f2318b1fb..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspaceDialogs.kt +++ /dev/null @@ -1,324 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.clickable -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.items -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.Alignment -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.ui.text.PlatformTextStyle -import androidx.compose.ui.unit.sp -import androidx.compose.material3.* -import androidx.compose.runtime.* -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Dialog -import androidx.compose.ui.window.DialogProperties -import com.openbitfun.mobile.app.ui.chat.statusText -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.workspace.* - -@Composable -internal fun RuntimeFullScreen(title: String, onBack: () -> Unit, actions: @Composable RowScope.() -> Unit = {}, content: @Composable ColumnScope.() -> Unit) { - Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { - Surface(Modifier.fillMaxSize()) { - Column(Modifier.fillMaxSize().safeDrawingPadding().imePadding()) { - Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = onBack) { Text(stringResource(R.string.common_back)) } - Text(title, Modifier.weight(1f).padding(vertical = 12.dp), style = MaterialTheme.typography.titleMedium, maxLines = 1) - actions() - } - HorizontalDivider() - content() - } - } - } -} - -@Composable -internal fun RuntimeFileEditorDialog(files: RuntimeFilesUiState, onIntent: (RemoteWorkspaceIntent) -> Unit) { - val file = files.file ?: return - var content by rememberSaveable(file) { mutableStateOf(files.content) } - var savedContent by rememberSaveable(file) { mutableStateOf(files.content) } - var discard by rememberSaveable(file) { mutableStateOf(false) } - var fileAction by remember { mutableStateOf("") } - var renamePath by remember(file) { mutableStateOf(file) } - var menu by remember { mutableStateOf(false) } - LaunchedEffect(files.content) { - // Recreation restores the draft; only a new host revision replaces it. - if (files.content != savedContent) { - content = files.content - savedContent = files.content - } - } - val dirty = content != files.content - val back = { if (!files.busy) { if (dirty) discard = true else onIntent(RemoteWorkspaceIntent.CloseFileEditor) } } - RuntimeFullScreen(file.substringAfterLast('/'), back, actions = { - Box { - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !files.busy && !dirty, onClick = { menu = true }) { Text("⋯") } - DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { - DropdownMenuItem(text = { Text(stringResource(R.string.workspace_rename_file)) }, onClick = { menu = false; fileAction = "rename" }) - DropdownMenuItem(text = { Text(stringResource(R.string.workspace_delete_file)) }, onClick = { menu = false; fileAction = "delete" }) - } - } - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !files.busy && dirty, onClick = { onIntent(RemoteWorkspaceIntent.SaveFile(content)) }) { Text(stringResource(R.string.workspace_save_file)) } - }) { - Text(file, Modifier.padding(horizontal = 16.dp, vertical = 8.dp), style = MaterialTheme.typography.bodySmall) - if (files.failed) Text(if (files.saveConflict) stringResource(R.string.workspace_file_conflict) else files.errorDetail ?: stringResource(R.string.workspace_files_failed), color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) - BoxWithConstraints(Modifier.fillMaxWidth().weight(1f)) { - val viewportWidth = maxWidth - 60.dp - val codeStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace, fontSize = 14.sp, lineHeight = 21.sp, platformStyle = PlatformTextStyle(includeFontPadding = false)) - Row(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) { - Text((1..(content.count { it == '\n' } + 1)).joinToString("\n"), Modifier.width(60.dp).padding(12.dp), style = codeStyle, color = MaterialTheme.colorScheme.onSurfaceVariant) - Box(Modifier.horizontalScroll(rememberScrollState())) { - BasicTextField(value = content, onValueChange = { content = it }, enabled = !files.busy, - textStyle = codeStyle.copy(color = MaterialTheme.colorScheme.onSurface), - modifier = Modifier.width(IntrinsicSize.Max).widthIn(min = viewportWidth).padding(12.dp)) - } - } - } - } - if (fileAction.isNotEmpty()) AlertDialog(onDismissRequest = { fileAction = "" }, - title = { Text(stringResource(if (fileAction == "rename") R.string.workspace_rename_file else R.string.workspace_delete_file)) }, - text = { if (fileAction == "rename") OutlinedTextField(value = renamePath, onValueChange = { renamePath = it }, singleLine = true) else Text(file) }, - confirmButton = { TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = fileAction != "rename" || renamePath.isNotBlank(), onClick = { - if (fileAction == "rename") onIntent(RemoteWorkspaceIntent.RenameFile(renamePath)) else onIntent(RemoteWorkspaceIntent.DeleteFile) - fileAction = "" - }) { Text(stringResource(if (fileAction == "rename") R.string.workspace_rename_file else R.string.workspace_delete_file)) } }, - dismissButton = { TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { fileAction = "" }) { Text(stringResource(R.string.common_cancel)) } }) - if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.workspace_discard_changes)) }, - confirmButton = { TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { discard = false; onIntent(RemoteWorkspaceIntent.CloseFileEditor) }) { Text(stringResource(R.string.workspace_discard)) } }, - dismissButton = { TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { discard = false }) { Text(stringResource(R.string.common_cancel)) } }) -} - -@Composable -internal fun RuntimeDirectoryPickerDialog(state: RuntimeFilesUiState, connectionId: String?, onIntent: (RemoteWorkspaceIntent) -> Unit, onChoose: (String) -> Unit, onBack: () -> Unit) { - RuntimeFullScreen(stringResource(R.string.workspace_choose_folder), onBack, actions = { - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !state.busy && !state.failed && state.directory.isNotBlank(), onClick = { onChoose(state.directory) }) { Text(stringResource(R.string.workspace_choose)) } - }) { - Text(state.directory, Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall) - if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth()) - if (state.failed) Text(state.errorDetail ?: stringResource(R.string.workspace_files_failed), color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) - Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp)) { - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !state.busy && state.directory != "/", onClick = { onIntent(RemoteWorkspaceIntent.BrowseWorkspaceDirectories(state.directory.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }, connectionId, false)) }) { Text(stringResource(R.string.workspace_parent_folder)) } - state.entries.filter { it.directory }.forEach { entry -> - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { onIntent(RemoteWorkspaceIntent.BrowseWorkspaceDirectories(entry.path, connectionId, false)) }, enabled = !state.busy, modifier = Modifier.fillMaxWidth()) { Text(entry.name) } - } - if (state.hasMore) TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { onIntent(RemoteWorkspaceIntent.BrowseWorkspaceDirectories(state.directory, connectionId, true)) }, enabled = !state.busy) { Text(stringResource(R.string.workspace_more_files)) } - } - } -} - -@Composable -internal fun RuntimeTerminalDialog(state: RuntimeTerminalUiState, onIntent: (RemoteWorkspaceIntent) -> Unit, onBack: () -> Unit) { - RuntimeFullScreen(stringResource(R.string.workspace_terminal), onBack, actions = { - if (state.sessionId != null) { - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !state.busy, onClick = { onIntent(RemoteWorkspaceIntent.WriteTerminal("\u0003")) }) { Text(stringResource(R.string.message_stop)) } - TextButton(colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !state.busy, onClick = { onIntent(RemoteWorkspaceIntent.CloseTerminal) }) { Text(stringResource(R.string.workspace_terminal_close)) } - } - }) { - if (state.failed) Text(state.errorDetail ?: stringResource(R.string.workspace_terminal_failed), color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(12.dp)) - if (state.busy) CircularProgressIndicator(Modifier.padding(12.dp)) - if (state.sessionId != null) { - RuntimeTerminalView(state, { onIntent(RemoteWorkspaceIntent.WriteTerminal(it)) }, { cols, rows -> onIntent(RemoteWorkspaceIntent.ResizeTerminal(cols, rows)) }, Modifier.fillMaxWidth().weight(1f)) - } else if (!state.busy) { - Box(Modifier.fillMaxWidth().weight(1f), contentAlignment = androidx.compose.ui.Alignment.Center) { - OutlinedButton( - onClick = { onIntent(RemoteWorkspaceIntent.ReopenTerminal) }, - colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), - ) { Text(stringResource(R.string.workspace_open_terminal)) } - } - } - } -} - -@Composable -internal fun RuntimeFileSortMenu(sort: RuntimeFileSort, onIntent: (RemoteWorkspaceIntent) -> Unit, enabled: Boolean = true) { - var open by remember { mutableStateOf(false) } - val labels = listOf(R.string.workspace_sort_name_asc, R.string.workspace_sort_name_desc, R.string.workspace_sort_modified_desc, R.string.workspace_sort_modified_asc) - Box { - TextButton(enabled = enabled, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), onClick = { open = true }) { Text(stringResource(labels[sort.ordinal]), maxLines = 1, overflow = TextOverflow.Ellipsis) } - DropdownMenu(expanded = open, onDismissRequest = { open = false }) { - RuntimeFileSort.entries.forEachIndexed { index, value -> DropdownMenuItem(text = { Text(stringResource(labels[index])) }, onClick = { open = false; onIntent(RemoteWorkspaceIntent.SortFiles(value)) }) } - } - } -} - -@Composable -internal fun RuntimeFilesDialog(state: RemoteWorkspaceUiState.Ready, onIntent: (RemoteWorkspaceIntent) -> Unit, onBack: () -> Unit) { - RuntimeFullScreen(stringResource(R.string.workspace_browse_files), onBack) { RuntimeFilesContent(state, onIntent) } -} - -private enum class FileListAction { FILE, DIRECTORY, RENAME, DELETE, UPLOAD } - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun ColumnScope.RuntimeFilesContent(state: RemoteWorkspaceUiState.Ready, onIntent: (RemoteWorkspaceIntent) -> Unit) { - // A new location/order starts at the top; pagination and refresh retain position. - val listState = remember(state.files.directory, state.files.sort) { LazyListState() } - var attached by remember { mutableStateOf(true) } - DisposableEffect(Unit) { onDispose { attached = false } } - val uploadContext = androidx.compose.ui.platform.LocalContext.current - var uploadFailed by rememberSaveable { mutableStateOf(false) } - var action by remember { mutableStateOf(null) } - var target by remember { mutableStateOf("") } - var name by rememberSaveable { mutableStateOf("") } - var submitted by remember { mutableStateOf(false) } - var submittedRevision by remember { mutableStateOf(0L) } - var toolbarMenu by remember { mutableStateOf(false) } - val neutral = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface) - fun begin(value: FileListAction, path: String = "", initial: String = "") { - action = value; target = path; name = initial; submitted = false; uploadFailed = false - } - LaunchedEffect(state.files.completedOperation, submitted) { - if (submitted && state.files.completedOperation > submittedRevision) { - if (!state.files.failed) action = null - submitted = false - } - } - val uploadPicker = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri -> - if (uri != null && attached) { - try { - val source = com.openbitfun.mobile.app.platform.AndroidRuntimeUploadSource(uploadContext.contentResolver, uri) - submittedRevision = state.files.completedOperation; submitted = true - onIntent(RemoteWorkspaceIntent.UploadFileEntry(name, source)); uploadFailed = false - } catch (_: Exception) { submitted = false; uploadFailed = true } - } - } - Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) { - Text(state.files.directory, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(vertical = 12.dp), maxLines = 2, overflow = TextOverflow.Ellipsis) - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - IconButton(enabled = !state.files.busy && state.files.directory != "/", onClick = { - onIntent(RemoteWorkspaceIntent.BrowseFiles(state.files.directory.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }, false)) - }) { Icon(painterResource(R.drawable.ic_symbol_arrow_up), stringResource(R.string.workspace_parent_folder), Modifier.size(20.dp)) } - IconButton(enabled = !state.files.busy, onClick = { onIntent(RemoteWorkspaceIntent.BrowseFiles(state.files.directory, false)) }) { - Icon(painterResource(R.drawable.ic_symbol_arrow_clockwise), stringResource(R.string.common_refresh), Modifier.size(20.dp)) - } - Box(Modifier.weight(1f)) { RuntimeFileSortMenu(state.files.sort, onIntent, enabled = !state.files.busy) } - Box { - IconButton(enabled = !state.files.busy && state.files.directory.isNotEmpty(), onClick = { toolbarMenu = true }) { - Icon(painterResource(R.drawable.ic_symbol_plus), stringResource(R.string.workspace_create_file), Modifier.size(20.dp)) - } - DropdownMenu(toolbarMenu, { toolbarMenu = false }) { - listOf(FileListAction.FILE to R.string.workspace_create_file, FileListAction.DIRECTORY to R.string.workspace_create_directory, - FileListAction.UPLOAD to R.string.workspace_upload_file).forEach { (value, label) -> - DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = { toolbarMenu = false; begin(value) }) - } - } - } - } - if (state.files.busy) LinearProgressIndicator(Modifier.fillMaxWidth()) - if (state.files.failed && action == null) Text(state.files.errorDetail ?: stringResource(R.string.workspace_files_failed), color = MaterialTheme.colorScheme.error) - } - LazyColumn(Modifier.fillMaxWidth().weight(1f), state = listState, contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)) { - items(state.files.entries, key = { it.path }) { entry -> - var menu by remember { mutableStateOf(false) } - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Row(Modifier.weight(1f).heightIn(min = 52.dp).clickable(enabled = !state.files.busy) { - if (entry.directory) onIntent(RemoteWorkspaceIntent.BrowseFiles(entry.path, false)) else onIntent(RemoteWorkspaceIntent.ReadFile(entry.path)) - }, verticalAlignment = Alignment.CenterVertically) { - Icon(painterResource(if (entry.directory) R.drawable.ic_symbol_folder else R.drawable.ic_symbol_doc), null, - Modifier.padding(end = 12.dp).size(22.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) - Text(entry.name, style = MaterialTheme.typography.bodyMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) - } - Box { - IconButton(enabled = !state.files.busy, onClick = { menu = true }) { - Icon(painterResource(R.drawable.ic_symbol_ellipsis), stringResource(R.string.workspace_file_actions), Modifier.size(20.dp)) - } - DropdownMenu(menu, { menu = false }) { - if (!entry.directory) DropdownMenuItem(text = { Text(stringResource(R.string.file_download)) }, - enabled = state.download !is RemoteFileDownloadUiState.Loading, - onClick = { menu = false; onIntent(RemoteWorkspaceIntent.DownloadFile(entry.path, entry.name, "")) }) - DropdownMenuItem(text = { Text(stringResource(R.string.session_rename)) }, onClick = { menu = false; begin(FileListAction.RENAME, entry.path, entry.name) }) - DropdownMenuItem(text = { Text(stringResource(R.string.session_delete), color = MaterialTheme.colorScheme.error) }, onClick = { menu = false; begin(FileListAction.DELETE, entry.path, entry.name) }) - } - } - } - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - } - if (state.files.hasMore) item { - TextButton(colors = neutral, onClick = { onIntent(RemoteWorkspaceIntent.BrowseFiles(state.files.directory, true)) }, enabled = !state.files.busy) { - Text(stringResource(R.string.workspace_more_files)) - } - } - } - RuntimeDownloadStatus(state.download, onIntent) - action?.let { current -> - val label = when (current) { - FileListAction.FILE -> R.string.workspace_create_file - FileListAction.DIRECTORY -> R.string.workspace_create_directory - FileListAction.RENAME -> R.string.session_rename - FileListAction.DELETE -> R.string.session_delete - FileListAction.UPLOAD -> R.string.workspace_upload_file - } - ModalBottomSheet(onDismissRequest = { if (!state.files.busy) action = null }, - sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true, confirmValueChange = { !state.files.busy }), - containerColor = MaterialTheme.colorScheme.surface) { - Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp).padding(bottom = 24.dp).imePadding(), verticalArrangement = Arrangement.spacedBy(16.dp)) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) { - TextButton(colors = neutral, enabled = !state.files.busy, onClick = { action = null }) { Text(stringResource(R.string.common_cancel)) } - Text(stringResource(label), style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f), textAlign = androidx.compose.ui.text.style.TextAlign.Center) - Button( - colors = ButtonDefaults.buttonColors(containerColor = if (current == FileListAction.DELETE) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface, - contentColor = if (current == FileListAction.DELETE) MaterialTheme.colorScheme.onError else MaterialTheme.colorScheme.surface), - enabled = !state.files.busy && !submitted && (current == FileListAction.DELETE || name.isNotBlank()), onClick = { - if (current == FileListAction.UPLOAD) uploadPicker.launch(arrayOf("*/*")) - else { - submittedRevision = state.files.completedOperation; submitted = true - onIntent(when (current) { - FileListAction.FILE -> RemoteWorkspaceIntent.CreateFileEntry(name, false) - FileListAction.DIRECTORY -> RemoteWorkspaceIntent.CreateFileEntry(name, true) - FileListAction.RENAME -> RemoteWorkspaceIntent.RenameFileEntry(target, name) - else -> RemoteWorkspaceIntent.DeleteFileEntry(target) - }) - } - }) { Text(stringResource(label)) } - } - if (current == FileListAction.DELETE) Text(target, color = MaterialTheme.colorScheme.onSurfaceVariant) - else OutlinedTextField(value = name, onValueChange = { name = it }, label = { Text(stringResource(R.string.workspace_file_name)) }, - modifier = Modifier.fillMaxWidth(), enabled = !state.files.busy, singleLine = true) - if (state.files.busy) LinearProgressIndicator(Modifier.fillMaxWidth()) - if (state.files.failed || uploadFailed) Text((if (uploadFailed) null else state.files.errorDetail) ?: stringResource(R.string.workspace_files_failed), color = MaterialTheme.colorScheme.error) - } - } - } - - RuntimeFileEditorDialog(state.files, onIntent) -} - -/** Projects transfer state; KMP retains the immutable host/path used by retry. */ -@Composable -internal fun RuntimeDownloadStatus(download: RemoteFileDownloadUiState, onIntent: (RemoteWorkspaceIntent) -> Unit) { - val target = when (download) { - RemoteFileDownloadUiState.None -> return - is RemoteFileDownloadUiState.Loading -> download.target - is RemoteFileDownloadUiState.AwaitingSave -> download.target - is RemoteFileDownloadUiState.Saved -> download.target - is RemoteFileDownloadUiState.Failed -> download.target - } - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { - Column(Modifier.weight(1f)) { - Text(target.displayName.ifBlank { target.path.substringAfterLast('/') }, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall) - Text(download.statusText(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - if (download is RemoteFileDownloadUiState.Loading || download is RemoteFileDownloadUiState.AwaitingSave) { - CircularProgressIndicator(Modifier.size(20.dp), color = MaterialTheme.colorScheme.onSurface, strokeWidth = 2.dp) - } - if (download is RemoteFileDownloadUiState.Failed && download.retryable) { - TextButton(onClick = { onIntent(RemoteWorkspaceIntent.RetryDownload) }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface)) { - Text(stringResource(R.string.chat_retry)) - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspacePickerDialog.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspacePickerDialog.kt deleted file mode 100644 index 6b9995d158..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/RuntimeWorkspacePickerDialog.kt +++ /dev/null @@ -1,113 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.* -import androidx.compose.runtime.* -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import com.openbitfun.mobile.core.feature.workspace.WorkspaceReferenceFailure - -/** Typed reference failures from the shared store, mapped to copy. */ -internal fun workspaceReferenceFailureText(failure: WorkspaceReferenceFailure): Int = when (failure) { - WorkspaceReferenceFailure.ID_REFERENCES_UNSUPPORTED -> R.string.workspace_reference_unsupported - WorkspaceReferenceFailure.UNKNOWN_ID -> R.string.workspace_reference_unknown - WorkspaceReferenceFailure.AMBIGUOUS_PATH -> R.string.workspace_reference_ambiguous -} - -/** Native presentation only; directory access and workspace mutation stay in KMP. */ -@Composable -internal fun RuntimeWorkspacePickerDialog( - state: RemoteWorkspaceUiState.Ready, - onIntent: (RemoteWorkspaceIntent) -> Unit, - onDismiss: () -> Unit, -) { - val actionColors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface) - val selectionColors = RadioButtonDefaults.colors(selectedColor = MaterialTheme.colorScheme.onSurface) - var path by rememberSaveable { mutableStateOf("") } - var connectionId by rememberSaveable { mutableStateOf(null) } - var browsing by rememberSaveable { mutableStateOf(false) } - var submittedPath by rememberSaveable { mutableStateOf(null) } - var submittedConnectionId by rememberSaveable { mutableStateOf(null) } - var submittedWorkspaceId by rememberSaveable { mutableStateOf(null) } - LaunchedEffect(state.busy, state.selected, state.loadFailure, state.workspaceReferenceFailure, submittedPath, submittedConnectionId, submittedWorkspaceId) { - val targetPath = submittedPath ?: return@LaunchedEffect - if (state.busy || state.loadFailure || state.workspaceReferenceFailure != null) return@LaunchedEffect - val selected = state.selected ?: return@LaunchedEffect - // ID first: a submitted ID is confirmed only by the same ID. Hand-typed paths have none. - val confirmed = submittedWorkspaceId?.let { it == selected.workspaceId } - ?: (selected.path == targetPath && selected.remoteConnectionId == submittedConnectionId) - if (confirmed) onDismiss() - } - fun open(targetPath: String, targetConnection: String?, sshHost: String?, workspaceId: String?) { - submittedPath = targetPath - submittedConnectionId = targetConnection - submittedWorkspaceId = workspaceId - onIntent(RemoteWorkspaceIntent.SelectWorkspace(targetPath, targetConnection, sshHost, false, workspaceId)) - } - if (browsing) RuntimeDirectoryPickerDialog( - state.directoryPicker, connectionId, onIntent, - { path = it; browsing = false }, { browsing = false }, - ) - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(stringResource(R.string.workspace_open_path)) }, - text = { - Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(8.dp)) { - TextButton(colors = actionColors, onClick = { connectionId = null; path = "" }, enabled = !state.busy) { - RadioButton(colors = selectionColors, selected = connectionId == null, onClick = null) - Text(stringResource(R.string.workspace_target_device)) - } - state.savedConnections.forEach { connection -> - TextButton(colors = actionColors, onClick = { connectionId = connection.id; path = "" }, enabled = !state.busy) { - RadioButton(colors = selectionColors, selected = connectionId == connection.id, onClick = null) - Text(connection.name) - } - } - if (state.savedConnectionsFailure) Text(stringResource(R.string.workspace_connections_failed), - color = MaterialTheme.colorScheme.error) - OutlinedTextField(value = path, onValueChange = { path = it }, singleLine = true, - label = { Text(stringResource(R.string.workspace_target_path)) }, - enabled = !state.busy, modifier = Modifier.fillMaxWidth()) - TextButton(colors = actionColors, enabled = !state.busy, onClick = { - browsing = true - onIntent(RemoteWorkspaceIntent.BrowseWorkspaceDirectories(path.ifBlank { "/" }, connectionId, false)) - }) { Text(stringResource(R.string.workspace_choose_folder)) } - if (state.loadFailure) { - Text(stringResource(R.string.workspace_failed), color = MaterialTheme.colorScheme.error) - TextButton(colors = actionColors, onClick = { onIntent(RemoteWorkspaceIntent.Load) }, enabled = !state.busy) { - Text(stringResource(R.string.sessions_refresh)) - } - } - state.workspaceReferenceFailure?.let { failure -> - Text(stringResource(workspaceReferenceFailureText(failure)), color = MaterialTheme.colorScheme.error) - } - state.workspaces.forEach { workspace -> - TextButton(colors = actionColors, enabled = !state.busy && !state.isSelected(workspace), onClick = { - open(workspace.path, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId) - }, modifier = Modifier.fillMaxWidth()) { - Column(Modifier.fillMaxWidth()) { - Text(workspace.displayName, style = MaterialTheme.typography.bodyMedium) - Text(workspace.path, style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - } - } - }, - confirmButton = { - // A hand-typed path never carries an ID; it is sent as the legacy projection only. - TextButton(colors = actionColors, enabled = !state.busy && path.isNotBlank(), onClick = { open(path.trim(), connectionId, null, null) }) { - Text(stringResource(R.string.workspace_open_path)) - } - }, - dismissButton = { TextButton(colors = actionColors, onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, - ) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/SessionActionSheet.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/SessionActionSheet.kt deleted file mode 100644 index c1bae373b9..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/SessionActionSheet.kt +++ /dev/null @@ -1,639 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.rememberModalBottomSheetState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.shadow -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.unit.sp -import androidx.compose.ui.window.Popup -import androidx.compose.ui.window.PopupPositionProvider -import androidx.compose.ui.window.PopupProperties -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.settings.statusText -import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface -import com.openbitfun.mobile.core.feature.session.SessionActionCapabilities -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.session.SessionTimePresentation -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry - -internal const val SESSION_ACTIONS_TEST_TAG: String = "session-actions" -internal const val SESSION_DETAILS_TEST_TAG: String = "session-details" - -/** - * A session row's overflow menu, ported from - * `pages/components/SessionActionSurface.ets`. - * - * Which rows appear is [SessionActionCapabilities]' answer, not this file's: - * archive and export are local-storage operations that a remote session cannot - * offer however it is typed, and while a command is in flight nothing is - * offered at all because the row this was opened over may not survive the - * answer. - * - * Deleting replaces the action list in place instead of stacking a dialog on - * top of it, as the source does. Two layers of scrim over a bottom sheet gives - * the confirmation two dismiss gestures with different meanings — tapping - * outside would cancel the delete or the whole menu depending on how far the - * finger landed. - * - * Takes the fields rather than the session: `RemoteSession` lives in - * `core-domain`, which the app is not allowed to import (design doc §5 rule 3), - * and re-exporting a domain type through `core-feature` just to name it here - * would defeat the rule rather than satisfy it. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun SessionActionSheet( - title: String, - status: String, - capabilities: SessionActionCapabilities, - onViewDetails: () -> Unit, - onArchive: (() -> Unit)? = null, - onExport: (() -> Unit)? = null, - onDelete: () -> Unit, - onDismiss: () -> Unit, -) { - // Deliberately not `rememberSaveable`: the confirmation is a step inside a - // sheet that is itself gone after a process death, and restoring "about to - // delete" without the tap that got there is not a state worth rebuilding. - var confirmingDelete by remember { mutableStateOf(false) } - // Archive and export are local-storage operations a remote session can never - // offer, so those callbacks are optional: a surface without them renders no - // row instead of rendering one that does nothing. - val showArchive = capabilities.canArchive && onArchive != null - val showExport = capabilities.canExport && onExport != null - - ModalBottomSheet( - onDismissRequest = onDismiss, - sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), - shape = RoundedCornerShape( - topStart = MobileDesignGeometry.PopoverRadius, - topEnd = MobileDesignGeometry.PopoverRadius, - ), - containerColor = MaterialTheme.colorScheme.surface, - tonalElevation = 0.dp, - dragHandle = null, - modifier = Modifier - .testTag(SESSION_ACTIONS_TEST_TAG) - .border( - width = 1.dp, - color = MaterialTheme.colorScheme.outlineVariant, - shape = RoundedCornerShape( - topStart = MobileDesignGeometry.PopoverRadius, - topEnd = MobileDesignGeometry.PopoverRadius, - ), - ), - ) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(start = 16.dp, end = 16.dp, top = 10.dp, bottom = 18.dp), - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Box( - modifier = Modifier - .padding(bottom = 10.dp) - .size(width = 36.dp, height = 4.dp) - .clip(RoundedCornerShape(2.dp)) - .background(MaterialTheme.colorScheme.outlineVariant), - ) - Row( - modifier = Modifier.fillMaxWidth().height(52.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(3.dp), - ) { - Text( - stringResource(R.string.session_actions), - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - title.ifBlank { stringResource(R.string.sidebar_untitled) }, - fontSize = 15.sp, - fontWeight = FontWeight.Medium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Box( - modifier = Modifier - .size(40.dp) - .clip(RoundedCornerShape(20.dp)) - .clickable(onClick = onDismiss), - contentAlignment = Alignment.Center, - ) { - Icon( - painter = painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - } - - HorizontalDivider(modifier = Modifier.padding(top = 6.dp, bottom = 8.dp)) - - if (confirmingDelete) { - Text( - stringResource(R.string.session_delete_confirm), - fontSize = 13.sp, - lineHeight = 19.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth().padding(top = 4.dp), - ) - Row( - modifier = Modifier.fillMaxWidth().padding(top = 12.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - ConfirmationButton( - label = stringResource(R.string.common_cancel), - containerColor = MaterialTheme.colorScheme.surfaceVariant, - contentColor = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.weight(1f), - onClick = { confirmingDelete = false }, - ) - ConfirmationButton( - label = stringResource(R.string.session_delete), - containerColor = MaterialTheme.colorScheme.error, - contentColor = MaterialTheme.colorScheme.onError, - modifier = Modifier.weight(1f), - onClick = { - onDelete() - onDismiss() - }, - ) - } - return@Column - } - - if (capabilities.canViewDetails) { - ActionRow(R.drawable.ic_symbol_info_circle, stringResource(R.string.session_view_details)) { - onViewDetails() - onDismiss() - } - } - if (showArchive) { - val archived = status.equals("archived", ignoreCase = true) - val label = stringResource( - if (archived) R.string.session_unarchive else R.string.session_archive, - ) - ActionRow(R.drawable.ic_symbol_archivebox, label) { - onArchive() - onDismiss() - } - } - if (showExport) { - // The label says "Copy Markdown" for Harmony parity, but Android - // opens an Intent.ACTION_SEND text/plain share sheet; this icon - // must not promise a file or cloud export. - ActionRow( - R.drawable.ic_symbol_doc_text_badge_arrow_up, - stringResource(R.string.general_chat_export), - ) { - onExport() - onDismiss() - } - } - if (capabilities.canDelete) { - if (showArchive || showExport) { - HorizontalDivider(modifier = Modifier.padding(vertical = 6.dp)) - } - ActionRow( - icon = R.drawable.ic_symbol_trash, - label = stringResource(R.string.session_delete), - destructive = true, - ) { confirmingDelete = true } - } - } - } -} - -/** Wide-sidebar counterpart of [SessionActionSheet]. It renders the same rows - * next to the row that opened it and keeps the native popup lifecycle arrowless. */ -@Composable -internal fun SessionActionPopup( - anchorBounds: IntRect, - title: String, - status: String, - capabilities: SessionActionCapabilities, - onViewDetails: () -> Unit, - onArchive: (() -> Unit)? = null, - onExport: (() -> Unit)? = null, - onDelete: () -> Unit, - onDismiss: () -> Unit, -) { - var confirmingDelete by remember { mutableStateOf(false) } - val showArchive = capabilities.canArchive && onArchive != null - val showExport = capabilities.canExport && onExport != null - val targetBounds = anchorBounds - val positionProvider = remember(targetBounds) { - object : PopupPositionProvider { - override fun calculatePosition( - anchorBounds: IntRect, - windowSize: IntSize, - layoutDirection: LayoutDirection, - popupContentSize: IntSize, - ): IntOffset { - val desiredX = targetBounds.right + 6 - val desiredY = ( - targetBounds.top + targetBounds.bottom - - popupContentSize.height - ) / 2 - return IntOffset( - x = desiredX.coerceIn( - 8, - (windowSize.width - popupContentSize.width - 8).coerceAtLeast(8), - ), - y = desiredY.coerceIn( - 8, - (windowSize.height - popupContentSize.height - 8).coerceAtLeast(8), - ), - ) - } - } - } - Popup( - popupPositionProvider = positionProvider, - onDismissRequest = onDismiss, - properties = PopupProperties(focusable = true), - ) { - Column( - modifier = Modifier - .width(300.dp) - .shadow(20.dp, RoundedCornerShape(MobileDesignGeometry.PopoverRadius)) - .clip(RoundedCornerShape(MobileDesignGeometry.PopoverRadius)) - .background(MaterialTheme.colorScheme.surface) - .border( - 1.dp, - MaterialTheme.colorScheme.outlineVariant, - RoundedCornerShape(MobileDesignGeometry.PopoverRadius), - ) - .padding(start = 16.dp, end = 16.dp, top = 10.dp, bottom = 18.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth().height(52.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { - Text( - stringResource(R.string.session_actions), - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - title.ifBlank { stringResource(R.string.sidebar_untitled) }, - fontSize = 15.sp, - fontWeight = FontWeight.Medium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Box( - modifier = Modifier.size(40.dp).clip(RoundedCornerShape(20.dp)).clickable(onClick = onDismiss), - contentAlignment = Alignment.Center, - ) { - Icon( - painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - } - HorizontalDivider(modifier = Modifier.padding(top = 6.dp, bottom = 8.dp)) - if (confirmingDelete) { - Text( - stringResource(R.string.session_delete_confirm), - fontSize = 13.sp, - lineHeight = 19.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth().padding(top = 4.dp), - ) - Row( - modifier = Modifier.fillMaxWidth().padding(top = 12.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - ConfirmationButton( - stringResource(R.string.common_cancel), - MaterialTheme.colorScheme.surfaceVariant, - MaterialTheme.colorScheme.onSurface, - Modifier.weight(1f), - ) { confirmingDelete = false } - ConfirmationButton( - stringResource(R.string.session_delete), - MaterialTheme.colorScheme.error, - MaterialTheme.colorScheme.onError, - Modifier.weight(1f), - ) { - onDelete() - onDismiss() - } - } - } else { - if (capabilities.canViewDetails) { - ActionRow(R.drawable.ic_symbol_info_circle, stringResource(R.string.session_view_details)) { - onViewDetails(); onDismiss() - } - } - if (showArchive) { - ActionRow( - R.drawable.ic_symbol_archivebox, - stringResource( - if (status.equals("archived", true)) R.string.session_unarchive - else R.string.session_archive, - ), - ) { onArchive(); onDismiss() } - } - if (showExport) { - ActionRow( - R.drawable.ic_symbol_doc_text_badge_arrow_up, - stringResource(R.string.general_chat_export), - ) { - onExport(); onDismiss() - } - } - if (capabilities.canDelete) { - if (showArchive || showExport) { - HorizontalDivider(modifier = Modifier.padding(vertical = 6.dp)) - } - ActionRow( - R.drawable.ic_symbol_trash, - stringResource(R.string.session_delete), - destructive = true, - ) { confirmingDelete = true } - } - } - } - } -} - -@Composable -private fun ConfirmationButton( - label: String, - containerColor: androidx.compose.ui.graphics.Color, - contentColor: androidx.compose.ui.graphics.Color, - modifier: Modifier = Modifier, - onClick: () -> Unit, -) { - Box( - modifier = modifier - .height(44.dp) - .clip(RoundedCornerShape(8.dp)) - .background(containerColor) - .clickable(onClick = onClick), - contentAlignment = Alignment.Center, - ) { - Text( - text = label, - color = contentColor, - fontSize = 14.sp, - fontWeight = if (containerColor == MaterialTheme.colorScheme.error) { - FontWeight.Medium - } else { - FontWeight.Normal - }, - maxLines = 1, - ) - } -} - -@Composable -private fun ActionRow( - @DrawableRes icon: Int, - label: String, - destructive: Boolean, - onClick: () -> Unit, -) { - val tint = if (destructive) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.colorScheme.onSurfaceVariant - } - Row( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(8.dp)) - .clickable(onClick = onClick) - .heightIn(min = 46.dp) - .padding(horizontal = 10.dp), - horizontalArrangement = Arrangement.spacedBy(12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(icon), - contentDescription = null, - tint = tint, - // The source draws these at fontSize 19, a size up from a list - // glyph: this sheet is where a session gets destroyed. - modifier = Modifier.size(19.dp), - ) - Text( - label, - fontSize = 15.sp, - color = if (destructive) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } -} - -@Composable -private fun ActionRow(@DrawableRes icon: Int, label: String, onClick: () -> Unit) { - ActionRow(icon, label, destructive = false, onClick = onClick) -} - -/** - * The read-only facts about a session, ported from - * `pages/components/SessionDetailsView.ets`. - * - * Every row is conditional on having something to say. A timestamp the desktop - * never sent is left out rather than rendered as "unknown", which is the same - * rule the list rows follow. - * - * Takes fields rather than the session for the reason [SessionActionSheet] does. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun SessionDetailsSheet( - title: String, - agentType: String, - status: String, - workspaceName: String?, - workspacePath: String?, - createdAt: String, - updatedAt: String, - messageCount: Int, - placement: SettingsPlacement, - onDismiss: () -> Unit, -) { - val now = remember(createdAt, updatedAt) { System.currentTimeMillis() } - val created = relativeTimeText( - remember(createdAt, now) { SessionTimePresentation.relative(createdAt, now) }, - ) - val updated = relativeTimeText( - remember(updatedAt, now) { SessionTimePresentation.relative(updatedAt, now) }, - ) - - AdaptiveModalSurface( - visible = true, - placement = placement, - onDismissRequest = onDismiss, - ) { surfaceModifier -> - Column( - modifier = surfaceModifier - .testTag(SESSION_DETAILS_TEST_TAG) - .padding(start = 20.dp, end = 16.dp, bottom = 24.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - stringResource(R.string.session_details), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - title.ifBlank { stringResource(R.string.sidebar_untitled) }, - style = MaterialTheme.typography.titleMedium, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_close)) } - } - - HorizontalDivider(modifier = Modifier.padding(top = 12.dp)) - - Column(modifier = Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { - DetailRow( - stringResource(R.string.session_agent_type), - agentType.ifBlank { stringResource(R.string.common_unknown) }, - ) - workspaceName?.takeIf { it.isNotBlank() }?.let { - DetailRow(stringResource(R.string.session_workspace), it) - } - workspacePath?.takeIf { it.isNotBlank() }?.let { - PathRow(stringResource(R.string.session_workspace_path), it) - } - created?.let { DetailRow(stringResource(R.string.session_created_at), it) } - updated?.let { DetailRow(stringResource(R.string.session_updated_at), it) } - DetailRow( - stringResource(R.string.session_message_count), - messageCount.coerceAtLeast(0).toString(), - ) - if (status.isNotBlank()) { - DetailRow(stringResource(R.string.session_status), statusText(status)) - } - } - } - } -} - -@Composable -private fun DetailRow(label: String, value: String) { - Row( - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 52.dp) - .padding(vertical = 8.dp), - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - label, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.width(104.dp), - ) - Text( - value, - style = MaterialTheme.typography.bodyMedium, - textAlign = TextAlign.End, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - } - HorizontalDivider() -} - -/** - * A path gets its own full-width row and stays selectable. - * - * The source marks it `CopyOptions.LocalDevice` for the same reason: it is the - * one value here a user needs somewhere else, and it is too long to retype. - */ -@Composable -private fun PathRow(label: String, value: String) { - Column( - modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - label, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - SelectionContainer { - Text( - value, - style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(6.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant) - .padding(horizontal = 10.dp, vertical = 8.dp), - ) - } - } - HorizontalDivider() -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/CurrentControlCard.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/CurrentControlCard.kt deleted file mode 100644 index 6fbe8006dd..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/CurrentControlCard.kt +++ /dev/null @@ -1,137 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.defaultMinSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.common.labelRes -import com.openbitfun.mobile.core.feature.connection.RemoteControlAction -import com.openbitfun.mobile.core.feature.connection.RemoteControlSource -import com.openbitfun.mobile.core.feature.connection.RemoteControlSummary - -internal const val CURRENT_CONTROL_TEST_TAG: String = "current-control" -internal const val CONTROL_ACTION_TEST_TAG: String = "current-control-action" - -/** - * What this phone is driving right now, ported from `CurrentControlCard()`. - * - * The card answers three questions in the order the source asks them: which - * desktop, whether it is answering, and how the link was made. The third is the - * one neither screen behind this page can say on its own — the account lists - * devices and the pairing screen holds a room, and only here do the two become - * one connection with a provenance. - */ -@Composable -internal fun CurrentControlCard( - summary: RemoteControlSummary, - onDisconnect: () -> Unit, - onReconnect: () -> Unit, - modifier: Modifier, -) { - SettingsCard(modifier = modifier.testTag(CURRENT_CONTROL_TEST_TAG)) { - Row( - modifier = Modifier - .fillMaxWidth() - .defaultMinSize(minHeight = 92.dp) - .padding(horizontal = 18.dp, vertical = 16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(14.dp), - ) { - SettingsAvatar(icon = R.drawable.ic_symbol_desktop, diameter = 40) - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - Text( - stringResource(R.string.remote_settings_desktop_product), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - summary.desktopName.ifBlank { - stringResource(R.string.remote_settings_no_desktop) - }, - style = MaterialTheme.typography.titleMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - stringResource(summary.phase.labelRes()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - when (summary.action) { - RemoteControlAction.DISCONNECT -> SettingsChip( - label = stringResource(R.string.remote_settings_disconnect), - enabled = true, - onClick = onDisconnect, - modifier = Modifier.testTag(CONTROL_ACTION_TEST_TAG), - ) - - RemoteControlAction.RECONNECT -> SettingsChip( - label = stringResource(R.string.remote_settings_reconnect), - enabled = true, - onClick = onReconnect, - modifier = Modifier.testTag(CONTROL_ACTION_TEST_TAG), - ) - - // Nothing is selected, so there is neither a link to leave nor one - // to try again; the account's device list below makes the first. - RemoteControlAction.NONE -> Unit - } - } - - HorizontalDivider(Modifier.padding(horizontal = 18.dp)) - - Row( - modifier = Modifier - .fillMaxWidth() - .defaultMinSize(minHeight = 52.dp) - .padding(horizontal = 18.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - // How the link was made: today only through the signed-in account. - Icon( - painterResource(R.drawable.ic_symbol_link), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.58f), - modifier = Modifier.size(20.dp), - ) - Text( - stringResource(R.string.remote_settings_connection_source), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.weight(1f), - ) - SettingsChip( - label = stringResource(summary.source.sourceLabelRes()), - enabled = true, - onClick = null, - modifier = Modifier, - ) - } - } -} - -private fun RemoteControlSource.sourceLabelRes(): Int = when (this) { - RemoteControlSource.ACCOUNT_DEVICE -> R.string.remote_settings_source_account_device - RemoteControlSource.NONE -> R.string.remote_settings_source_none -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/ModelServiceScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/ModelServiceScreen.kt deleted file mode 100644 index d4eb63b278..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/ModelServiceScreen.kt +++ /dev/null @@ -1,865 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.annotation.DrawableRes -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.defaultMinSize -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.FilledTonalButton -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextField -import androidx.compose.material3.TextFieldDefaults -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.text.input.VisualTransformation -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.chat.messageRes -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatConfigFailure -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatConfigUi -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatConnectionTestUi -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatIntent -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatModelSource -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatModelUi - -internal const val MODEL_SERVICE_TEST_TAG: String = "model-service" -internal const val MODEL_SERVICE_CURRENT_TEST_TAG: String = "model-service-current" -internal const val MODEL_SERVICE_ACCOUNT_TEST_TAG: String = "model-service-account" -internal const val MODEL_SERVICE_LOCAL_TEST_TAG: String = "model-service-local" -internal const val MODEL_SERVICE_BACK_TEST_TAG: String = "model-service-back" -internal const val MODEL_SERVICE_CLOSE_TEST_TAG: String = "model-service-close" -internal const val MODEL_SERVICE_URL_TEST_TAG: String = "model-service-url" -internal const val MODEL_SERVICE_KEY_TEST_TAG: String = "model-service-key" -internal const val MODEL_SERVICE_MODEL_TEST_TAG: String = "model-service-model" -internal const val MODEL_SERVICE_PROBE_TEST_TAG: String = "model-service-probe" -internal const val MODEL_SERVICE_SAVE_TEST_TAG: String = "model-service-save" - -/** - * The model panel, ported from `pages/components/ModelServiceSettingsPanel.ets`. - * - * Two pages behind one header, as the source is: an overview that says which - * model is answering and where it came from, and — behind the local row — the - * form that defines one. The form is not the landing page because most openings - * of this panel are to check rather than to edit, and a page of empty credential - * fields is a poor answer to "which model am I using". - * - * The middle section, the account's synced models, is a summary rather than a - * list, exactly as the source draws it: it says how many arrived and whether one - * of them is answering, and nothing on it is tappable. Picking among them is the - * composer's model control, not this panel's. - * - * @param models every model that could answer, from [GeneralChatUiState]; the - * account's arrive only while signed in. - * @param activeModelId which of [models] is answering, empty when none can. - * @param connectionTest the result of the last probe, deliberately not the result - * of the last save — testing writes nothing either way. - * @param onSave dispatches the save and answers whether the store took it, which - * decides whether the form may close. Dispatch is synchronous, so the caller can - * read the verdict back immediately; waiting for a recomposition here would close - * the form over a refusal and leave the reason on a page that has no field to - * put it beside. - */ -@Composable -internal fun ModelServiceScreen( - config: GeneralChatConfigUi, - models: List, - activeModelId: String, - failure: GeneralChatConfigFailure?, - connectionTest: GeneralChatConnectionTestUi, - onIntent: (GeneralChatIntent) -> Unit, - onSave: (GeneralChatIntent.SaveConfig) -> Boolean, - onClose: () -> Unit, - modifier: Modifier, -) { - var page by rememberSaveable { mutableStateOf(ModelServicePage.OVERVIEW) } - val leaveChild = { - page = ModelServicePage.OVERVIEW - onIntent(GeneralChatIntent.ClearConfigFailure) - onIntent(GeneralChatIntent.ClearConnectionTest) - } - BackHandler(enabled = page != ModelServicePage.OVERVIEW, onBack = leaveChild) - - Column(modifier = modifier.testTag(MODEL_SERVICE_TEST_TAG)) { - ModelServiceHeader( - title = stringResource( - when (page) { - ModelServicePage.OVERVIEW -> R.string.model_service_manage_title - ModelServicePage.ACCOUNT -> R.string.model_service_choose_account - ModelServicePage.LOCAL -> R.string.model_service_local_title - }, - ), - onBack = if (page == ModelServicePage.OVERVIEW) null else leaveChild, - onClose = onClose, - ) - - when (page) { - ModelServicePage.LOCAL -> LocalModelEditor( - config = config, - failure = failure, - connectionTest = connectionTest, - onIntent = onIntent, - onSave = onSave, - onSaved = { page = ModelServicePage.OVERVIEW }, - modifier = Modifier.weight(1f), - ) - ModelServicePage.ACCOUNT -> AccountModelSelection( - models = models.filter { it.source == GeneralChatModelSource.ACCOUNT }, - activeModelId = activeModelId, - onSelect = { - onIntent(GeneralChatIntent.SelectModel(it)) - page = ModelServicePage.OVERVIEW - }, - modifier = Modifier.weight(1f), - ) - ModelServicePage.OVERVIEW -> ModelOverview( - config = config, - models = models, - activeModelId = activeModelId, - onOpenAccount = { page = ModelServicePage.ACCOUNT }, - onSelectLocal = { - models.firstOrNull { it.source == GeneralChatModelSource.LOCAL }?.let { model -> - onIntent(GeneralChatIntent.SelectModel(model.id)) - } - }, - onEditLocal = { - page = ModelServicePage.LOCAL - onIntent(GeneralChatIntent.ClearConfigFailure) - onIntent(GeneralChatIntent.ClearConnectionTest) - }, - modifier = Modifier.weight(1f), - ) - } - } -} - -private enum class ModelServicePage { OVERVIEW, ACCOUNT, LOCAL } - -/** - * Back, title, close — the one row that stays put while the page under it swaps. - * - * [onBack] is null on the overview because there is nothing behind it, which is - * the same `if (this.showLocalEditor)` that draws the source's chevron. - */ -@Composable -private fun ModelServiceHeader(title: String, onBack: (() -> Unit)?, onClose: () -> Unit) { - Column { - Row( - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.SheetHeaderHeight) - .padding(start = 16.dp, end = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - onBack?.let { back -> - IconButton( - onClick = back, - modifier = Modifier - .padding(end = 8.dp) - .size(42.dp) - .testTag(MODEL_SERVICE_BACK_TEST_TAG), - ) { - Icon( - painterResource(R.drawable.ic_symbol_chevron_left), - contentDescription = stringResource(R.string.common_back), - modifier = Modifier.size(20.dp), - ) - } - } - Text( - title, - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - // One weight, not a weighted title beside a weighted spacer: - // two of them split the free space evenly and ellipsise a title - // that had room to spare. - modifier = Modifier.weight(1f).padding(end = 12.dp), - ) - IconButton( - onClick = onClose, - modifier = Modifier.size(MobileDesignGeometry.SelectionCloseSize) - .testTag(MODEL_SERVICE_CLOSE_TEST_TAG), - ) { - Icon( - painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - modifier = Modifier.size(18.dp), - ) - } - } - HorizontalDivider() - } -} - -@Composable -private fun ModelOverview( - config: GeneralChatConfigUi, - models: List, - activeModelId: String, - onOpenAccount: () -> Unit, - onSelectLocal: () -> Unit, - onEditLocal: () -> Unit, - modifier: Modifier, -) { - val complete = config.baseUrl.isNotBlank() && config.model.isNotBlank() && config.hasApiKey - val notConfigured = stringResource(R.string.model_service_not_configured) - val localSource = stringResource(R.string.model_service_local_source) - val accountSource = stringResource(R.string.model_service_account_source) - val active = models.firstOrNull { it.id == activeModelId } - val accountModels = models.filter { it.source == GeneralChatModelSource.ACCOUNT } - - Column( - modifier = modifier - .verticalScroll(rememberScrollState()) - .padding( - start = 16.dp, - end = 16.dp, - top = MobileDesignGeometry.ModelOverviewTopPadding, - bottom = MobileDesignGeometry.ModelOverviewBottomPadding, - ), - verticalArrangement = Arrangement.spacedBy(MobileDesignGeometry.ModelSectionGap), - ) { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - OverviewSectionHeader(stringResource(R.string.model_service_current)) - OverviewRow( - icon = R.drawable.ic_symbol_checkmark_circle_fill, - iconSize = 21, - iconTint = if (active != null) { - MaterialTheme.colorScheme.onSurface - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - title = active?.label ?: notConfigured, - // Where it came from, not what it is called: the same model name - // can arrive from this phone's own form and from the account, and - // which of the two is answering decides whose key is being spent. - subtitle = when (active?.source) { - GeneralChatModelSource.LOCAL -> localSource - GeneralChatModelSource.ACCOUNT -> accountSource - null -> "" - }, - minHeight = MobileDesignGeometry.ModelCurrentRowHeight.value.toInt(), - selected = false, - chevron = false, - onClick = null, - modifier = Modifier.testTag(MODEL_SERVICE_CURRENT_TEST_TAG), - ) - } - - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - OverviewSectionHeader(stringResource(R.string.model_service_sources)) - Column( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(MobileDesignGeometry.SettingsCompactCardRadius)) - .background(MaterialTheme.colorScheme.surfaceVariant), - ) { - ModelSourceRow( - icon = R.drawable.ic_symbol_cloud, - iconTint = if (accountModels.isEmpty()) { - MaterialTheme.colorScheme.outline - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - title = stringResource(R.string.model_service_account_summary), - subtitle = if (accountModels.isEmpty()) { - stringResource(R.string.model_service_account_empty) - } else { - stringResource(R.string.model_service_account_synced, accountModels.size) - }, - onBodyClick = onOpenAccount, - onChevronClick = onOpenAccount, - modifier = Modifier.testTag(MODEL_SERVICE_ACCOUNT_TEST_TAG), - ) - HorizontalDivider(modifier = Modifier.padding(start = 56.dp)) - ModelSourceRow( - icon = R.drawable.ic_symbol_wrench_and_screwdriver, - iconTint = MaterialTheme.colorScheme.onSurfaceVariant, - title = if (complete) config.model else notConfigured, - subtitle = if (complete) localSource else "", - onBodyClick = if (complete) onSelectLocal else onEditLocal, - onChevronClick = onEditLocal, - modifier = Modifier.testTag(MODEL_SERVICE_LOCAL_TEST_TAG), - ) - } - } - } -} - -@Composable -private fun ModelSourceRow( - @DrawableRes icon: Int, - iconTint: Color, - title: String, - subtitle: String, - onBodyClick: () -> Unit, - onChevronClick: () -> Unit, - modifier: Modifier, -) { - Row(modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Row( - modifier = Modifier - .weight(1f) - .height(MobileDesignGeometry.ModelSourceRowHeight) - .clickable(onClick = onBodyClick) - .padding(start = 16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Icon( - painterResource(icon), - contentDescription = null, - tint = iconTint, - modifier = Modifier.size(22.dp), - ) - Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { - Text( - title, - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (subtitle.isNotEmpty()) { - Text( - subtitle, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - ) - } - } - } - IconButton( - onClick = onChevronClick, - modifier = Modifier.size(44.dp), - ) { - Icon( - painterResource(R.drawable.ic_symbol_chevron_right), - contentDescription = stringResource(R.string.common_open), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - } -} - -@Composable -private fun AccountModelSelection( - models: List, - activeModelId: String, - onSelect: (String) -> Unit, - modifier: Modifier, -) { - if (models.isEmpty()) { - Text( - stringResource(R.string.model_service_account_empty), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = modifier - .fillMaxWidth() - .heightIn(min = MobileDesignGeometry.ModelEmptyAccountHeight) - .padding(horizontal = 16.dp, vertical = MobileDesignGeometry.ModelListTopPadding), - ) - return - } - Column( - modifier = modifier - .verticalScroll(rememberScrollState()) - .padding( - start = 10.dp, - end = 10.dp, - top = MobileDesignGeometry.ModelListTopPadding, - bottom = MobileDesignGeometry.ModelListBottomPadding, - ), - verticalArrangement = Arrangement.spacedBy(MobileDesignGeometry.ModelAccountRowGap), - ) { - models.forEach { model -> - Row( - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.ModelAccountRowHeight) - .clip(RoundedCornerShape(9.dp)) - .background( - if (model.id == activeModelId) MaterialTheme.colorScheme.surfaceVariant - else openBitFunColors.transparent, - ) - .clickable { onSelect(model.id) } - .padding(horizontal = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - Box(modifier = Modifier.size(20.dp), contentAlignment = Alignment.Center) { - if (model.id == activeModelId) { - Icon( - painterResource(R.drawable.ic_symbol_checkmark_circle), - contentDescription = null, - modifier = Modifier.size(16.dp), - ) - } - } - Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - model.label, - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - stringResource(R.string.model_service_account_source), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } - } -} - -/** - * The body both pages share: centred when it fits, scrolled when it does not. - * - * The source's `Scroll` centres its content, and on a phone neither of these - * pages fills the sheet — the overview is two rows and the form is three fields, - * so a top-aligned column would leave the whole lower half empty and hang the - * content off the header. `heightIn(min = maxHeight)` is what lets - * [Arrangement.Center] mean anything inside a scroller, whose own height is - * unbounded: it floors the column at the viewport, and anything taller than that - * scrolls from the top as usual. - */ -@Composable -private fun CentredPage(modifier: Modifier, content: @Composable ColumnScope.() -> Unit) { - BoxWithConstraints(modifier = modifier) { - // A sheet can hand its content an unbounded height, and `maxHeight` is - // then a number no page should be floored at. Nothing to centre against - // in that case, so the column simply wraps. - val floor = if (constraints.hasBoundedHeight) maxHeight else 0.dp - Column( - modifier = Modifier - .verticalScroll(rememberScrollState()) - .heightIn(min = floor) - .padding(start = 22.dp, end = 22.dp, top = 18.dp, bottom = 30.dp), - verticalArrangement = Arrangement.spacedBy(20.dp, Alignment.CenterVertically), - content = content, - ) - } -} - -@Composable -private fun OverviewSectionHeader(text: String) { - Text( - text, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), - ) -} - -/** - * One soft-filled row of the overview. - * - * [selected] draws the check the source puts on whichever model is actually in - * use, so the answer to "which one" survives there being more than one row. - */ -@Composable -private fun OverviewRow( - @DrawableRes icon: Int, - iconSize: Int, - iconTint: Color, - title: String, - subtitle: String, - minHeight: Int, - selected: Boolean, - chevron: Boolean, - onClick: (() -> Unit)?, - modifier: Modifier, -) { - Row( - modifier = modifier - .fillMaxWidth() - .clip(RoundedCornerShape(8.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant) - .then(if (onClick == null) Modifier else Modifier.clickable(onClick = onClick)) - .defaultMinSize(minHeight = minHeight.dp) - .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - // A fixed 28dp box rather than the glyph's own size: the source's icons - // are drawn at different weights and the text column has to start in the - // same place on every row regardless. - Box(modifier = Modifier.size(28.dp), contentAlignment = Alignment.Center) { - Icon( - painterResource(icon), - contentDescription = null, - tint = iconTint, - modifier = Modifier.size(iconSize.dp), - ) - } - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(3.dp), - ) { - Text( - title, - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (subtitle.isNotEmpty()) { - Text( - subtitle, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - if (selected) { - Icon( - painterResource(R.drawable.ic_symbol_checkmark_circle_fill), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(18.dp), - ) - } - if (chevron) { - Icon( - painterResource(R.drawable.ic_symbol_chevron_right), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - } -} - -/** - * The provider form. - * - * The key field starts empty even when a key is stored, and a blank field means - * "keep it": a saved key is never read back out of the keystore for display, so - * there is nothing here for a screenshot or an accessibility dump to leak. - * Forgetting a key is an explicit choice rather than an empty field. - * - * The two visible fields survive process death and the key deliberately does not - * — saved instance state is a plain file, and no secret goes into one. - */ -@Composable -private fun LocalModelEditor( - config: GeneralChatConfigUi, - failure: GeneralChatConfigFailure?, - connectionTest: GeneralChatConnectionTestUi, - onIntent: (GeneralChatIntent) -> Unit, - onSave: (GeneralChatIntent.SaveConfig) -> Boolean, - onSaved: () -> Unit, - modifier: Modifier, -) { - var apiUrl by rememberSaveable(config.baseUrl) { mutableStateOf(config.baseUrl) } - var modelName by rememberSaveable(config.model) { mutableStateOf(config.model) } - var apiKey by remember(config.hasApiKey) { mutableStateOf("") } - var clearApiKey by rememberSaveable(config.hasApiKey) { mutableStateOf(false) } - // Not saveable either: which way the eye is pointing is only interesting - // while the field is on screen, and restoring it as "revealed" would put a - // key back in the clear on a screen the user has just returned to. - var revealKey by remember(config.hasApiKey) { mutableStateOf(false) } - val busy = connectionTest.running - // The button is disabled rather than left to fail: a probe with no credential - // to send would be answered 401 by a perfectly healthy endpoint. - val testable = apiKey.isNotBlank() || (config.hasApiKey && !clearApiKey) - // Any edit invalidates the last verdict — it was about the endpoint as it was - // typed then, and leaving "passed" under a changed URL would vouch for one - // the app has never called. - val edited = { onIntent(GeneralChatIntent.ClearConnectionTest) } - - CentredPage(modifier = modifier) { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - FieldLabel(stringResource(R.string.model_service_api_url), trailing = "") - SoftTextField( - value = apiUrl, - onValueChange = { apiUrl = it; edited() }, - placeholder = stringResource(R.string.model_service_api_url_placeholder), - isError = failure == GeneralChatConfigFailure.INVALID_URL, - keyboardType = KeyboardType.Uri, - password = false, - trailing = null, - enabled = !busy, - modifier = Modifier.testTag(MODEL_SERVICE_URL_TEST_TAG), - ) - } - - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - FieldLabel( - stringResource(R.string.model_service_api_key), - trailing = if (config.hasApiKey && !clearApiKey) { - stringResource(R.string.model_service_key_saved) - } else { - "" - }, - ) - SoftTextField( - value = apiKey, - onValueChange = { - apiKey = it - // Typing a key and asking to forget one are contradictory, and - // the newer of the two is the one the user meant. - if (it.isNotEmpty()) clearApiKey = false - edited() - }, - placeholder = stringResource( - if (config.hasApiKey && !clearApiKey) { - R.string.model_service_api_key_keep_placeholder - } else { - R.string.model_service_api_key_placeholder - }, - ), - isError = failure == GeneralChatConfigFailure.API_KEY_REQUIRED, - keyboardType = KeyboardType.Password, - password = !revealKey, - // The source's eye, which exists because an API key is pasted or - // typed once and a mistyped one fails as an authentication error - // hours later, with nothing on screen to check it against. - trailing = { - IconButton(onClick = { revealKey = !revealKey }, enabled = !busy) { - Icon( - painterResource( - if (revealKey) { - R.drawable.ic_symbol_eye - } else { - R.drawable.ic_symbol_eye_slash - }, - ), - contentDescription = stringResource( - if (revealKey) { - R.string.model_service_hide_key - } else { - R.string.model_service_show_key - }, - ), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(21.dp), - ) - } - }, - enabled = !busy, - modifier = Modifier.testTag(MODEL_SERVICE_KEY_TEST_TAG), - ) - if (config.hasApiKey) { - // A line of text rather than a switch, as the source draws it: the - // choice is one-off and destructive, and it reads as the sentence - // it is — "clear the saved key" — rather than as a setting whose - // on-state has to be decoded before it can be trusted. - Text( - stringResource( - if (clearApiKey) { - R.string.model_service_keep_key - } else { - R.string.model_service_clear_key - }, - ), - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium), - color = if (clearApiKey) { - MaterialTheme.colorScheme.onSurface - } else { - MaterialTheme.colorScheme.error - }, - modifier = Modifier - .fillMaxWidth() - .clickable(enabled = !busy) { - clearApiKey = !clearApiKey - apiKey = "" - edited() - } - .padding(vertical = 4.dp), - ) - } - } - - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - FieldLabel(stringResource(R.string.model_service_model_name), trailing = "") - SoftTextField( - value = modelName, - onValueChange = { modelName = it; edited() }, - placeholder = stringResource(R.string.model_service_model_placeholder), - isError = failure == GeneralChatConfigFailure.MODEL_REQUIRED, - keyboardType = KeyboardType.Text, - password = false, - trailing = null, - enabled = !busy, - modifier = Modifier.testTag(MODEL_SERVICE_MODEL_TEST_TAG), - ) - } - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - FilledTonalButton( - onClick = { - onIntent(GeneralChatIntent.TestConnection(apiUrl, modelName, apiKey, clearApiKey)) - }, - enabled = !busy && testable, - shape = RoundedCornerShape(25.dp), - modifier = Modifier.weight(1f).height(44.dp).testTag(MODEL_SERVICE_PROBE_TEST_TAG), - ) { - Text( - stringResource( - if (busy) R.string.model_service_testing else R.string.model_service_test_connection, - ), - ) - } - Button( - onClick = { - val accepted = onSave( - GeneralChatIntent.SaveConfig(apiUrl, modelName, apiKey, clearApiKey), - ) - if (accepted) onSaved() - }, - enabled = !busy, - shape = RoundedCornerShape(25.dp), - modifier = Modifier.weight(1f).height(44.dp).testTag(MODEL_SERVICE_SAVE_TEST_TAG), - ) { - Text(stringResource(R.string.model_service_save)) - } - } - - if (!testable) { - Text( - stringResource(R.string.model_service_test_needs_key), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - - failure?.let { reason -> - Text( - stringResource(reason.messageRes()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - - connectionTest.failure?.let { reason -> - Text( - stringResource(reason.messageRes()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - - if (connectionTest.passed) { - Text( - stringResource(R.string.model_service_test_success), - style = MaterialTheme.typography.bodySmall, - color = openBitFunColors.statusSuccess, - ) - } - } -} - -/** A field's name, and on the right whatever the field admits about itself. */ -@Composable -private fun FieldLabel(text: String, trailing: String) { - Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text( - text, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium), - color = MaterialTheme.colorScheme.onSurface, - ) - Spacer(Modifier.weight(1f)) - if (trailing.isNotEmpty()) { - Text( - trailing, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -/** - * A filled box with no label of its own and no underline, which is how the - * source's `TextInput` on `SOFT` reads. Material's floating label would put the - * field's name in two places at once and move one of them while the user types. - */ -@Composable -private fun SoftTextField( - value: String, - onValueChange: (String) -> Unit, - placeholder: String, - isError: Boolean, - keyboardType: KeyboardType, - password: Boolean, - trailing: (@Composable () -> Unit)?, - enabled: Boolean, - modifier: Modifier, -) { - TextField( - value = value, - onValueChange = onValueChange, - placeholder = { Text(placeholder, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - trailingIcon = trailing, - singleLine = true, - enabled = enabled, - isError = isError, - shape = RoundedCornerShape(8.dp), - visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None, - keyboardOptions = KeyboardOptions(keyboardType = keyboardType), - colors = TextFieldDefaults.colors( - focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, - unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, - disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant, - focusedIndicatorColor = openBitFunColors.transparent, - unfocusedIndicatorColor = openBitFunColors.transparent, - disabledIndicatorColor = openBitFunColors.transparent, - ), - modifier = modifier.fillMaxWidth().defaultMinSize(minHeight = 48.dp), - ) -} - -internal fun GeneralChatConfigFailure.messageRes(): Int = when (this) { - GeneralChatConfigFailure.INVALID_URL -> R.string.model_service_invalid_url - GeneralChatConfigFailure.MODEL_REQUIRED -> R.string.model_service_model_required - GeneralChatConfigFailure.API_KEY_REQUIRED -> R.string.model_service_api_key_required - GeneralChatConfigFailure.SECURE_STORAGE -> R.string.model_service_secure_store_failed -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/PermissionModeCard.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/PermissionModeCard.kt deleted file mode 100644 index cebd32261e..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/PermissionModeCard.kt +++ /dev/null @@ -1,330 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.defaultMinSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry -import com.openbitfun.mobile.core.feature.session.PermissionModeFailure -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.SessionPermissionMode - -internal const val FULL_ACCESS_CONFIRM_TEST_TAG: String = "full-access-confirm" -internal const val PERMISSION_SECTION_TEST_TAG: String = "permission-section" - -/** - * Whether the desktop runs a tool without asking, ported from - * `PermissionSectionHeader()` + `PermissionModeCard()`. - * - * The consequential setting on either client, which is why each mode carries the - * sentence that says what it will do and why the widest one is a two-step choice - * with its own red card. - * - * It belongs to the desktop rather than to one of its sessions — both permission - * commands go out unaddressed — so it sits on the settings page beside the - * connection it describes, where the source puts it, and needs no session open to - * be asked or answered. - * - * Always on the settings page. With no Ready session store ([state] null) there - * is no desktop to be permitted by, so the section stays in place but disabled — - * rows faded and inert, the connection hint under them — rather than vanishing - * and moving the rest of the page. - */ -@Composable -internal fun PermissionSection( - state: RemoteSessionUiState.Ready?, - connected: Boolean, - onIntent: (RemoteSessionIntent) -> Unit, - modifier: Modifier, -) { - // Cleared whenever the mode changes underneath it: a confirmation left - // standing after a successful change would confirm the wrong thing. - val permissionMode = state?.permissionMode - // Nothing to command without a Ready store, whatever the link says. - val live = state != null && connected - var confirmFullAccess by rememberSaveable(permissionMode, live) { mutableStateOf(false) } - val refreshEnabled = live && state?.busy == false - val selectEnabled = refreshEnabled && permissionMode != SessionPermissionMode.UNKNOWN - - Column( - modifier = modifier.fillMaxWidth().testTag(PERMISSION_SECTION_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - SettingsSectionHeader( - stringResource(R.string.permission_title), - modifier = Modifier.weight(1f), - ) - // Gone rather than disabled while there is no desktop answering, as - // `if (this.canManagePermissions())` has it: a refresh that cannot - // reach anything is not an action the page should keep offering, and - // the line under the modes already says why. - if (live) { - TextButton( - onClick = { onIntent(RemoteSessionIntent.RefreshPermissionMode) }, - enabled = refreshEnabled, - ) { Text(stringResource(R.string.sessions_refresh)) } - } - } - - SettingsCard( - modifier = Modifier, - radius = MobileDesignGeometry.SettingsProminentCardRadius, - ) { - Text( - stringResource(R.string.permission_scope), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(start = 18.dp, end = 18.dp, top = 16.dp, bottom = 4.dp), - ) - PERMISSION_MODES.forEachIndexed { index, entry -> - if (index > 0) HorizontalDivider(Modifier.padding(horizontal = 18.dp)) - PermissionModeRow( - label = stringResource(entry.label), - description = stringResource(entry.description), - selected = permissionMode == entry.mode, - enabled = selectEnabled, - onSelect = { - // Full access removes every confirmation the desktop - // would otherwise ask for, so this one is confirmed. - if (entry.mode == SessionPermissionMode.FULL_ACCESS) { - confirmFullAccess = true - } else { - confirmFullAccess = false - onIntent(RemoteSessionIntent.SetPermissionMode(entry.mode)) - } - }, - ) - } - PermissionStatus(state = state, connected = live) - - // Inside the card, under the row it is about, where the source puts - // it. Below the card it would read as a fourth section of the page - // rather than as the second half of choosing Full access. - if (confirmFullAccess) { - FullAccessConfirmation( - enabled = selectEnabled, - onCancel = { confirmFullAccess = false }, - onConfirm = { - onIntent( - RemoteSessionIntent.SetPermissionMode( - SessionPermissionMode.FULL_ACCESS, - ), - ) - confirmFullAccess = false - }, - ) - } - } - } -} - -/** - * One mode. - * - * A checkmark rather than a radio button, which is what `PermissionModeRow` - * draws: the choice is remembered on the desktop, not made in this card, so the - * glyph reports the desktop's answer rather than offering three empty slots. A - * row that cannot be changed fades whole, the way the source's `.opacity(0.54)` - * does, instead of leaving a lit label above a dead control. - */ -@Composable -private fun PermissionModeRow( - label: String, - description: String, - selected: Boolean, - enabled: Boolean, - onSelect: () -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .selectable(selected = selected, enabled = enabled, onClick = onSelect) - .defaultMinSize(minHeight = 72.dp) - .padding(horizontal = 18.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - val alpha = if (enabled) 1f else 0.54f - // Ahead of the label, as the source draws it, and reserved whether or - // not it is filled so the three rows keep one left edge. Leading rather - // than trailing because it reads as the answer to "which one is on" - // before the labels are read, not as a tick beside one of them. - Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) { - if (selected) { - Icon( - painterResource(R.drawable.ic_symbol_checkmark_circle_fill), - contentDescription = null, - tint = MaterialTheme.colorScheme.primary.copy(alpha = alpha), - modifier = Modifier.size(22.dp), - ) - } - } - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - Text( - label, - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), - color = MaterialTheme.colorScheme.onSurface.copy(alpha = alpha), - ) - Text( - description, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha), - ) - } - } -} - -/** One line under the modes: loading, unreachable, or which command failed. */ -@Composable -private fun ColumnScope.PermissionStatus(state: RemoteSessionUiState.Ready?, connected: Boolean) { - if (state == null || !connected) { - Text( - stringResource(R.string.permission_needs_connection), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(start = 18.dp, end = 18.dp, top = 4.dp, bottom = 16.dp), - ) - return - } - val failure = state.permissionModeFailure - val text = when { - failure == PermissionModeFailure.LOAD -> stringResource(R.string.permission_load_failed) - failure == PermissionModeFailure.SAVE -> stringResource(R.string.permission_save_failed) - state.permissionMode == SessionPermissionMode.UNKNOWN -> stringResource(R.string.permission_unknown) - state.permissionMode == null -> stringResource(R.string.permission_loading) - else -> return - } - Text( - text, - style = MaterialTheme.typography.bodySmall, - color = if (failure == null && state.permissionMode != SessionPermissionMode.UNKNOWN) { - MaterialTheme.colorScheme.onSurfaceVariant - } else { - MaterialTheme.colorScheme.error - }, - modifier = Modifier.padding(start = 18.dp, end = 18.dp, top = 4.dp, bottom = 16.dp), - ) -} - -/** - * The second step, ported from `FullAccessConfirmation()`. - * - * A card outlined in red with a filled red confirm, rather than two equal text - * buttons on a tinted surface: this is the one control in the app that hands a - * remote machine the right to run commands unasked, and it has to look unlike - * every other row on the page. - */ -@Composable -private fun FullAccessConfirmation( - enabled: Boolean, - onCancel: () -> Unit, - onConfirm: () -> Unit, -) { - Card( - shape = RoundedCornerShape(18.dp), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), - border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), - // Inset from the card it sits in, so its red outline reads as something - // laid on the card rather than as the card's own edge. - modifier = Modifier - .fillMaxWidth() - .padding(start = 12.dp, end = 12.dp, bottom = 14.dp) - .testTag(FULL_ACCESS_CONFIRM_TEST_TAG), - ) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - Text( - stringResource(R.string.permission_full_confirm_title), - style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.error, - ) - Text( - stringResource(R.string.permission_full_confirm_body), - style = MaterialTheme.typography.bodySmall, - ) - Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { - Button( - onClick = onCancel, - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - contentColor = MaterialTheme.colorScheme.onSurface, - ), - modifier = Modifier.weight(1f), - ) { Text(stringResource(R.string.common_cancel)) } - Button( - onClick = onConfirm, - enabled = enabled, - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.error, - contentColor = MaterialTheme.colorScheme.onError, - ), - modifier = Modifier.weight(1f), - ) { Text(stringResource(R.string.permission_full_confirm_action)) } - } - } - } -} - -private class PermissionModeEntry( - val mode: SessionPermissionMode, - val label: Int, - val description: Int, -) - -private val PERMISSION_MODES = listOf( - PermissionModeEntry( - SessionPermissionMode.ASK, - R.string.permission_ask, - R.string.permission_ask_description, - ), - PermissionModeEntry( - SessionPermissionMode.AUTO, - R.string.permission_auto, - R.string.permission_auto_description, - ), - PermissionModeEntry( - SessionPermissionMode.FULL_ACCESS, - R.string.permission_full, - R.string.permission_full_description, - ), -) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/RemoteSettingsSheet.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/RemoteSettingsSheet.kt deleted file mode 100644 index b3f1e94a92..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/RemoteSettingsSheet.kt +++ /dev/null @@ -1,204 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Card -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.RadioButton -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.session.ModelCatalogFailure -import com.openbitfun.mobile.core.feature.session.ModelOption -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.modelOptions - -internal const val REMOTE_SETTINGS_TEST_TAG: String = "remote-settings" -internal const val MODEL_CATALOG_FAILURE_TEST_TAG: String = "model-catalog-failure" -internal const val MODEL_CATALOG_RETRY_TEST_TAG: String = "model-catalog-retry" - -/** - * The settings that belong to one open session. - * - * Everything a desktop carries as a whole — which desktop, how it was reached, - * who is signed in, and what it is allowed to run without asking — lives on - * the one [SettingsScreen]. What stays here is - * addressed to a session id on the wire and so has nowhere else to live. - */ -@Composable -internal fun RemoteSettingsSheet( - state: RemoteSessionUiState.Ready, - sessionId: String, - onIntent: (RemoteSessionIntent) -> Unit, - modifier: Modifier, -) { - Column( - modifier = modifier - .fillMaxWidth() - .verticalScroll(rememberScrollState()) - .testTag(REMOTE_SETTINGS_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - ModelSection(state = state, sessionId = sessionId, onIntent = onIntent) - } -} - -@Composable -private fun ModelSection( - state: RemoteSessionUiState.Ready, - sessionId: String, - onIntent: (RemoteSessionIntent) -> Unit, -) { - val fallback = stringResource(R.string.models_unnamed) - val options: List = state.timeline?.modelOptions(fallback).orEmpty() - val failure = state.modelCatalogFailure - - Text(stringResource(R.string.models_title), style = MaterialTheme.typography.titleMedium) - - when { - failure == ModelCatalogFailure.LOAD_FAILED && options.isEmpty() -> { - ModelCatalogNotice( - text = stringResource(R.string.model_catalog_load_failed), - isError = true, - showRetry = true, - retryEnabled = !state.busy, - onRetry = { onIntent(RemoteSessionIntent.RefreshModelCatalog) }, - ) - } - - failure == ModelCatalogFailure.UNSUPPORTED_BY_PEER && options.isEmpty() -> { - ModelCatalogNotice( - text = stringResource(R.string.model_catalog_unsupported), - isError = true, - showRetry = false, - retryEnabled = false, - onRetry = {}, - ) - } - - options.isEmpty() -> { - Text( - stringResource(R.string.model_selector_empty), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - - else -> { - if (failure != null) { - ModelCatalogNotice( - text = when (failure) { - ModelCatalogFailure.LOAD_FAILED -> - stringResource(R.string.model_catalog_stale_warning) - - ModelCatalogFailure.UNSUPPORTED_BY_PEER -> - stringResource(R.string.model_catalog_unsupported) - }, - isError = false, - showRetry = failure == ModelCatalogFailure.LOAD_FAILED, - retryEnabled = !state.busy, - onRetry = { onIntent(RemoteSessionIntent.RefreshModelCatalog) }, - ) - } - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(vertical = 4.dp)) { - options.forEachIndexed { index, option -> - if (index > 0) HorizontalDivider() - SelectableRow( - label = com.openbitfun.mobile.app.ui.chat.modelOptionTitle(option), - description = com.openbitfun.mobile.app.ui.chat.modelOptionSubtitle(option), - selected = option.selected, - enabled = !state.busy && sessionId.isNotEmpty(), - onSelect = { - onIntent(RemoteSessionIntent.SelectModel(sessionId, option.id)) - }, - ) - } - } - } - } - } -} - -/** - * The model catalog section's non-happy-path copy: a blocking error when there - * are no options to show, or a non-fatal warning when a previously loaded list - * is retained. [isError] keeps the blocking case red while the warning stays a - * muted note above the list it qualifies. - */ -@Composable -private fun ModelCatalogNotice( - text: String, - isError: Boolean, - showRetry: Boolean, - retryEnabled: Boolean, - onRetry: () -> Unit, -) { - Column( - verticalArrangement = Arrangement.spacedBy(4.dp), - modifier = Modifier - .fillMaxWidth() - .testTag(MODEL_CATALOG_FAILURE_TEST_TAG), - ) { - Text( - text, - style = MaterialTheme.typography.bodySmall, - color = if (isError) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, - ) - if (showRetry) { - TextButton( - onClick = onRetry, - enabled = retryEnabled, - modifier = Modifier.testTag(MODEL_CATALOG_RETRY_TEST_TAG), - ) { - Text(stringResource(R.string.model_catalog_retry)) - } - } - } -} - -@Composable -private fun SelectableRow( - label: String, - description: String, - selected: Boolean, - enabled: Boolean, - onSelect: () -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .selectable(selected = selected, enabled = enabled, onClick = onSelect) - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - RadioButton(selected = selected, onClick = onSelect, enabled = enabled) - Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text(label, style = MaterialTheme.typography.bodyLarge) - Text( - description, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SessionViewSettingsSheet.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SessionViewSettingsSheet.kt deleted file mode 100644 index 9221bc1621..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SessionViewSettingsSheet.kt +++ /dev/null @@ -1,257 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.selection.toggleable -import androidx.compose.material3.Card -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.RadioButton -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.state.SessionViewSettings -import com.openbitfun.mobile.core.feature.session.SessionAgentGroup -import com.openbitfun.mobile.core.feature.session.SessionGroupMode -import com.openbitfun.mobile.core.feature.session.SessionListPresentation -import com.openbitfun.mobile.core.feature.session.SessionStatusLabel -import com.openbitfun.mobile.core.feature.session.SessionWorkspaceOption - -internal const val VIEW_SETTINGS_TEST_TAG: String = "session-view-settings" - -/** The sheet's own header repeats its name, so the button that opens it is tagged. */ -internal const val VIEW_SETTINGS_TOGGLE_TEST_TAG: String = "session-view-settings-toggle" - -/** - * The view-settings sheet, ported from `pages/components/ConversationViewSettings.ets`. - * - * The option lists are passed in rather than derived here: they come from - * [com.openbitfun.mobile.core.feature.session.SessionListPresentation], which reads - * them off the same sessions the list is drawing, so a filter can never offer a - * value that would empty the list. - * - * It does not scroll: it is inlined above the list inside a column the caller - * already scrolls, and a second scroller in the same direction has no height to - * measure against. - */ -@Composable -internal fun SessionViewSettingsSheet( - settings: SessionViewSettings, - workspaces: List, - agentGroups: List, - statuses: List, - onChange: (SessionViewSettings) -> Unit, - onClose: () -> Unit, - modifier: Modifier, -) { - Column( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = 20.dp, vertical = 16.dp) - .testTag(VIEW_SETTINGS_TEST_TAG), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - stringResource(R.string.view_settings_title), - style = MaterialTheme.typography.titleMedium, - ) - Text( - stringResource(R.string.view_settings_subtitle), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - TextButton(onClick = onClose) { Text(stringResource(R.string.common_close)) } - } - - SectionTitle(stringResource(R.string.view_settings_grouping)) - Card(modifier = Modifier.fillMaxWidth()) { - Column { - GROUP_MODES.forEachIndexed { index, entry -> - if (index > 0) HorizontalDivider() - ChoiceRow( - label = stringResource(entry.label), - selected = settings.groupMode == entry.mode, - onSelect = { onChange(settings.copy(groupMode = entry.mode)) }, - ) - } - } - } - - SectionTitle(stringResource(R.string.view_settings_filters)) - - FilterLabel(stringResource(R.string.view_settings_workspace)) - Card(modifier = Modifier.fillMaxWidth()) { - Column { - ChoiceRow( - label = stringResource(R.string.view_settings_all_workspaces), - selected = settings.workspaceFilter.isEmpty(), - onSelect = { onChange(settings.copy(workspaceFilter = "")) }, - ) - workspaces.forEach { option -> - HorizontalDivider() - ChoiceRow( - label = option.name, - // Filters store the identity key (workspace ID first). A filter - // persisted as a bare path before IDs still highlights its row. - selected = settings.workspaceFilter == option.key || settings.workspaceFilter == option.path, - onSelect = { onChange(settings.copy(workspaceFilter = option.key)) }, - ) - } - } - } - - FilterLabel(stringResource(R.string.view_settings_agent_type)) - Card(modifier = Modifier.fillMaxWidth()) { - Column { - ChoiceRow( - label = stringResource(R.string.view_settings_all_agent_types), - selected = settings.agentFilter == null, - onSelect = { onChange(settings.copy(agentFilter = null)) }, - ) - agentGroups.forEach { group -> - HorizontalDivider() - ChoiceRow( - label = stringResource(group.labelRes()), - selected = settings.agentFilter == group, - onSelect = { onChange(settings.copy(agentFilter = group)) }, - ) - } - } - } - - FilterLabel(stringResource(R.string.view_settings_status)) - Card(modifier = Modifier.fillMaxWidth()) { - Column { - ChoiceRow( - label = stringResource(R.string.view_settings_all_statuses), - selected = settings.statusFilter.isEmpty(), - onSelect = { onChange(settings.copy(statusFilter = "")) }, - ) - statuses.forEach { status -> - HorizontalDivider() - ChoiceRow( - label = statusText(status), - selected = settings.statusFilter == status, - onSelect = { onChange(settings.copy(statusFilter = status)) }, - ) - } - } - } - - SectionTitle(stringResource(R.string.view_settings_metadata)) - Card(modifier = Modifier.fillMaxWidth()) { - Column { - ToggleRow( - label = stringResource(R.string.view_settings_workspace), - checked = settings.showWorkspace, - onChange = { onChange(settings.copy(showWorkspace = it)) }, - ) - HorizontalDivider() - ToggleRow( - label = stringResource(R.string.view_settings_updated), - checked = settings.showUpdated, - onChange = { onChange(settings.copy(showUpdated = it)) }, - ) - HorizontalDivider() - ToggleRow( - label = stringResource(R.string.view_settings_status), - checked = settings.showStatus, - onChange = { onChange(settings.copy(showStatus = it)) }, - ) - } - } - } -} - -/** The desktop's own word when we have none of our own; see [SessionStatusLabel]. */ -@Composable -internal fun statusText(status: String): String = - when (SessionListPresentation.statusLabel(status)) { - SessionStatusLabel.RUNNING -> stringResource(R.string.status_running) - SessionStatusLabel.READY -> stringResource(R.string.status_ready) - SessionStatusLabel.ARCHIVED -> stringResource(R.string.session_archived) - SessionStatusLabel.RAW -> status - } - -internal fun SessionAgentGroup.labelRes(): Int = when (this) { - SessionAgentGroup.CHAT -> R.string.session_group_chat - SessionAgentGroup.CODE -> R.string.sessions_filter_code - SessionAgentGroup.COWORK -> R.string.sessions_filter_cowork -} - -@Composable -private fun SectionTitle(title: String) { - Text( - title, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 8.dp), - ) -} - -@Composable -private fun FilterLabel(label: String) { - Text( - label, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) -} - -// The whole row is the control in both cases: the radio and the switch report -// no click of their own, so the row's semantics stay a single target rather -// than a label sitting next to an unrelated tappable box. -@Composable -private fun ChoiceRow(label: String, selected: Boolean, onSelect: () -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .selectable(selected = selected, onClick = onSelect) - .padding(horizontal = 16.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - RadioButton(selected = selected, onClick = null) - Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) - } -} - -@Composable -private fun ToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .toggleable(value = checked, onValueChange = onChange) - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(label, modifier = Modifier.weight(1f)) - Switch(checked = checked, onCheckedChange = null) - } -} - -private class GroupModeEntry(val mode: SessionGroupMode, val label: Int) - -private val GROUP_MODES = listOf( - GroupModeEntry(SessionGroupMode.PROJECT, R.string.group_by_project), - GroupModeEntry(SessionGroupMode.TIME, R.string.group_by_time), - GroupModeEntry(SessionGroupMode.CHAT, R.string.group_chat_first), -) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsChrome.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsChrome.kt deleted file mode 100644 index 6a9658f681..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsChrome.kt +++ /dev/null @@ -1,149 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.Dp -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry - -/** - * The pieces every section of the remote-control settings page is built from. - * - * `RemoteControlSettingsSheet.ets` draws one page out of four repeated shapes: a - * muted section heading, a rounded CARD, a row that leads somewhere and says so - * with a chevron, and a soft pill that carries the row's one action. They live - * here rather than in each section's file so the page cannot drift apart by a - * corner radius. - */ - -/** - * The 18sp Bold MUTED heading the source puts above every card. - * - * Indented 12dp, the same inset as every other section title on the settings - * page, so the page's headings share one left edge. - */ -@Composable -internal fun SettingsSectionHeader(text: String, modifier: Modifier) { - Text( - text, - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = modifier.padding(start = 12.dp), - ) -} - -/** - * The CARD-on-PAGE_BG container: surface fill, hairline LINE border, radius 24. - * - * [radius] because the source rounds the permission card at 28 rather than 24 — - * it is the tallest card on the page, and the same corner on a taller block reads - * as a sharper one. - */ -@Composable -internal fun SettingsCard( - modifier: Modifier, - radius: Dp = MobileDesignGeometry.SettingsCardRadius, - bordered: Boolean = false, - content: @Composable ColumnScope.() -> Unit, -) { - Card( - shape = RoundedCornerShape(radius), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), - border = if (bordered) { - BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant) - } else { - null - }, - modifier = modifier.fillMaxWidth(), - content = content, - ) -} - -/** The soft round glyph slot the source draws in front of a row. */ -@Composable -internal fun SettingsAvatar(@DrawableRes icon: Int, diameter: Int) { - Box( - modifier = Modifier - .size(diameter.dp) - .clip(CircleShape) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - Icon( - painterResource(icon), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size((diameter * 0.52f).dp), - ) - } -} - -/** - * The SOFT pill an action or a badge sits in. - * - * [onClick] is null for the connection-source badge, which says where the link - * came from and is not something to press. - */ -@Composable -internal fun SettingsChip( - label: String, - enabled: Boolean, - onClick: (() -> Unit)?, - modifier: Modifier, -) { - val shape = RoundedCornerShape(14.dp) - val content: @Composable RowScope.() -> Unit = { - Text( - label, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (enabled) 1f else 0.5f), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - val padded: @Composable () -> Unit = { - Row( - modifier = Modifier.padding(horizontal = 14.dp, vertical = 7.dp), - verticalAlignment = Alignment.CenterVertically, - content = content, - ) - } - if (onClick == null) { - Surface( - shape = shape, - color = MaterialTheme.colorScheme.surfaceVariant, - modifier = modifier, - ) { padded() } - } else { - Surface( - onClick = onClick, - enabled = enabled, - shape = shape, - color = MaterialTheme.colorScheme.surfaceVariant, - modifier = modifier, - ) { padded() } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsScreen.kt deleted file mode 100644 index 94e198a536..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/settings/SettingsScreen.kt +++ /dev/null @@ -1,425 +0,0 @@ -package com.openbitfun.mobile.app.ui.settings - -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.defaultMinSize -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.account.AccountSettingsDevicesSection -import com.openbitfun.mobile.app.ui.account.AccountSettingsIdentityCard -import com.openbitfun.mobile.app.ui.account.AccountSettingsSignOutRow -import com.openbitfun.mobile.core.feature.account.AccountUiState -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.RemoteControlSummary -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.app.platform.AppLocale -import com.openbitfun.mobile.app.platform.AppLocaleController -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry - -internal const val SETTINGS_TEST_TAG: String = "settings" -internal const val SETTINGS_PROFILE_TEST_TAG: String = "settings-profile" -internal const val SETTINGS_MODEL_TEST_TAG: String = "settings-model" -internal const val SETTINGS_CLOSE_TEST_TAG: String = "settings-close" - -/** - * The app's one settings page: the account, what this phone is driving, what - * that desktop may run unasked, then phone preferences, devices, and about. - * - * The sidebar gear and the remote home header both open it; there is no - * separate remote-control page. The account is embedded rather than linked, as - * `SettingsSheet.ets` embeds `AccountProfilePanel`: who is signed in, the - * account's desktops, and sign out all sit here. [onSignIn] is the only way off - * the page, to the login sheet. Model configuration belongs to the controlled - * host. - * - * @param summary which desktop this phone is driving, decided by - * `RemoteControlPresenter` rather than here. - * @param remoteState the session store of whichever connection [summary] named, - * read here only for the desktop-wide permission mode. - */ -@Composable -internal fun SettingsScreen( - modifier: Modifier, - account: AccountUiState.Ready?, - summary: RemoteControlSummary, - remoteState: RemoteSessionUiState, - onSignIn: () -> Unit, - onRefreshDevices: () -> Unit, - onSelectDevice: (String) -> Unit, - onSignOut: () -> Unit, - onDisconnect: () -> Unit, - onReconnect: () -> Unit, - onSessionIntent: (RemoteSessionIntent) -> Unit, - onClose: () -> Unit, -) { - var showLanguagePicker by rememberSaveable { mutableStateOf(false) } - val connected = summary.phase == ConnectionPhase.CONNECTED - val readyRemote = remoteState as? RemoteSessionUiState.Ready - - // What `aboutToAppear` does in the source: the mode is the desktop's, so it - // may have been changed from the desktop or from another phone since the - // page was last open, and only asking again can say so. Keyed on readiness - // too, so a session that becomes Ready while the page is open is asked then. - LaunchedEffect(connected, readyRemote != null) { - if (connected && readyRemote != null) { - onSessionIntent(RemoteSessionIntent.RefreshPermissionMode) - } - } - val context = LocalContext.current - val selectedLocale = AppLocaleController.current(LocalConfiguration.current) - - BackHandler(enabled = showLanguagePicker) { - showLanguagePicker = false - } - - Box(modifier = modifier.fillMaxSize().testTag(SETTINGS_TEST_TAG)) { - Column( - modifier = Modifier - .fillMaxSize() - .verticalScroll(rememberScrollState()) - // The title starts below the close button rather than beside it, - // which is the source's `top: 64` over a floating `CloseButton()`: - // a 28sp heading and a 44dp circle on one line read as a top bar, - // and this page is not one — nothing here goes back anywhere. - .padding(start = 16.dp, end = 16.dp, top = 64.dp, bottom = 34.dp), - ) { - Text( - stringResource(R.string.settings_title), - fontSize = 28.sp, - lineHeight = 34.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.fillMaxWidth().padding(bottom = 30.dp), - ) - - AccountSettingsIdentityCard( - account = account, - onSignIn = onSignIn, - modifier = Modifier.testTag(SETTINGS_PROFILE_TEST_TAG), - ) - - GeneralSectionTitle(stringResource(R.string.remote_settings_current_control)) - CurrentControlCard( - summary = summary, - onDisconnect = onDisconnect, - onReconnect = onReconnect, - modifier = Modifier, - ) - - PermissionSection( - state = readyRemote, - connected = connected, - onIntent = onSessionIntent, - modifier = Modifier.padding(top = 24.dp), - ) - - GeneralSectionTitle(stringResource(R.string.settings_general_section)) - SettingsCard( - modifier = Modifier, - radius = MobileDesignGeometry.SettingsCompactCardRadius, - bordered = false, - ) { - Column(modifier = Modifier.padding(vertical = 5.dp)) { - LanguageSettingsRow( - value = when (selectedLocale) { - AppLocale.ENGLISH -> stringResource(R.string.settings_language_english) - AppLocale.SIMPLIFIED_CHINESE -> stringResource(R.string.settings_language_chinese) - }, - onClick = { showLanguagePicker = true }, - ) - - } - } - - AccountSettingsDevicesSection( - account = account, - onRefresh = onRefreshDevices, - onSelect = onSelectDevice, - modifier = Modifier.padding(top = 24.dp), - ) - - GeneralSectionTitle(stringResource(R.string.settings_about_section)) - SettingsCard( - modifier = Modifier, - radius = MobileDesignGeometry.SettingsCompactCardRadius, - bordered = false, - ) { - Column(modifier = Modifier.padding(vertical = 5.dp)) { - StaticSettingsRow( - title = stringResource(R.string.settings_about_product), - value = stringResource(R.string.settings_about_product_value), - ) - // Short of the card's width and centred, as the source's - // 84%-wide rule is: a divider that reached the corners would - // read as two cards rather than as two rows of one. - HorizontalDivider( - modifier = Modifier.fillMaxWidth(0.84f).align(Alignment.CenterHorizontally), - ) - StaticSettingsRow( - title = stringResource(R.string.settings_about_version), - value = appVersionName(), - ) - } - } - - if (account != null) { - AccountSettingsSignOutRow(onSignOut = onSignOut, modifier = Modifier.padding(top = 28.dp)) - } - } - - // The source's `CloseButton()`, floating over the page's top-right corner. - Surface( - onClick = onClose, - shape = androidx.compose.foundation.shape.CircleShape, - color = MaterialTheme.colorScheme.surface, - shadowElevation = 3.dp, - modifier = Modifier - .align(Alignment.TopEnd) - .padding(top = 22.dp, end = 18.dp) - .size(50.dp) - .testTag(SETTINGS_CLOSE_TEST_TAG), - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - modifier = Modifier.size(21.dp), - ) - } - } - - if (showLanguagePicker) { - LanguagePickerOverlay( - selected = selectedLocale, - onDismiss = { showLanguagePicker = false }, - onSelect = { locale -> - showLanguagePicker = false - AppLocaleController.set(context, locale) - }, - ) - } - - - } -} - -@Composable -private fun LanguageSettingsRow(value: String, onClick: () -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .defaultMinSize(minHeight = 52.dp) - .padding(horizontal = 18.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - Text( - "Aa", - color = MaterialTheme.colorScheme.onSurfaceVariant, - fontSize = 20.sp, - modifier = Modifier.widthIn(min = 23.dp), - ) - Text( - stringResource(R.string.settings_language_title), - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), - ) - Spacer(Modifier.weight(1f)) - Text( - value, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.widthIn(max = 130.dp), - ) - SettingsChevron() - } -} - -@Composable -private fun LanguagePickerOverlay( - selected: AppLocale, - onDismiss: () -> Unit, - onSelect: (AppLocale) -> Unit, -) { - Surface( - color = MaterialTheme.colorScheme.surface, - shape = RoundedCornerShape( - topStart = MobileDesignGeometry.SelectionTopRadius, - topEnd = MobileDesignGeometry.SelectionTopRadius, - ), - modifier = Modifier.fillMaxSize(), - ) { - Column(Modifier.fillMaxSize()) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.SheetHeaderHeight) - .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.settings_language_choose), - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onSurface, - ) - Spacer(Modifier.weight(1f)) - Surface( - onClick = onDismiss, - shape = androidx.compose.foundation.shape.CircleShape, - color = MaterialTheme.colorScheme.surface, - modifier = Modifier.size(MobileDesignGeometry.SelectionCloseSize), - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - painterResource(R.drawable.ic_symbol_xmark), - contentDescription = stringResource(R.string.common_close), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(18.dp), - ) - } - } - } - HorizontalDivider() - Column(Modifier.padding(top = 8.dp, bottom = 28.dp)) { - LanguageChoiceRow( - label = stringResource(R.string.settings_language_chinese), - selected = selected == AppLocale.SIMPLIFIED_CHINESE, - onClick = { onSelect(AppLocale.SIMPLIFIED_CHINESE) }, - ) - LanguageChoiceRow( - label = stringResource(R.string.settings_language_english), - selected = selected == AppLocale.ENGLISH, - onClick = { onSelect(AppLocale.ENGLISH) }, - ) - } - } - } -} - -@Composable -private fun LanguageChoiceRow(label: String, selected: Boolean, onClick: () -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(MobileDesignGeometry.SelectionRowHeight) - .clickable(onClick = onClick) - .padding(horizontal = 22.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - label, - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.weight(1f), - ) - if (selected) { - Icon( - painterResource(R.drawable.ic_symbol_list_checkmark), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.size(18.dp), - ) - } - } -} - -/** The 18sp Bold MUTED heading, indented onto the card's own text column. */ -@Composable -private fun GeneralSectionTitle(text: String) { - Text( - text, - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth().padding(start = 12.dp, top = 24.dp, bottom = 8.dp), - ) -} - -/** A row that only reports: no chevron, nothing to tap. */ -@Composable -private fun StaticSettingsRow(title: String, value: String) { - Row( - modifier = Modifier - .fillMaxWidth() - .defaultMinSize(minHeight = 52.dp) - .padding(horizontal = 18.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - Text(title, style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium)) - Spacer(Modifier.weight(1f)) - Text( - value, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } -} - -@Composable -private fun SettingsChevron() { - Icon( - painterResource(R.drawable.ic_symbol_chevron_right), - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) -} - -/** - * The version the user is actually running, asked of the package rather than - * written into a string: a hardcoded number is right exactly once. - */ -@Composable -private fun appVersionName(): String { - val context = LocalContext.current - val unknown = stringResource(R.string.common_unknown) - return remember(context) { - runCatching { - context.packageManager.getPackageInfo(context.packageName, 0).versionName - }.getOrNull().orEmpty().ifBlank { unknown } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/ColdStartHomeTransition.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/ColdStartHomeTransition.kt deleted file mode 100644 index b45a33b810..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/ColdStartHomeTransition.kt +++ /dev/null @@ -1,72 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.LinearEasing -import androidx.compose.animation.core.tween -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.offset -import androidx.compose.foundation.layout.size -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.layout.boundsInRoot -import androidx.compose.ui.unit.dp -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.semantics.clearAndSetSemantics -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignMotion -import kotlin.math.* - -/** Logged-in cold-start transition. The underlying home is already laid out. */ -@Composable -internal fun ColdStartHomeTransition(target: androidx.compose.ui.geometry.Rect?, onFinished: () -> Unit) { - val progress = remember { Animatable(0f) } - LaunchedEffect(Unit) { - progress.animateTo(1f, tween(MobileDesignMotion.ColdStartHome, easing = LinearEasing)) - onFinished() - } - val density = androidx.compose.ui.platform.LocalDensity.current - val p = progress.value - val travel = smooth((p - .16f) / .52f) - val overlayAlpha = 1f - smooth((p - .68f) / .32f) - BoxWithConstraints( - Modifier.fillMaxSize() - .graphicsLayer { alpha = overlayAlpha } - .background(androidx.compose.material3.MaterialTheme.colorScheme.background) - .pointerInput(Unit) { awaitPointerEventScope { while (true) awaitPointerEvent().changes.forEach { it.consume() } } } - .clearAndSetSemantics { }, - contentAlignment = Alignment.TopCenter, - ) { - val targetY = target?.let { with(density) { it.center.y.toDp() } } ?: (maxHeight * .53f) - val targetX = target?.let { with(density) { it.center.x.toDp() } } ?: (maxWidth / 2) - val targetSize = target?.let { with(density) { it.width.toDp() } } ?: 56.dp - val centerY = maxHeight * .53f - val y = centerY + (targetY - centerY) * travel - (if (target != null) 9.dp else 0.dp) * sin(travel * PI).toFloat() - val size = 56.dp + (targetSize - 56.dp) * travel - WelcomeBrandFlow( - Modifier.size(size) - .offset(x = (targetX - maxWidth / 2) * travel, y = y - size / 2) - .graphicsLayer { alpha = (p / .13f).coerceIn(0f, 1f) }, - sweep = true, - ) - } -} - -private fun smooth(value: Float): Float { - val p = value.coerceIn(0f, 1f) - return p * p * (3f - 2f * p) -} - -internal val LocalColdStartTarget = androidx.compose.runtime.staticCompositionLocalOf?> { null } - -@Composable -internal fun ColdStartHomeMark(modifier: Modifier) { - val target = LocalColdStartTarget.current - androidx.compose.runtime.DisposableEffect(target) { onDispose { target?.value = null } } - WelcomeBrandFlow(modifier.onGloballyPositioned { target?.value = it.boundsInRoot() }, sweep = true) -} 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 deleted file mode 100644 index 95f7a7ca1b..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt +++ /dev/null @@ -1,709 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import com.openbitfun.mobile.app.ui.account.messageRes -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.ime -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.safeDrawingPadding -import androidx.compose.foundation.layout.union -import androidx.compose.foundation.layout.only -import androidx.compose.foundation.layout.WindowInsetsSides -import androidx.compose.foundation.layout.consumeWindowInsets -import androidx.compose.foundation.layout.width -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.PermanentDrawerSheet -import androidx.compose.material3.Scaffold -import androidx.compose.material3.ScaffoldDefaults -import androidx.compose.material3.Surface -import androidx.compose.material3.VerticalDivider -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalLayoutDirection -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.LayoutDirection -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.platform.rememberWindowMetrics -import com.openbitfun.mobile.app.state.MobileSurface -import com.openbitfun.mobile.app.state.resolveRoutedRemoteSessionId -import com.openbitfun.mobile.app.state.rememberAppShellState -import com.openbitfun.mobile.app.ui.account.AccountLoginScreen -import com.openbitfun.mobile.app.ui.common.AdaptiveModalSurface -import com.openbitfun.mobile.app.ui.remote.AccountRemoteScreen -import com.openbitfun.mobile.app.ui.remote.ConnectAccountDeviceScreen -import com.openbitfun.mobile.app.ui.remote.FilePreviewSurface -import com.openbitfun.mobile.app.ui.settings.SettingsScreen -import com.openbitfun.mobile.app.ui.shell.sidebar.AppSidebar -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.app.viewmodel.AccountViewModel -import com.openbitfun.mobile.core.feature.account.AccountIntent -import com.openbitfun.mobile.core.feature.account.AccountUiState -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.RemoteControlPresenter -import com.openbitfun.mobile.core.feature.connection.RemoteControlSource -import com.openbitfun.mobile.core.feature.connection.allowsRemoteCommands -import com.openbitfun.mobile.core.feature.layout.ConversationLayoutPolicy -import com.openbitfun.mobile.core.feature.layout.AdaptiveLayoutInput -import com.openbitfun.mobile.core.feature.layout.FilePreviewPlacement -import com.openbitfun.mobile.core.feature.layout.FilePreviewPlacementPolicy -import com.openbitfun.mobile.core.feature.layout.SettingsPlacementPolicy -import com.openbitfun.mobile.core.feature.layout.SettingsSheetKind -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.WorkspaceSessionDirectoryUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteFilePreviewUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteFileDownloadUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState - -internal const val MENU_TEST_TAG: String = "shell-menu" - -/** Present only while the sidebar is permanent, which is the whole assertion. */ -internal const val MASTER_DETAIL_TEST_TAG: String = "shell-master-detail" - -/** - * Keeps the detail pane's content off a hinge it would otherwise be laid across. - * - * The policy answers in window coordinates; the padding here is what that offset - * is once the master pane has already taken its own width. A flat screen asks - * for no padding at all, and so does a fold that falls behind the master pane — - * in both cases the pane is its own content. - */ -private fun Modifier.dodgingCrease( - paneWidth: Int, - contentOffset: Int, - contentWidth: Int, -): Modifier { - if (contentWidth <= 0) return this - val leading = contentOffset.coerceAtLeast(0) - val trailing = (paneWidth - contentOffset - contentWidth).coerceAtLeast(0) - if (leading == 0 && trailing == 0) return this - return padding(start = leading.dp, end = trailing.dp) -} - -/** - * What goes between two panes. - * - * A hinge is already a seam, so nothing is drawn on one; a flat window gets the - * hairline the policy did not reserve room for, out of the pane that can spare it. - */ -@Composable -private fun PaneSeparator(gapWidth: Int) { - if (gapWidth > 0) Spacer(Modifier.width(gapWidth.dp)) else VerticalDivider(Modifier.fillMaxHeight()) -} - -/** - * The app shell: a drawer beside the content, with settings and the account as - * sheets over it. Ported from `pages/components/AppShell.ets`. - * - * Both view models are resolved here as well as inside their screens; they are - * activity-scoped, so this is the same instance and not a second store. Reading - * them at the shell is what lets the drawer show connection state and decide - * between its signed-in and signed-out chrome, and it is also why swapping the - * content surface cannot drop an open conversation — the timeline lives in the - * view model, not in the composable that was removed. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun MobileScreen(onAccountRestored: (Boolean) -> Unit = {}) { - var compactDrawerOpen by rememberSaveable { mutableStateOf(false) } - val shell = rememberAppShellState() - - val accountViewModel: AccountViewModel = viewModel(factory = AccountViewModel.Factory) - val accountWorkspaceState by accountViewModel.workspaceState.collectAsStateWithLifecycle() - val accountState by accountViewModel.state.collectAsStateWithLifecycle() - val accountRemoteState by accountViewModel.remoteState.collectAsStateWithLifecycle() - val accountPhase by accountViewModel.connectionPhase.collectAsStateWithLifecycle() - val accountWorkspaceDirectory by accountViewModel.workspaceDirectory.collectAsStateWithLifecycle() - val readyAccount = accountState as? AccountUiState.Ready - LaunchedEffect(accountPhase, shell.remoteCreating) { - // A create failure is terminal for the creation route. The shared - // store keeps the last valid session projection so returning to the - // remote home here restores the same pre-create route as Harmony and - // iOS, while the store's typed create error remains available to the - // surface-level error/toast handling. - if (shell.remoteCreating && accountPhase == ConnectionPhase.FAILED) { - shell.closeRemoteSession() - } - } - LaunchedEffect(accountState) { - if (accountState !is AccountUiState.Idle && accountState !is AccountUiState.Restoring) { - onAccountRestored(readyAccount?.userId?.isNotBlank() == true) - } - } - // Login is its own sheet only while it is running. Once the account is - // ready it shows inside settings, so the sheet hands the user over there. - LaunchedEffect(shell.showAccount, readyAccount != null) { - if (shell.showAccount && readyAccount != null) shell.completeLogin() - } - // A connect sheet restored from before sign-out has no picker to show; drop - // it once the account has settled as signed out rather than reopen it later. - LaunchedEffect(shell.remoteConnectOpen, accountState) { - if (shell.remoteConnectOpen && (accountState is AccountUiState.SignedOut || accountState is AccountUiState.Failed)) { - shell.closeRemoteConnect() - } - } - - val accountUserId = readyAccount?.userId - val controlSummary = remember(readyAccount, accountPhase) { - RemoteControlPresenter.summarize( - accountDeviceId = readyAccount?.selectedDeviceId.orEmpty(), - accountDeviceName = readyAccount?.selectedDeviceName.orEmpty(), - accountPhase = accountPhase, - ) - } - val phase = controlSummary.phase - val activeWorkspaceState = when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> accountWorkspaceState - RemoteControlSource.NONE -> RemoteWorkspaceUiState.Idle - } - val activeRemoteState = when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> accountRemoteState - RemoteControlSource.NONE -> RemoteSessionUiState.Idle - } - val committedRemoteSessions = (activeRemoteState as? RemoteSessionUiState.Ready)?.sessions.orEmpty() - val pendingRemoteSessionId = shell.pendingRemoteSessionId - LaunchedEffect(pendingRemoteSessionId, activeRemoteState) { - val pending = pendingRemoteSessionId ?: return@LaunchedEffect - val ready = activeRemoteState as? RemoteSessionUiState.Ready ?: return@LaunchedEffect - shell.observeRemoteSessionOpen(pending, ready.selectedSessionId, ready.busy) - } - // A pending open routes before the current session page knows about the ID. - // Once it settles, valid shell requests and the store selection take over; - // a deleted row no longer routes because neither contains its ID. - val routedSessionId = resolveRoutedRemoteSessionId( - pendingSessionId = pendingRemoteSessionId, - requestedSessionId = shell.remoteSessionId, - committedSessionIds = committedRemoteSessions.mapTo(mutableSetOf()) { it.id }, - selectedSessionId = (activeRemoteState as? RemoteSessionUiState.Ready)?.selectedSessionId, - ) - val activeWorkspaceDirectory = when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> accountWorkspaceDirectory - RemoteControlSource.NONE -> WorkspaceSessionDirectoryUiState(emptyList()) - } - - fun dispatchActiveWorkspace(intent: RemoteWorkspaceIntent) { - when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> accountViewModel.dispatchWorkspace(intent) - RemoteControlSource.NONE -> Unit - } - } - - // Full-screen previews replace the conversation composition. Keep the - // platform document launcher alive across both presentation surfaces. - com.openbitfun.mobile.app.ui.remote.RemoteDownloadSaver(activeWorkspaceState, ::dispatchActiveWorkspace) - - fun dispatchActiveSession(intent: RemoteSessionIntent) { - when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> accountViewModel.dispatchSession(intent) - RemoteControlSource.NONE -> Unit - } - } - - fun closeDrawer() { - // A no-op while the sidebar is permanent, which is why the sidebar's - // callbacks are the same lambdas in both shapes: only the container that - // holds it changes, not what its rows do. - compactDrawerOpen = false - } - - // Whether there is room for the sidebar to stay. The policy is the same one - // `AppRootPresentation.ets` asks, given the same three facts. - val window = rememberWindowMetrics() - val layoutCreases = if (window.isFolded || window.isHoverLayout) { - emptyList() - } else { - ConversationLayoutPolicy.effectiveVerticalCreases( - viewportWidth = window.widthDp, - creases = window.creases, - synthesizeCenterHinge = window.isExpandedFoldable, - ) - } - val wide = ConversationLayoutPolicy.useMasterDetail( - viewportWidth = window.widthDp, - wideViewportMatched = window.wideViewportMatched, - isFolded = window.isFolded, - creases = layoutCreases, - isExpandedFoldable = window.isExpandedFoldable, - isHover = window.isHoverLayout, - ) - val geometry = ConversationLayoutPolicy.resolveWideGeometry(window.widthDp, layoutCreases) - val adaptiveLayoutInput = AdaptiveLayoutInput( - viewportWidth = window.widthDp, - viewportHeight = window.heightDp, - isFolded = window.isFolded, - isExpandedFoldable = window.isExpandedFoldable, - isHoverOperate = window.isHoverLayout, - wideLayoutMatched = window.wideViewportMatched, - verticalCreases = window.creases, - horizontalCreases = window.horizontalCreases, - isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl, - ) - val settingsPlacement = SettingsPlacementPolicy.resolve( - adaptiveLayoutInput, - SettingsSheetKind.SETTINGS, - ) - val connectPlacement = SettingsPlacementPolicy.resolve(adaptiveLayoutInput, SettingsSheetKind.CONNECT) - val sessionDetailsPlacement = SettingsPlacementPolicy.resolve( - adaptiveLayoutInput, - SettingsSheetKind.SESSION_DETAILS, - ) - val remoteViewSettingsPlacement = SettingsPlacementPolicy.resolve( - adaptiveLayoutInput, - SettingsSheetKind.REMOTE_VIEW_SETTINGS, - ) - - // A file the agent referenced is the third thing that wants the window, and - // the one that decides whether the other two still fit. Only the remote - // surface has one to place: a file opened from the account sheet belongs to - // that sheet's own store and stays inside it. - val preview = (activeWorkspaceState as? RemoteWorkspaceUiState.Ready)?.preview - val previewVisible = shell.surface == MobileSurface.REMOTE && - preview != null && preview !is RemoteFilePreviewUiState.None - val previewLayout = FilePreviewPlacementPolicy.resolveLayout( - previewVisible = previewVisible, - largeScreenLayout = wide, - viewportWidth = window.widthDp, - creases = layoutCreases, - // So the list does not jump sideways the moment a file opens beside it. - preferredMasterWidth = geometry.masterPaneWidth, - ) - val sidebarWidth = when { - !wide -> 0 - previewLayout.placement == FilePreviewPlacement.Hidden -> geometry.masterPaneWidth - // A focus split gave the list's room to the file; a full-page preview - // never had room for either. - else -> previewLayout.masterPaneWidth - } - // Match `AppShell.sidebarWidth()` for the compact drawer. Material's - // default drawer is 360dp, which is visibly wider than Harmony's 280dp - // sidebar on a normal phone window. - val compactDrawerWidth = minOf(280, maxOf(220, (window.widthDp * 0.68f).toInt())) - // The button and the pane are the same sidebar; exactly one of them is real. - val showMenu = sidebarWidth == 0 - - // Persist the owner with the visibility flag: rememberSaveable inputs alone - // do not validate the identity of restored values after recreation. - val workspacePickerOwner = listOf(readyAccount?.relayUrl.orEmpty(), readyAccount?.userId.orEmpty(), - readyAccount?.selectedDeviceId.orEmpty(), controlSummary.source.name) - var workspacePickerSavedOwner by rememberSaveable { mutableStateOf(workspacePickerOwner) } - var workspacePickerOpen by rememberSaveable { mutableStateOf(false) } - LaunchedEffect(workspacePickerOwner) { - if (workspacePickerSavedOwner != workspacePickerOwner) { - workspacePickerOpen = false - workspacePickerSavedOwner = workspacePickerOwner - } - } - if (workspacePickerOpen && workspacePickerSavedOwner == workspacePickerOwner) { - (activeWorkspaceState as? RemoteWorkspaceUiState.Ready)?.let { ready -> - com.openbitfun.mobile.app.ui.remote.RuntimeWorkspacePickerDialog( - ready, ::dispatchActiveWorkspace, { workspacePickerOpen = false }, - ) - } - } - (activeWorkspaceState as? RemoteWorkspaceUiState.Ready)?.let { ready -> - if (ready.deviceTools.visible) com.openbitfun.mobile.app.ui.remote.DeviceToolsDialog(ready, ::dispatchActiveWorkspace) - } - val sidebar: @Composable () -> Unit = { - AppSidebar( - permanent = sidebarWidth > 0, - sessionDetailsPlacement = sessionDetailsPlacement, - accountUserId = accountUserId, - connectionPhase = phase, - remoteControlSource = controlSummary.source, - remoteDevices = readyAccount?.devices.orEmpty(), - remoteSelectedDeviceId = readyAccount?.selectedDeviceId - .takeIf { controlSummary.source == RemoteControlSource.ACCOUNT_DEVICE }, - remoteDeviceName = controlSummary.desktopName, - remoteState = activeRemoteState, - workspaceState = activeWorkspaceState, - workspaceDirectory = activeWorkspaceDirectory, - remoteActive = shell.surface == MobileSurface.REMOTE, - // The session store owns selection. The shell only owns the - // container route, so deleting the active row clears this value - // without leaving a stale requested session behind. - remoteSelectedSessionId = routedSessionId, - query = shell.sidebarQuery, - searchOpen = shell.searchOpen, - onQueryChange = shell::search, - onToggleSearch = shell::toggleSearch, - onConnectDesktop = { - // Desktops are reached only through the account: signed in, the - // row opens the account's device picker; signed out, login. - if (readyAccount != null) shell.openRemoteConnect() else shell.openAccount(signedIn = false) - closeDrawer() - }, - onRefreshRemoteDevices = { accountViewModel.dispatch(AccountIntent.RefreshDevices) }, - refreshingRemoteDevices = readyAccount?.refreshing == true, - directoryRefreshError = readyAccount?.refreshFailure?.let { stringResource(it.messageRes()) }, - onRetryRemoteDevice = { - dispatchActiveSession(RemoteSessionIntent.Load) - dispatchActiveWorkspace(RemoteWorkspaceIntent.Load) - }, - onSelectRemoteDevice = { deviceId -> - accountViewModel.selectDevice(deviceId) - shell.show(MobileSurface.REMOTE) - shell.closeRemoteSession() - }, - onOpenRemoteSession = { sessionId -> - shell.openRemoteSession(sessionId) - closeDrawer() - dispatchActiveSession(RemoteSessionIntent.Open(sessionId)) - }, - onCreateRemoteInWorkspace = { workspace, agentType -> - // Workspace quick-create used to dispatch directly while the - // shell still rendered the home surface, so its committed - // session had no creation route callback. Enter the same - // creation route as the global new-session action first. - shell.createRemoteSession() - // With an ID the create carries only the ID; the legacy triple is for pre-ID rows. - dispatchActiveSession( - RemoteSessionIntent.CreateSession( - agentType = agentType, - title = "", - instruction = "", - modelId = null, - workspacePath = workspace.path, - remoteConnectionId = workspace.remoteConnectionId, - remoteSshHost = workspace.remoteSshHost, - workspaceId = workspace.workspaceId, - ), - ) - closeDrawer() - }, - onWorkspaceTool = { path, connectionId, terminal -> - dispatchActiveWorkspace(RemoteWorkspaceIntent.OpenDeviceTools(path, connectionId)) - if (terminal) dispatchActiveWorkspace(RemoteWorkspaceIntent.SelectDeviceToolsPanel(com.openbitfun.mobile.core.feature.workspace.DeviceToolsPanel.TERMINAL)) - closeDrawer() - }, - onAddRemoteWorkspace = { workspacePickerOpen = true }, - onOpenRemoteWorkspace = { workspace -> - dispatchActiveWorkspace(RemoteWorkspaceIntent.SelectWorkspace(workspace.path, workspace.remoteConnectionId, workspace.remoteSshHost, false, workspace.workspaceId)) - shell.show(MobileSurface.REMOTE) - shell.closeRemoteSession() - closeDrawer() - }, - onExpandRemoteWorkspace = { workspace -> - // The branch is loaded by workspace ID; the legacy triple only serves pre-ID rows. - dispatchActiveSession( - RemoteSessionIntent.LoadWorkspaceSessions( - workspace.path, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId, - ), - ) - }, - onRetryRemoteWorkspaceSessions = { workspace -> - dispatchActiveSession( - RemoteSessionIntent.RetryWorkspaceSessions( - workspace.path, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId, - ), - ) - }, - onDeleteRemoteSession = { id -> dispatchActiveSession(RemoteSessionIntent.DeleteSession(id)) }, - onOpenSettings = { - // The gear and the remote home header open the same page. - shell.openSettings() - closeDrawer() - }, - onOpenAccount = { - shell.openAccount(signedIn = readyAccount != null) - closeDrawer() - }, - modifier = Modifier, - ) - } - - val content: @Composable () -> Unit = { - if (controlSummary.source == RemoteControlSource.NONE && readyAccount == null) { - // The compact signed-out welcome surface owns the full window, - // including the gesture/navigation area. Keeping it outside the - // Scaffold prevents Scaffold's content insets from leaving a - // platform-colored strip below the welcome dock. - WelcomeHome( - signedIn = false, - onLogin = { shell.openAccount(signedIn = false) }, - modifier = Modifier.fillMaxSize(), - ) - } else Scaffold( - // The manifest asks for `adjustResize`, but an edge-to-edge window - // is never resized by it — the keyboard simply draws on top, and - // what it draws on top of is the composer. Adding the IME to the - // insets the content already lifts itself out of is what actually - // keeps the input bar above the keyboard. `union` rather than a - // second padding: the IME inset already contains the navigation - // bar's, and adding them would leave a gap the height of the bar. - contentWindowInsets = (if (shell.surface == MobileSurface.REMOTE && routedSessionId != null) { - // The conversation owns the bottom strip: its viewport reaches - // the screen edge while the fixed composer clears navigation. - ScaffoldDefaults.contentWindowInsets.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal) - } else ScaffoldDefaults.contentWindowInsets).union(WindowInsets.ime), - // HarmonyOS hides the platform title bar. Each product surface owns - // its 44dp controls and title row, so a Material TopAppBar here would - // add a second header above every conversation and remote page. - topBar = {}, - ) { insets -> - Box(Modifier.padding(insets).consumeWindowInsets(insets)) { - when (shell.surface) { - MobileSurface.REMOTE -> when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> AccountRemoteScreen( - remoteState = accountRemoteState, - workspaceState = accountWorkspaceState, - deviceId = readyAccount?.selectedDeviceId.orEmpty(), - deviceName = controlSummary.desktopName, - createDevices = readyAccount?.devices.orEmpty().map { device -> - com.openbitfun.mobile.app.ui.remote.CreateDeviceChoice( - id = device.id, - name = device.displayName, - online = device.online, - selected = device.id == readyAccount?.selectedDeviceId, - ) - }, - accountUsername = readyAccount?.username.orEmpty(), - attachmentOwner = org.json.JSONArray(listOf(readyAccount?.relayUrl, readyAccount?.username, readyAccount?.selectedDeviceId)).toString(), - phase = accountPhase, - settingsPlacement = settingsPlacement, - sessionDetailsPlacement = sessionDetailsPlacement, - viewSettingsPlacement = remoteViewSettingsPlacement, - onOpenRemoteSettings = { shell.openSettings() }, - onCreateDevicePick = accountViewModel::selectDevice, - onSessionIntent = accountViewModel::dispatchSession, - onWorkspaceIntent = accountViewModel::dispatchWorkspace, - onOpenSidebar = if (showMenu) { - { compactDrawerOpen = true } - } else { - null - }, - compact = !wide, - requestedSessionId = routedSessionId, - creatingSession = shell.remoteCreating, - onOpenSession = shell::openRemoteSession, - onCreatedSession = { id -> - shell.openRemoteSession(id) - closeDrawer() - }, - onCreateSession = shell::createRemoteSession, - onRemoteHome = shell::closeRemoteSession, - modifier = Modifier, - ) - - RemoteControlSource.NONE -> if (readyAccount != null) { - com.openbitfun.mobile.app.ui.remote.RemoteCompactHome( - remoteState = RemoteSessionUiState.Idle, - desktopName = "", - onOpenSidebar = { compactDrawerOpen = true }, - onBrowse = { shell.openRemoteConnect() }, - onOpen = {}, - ) - } else WelcomeHome( - signedIn = readyAccount != null, - onLogin = { - if (readyAccount != null) shell.openRemoteConnect() else shell.openAccount(signedIn = false) - }, - modifier = Modifier.fillMaxSize(), - ) - } - } - } - } - } - - val previewPane: @Composable () -> Unit = { - preview?.let { current -> - FilePreviewSurface( - preview = current, - download = (activeWorkspaceState as? RemoteWorkspaceUiState.Ready)?.download - ?: RemoteFileDownloadUiState.None, - remoteAvailable = phase.allowsRemoteCommands(), - onIntent = ::dispatchActiveWorkspace, - modifier = Modifier.fillMaxSize(), - ) - } - } - - // The drawer wraps both shapes rather than only the compact one: a window - // that loses its permanent sidebar to a preview still has a menu button, and - // that button needs something to open. - LaunchedEffect(showMenu) { - if (!showMenu) compactDrawerOpen = false - } - OpenBitFunCompactDrawer( - open = showMenu && compactDrawerOpen, - compact = showMenu, - drawerWidth = compactDrawerWidth.dp, - onDismiss = ::closeDrawer, - drawerContent = { - Surface( - color = MaterialTheme.colorScheme.background, - modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding(), - ) { sidebar() } - }, - ) { - if (previewLayout.placement == FilePreviewPlacement.CompactFullPage) { - // Two documents in one phone width is two columns of hyphenation, so - // the file covers the conversation — the same trade - // `FilePreviewSurface.ets` makes. Covering the page means covering - // the app bar with it, so the way out has to be the system's own - // back gesture as well as the card's button, and the insets the - // scaffold was applying have to be applied here instead. - BackHandler { - dispatchActiveWorkspace(RemoteWorkspaceIntent.DismissPreview) - } - Surface(Modifier.fillMaxSize()) { - Box(Modifier.safeDrawingPadding()) { previewPane() } - } - } else { - Row(Modifier.fillMaxSize()) { - if (sidebarWidth > 0) { - PermanentDrawerSheet( - Modifier.width(sidebarWidth.dp).testTag(MASTER_DETAIL_TEST_TAG), - // Material fills a drawer sheet from surfaceContainerLow; - // the rail paints its own chrome, so the sheet gets out - // of the way rather than tinting a second layer under it. - drawerContainerColor = openBitFunColors.sidebar.background, - ) { sidebar() } - PaneSeparator( - if (previewVisible) { - previewLayout.masterConversationGap - } else { - geometry.masterDetailGap - }, - ) - } - if (previewLayout.placement == FilePreviewPlacement.Hidden) { - val hasMaster = sidebarWidth > 0 - Box( - Modifier - .weight(1f) - .dodgingCrease( - paneWidth = window.widthDp - sidebarWidth - geometry.masterDetailGap, - contentOffset = if (hasMaster) { - geometry.detailContentOffset - } else { - geometry.collapsedDetailContentOffset - }, - contentWidth = if (hasMaster) { - geometry.detailContentWidth - } else { - geometry.collapsedDetailContentWidth - }, - ), - ) { content() } - } else { - Box(Modifier.width(previewLayout.conversationPaneWidth.dp)) { content() } - PaneSeparator(previewLayout.conversationPreviewGap) - Box(Modifier.width(previewLayout.previewPaneWidth.dp)) { previewPane() } - } - } - } - } - - // The settings page embeds the account, so it takes these verbs. - val signInFromSettings: () -> Unit = { shell.openAccount(signedIn = false) } - val refreshAccountDevices: () -> Unit = { accountViewModel.dispatch(AccountIntent.RefreshDevices) } - val selectAccountDevice: (String) -> Unit = { deviceId -> - accountViewModel.selectDevice(deviceId) - shell.dismissSettings() - shell.closeRemoteSession() - shell.show(MobileSurface.REMOTE) - } - val signOutFromSettings: () -> Unit = { - accountViewModel.dispatch(AccountIntent.Logout) - shell.dismissSettings() - } - val settingsContent: @Composable (Modifier) -> Unit = { contentModifier -> - SettingsScreen( - modifier = contentModifier, - account = readyAccount, - summary = controlSummary, - // The permission mode belongs to the desktop the summary named, so - // it has to be asked of that desktop's store — asking another would - // answer for a connection this page is not describing. - remoteState = activeRemoteState, - onSessionIntent = ::dispatchActiveSession, - onClose = shell::dismissSettings, - onSignIn = signInFromSettings, - onRefreshDevices = refreshAccountDevices, - onSelectDevice = selectAccountDevice, - onSignOut = signOutFromSettings, - onDisconnect = { accountViewModel.disconnectDevice() }, - onReconnect = { - // A device is asked for again, which is the same command its - // row in the account sends. Nothing re-pairs behind the user's - // back. - when (controlSummary.source) { - RemoteControlSource.ACCOUNT_DEVICE -> { - val deviceId = readyAccount?.selectedDeviceId - if (deviceId != null) { - accountViewModel.selectDevice(deviceId) - } - } - - RemoteControlSource.NONE -> Unit - } - }, - ) - } - - // The connect sheet is the account's device picker and nothing else; a - // signed-out user is sent to login by every entry point instead. - val connectAccount = readyAccount - AdaptiveModalSurface( - visible = shell.remoteConnectOpen && connectAccount != null, - edgeToEdgeContent = true, - placement = connectPlacement, - onDismissRequest = shell::closeRemoteConnect, - ) { sheetModifier -> - if (connectAccount != null) { - ConnectAccountDeviceScreen( - state = connectAccount, - onBack = shell::closeRemoteConnect, - onRefresh = { accountViewModel.dispatch(AccountIntent.RefreshDevices) }, - onSelect = { shell.closeRemoteConnect(); accountViewModel.selectDevice(it) }, - modifier = sheetModifier, - ) - } - } - AdaptiveModalSurface( - visible = shell.showSettings, - placement = settingsPlacement, - onDismissRequest = shell::dismissSettings, - // The settings body is one long scroll, so a pull-down has to scroll it - // rather than drag the page away. The page closes through its own close - // button, the back action, and a tap on the scrim. - draggable = false, - content = settingsContent, - ) - AdaptiveModalSurface( - visible = shell.showAccount, - fitContent = true, - placement = settingsPlacement, - onDismissRequest = shell::dismissAccount, - ) { modifier -> - AccountLoginScreen( - modifier = modifier, - onBack = shell::dismissAccount, - viewModel = accountViewModel, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/NotificationOnboarding.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/NotificationOnboarding.kt deleted file mode 100644 index 44d4e9e2fa..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/NotificationOnboarding.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import android.Manifest -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.res.stringResource -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.platform.NotificationOnboarding as OnboardingStore - -@Composable -internal fun NotificationOnboarding() { - val context = LocalContext.current - val store = remember(context) { OnboardingStore(context) } - var visible by remember { mutableStateOf(store.shouldOffer()) } - val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { } - fun dismiss() { - store.complete() - visible = false - } - if (visible) { - AlertDialog( - onDismissRequest = { dismiss() }, - title = { Text(stringResource(R.string.notification_onboarding_title)) }, - text = { Text(stringResource(R.string.notification_onboarding_body)) }, - confirmButton = { - TextButton(onClick = { - dismiss() - permission.launch(Manifest.permission.POST_NOTIFICATIONS) - }) { Text(stringResource(R.string.notification_onboarding_enable)) } - }, - dismissButton = { - TextButton(onClick = { dismiss() }) { Text(stringResource(R.string.notification_onboarding_later)) } - }, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/OpenBitFunCompactDrawer.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/OpenBitFunCompactDrawer.kt deleted file mode 100644 index 694548de6b..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/OpenBitFunCompactDrawer.kt +++ /dev/null @@ -1,303 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import androidx.activity.compose.BackHandler -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.tween -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxScope -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.shadow -import androidx.compose.ui.graphics.TransformOrigin -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.OpenBitFunEaseOut -import com.openbitfun.mobile.app.ui.theme.MotionDrawerCloseMillis -import com.openbitfun.mobile.app.ui.theme.MotionDrawerHideMillis -import com.openbitfun.mobile.app.ui.theme.MotionDrawerOpenMillis -import com.openbitfun.mobile.app.ui.theme.MotionDrawerRevealMillis -import com.openbitfun.mobile.app.ui.theme.MotionDrawerScrimMillis -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch - -private const val CONTENT_SCALE_X = 0.985f -private const val CONTENT_SCALE_Y = 0.992f -private const val CONTENT_RADIUS_DP = 28 -private const val CONTENT_ELEVATION_DP = 18 - -/** - * Whether the full-screen content is drawn as a flat card or as the receded - * drawer companion (rounded corner + shadow). This is a boundary switch, not a - * per-frame property: the rounded clip and shadow are static modifiers toggled - * only when the content leaves or returns to its resting position, so per-frame - * work stays limited to translation/scale/alpha. - */ -internal enum class ContentCardPhase { Flat, Receded } - -/** - * Pure, Compose-observable coordinator for [ContentCardPhase]. - * - * The timing rules live here, separate from the animation loop, so they can be - * tested without standing up a Compose tree: - * - Opening starts flat and only recedes after the content has left its resting - * position, which [onContentProgress] enforces by guarding on progress > 0; - * [onRevealStarted] records the intent but must not recede the card on the - * first, still-full-screen frame. - * - Closing settles back to flat only after the content animation has finished - * ([onContentSettled]); there is no earlier deadline that pops the shadow and - * clip while the content is still moving. - */ -internal class ContentCardCoordinator(initialOpen: Boolean) { - var phase by mutableStateOf(if (initialOpen) ContentCardPhase.Receded else ContentCardPhase.Flat) - private set - - fun onRevealStarted() { - // No phase change: the first open frame must stay a full-screen flat - // card. onContentProgress is what recedes it, once the content has left - // its resting position. - } - - fun onContentProgress(progress: Float) { - // Recede only once the content has actually left its resting position. - // progress must be strictly positive: zero still means the full-screen - // card, and attaching the corner/shadow there is the snap this - // coordinator exists to prevent. - if (progress > 0f) { - phase = ContentCardPhase.Receded - } - } - - fun onContentSettled() { - phase = ContentCardPhase.Flat - } -} - -/** Compact app shell motion shared with `AppShell.ets`. */ -@Composable -internal fun OpenBitFunCompactDrawer( - open: Boolean, - compact: Boolean, - drawerWidth: Dp, - onDismiss: () -> Unit, - drawerContent: @Composable BoxScope.() -> Unit, - content: @Composable BoxScope.() -> Unit, -) { - BackHandler(enabled = open, onBack = onDismiss) - - // Translation and scale share one progress value so they stay in lockstep. - // Only these two properties are driven per frame: they are cheap render-thread - // layer properties, so the content never recomposes or re-lays-out per frame. - // The rounded-corner clip and the shadow are deliberately *not* derived from - // contentProgress — changing shape/clip/shadowElevation every frame forces the - // full-screen content to re-rasterize its clip and shadow outline each frame - // (and allocates a new RoundedCornerShape), which is the open-drawer jank. - val contentProgress = remember { Animatable(if (open) 1f else 0f) } - val density = LocalDensity.current - val drawerWidthPx = with(density) { drawerWidth.toPx() } - val contentShape = remember { RoundedCornerShape(CONTENT_RADIUS_DP.dp) } - val interactionSource = remember { MutableInteractionSource() } - val dismissSidebarLabel = stringResource(R.string.common_close) - - // The drawer and scrim run on `Animatable` so their reveal/hide values are - // read only inside `graphicsLayer` blocks (layer-only updates, no relayout or - // recomposition). Composition is gated by plain booleans that flip only at - // open/close boundaries, so the screen is not recomposed every frame. - // - // The drawer's content (sessions, devices, workspaces) is the expensive half - // of the open animation, not the geometry. Re-composing it on every open is - // the connected-state jank, so once it has been shown it stays composed and is - // hidden off-screen with its semantics cleared instead of being disposed. That - // is only safe while this compact drawer owns the sidebar; a wide layout has a - // permanent sidebar, so the resident copy is dropped when `compact` turns off. - val drawerProgress = remember { Animatable(0f) } - val scrimProgress = remember { Animatable(0f) } - var drawerComposed by remember { mutableStateOf(open) } - var drawerRevealed by remember { mutableStateOf(open) } - var scrimComposed by remember { mutableStateOf(open) } - // The content's card treatment (rounded clip + shadow) is a static modifier - // toggled at open/close boundaries, not a per-frame graphicsLayer property. - // The coordinator encodes exactly when those boundaries fire: not on the - // first full-screen frame when opening, and not before the content has - // settled when closing. - val contentCard = remember { ContentCardCoordinator(open) } - - LaunchedEffect(open, compact) { - if (!compact) { - // Wide layout: the permanent sidebar owns this role. Drop any resident - // copy so the window does not end up with a second, hidden Sidebar. - contentProgress.snapTo(0f) - drawerProgress.snapTo(0f) - scrimProgress.snapTo(0f) - drawerComposed = false - drawerRevealed = false - scrimComposed = false - contentCard.onContentSettled() - } else if (open) { - drawerComposed = true - drawerRevealed = true - scrimComposed = true - // Record the reveal without receding the card yet: the first frame - // after opening is still the full-screen content at rest, and a 28dp - // corner must not snap onto it before the content has moved. - contentCard.onRevealStarted() - coroutineScope { - launch { - drawerProgress.animateTo( - targetValue = 1f, - animationSpec = tween(MotionDrawerRevealMillis, easing = OpenBitFunEaseOut), - ) - } - launch { - scrimProgress.animateTo( - targetValue = 0.62f, - animationSpec = tween(MotionDrawerScrimMillis, easing = OpenBitFunEaseOut), - ) - } - launch { - contentProgress.animateTo( - targetValue = 1f, - animationSpec = tween(MotionDrawerOpenMillis, easing = OpenBitFunEaseOut), - ) - } - // Value guard, not a frame count: recede only once the content - // animation has actually advanced past rest (progress > 0). - // snapshotFlow observes the Animatable value and first{} yields - // the first positive frame, so the corner never snaps onto a - // still-full-screen frame. No fixed threshold or delay. - contentCard.onContentProgress( - snapshotFlow { contentProgress.value }.first { it > 0f }, - ) - } - } else if (drawerComposed) { - coroutineScope { - launch { - drawerProgress.animateTo( - targetValue = 0f, - animationSpec = tween(MotionDrawerHideMillis, easing = OpenBitFunEaseOut), - ) - drawerRevealed = false - } - launch { - scrimProgress.animateTo( - targetValue = 0f, - animationSpec = tween(MotionDrawerScrimMillis, easing = OpenBitFunEaseOut), - ) - scrimComposed = false - } - launch { - // The shadow and clip stay until the content itself has - // settled back to full screen — no earlier deadline pops - // them while the content is still moving. - contentProgress.animateTo( - targetValue = 0f, - animationSpec = tween(MotionDrawerCloseMillis, easing = OpenBitFunEaseOut), - ) - contentCard.onContentSettled() - } - } - } - } - - Box(Modifier.fillMaxSize()) { - // The open drawer's fill is a floor under the whole shell, not a panel - // the width of the sidebar. The content card's rounded corners have to - // curve onto something: a fill that stopped at the card's left edge - // left them curving onto the page white, so a square-cornered grey - // block sat against a rounded card with a white wedge between them. - // Driven by contentProgress rather than drawerProgress so the floor is - // never thinner than the card has already moved, in either direction. - if (compact && drawerComposed) { - Box( - Modifier - .fillMaxSize() - .background(openBitFunColors.sidebar.background) - .graphicsLayer { alpha = contentProgress.value }, - ) - - Box( - modifier = Modifier - .width(drawerWidth) - .fillMaxHeight() - .graphicsLayer { - alpha = drawerProgress.value - translationX = if (drawerRevealed) { - drawerWidthPx * -0.1f * (1f - drawerProgress.value) - } else { - -(drawerWidthPx + 1f) - } - } - .then( - if (drawerRevealed) { - Modifier - } else { - Modifier.clearAndSetSemantics {} - }, - ), - content = drawerContent, - ) - } - - Box( - modifier = Modifier - .fillMaxSize() - .graphicsLayer { - translationX = drawerWidthPx * contentProgress.value - scaleX = 1f - (1f - CONTENT_SCALE_X) * contentProgress.value - scaleY = 1f - (1f - CONTENT_SCALE_Y) * contentProgress.value - transformOrigin = TransformOrigin(0f, com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry.ConversationHeaderHeight.toPx() / 2f / size.height.coerceAtLeast(1f)) - } - .then( - if (contentCard.phase == ContentCardPhase.Receded) { - Modifier.shadow( - elevation = CONTENT_ELEVATION_DP.dp, - shape = contentShape, - clip = true, - ) - } else { - Modifier - }, - ), - ) { - content() - if (scrimComposed) { - Box( - Modifier - .fillMaxSize() - // Use the semantic scrim token. Using the page - // background here makes a light-theme drawer paint a - // white sheet over the entire detail page, so opening - // the sidebar looks like the page disappeared. - .background(androidx.compose.material3.MaterialTheme.colorScheme.scrim) - .graphicsLayer { alpha = scrimProgress.value } - .clickable( - enabled = open, - interactionSource = interactionSource, - indication = null, - onClickLabel = dismissSidebarLabel, - onClick = onDismiss, - ), - ) - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/StartupBrandReveal.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/StartupBrandReveal.kt deleted file mode 100644 index 1f67fc16de..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/StartupBrandReveal.kt +++ /dev/null @@ -1,118 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import android.graphics.Paint -import android.graphics.Typeface -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.LinearEasing -import androidx.compose.animation.core.tween -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.* -import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.* -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.drawscope.drawIntoCanvas -import androidx.compose.ui.graphics.nativeCanvas -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.unit.dp -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver -import androidx.lifecycle.compose.LocalLifecycleOwner -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignColors -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignTypography -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignMotion -import kotlin.math.* - -/** Presentation-only cold-start timeline; Compose honors the system animator scale. */ -@Composable -internal fun StartupBrandReveal(onFinished: () -> Unit) { - val progress = remember { Animatable(0f) } - val finish by rememberUpdatedState(onFinished) - val lifecycle = LocalLifecycleOwner.current.lifecycle - DisposableEffect(lifecycle) { - val observer = LifecycleEventObserver { _, event -> - if (event == Lifecycle.Event.ON_STOP) finish() - } - lifecycle.addObserver(observer) - onDispose { lifecycle.removeObserver(observer) } - } - LaunchedEffect(Unit) { - progress.animateTo(1f, tween(MobileDesignMotion.StartupBrand, easing = LinearEasing)) - finish() - } - val p = progress.value - val t = min(p / .65f * .9f, .9f) - val settle = smooth((p - .66f) / .19f) - val ink = MaterialTheme.colorScheme.onBackground - val dotColor = MobileDesignColors.Light.BrandDot - val paint = remember { Paint(Paint.ANTI_ALIAS_FLAG).apply { - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - textAlign = Paint.Align.CENTER - textSize = MobileDesignTypography.BrandWordmark.fontSize.value - } } - val widths = remember { listOf(30f,25f,24f,25f,28f,10f,16f,24f,25f,25f) } - val positions = remember { widths.runningFold(24f) { x, w -> x + w } } - BoxWithConstraints(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background) - .graphicsLayer { alpha = 1 - smooth((p - .97f) / .03f) } - .clearAndSetSemantics { } - .pointerInput(Unit) { awaitPointerEventScope { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }, - contentAlignment = Alignment.Center) { - val stageScale = min(1f, ((maxWidth.value - 32f) / 280f).coerceAtLeast(.1f)) - Box(Modifier.size(280.dp, 240.dp).graphicsLayer { scaleX = stageScale; scaleY = stageScale }) { - val markProgress = ((p - .66f) / .19f).coerceIn(0f, 1f) - val q = markProgress - 1 - val markScale = .65f + .35f * (1 + 2.2f*q*q*q + 1.2f*q*q) - WelcomeBrandFlow( - Modifier.offset(94.dp, 14.dp).size(92.dp).graphicsLayer { - alpha = ease(markProgress); scaleX = markScale; scaleY = markScale - }) - Canvas(Modifier.fillMaxSize()) { - drawIntoCanvas { canvas -> - val native = canvas.nativeCanvas - native.save(); native.scale(size.width / 280f, size.height / 240f) - "OpenBıtFun".forEachIndexed { i, ch -> - val reveal = ease((t - (.19f + i * .048f)) / .05f) - val phase = ((t - (.19f + i * .048f)) / .085f).coerceIn(0f,1f) - val bounce = sin(phase * PI).toFloat() * (1-phase).pow(.65f) - val x = positions[i] + widths[i]/2 - val y = 110 + 42*settle + 7*(1-reveal)-8*bounce - paint.color = ink.toArgb(); paint.alpha = (255*reveal).toInt() - native.save(); native.rotate((if(i%2==0) -1 else 1)*bounce*6, x, y) - native.drawText(ch.toString(), x, y-(paint.fontMetrics.ascent+paint.fontMetrics.descent)/2, paint) - native.restore() - } - var x = 9f; var y = 110f; var sx=1f; var sy=1f - for (i in 0..9) { - val end=.19f+i*.048f; val begin=if(i==0) end-.065f else end-.048f - val from=if(i==0) 9f else positions[i]+10; val to=positions[i+1]+10 - if(t>=end){x=to;continue} - if(t>=begin){ - val step=((t-begin)/(end-begin)).coerceIn(0f,1f) - val hop=((step-.16f)/.84f).coerceIn(0f,1f) - val squash=sin((step/.16f).coerceIn(0f,1f)*PI).toFloat() - x=from+(to-from)*smooth(hop); y-=4*hop*(1-hop)*(if(i==0)20 else 15) - sx=1+.2f*squash;sy=1-.18f*squash - }; break - } - if(t>=.70f){ - val flight=((t-.70f)/.16f).coerceIn(0f,1f);val travel=smooth(flight) - x+=(positions[5]+5-x)*travel;y=110-15*travel-sin(PI*flight).toFloat()*44 - sx=1+(7.35f/9-1)*travel;sy=sx - if(t>.86f&&t<.9f)y-=sin((t-.86f)/.04f*PI).toFloat()*2 - } - y+=42*settle;paint.color=dotColor.toArgb() - val halo=sin(((t-.86f)/.04f).coerceIn(0f,1f)*PI).toFloat() - paint.alpha=(255*.16f*halo).toInt().coerceIn(0,255);native.drawCircle(x,y,11f,paint) - paint.alpha=(255*ease(t/.12f)).toInt();native.save();native.scale(sx,sy,x,y) - native.drawCircle(x,y,4.5f,paint);native.restore();native.restore() - } - } - } - } -} -private fun smooth(x: Float): Float { val p=x.coerceIn(0f,1f);return p*p*(3-2*p) } -private fun ease(x: Float): Float = 1-(1-x.coerceIn(0f,1f)).pow(3) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeBrandFlow.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeBrandFlow.kt deleted file mode 100644 index ef12abd7bc..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeBrandFlow.kt +++ /dev/null @@ -1,88 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import android.graphics.Paint -import android.graphics.DashPathEffect -import androidx.core.graphics.PathParser -import androidx.compose.foundation.Canvas -import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.* -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.drawscope.drawIntoCanvas -import androidx.compose.ui.graphics.nativeCanvas -import androidx.compose.ui.graphics.toArgb -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.compose.LocalLifecycleOwner -import androidx.lifecycle.repeatOnLifecycle -import androidx.compose.animation.core.LinearEasing -import androidx.compose.animation.core.RepeatMode -import androidx.compose.animation.core.animateFloat -import androidx.compose.animation.core.infiniteRepeatable -import androidx.compose.animation.core.rememberInfiniteTransition -import androidx.compose.animation.core.tween -import kotlinx.coroutines.awaitCancellation -import kotlin.coroutines.coroutineContext - -private val contourData = listOf( - "M154.860 59.584 Q167.500 59.584 173.820 70.531 L200.680 117.053 Q207.000 128.000 200.680 138.947 L173.820 185.469 Q167.500 196.416 154.860 196.416 L101.140 196.416 Q88.500 196.416 82.180 185.469 L55.320 138.947 Q49.000 128.000 55.320 117.053 L82.180 70.531 Q88.500 59.584 101.140 59.584 Z", - "M152.788 57.185 Q165.682 56.702 172.547 67.628 L201.722 114.060 Q208.586 124.985 202.557 136.392 L176.934 184.875 Q170.905 196.282 158.011 196.765 L103.212 198.815 Q90.318 199.298 83.453 188.372 L54.278 141.940 Q47.414 131.015 53.443 119.608 L79.066 71.125 Q85.095 59.718 97.989 59.235 Z", - "M150.574 54.847 Q163.702 53.863 171.119 64.741 L202.639 110.973 Q210.056 121.851 204.343 133.713 L180.066 184.126 Q174.353 195.988 161.224 196.972 L105.426 201.153 Q92.298 202.137 84.881 191.259 L53.361 145.027 Q45.944 134.149 51.657 122.287 L75.934 71.874 Q81.647 60.012 94.776 59.028 Z", - "M148.218 52.578 Q161.562 51.074 169.537 61.879 L203.427 107.798 Q211.401 118.603 206.031 130.911 L183.208 183.221 Q177.838 195.529 164.494 197.032 L107.782 203.422 Q94.438 204.926 86.463 194.121 L52.573 148.202 Q44.599 137.397 49.969 125.089 L72.792 72.779 Q78.162 60.471 91.506 58.968 Z", - "M145.724 50.384 Q159.263 48.344 167.799 59.048 L204.079 104.542 Q212.616 115.246 207.614 127.991 L186.355 182.157 Q181.353 194.902 167.814 196.943 L110.276 205.616 Q96.737 207.656 88.201 196.952 L51.921 151.458 Q43.384 140.754 48.386 128.009 L69.645 73.843 Q74.647 61.098 88.186 59.057 Z", - "M143.094 48.274 Q156.805 45.680 165.907 56.257 L204.592 101.209 Q213.694 111.786 209.085 124.957 L189.498 180.935 Q184.889 194.106 171.178 196.700 L112.906 207.726 Q99.195 210.320 90.093 199.743 L51.408 154.791 Q42.306 144.214 46.915 131.043 L66.502 75.065 Q71.111 61.894 84.822 59.300 Z", - "M140.330 46.254 Q154.191 43.091 163.861 53.512 L204.959 97.806 Q214.629 108.227 210.439 121.813 L192.629 179.551 Q188.438 193.137 174.578 196.301 L115.670 209.746 Q101.809 212.909 92.139 202.488 L51.041 158.194 Q41.371 147.773 45.561 134.187 L63.371 76.449 Q67.562 62.863 81.422 59.699 Z", - "M137.437 44.331 Q151.423 40.584 161.662 50.823 L205.177 94.338 Q215.416 104.577 211.669 118.563 L195.741 178.007 Q191.993 191.993 178.007 195.741 L118.563 211.669 Q104.577 215.416 94.338 205.177 L50.823 161.662 Q40.584 151.423 44.331 137.437 L60.259 77.993 Q64.007 64.007 77.993 60.259 Z", - "M134.416 42.513 Q148.504 38.167 159.311 48.195 L205.242 90.813 Q216.049 100.840 212.769 115.214 L198.826 176.300 Q195.545 190.673 181.458 195.019 L121.584 213.487 Q107.496 217.833 96.689 207.805 L50.758 165.187 Q39.951 155.160 43.231 140.786 L57.174 79.700 Q60.455 65.327 74.542 60.981 Z", - "M131.272 40.805 Q145.436 35.849 156.810 45.637 L205.149 87.237 Q216.523 97.025 213.733 111.769 L201.877 174.431 Q199.087 189.175 184.923 194.131 L124.728 215.195 Q110.564 220.151 99.190 210.363 L50.851 168.763 Q39.477 158.975 42.267 144.231 L54.123 81.569 Q56.913 66.825 71.077 61.869 Z", - "M128.010 39.216 Q142.223 33.637 154.160 43.157 L204.895 83.616 Q216.832 93.136 214.556 108.234 L204.885 172.401 Q202.609 187.499 188.396 193.077 L127.990 216.784 Q113.777 222.363 101.840 212.843 L51.105 172.384 Q39.168 162.864 41.444 147.766 L51.115 83.599 Q53.391 68.501 67.604 62.923 Z", - "M124.633 37.750 Q138.869 31.539 151.365 40.762 L204.475 79.959 Q216.972 89.182 215.233 104.616 L207.842 170.209 Q206.103 185.643 191.868 191.854 L131.367 218.250 Q117.131 224.461 104.635 215.238 L51.525 176.041 Q39.028 166.818 40.767 151.384 L48.158 85.791 Q49.897 70.357 64.132 64.146 Z", - "M121.147 36.415 Q135.377 29.562 148.427 38.459 L203.889 76.272 Q216.938 85.169 215.758 100.920 L210.742 167.858 Q209.562 183.608 195.331 190.461 L134.853 219.585 Q120.623 226.438 107.573 217.541 L52.111 179.728 Q39.062 170.831 40.242 155.080 L45.258 88.142 Q46.438 72.392 60.669 65.539 Z", - "M117.556 35.216 Q131.752 27.713 145.348 36.256 L203.131 72.563 Q216.727 81.106 216.127 97.152 L213.575 165.347 Q212.975 181.393 198.778 188.896 L138.444 220.784 Q124.248 228.287 110.652 219.744 L52.869 183.437 Q39.273 174.894 39.873 158.848 L42.425 90.653 Q43.025 74.607 57.222 67.104 Z", - "M113.866 34.160 Q128.000 26.000 142.134 34.160 L202.201 68.840 Q216.335 77.000 216.335 93.320 L216.335 162.680 Q216.335 179.000 202.201 187.160 L142.134 221.840 Q128.000 230.000 113.866 221.840 L53.799 187.160 Q39.665 179.000 39.665 162.680 L39.665 93.320 Q39.665 77.000 53.799 68.840 Z" -) -private val contourLengths = listOf(460.633f,470.212f,479.792f,489.371f,498.950f,508.529f,518.108f,527.687f,537.267f,546.846f,556.425f,566.004f,575.583f,585.163f,594.742f) -@Composable -internal fun WelcomeBrandFlow(modifier: Modifier, sweep: Boolean = false) { - val paths=remember { contourData.map { PathParser.createPathFromPathData(it)!! } } - val paint=remember { Paint(Paint.ANTI_ALIAS_FLAG).apply { style=Paint.Style.STROKE;strokeWidth=1f } } - var moving by remember { mutableStateOf(false) } - val lifecycle=LocalLifecycleOwner.current.lifecycle - LaunchedEffect(lifecycle) { - lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) { - moving=coroutineContext[androidx.compose.ui.MotionDurationScale]?.scaleFactor!=0f - try { awaitCancellation() } finally { moving = false } - } - } - // Use Compose's animation clock so tooling can recognize an infinite decorative - // animation. A timer mutating state every 33 ms kept the entire UI perpetually busy. - val animatedPhase = if (moving) rememberInfiniteTransition(label = "brand-flow").animateFloat( - initialValue = 0f, targetValue = 1f, - animationSpec = infiniteRepeatable(tween(if (sweep) 5000 else 18000, easing = LinearEasing), RepeatMode.Restart), - label = "brand-phase", - ) else remember { mutableFloatStateOf(0f) } - val ink=MaterialTheme.colorScheme.onBackground - Canvas(modifier) { - val framePhase = animatedPhase.value - // Keep the cover and measured home mark on the same sweep during handoff. - val phase = if (sweep && moving) (android.os.SystemClock.uptimeMillis() % 5000L) / 5000f else framePhase - drawIntoCanvas { canvas -> - val c=canvas.nativeCanvas;c.save();c.scale(size.width/256,size.height/256);paint.color=ink.toArgb() - if(sweep) { - val shift=(minOf(1f,phase/.75f)*2-1)*256 - val colors=floatArrayOf(.16f,.25f,1f,.25f,.16f).map { alpha -> - ink.copy(alpha = if(moving) alpha else .5f).toArgb() - }.toIntArray() - paint.pathEffect=null;paint.alpha=255;paint.strokeWidth=1.45f - paint.shader=android.graphics.LinearGradient(shift,shift,256+shift,256+shift,colors, - floatArrayOf(0f,.46f,.55f,.65f,1f),android.graphics.Shader.TileMode.CLAMP) - paths.forEach { c.drawPath(it,paint) };paint.shader=null - } else paths.forEachIndexed { index,path -> - paint.pathEffect=null;paint.alpha=64;c.drawPath(path,paint) - if(moving) listOf(.34f,.26f,.18f).forEachIndexed { layer,length -> - val total=contourLengths[index] - paint.pathEffect=DashPathEffect(floatArrayOf(total*length/2,total*(1-length),total*length/2,0f),-total*(phase+index*.03f)) - paint.alpha=(255*listOf(.12f,.14f,.36f)[layer]).toInt();c.drawPath(path,paint) - } - };c.restore() - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeHome.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeHome.kt deleted file mode 100644 index 8ce529fb54..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/WelcomeHome.kt +++ /dev/null @@ -1,117 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import androidx.compose.animation.core.* -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.* -import androidx.compose.runtime.* -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.draw.drawWithContent -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.compose.LocalLifecycleOwner -import androidx.lifecycle.repeatOnLifecycle -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignColors -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry as G -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.awaitCancellation -import kotlin.math.* - -/** A welcome layout, C text motion. Only presentation state is kept here. */ -@Composable -internal fun WelcomeHome(onLogin: () -> Unit, signedIn: Boolean = false, modifier: Modifier = Modifier) { - val phrases = listOf("OpenBitFun", stringResource(R.string.welcome_work), stringResource(R.string.welcome_play), stringResource(R.string.welcome_yours)) - var moving by remember { mutableStateOf(false) } - val lifecycle = LocalLifecycleOwner.current.lifecycle - LaunchedEffect(lifecycle) { - lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) { - moving = currentCoroutineContext()[androidx.compose.ui.MotionDurationScale]?.scaleFactor != 0f - try { awaitCancellation() } finally { moving = false } - } - } - val duration = phrases.sumOf { welcomeDuration(it) } - val elapsed = if (moving) rememberInfiniteTransition(label = "welcome-copy").animateFloat( - initialValue = 0f, targetValue = duration.toFloat(), - animationSpec = infiniteRepeatable(tween(duration, easing = LinearEasing), RepeatMode.Restart), - label = "welcome-time", - ) else remember { mutableFloatStateOf(2700f) } - var time = elapsed.value - var phrase = phrases.first() - for (item in phrases) { phrase = item; if (time < welcomeDuration(item)) break; time -= welcomeDuration(item) } - val ink = MaterialTheme.colorScheme.onBackground - BoxWithConstraints(modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.TopCenter) { - val pageHeight = maxHeight.coerceAtLeast(540.dp) - Column(Modifier.widthIn(max = G.WelcomeMaxWidth).fillMaxWidth().verticalScroll(rememberScrollState()).heightIn(min = pageHeight)) { - Row(Modifier.fillMaxWidth().height(G.WelcomeHeaderHeight).padding(horizontal = G.WelcomeGutter), verticalAlignment = Alignment.CenterVertically) { - Row { "OpenBitFun".forEach { c -> WelcomeGlyph(c, G.WelcomeHeaderWordSize.value, Modifier) } } - } - Box(Modifier.fillMaxWidth().height((pageHeight - G.WelcomeHeaderHeight - 228.dp).coerceAtLeast(270.dp)), contentAlignment = Alignment.Center) { - Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.offset(y = (-28).dp)) { - WelcomeBrandFlow(Modifier.size(G.WelcomeMarkSize)) - Spacer(Modifier.height(29.dp)) - Row(Modifier.height(48.dp).clearAndSetSemantics { contentDescription = "OpenBitFun" }, verticalAlignment = Alignment.CenterVertically) { - phrase.forEachIndexed { index, c -> - val p = ((time - 180 - index * 55) / 800).coerceIn(0f, 1f) - val ease = 1 - (1-p).pow(3) - val bump = sin(p * PI).toFloat() * (1-p) - val out = ((time-welcomeDuration(phrase)+650)/650).coerceIn(0f,1f) - WelcomeGlyph(c, if(phrase.length>12) 27f else G.WelcomeWordSize.value, Modifier.graphicsLayer { - alpha = (p*3).coerceIn(0f,1f)*(1-out) - translationX = ((1-ease)*38-bump*5-out*out*30).dp.toPx() - scaleX = 1+bump*.045f; scaleY = scaleX - }) - } - } - } - } - Column( - Modifier.fillMaxWidth().background( - MobileDesignColors.Light.WelcomeDock, - RoundedCornerShape(topStart = G.WelcomeDockRadius, topEnd = G.WelcomeDockRadius), - ), - ) { - Column( - Modifier.fillMaxWidth() - .padding(start = G.WelcomeGutter, end = G.WelcomeGutter, top = G.WelcomeGutter, bottom = G.WelcomeDockBottom) - .navigationBarsPadding(), - verticalArrangement = Arrangement.spacedBy(G.WelcomeButtonGap), - ) { - WelcomeAction(stringResource(if (signedIn) R.string.sidebar_connect_desktop else R.string.welcome_login), onLogin) - com.openbitfun.mobile.app.ui.miniapps.MiniAppsButton(contentColor = MobileDesignColors.Light.WelcomeButton) - } - } - } - } -} - -@Composable -private fun WelcomeAction(label: String, onClick: () -> Unit) { - Button(onClick, Modifier.fillMaxWidth().height(G.WelcomeButtonHeight), shape = RoundedCornerShape(28.dp), - colors = ButtonDefaults.buttonColors(containerColor = MobileDesignColors.Light.WelcomeButton, contentColor = MobileDesignColors.Light.WelcomeButtonLabel)) { - Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold) - } -} -private fun welcomeDuration(word: String) = 250+word.length*185+(if(word=="OpenBitFun")600 else 0)+1800+650 - -@Composable -private fun WelcomeGlyph(letter: Char, fontSize: Float, modifier: Modifier) { - Text(if(letter=='i') "ı" else letter.toString(), fontSize = fontSize.sp, - fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, - modifier = modifier.drawWithContent { - drawContent() - if(letter=='i') drawCircle(MobileDesignColors.Light.BrandDot, radius = fontSize.sp.toPx()*.07f, - center = Offset(size.width/2, fontSize.sp.toPx()*.25f)) - }) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/AppSidebar.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/AppSidebar.kt deleted file mode 100644 index 252127deb6..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/AppSidebar.kt +++ /dev/null @@ -1,242 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.compose.foundation.background -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon -import androidx.compose.material3.LocalContentColor -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.remote.SessionActionPopup -import com.openbitfun.mobile.app.ui.remote.SessionActionSheet -import com.openbitfun.mobile.app.ui.remote.SessionDetailsSheet -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.account.AccountDeviceUi -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.RemoteControlSource -import com.openbitfun.mobile.core.feature.session.SessionActionPolicy -import com.openbitfun.mobile.core.feature.session.SessionActionScope -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.WorkspaceSessionDirectoryUiState -import com.openbitfun.mobile.core.feature.layout.SettingsPlacement -import com.openbitfun.mobile.core.feature.shell.RemoteSidebarSessionRow -import com.openbitfun.mobile.core.feature.shell.RemoteSidebarWorkspaceRow -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState - -internal const val SIDEBAR_TEST_TAG: String = "app-sidebar" - -/** Tagged because "Code" also labels the session-list filter on the remote screen. */ -internal const val SIDEBAR_CODE_TEST_TAG: String = "app-sidebar-code" - -/** - * The drawer, ported from `pages/components/AppSidebar.ets`. - * - * The header, the source nav row and the footer are the same in every state so - * that signing in, or switching what the content area shows, never moves the - * shared chrome. Which half of the header and footer renders is decided by - * [accountUserId], exactly as `isAccountAuthenticated` decides it there. - * - * The per-row menu is hoisted here rather than into each row: only one row's menu - * can be open at a time, and holding that as one nullable id is what lets the - * open row stay highlighted underneath the sheet. - */ -@Composable -internal fun AppSidebar( - permanent: Boolean, - sessionDetailsPlacement: SettingsPlacement, - accountUserId: String?, - connectionPhase: ConnectionPhase, - remoteControlSource: RemoteControlSource, - remoteDevices: List, - remoteSelectedDeviceId: String?, - remoteDeviceName: String, - remoteState: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - workspaceDirectory: WorkspaceSessionDirectoryUiState, - remoteActive: Boolean, - remoteSelectedSessionId: String?, - query: String, - searchOpen: Boolean, - onQueryChange: (String) -> Unit, - onToggleSearch: () -> Unit, - onConnectDesktop: () -> Unit, - onRetryRemoteDevice: () -> Unit, - onRefreshRemoteDevices: () -> Unit, - refreshingRemoteDevices: Boolean, - directoryRefreshError: String? = null, - onSelectRemoteDevice: (String) -> Unit, - onOpenRemoteSession: (String) -> Unit, - onCreateRemoteInWorkspace: (RemoteSidebarWorkspaceRow, String) -> Unit, - onOpenRemoteWorkspace: (RemoteSidebarWorkspaceRow) -> Unit, - onExpandRemoteWorkspace: (RemoteSidebarWorkspaceRow) -> Unit, - onRetryRemoteWorkspaceSessions: (RemoteSidebarWorkspaceRow) -> Unit, - onAddRemoteWorkspace: (() -> Unit)? = null, - onWorkspaceTool: (String, String?, Boolean) -> Unit, - onDeleteRemoteSession: (String) -> Unit, - onOpenSettings: () -> Unit, - onOpenAccount: () -> Unit, - modifier: Modifier, -) { - val signedIn = !accountUserId.isNullOrBlank() - var remoteActionSession by remember { mutableStateOf(null) } - var remoteActionAnchor by remember { mutableStateOf(IntRect.Zero) } - var remoteDetailsSessionId by rememberSaveable { mutableStateOf(null) } - - // The rail is chrome, not another page: it paints the desktop client's - // `surface.chrome` itself and hands every unstyled descendant the matching - // ink, so nothing inside has to remember which layer it is on. - CompositionLocalProvider(LocalContentColor provides openBitFunColors.sidebar.ink) { - Box( - modifier = modifier - .fillMaxSize() - .background(openBitFunColors.sidebar.background) - .testTag(SIDEBAR_TEST_TAG), - ) { - // No spacedBy: the MiniApps row carries its own 4dp/8dp rhythm, and a - // column-level gap on top of it would push the section header away. - Column( - modifier = Modifier - .fillMaxSize() - .padding(start = 20.dp, end = 20.dp, top = 0.dp, bottom = 16.dp), - ) { - if (signedIn) { - SidebarAuthenticatedHeader(searchOpen, query, onQueryChange, onToggleSearch) - } else { - Text( - stringResource(R.string.app_name), - style = MaterialTheme.typography.titleLarge, - color = openBitFunColors.sidebar.ink, - ) - } - - com.openbitfun.mobile.app.ui.miniapps.MiniAppsButton(sidebar = true) - - Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(bottom = 142.dp)) { - SidebarRemoteWorkspaceSection( - connectionPhase = connectionPhase, - controlSource = remoteControlSource, - devices = remoteDevices, - selectedDeviceId = remoteSelectedDeviceId, - deviceName = remoteDeviceName, - remoteState = remoteState, - workspaceState = workspaceState, - workspaceDirectory = workspaceDirectory, - selectedSessionId = remoteSelectedSessionId.takeIf { remoteActive }, - onConnect = onConnectDesktop, - onRetryActive = onRetryRemoteDevice, - onRefreshDevices = onRefreshRemoteDevices, - refreshingDevices = refreshingRemoteDevices, - directoryRefreshError = directoryRefreshError, - onSelectDevice = onSelectRemoteDevice, - onOpenSession = onOpenRemoteSession, - onOpenActions = { row, anchor -> - remoteActionAnchor = anchor - remoteActionSession = row - }, - onCreateInWorkspace = onCreateRemoteInWorkspace, - onOpenWorkspace = onOpenRemoteWorkspace, - onExpandWorkspace = onExpandRemoteWorkspace, - onRetryWorkspaceSessions = onRetryRemoteWorkspaceSessions, - onAddWorkspace = onAddRemoteWorkspace, - onWorkspaceTool = onWorkspaceTool, - ) - } - - } - - // Over the list, not after it: the 84dp tail the list reserves is what - // keeps the last conversation from ending up underneath this. - Box( - modifier = Modifier - .align(Alignment.BottomCenter) - .fillMaxWidth() - .padding(start = 20.dp, end = 20.dp, bottom = 16.dp), - ) { - if (signedIn) { - SidebarAuthenticatedFooter({ onWorkspaceTool("", null, false) }, onOpenSettings) - } else { - SidebarSignedOutFooter(onOpenAccount = onOpenAccount) - } - } - } - } - - remoteActionSession?.let { session -> - val busy = (remoteState as? RemoteSessionUiState.Ready)?.busy == true - val capabilities = SessionActionPolicy.resolve( - SessionActionScope.REMOTE, - session.agentType, - busy, - ) - if (permanent) { - SessionActionPopup( - anchorBounds = remoteActionAnchor, - title = session.title, - status = "", - capabilities = capabilities, - onViewDetails = { remoteDetailsSessionId = session.id }, - onDelete = { onDeleteRemoteSession(session.id) }, - onDismiss = { remoteActionSession = null }, - ) - } else { - SessionActionSheet( - title = session.title, - status = "", - capabilities = capabilities, - onViewDetails = { remoteDetailsSessionId = session.id }, - onDelete = { onDeleteRemoteSession(session.id) }, - onDismiss = { remoteActionSession = null }, - ) - } - } - - remoteDetailsSessionId?.let { id -> - val session = (remoteState as? RemoteSessionUiState.Ready)?.sessions - ?.firstOrNull { it.id == id } - if (session == null) { - remoteDetailsSessionId = null - return@let - } - SessionDetailsSheet( - title = session.title, - agentType = session.agentType, - status = session.status, - workspaceName = session.workspaceName, - workspacePath = session.workspacePath, - createdAt = session.createdAt, - updatedAt = session.updatedAt, - messageCount = session.messageCount, - placement = sessionDetailsPlacement, - onDismiss = { remoteDetailsSessionId = null }, - ) - } - -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicy.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicy.kt deleted file mode 100644 index 2cc1530bea..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicy.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -/** Path comparisons for remote workspaces, whose wire format is POSIX-like on every client. */ -internal object RemoteWorkspacePathPolicy { - fun equal(left: String, right: String): Boolean = normalize(left) == normalize(right) - - fun normalize(path: String): String { - var value = path.trim() - while (value.length > 1 && (value.endsWith('/') || value.endsWith('\\'))) { - value = value.dropLast(1) - } - return value - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarChrome.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarChrome.kt deleted file mode 100644 index 70cb6a3172..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarChrome.kt +++ /dev/null @@ -1,85 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.annotation.DrawableRes -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.shadow -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.unit.dp -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.ConnectionStatusPresenter -import com.openbitfun.mobile.core.feature.connection.ConnectionTone - -/** - * The round carded button the sidebar's header and footer are built from, - * ported from the 38x38 and 46x46 stacks in `AppSidebar.ets`. - * - * Carded rather than a bare `IconButton`: the drawer's own background is flat - * chrome, so an icon drawn straight onto it has no edge and reads as decoration - * instead of as something to press. - * - * The colours default to the sidebar's own chrome because that is where this - * shape belongs. The session-list header reuses the shape on a page surface, so - * it passes the page roles instead — same button, correct layer. - */ -@Composable -internal fun SidebarCircleButton( - @DrawableRes icon: Int, - contentDescription: String, - diameter: Int, - onClick: () -> Unit, - modifier: Modifier, - background: Color = openBitFunColors.sidebar.raised, - border: Color = openBitFunColors.sidebar.line, - tint: Color = openBitFunColors.sidebar.ink, -) { - Box( - modifier = modifier - .size(diameter.dp) - .shadow(2.dp, CircleShape) - .clip(CircleShape) - .background(background) - .border(1.dp, border, CircleShape) - .clickable(role = Role.Button, onClick = onClick), - contentAlignment = Alignment.Center, - ) { - Icon( - painterResource(icon), - contentDescription = contentDescription, - tint = tint, - modifier = Modifier.size((diameter * 0.46f).dp), - ) - } -} - -/** The connection state as a dot, the way `SidebarGlyph({ kind: 'remote' })` renders it. */ -@Composable -internal fun ConnectionDot(phase: ConnectionPhase) { - val tone = ConnectionStatusPresenter.tone(phase) - // Keep automatic recovery quiet; color and accessibility state express reachability. - val color: Color = when (tone) { - ConnectionTone.OK -> openBitFunColors.statusSuccess - ConnectionTone.BUSY -> openBitFunColors.sidebar.muted - ConnectionTone.ERROR -> MaterialTheme.colorScheme.error - ConnectionTone.MUTED -> openBitFunColors.sidebar.muted - } - Box( - Modifier - .size(10.dp) - .clip(CircleShape) - .background(color), - ) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarDeviceSelectorRow.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarDeviceSelectorRow.kt deleted file mode 100644 index 4f053427e2..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarDeviceSelectorRow.kt +++ /dev/null @@ -1,87 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.semantics.selected -import androidx.compose.ui.semantics.stateDescription -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.common.labelRes -import com.openbitfun.mobile.app.ui.theme.openBitFunColors -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase - -@Composable -internal fun SidebarDeviceSelectorRow( - deviceName: String, - online: Boolean, - selected: Boolean, - loading: Boolean, - phase: ConnectionPhase? = null, - onSelect: () -> Unit, -) { - val deviceLabel = deviceName - val healthLabel = phase?.let { stringResource(it.labelRes()) } - Row( - modifier = Modifier - .fillMaxWidth() - .height(52.dp) - .clip(RoundedCornerShape(10.dp)) - .background(if (selected) openBitFunColors.sidebar.selection else openBitFunColors.transparent) - .clickable(enabled = online || (selected && phase in listOf(ConnectionPhase.FAILED, ConnectionPhase.DISCONNECTED)), role = Role.Button, onClick = onSelect) - .semantics(mergeDescendants = true) { - this.selected = selected - contentDescription = deviceLabel - healthLabel?.let { stateDescription = it } - } - .padding(start = 10.dp, end = 6.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_desktop), - contentDescription = null, - tint = openBitFunColors.sidebar.ink, - modifier = Modifier.size(21.dp), - ) - Text( - deviceName, - fontSize = 14.sp, - fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, - color = openBitFunColors.sidebar.ink, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - if (loading) { - CircularProgressIndicator( - color = openBitFunColors.sidebar.muted, - strokeWidth = 1.5.dp, - modifier = Modifier.size(14.dp), - ) - } else { - ConnectionDot(phase ?: if (online) ConnectionPhase.CONNECTED else ConnectionPhase.DISCONNECTED) - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarFooter.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarFooter.kt deleted file mode 100644 index 4bb1313b70..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarFooter.kt +++ /dev/null @@ -1,112 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -internal const val SIDEBAR_NEW_CHAT_TEST_TAG: String = "app-sidebar-new-chat" -internal const val SIDEBAR_SETTINGS_TEST_TAG: String = "app-sidebar-settings" - -/** Shared tools/settings navigation for compact and wide sidebars. */ -@Composable -internal fun SidebarAuthenticatedFooter(onOpenTools: () -> Unit, onOpenSettings: () -> Unit) { - val toolsLabel = stringResource(R.string.device_tools) - Row( - modifier = Modifier.fillMaxWidth().height(56.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - modifier = Modifier - .widthIn(min = 104.dp) - .height(48.dp) - .clip(RoundedCornerShape(24.dp)) - .background(openBitFunColors.sidebar.raised) - .border(1.dp, openBitFunColors.sidebar.line, RoundedCornerShape(24.dp)) - .clickable(role = Role.Button, onClick = onOpenTools) - .semantics(mergeDescendants = true) { - contentDescription = toolsLabel - } - .testTag(SIDEBAR_NEW_CHAT_TEST_TAG) - .padding(horizontal = 14.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_wrench_and_screwdriver), - contentDescription = null, - tint = openBitFunColors.sidebar.ink, - modifier = Modifier.size(24.dp), - ) - Text( - toolsLabel, - fontSize = 15.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.ink, - ) - } - Box(Modifier.weight(1f)) - SidebarCircleButton( - icon = R.drawable.ic_symbol_gearshape, - contentDescription = stringResource(R.string.navigation_settings), - diameter = 48, - onClick = onOpenSettings, - modifier = Modifier.testTag(SIDEBAR_SETTINGS_TEST_TAG), - ) - } -} - -/** - * The signed-out footer: one full-width call to sign in, the way `SignedOutFooter` - * draws it. Filled rather than carded because it is the only thing to press here. - */ -@Composable -internal fun SidebarSignedOutFooter(onOpenAccount: () -> Unit) { - val label = stringResource(R.string.sidebar_sign_in) - val shape = RoundedCornerShape(24.dp) - Box( - modifier = Modifier - .fillMaxWidth() - .height(48.dp) - .clip(shape) - .background(MaterialTheme.colorScheme.primary) - .clickable(role = Role.Button, onClick = onOpenAccount) - .semantics(mergeDescendants = true) { - contentDescription = label - }, - contentAlignment = Alignment.Center, - ) { - Text( - label, - fontSize = 16.sp, - fontWeight = FontWeight.Bold, - color = MaterialTheme.colorScheme.onPrimary, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarHeader.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarHeader.kt deleted file mode 100644 index 6cd5329d70..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarHeader.kt +++ /dev/null @@ -1,154 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.material3.Icon -import androidx.compose.material3.LocalTextStyle -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -internal const val SIDEBAR_SEARCH_TEST_TAG: String = "app-sidebar-search" - -/** - * The signed-in header, ported from `AuthenticatedHeader` in `AppSidebar.ets`: - * the product name, and the controls that act on the list below it. - */ -@Composable -internal fun SidebarAuthenticatedHeader( - searchOpen: Boolean, - query: String, - onQueryChange: (String) -> Unit, - onToggleSearch: () -> Unit, -) { - Row( - modifier = Modifier.fillMaxWidth().height(com.openbitfun.mobile.app.ui.theme.generated.MobileDesignGeometry.ConversationHeaderHeight), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.app_name), - fontSize = 20.sp, - fontWeight = FontWeight.Bold, - color = openBitFunColors.sidebar.ink, - modifier = Modifier.weight(1f), - ) - SidebarCircleButton( - icon = R.drawable.ic_symbol_magnifyingglass, - contentDescription = stringResource(R.string.sidebar_search), - diameter = 38, - onClick = onToggleSearch, - modifier = Modifier, - ) - } - if (searchOpen) SidebarSearchField(query, onQueryChange) -} - -/** - * The search field, drawn as the soft-filled 42dp box the source uses rather - * than a Material outlined field: it sits directly under the title with no label - * of its own, and an outlined box there reads as a second header. - */ -@Composable -private fun SidebarSearchField(query: String, onQueryChange: (String) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - // The header column adds no spacing of its own, so the field keeps - // its own gap under the title, matching the source's 12dp. - .padding(top = 12.dp) - .height(42.dp) - .clip(RoundedCornerShape(8.dp)) - .background(openBitFunColors.sidebar.hover) - .padding(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_magnifyingglass), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(18.dp), - ) - BasicTextField( - value = query, - onValueChange = onQueryChange, - singleLine = true, - textStyle = LocalTextStyle.current.copy( - fontSize = 15.sp, - color = openBitFunColors.sidebar.ink, - ), - cursorBrush = SolidColor(openBitFunColors.sidebar.ink), - decorationBox = { field -> - if (query.isEmpty()) { - Text( - stringResource(R.string.sidebar_search_placeholder), - fontSize = 15.sp, - color = openBitFunColors.sidebar.muted, - ) - } - field() - }, - modifier = Modifier.fillMaxWidth().testTag(SIDEBAR_SEARCH_TEST_TAG), - ) - } -} - -/** - * The signed-out header, ported from `SignedOutHeader`. - * - * Where the signed-in header names the product, this one is the one thing a - * signed-out user can still do — start a conversation — so it is a row that acts - * rather than a title. - */ -@Composable -internal fun SidebarSignedOutHeader(onNewChat: () -> Unit) { - val newChatLabel = stringResource(R.string.sidebar_signed_out_new_chat) - Row( - modifier = Modifier - .fillMaxWidth() - .height(50.dp) - .clip(RoundedCornerShape(12.dp)) - .clickable(role = Role.Button, onClick = onNewChat) - .semantics(mergeDescendants = true) { - contentDescription = newChatLabel - } - .padding(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_square_and_pencil), - contentDescription = null, - tint = openBitFunColors.sidebar.ink, - modifier = Modifier.size(22.dp), - ) - Text( - newChatLabel, - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.ink, - ) - } -} 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 deleted file mode 100644 index 5cc203f65c..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt +++ /dev/null @@ -1,689 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.getValue -import androidx.compose.runtime.setValue -import androidx.compose.runtime.Composable -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.layout.boundsInWindow -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.ui.remote.ProjectCreateControl -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.account.AccountDeviceUi -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.connection.ConnectionStatusPresenter -import com.openbitfun.mobile.core.feature.connection.RemoteControlSource -import com.openbitfun.mobile.core.feature.shell.RemoteSidebarSessionRow -import com.openbitfun.mobile.core.feature.shell.RemoteSidebarWorkspaceLoad -import com.openbitfun.mobile.core.feature.shell.RemoteSidebarWorkspaceRow -import com.openbitfun.mobile.core.feature.session.WorkspaceSessionDirectoryUiState -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -private const val SESSIONS_PER_WORKSPACE = 3 -private const val WORKSPACES_PER_BATCH = 3 -private const val DEVICES_PER_BATCH = 3 -internal const val SIDEBAR_REMOTE_SESSION_TEST_TAG: String = "app-sidebar-remote-session" - -/** The remote workspace tree appended under local conversations in Harmony's unified sidebar. */ -@OptIn(ExperimentalFoundationApi::class) -@Composable -internal fun SidebarRemoteWorkspaceSection( - connectionPhase: ConnectionPhase, - controlSource: RemoteControlSource, - devices: List, - selectedDeviceId: String?, - deviceName: String, - remoteState: RemoteSessionUiState, - workspaceState: RemoteWorkspaceUiState, - workspaceDirectory: WorkspaceSessionDirectoryUiState, - selectedSessionId: String?, - onConnect: () -> Unit, - onRetryActive: () -> Unit, - onRefreshDevices: () -> Unit, - refreshingDevices: Boolean, - directoryRefreshError: String? = null, - onSelectDevice: (String) -> Unit, - onOpenSession: (String) -> Unit, - onOpenActions: (RemoteSidebarSessionRow, IntRect) -> Unit, - /** The row carries the workspace identity (ID first); the agent type follows. */ - onCreateInWorkspace: (RemoteSidebarWorkspaceRow, String) -> Unit, - onOpenWorkspace: (RemoteSidebarWorkspaceRow) -> Unit, - onExpandWorkspace: (RemoteSidebarWorkspaceRow) -> Unit, - onRetryWorkspaceSessions: (RemoteSidebarWorkspaceRow) -> Unit, - onAddWorkspace: (() -> Unit)? = null, - onWorkspaceTool: (String, String?, Boolean) -> Unit, -) { - val connected = ConnectionStatusPresenter.canReachSessions(connectionPhase) - val refreshDevicesLabel = stringResource(R.string.account_devices_refresh) - val projectedDevices = devices - val activeDeviceId = if (controlSource == RemoteControlSource.ACCOUNT_DEVICE) selectedDeviceId else null - var visibleDeviceCount by rememberSaveable { mutableStateOf(DEVICES_PER_BATCH) } - val workspacePanels = androidx.compose.runtime.saveable.rememberSaveableStateHolder() - - Column(modifier = Modifier.fillMaxWidth().padding(top = 10.dp)) { - Row( - modifier = Modifier.fillMaxWidth().height(38.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.sidebar_devices), - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.muted, - ) - Box(Modifier.weight(1f)) - if (!connected && projectedDevices.isEmpty()) { - Text( - stringResource(R.string.sidebar_workspaces_offline), - fontSize = 12.sp, - color = openBitFunColors.sidebar.subtle, - modifier = Modifier.padding(end = 8.dp), - ) - } - Box( - modifier = Modifier - .size(32.dp) - .clip(CircleShape) - .clickable(enabled = !refreshingDevices, role = Role.Button, onClick = onRefreshDevices) - .testTag("sidebar-refresh-devices") - .semantics(mergeDescendants = true) { - contentDescription = refreshDevicesLabel - }, - contentAlignment = Alignment.Center, - ) { - if (refreshingDevices) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 1.5.dp) - else Icon( - painterResource(R.drawable.ic_symbol_arrow_clockwise), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(17.dp), - ) - } - } - - directoryRefreshError?.let { error -> - Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error, - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp) - .clickable(enabled = !refreshingDevices, role = Role.Button, onClick = onRefreshDevices)) - } - - if (projectedDevices.isEmpty()) { - SidebarActiveDeviceBody( - connected = connected, - loading = remoteState is RemoteSessionUiState.Loading || - workspaceState is RemoteWorkspaceUiState.Loading, - failed = remoteState is RemoteSessionUiState.Failed || - workspaceState is RemoteWorkspaceUiState.Failed, - deviceKey = deviceName, - remoteState = remoteState as? RemoteSessionUiState.Ready, - workspaceState = workspaceState as? RemoteWorkspaceUiState.Ready, - workspaceDirectory = workspaceDirectory, - selectedSessionId = selectedSessionId, - onConnect = onConnect, - onRetry = onRetryActive, - onOpenSession = onOpenSession, - onOpenActions = onOpenActions, - canActOnSessions = true, - onCreateInWorkspace = onCreateInWorkspace, - onOpenWorkspace = onOpenWorkspace, - onExpandWorkspace = onExpandWorkspace, - onRetryWorkspaceSessions = onRetryWorkspaceSessions, - onAddWorkspace = onAddWorkspace, - onWorkspaceTool = onWorkspaceTool, - ) - } else { - projectedDevices.take(visibleDeviceCount).forEach { device -> - val active = device.id == activeDeviceId - SidebarDeviceSelectorRow( - deviceName = device.displayName, - online = device.online, - selected = active, - loading = active && (remoteState is RemoteSessionUiState.Loading || - workspaceState is RemoteWorkspaceUiState.Loading), - phase = if (active) connectionPhase else null, - onSelect = { - if (active && connectionPhase in listOf(ConnectionPhase.FAILED, ConnectionPhase.DISCONNECTED)) { - onRetryActive() - } else if (!active && device.online) { - onSelectDevice(device.id) - } - }, - ) - } - if (visibleDeviceCount < projectedDevices.size) { - MoreRow( - hidden = projectedDevices.size - visibleDeviceCount, - startPadding = 10, - onClick = { visibleDeviceCount += DEVICES_PER_BATCH }, - devices = true, - ) - } - activeDeviceId?.let { id -> - workspacePanels.SaveableStateProvider(id) { - SidebarActiveDeviceBody( - connected = connected, - loading = remoteState is RemoteSessionUiState.Idle || remoteState is RemoteSessionUiState.Loading || - workspaceState is RemoteWorkspaceUiState.Idle || workspaceState is RemoteWorkspaceUiState.Loading, - failed = remoteState is RemoteSessionUiState.Failed || workspaceState is RemoteWorkspaceUiState.Failed, - deviceKey = id, - remoteState = remoteState as? RemoteSessionUiState.Ready, - workspaceState = workspaceState as? RemoteWorkspaceUiState.Ready, - workspaceDirectory = workspaceDirectory, - selectedSessionId = selectedSessionId, - onConnect = onConnect, - onRetry = onRetryActive, - onOpenSession = onOpenSession, - onOpenActions = onOpenActions, - canActOnSessions = true, - onCreateInWorkspace = onCreateInWorkspace, - onOpenWorkspace = onOpenWorkspace, - onExpandWorkspace = onExpandWorkspace, - onRetryWorkspaceSessions = onRetryWorkspaceSessions, - onAddWorkspace = onAddWorkspace, - onWorkspaceTool = onWorkspaceTool, - ) - } - } - } - } -} - -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun SidebarActiveDeviceBody( - connected: Boolean, - loading: Boolean, - failed: Boolean, - deviceKey: String, - remoteState: RemoteSessionUiState.Ready?, - workspaceState: RemoteWorkspaceUiState.Ready?, - workspaceDirectory: WorkspaceSessionDirectoryUiState, - selectedSessionId: String?, - onConnect: () -> Unit, - onRetry: () -> Unit, - onOpenSession: (String) -> Unit, - onOpenActions: (RemoteSidebarSessionRow, IntRect) -> Unit, - canActOnSessions: Boolean, - /** The row carries the workspace identity (ID first); the agent type follows. */ - onCreateInWorkspace: (RemoteSidebarWorkspaceRow, String) -> Unit, - onOpenWorkspace: (RemoteSidebarWorkspaceRow) -> Unit, - onExpandWorkspace: (RemoteSidebarWorkspaceRow) -> Unit, - onRetryWorkspaceSessions: (RemoteSidebarWorkspaceRow) -> Unit, - onAddWorkspace: (() -> Unit)? = null, - onWorkspaceTool: (String, String?, Boolean) -> Unit, -) { - val readyWorkspace = workspaceState - val readySessions = remoteState - val busy = remoteState?.busy == true - val entries = remember(readyWorkspace, readySessions, workspaceDirectory) { - com.openbitfun.mobile.core.feature.shell.RemoteSidebarPresentation.workspacesWithDirectory( - readyWorkspace, readySessions, workspaceDirectory, - ) - } - // A branch is open when the reader opened it, or when it is the selected - // workspace and they have not closed it. Everything else starts closed: - // each branch costs its own `list_sessions`, so they are fetched on - // disclosure rather than all at once, the way HarmonyOS already does it. - var expandedPaths by rememberSaveable(deviceKey) { mutableStateOf(emptyList()) } - var collapsedPaths by rememberSaveable(deviceKey) { mutableStateOf(emptyList()) } - var expandedSessionPaths by rememberSaveable(deviceKey) { mutableStateOf(emptyList()) } - var visibleWorkspaceCount by rememberSaveable(deviceKey) { - mutableStateOf(WORKSPACES_PER_BATCH) - } - - Row( - Modifier.fillMaxWidth().padding(top = 16.dp).height(48.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(stringResource(R.string.sidebar_workspaces), fontSize = 14.sp, - fontWeight = FontWeight.Medium, color = openBitFunColors.sidebar.muted, - modifier = Modifier.weight(1f)) - if (onAddWorkspace != null) { - androidx.compose.material3.IconButton(onClick = onAddWorkspace, - enabled = connected && canActOnSessions && readyWorkspace != null && !readyWorkspace.busy, - modifier = Modifier.testTag("sidebar-add-workspace")) { - Icon(painterResource(R.drawable.ic_symbol_plus), - contentDescription = stringResource(R.string.workspace_open_path), - modifier = Modifier.size(18.dp)) - } - } - } - - if (readyWorkspace?.catalog?.source == com.openbitfun.mobile.core.feature.workspace.WorkspaceCatalogSource.RECENT) { - Text( - stringResource(R.string.sidebar_legacy_workspace_catalog), - fontSize = 12.sp, - color = openBitFunColors.sidebar.muted, - modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp), - ) - } - - if (!connected) { - ConnectDesktopRow(onConnect) - } else if (failed) { - DeviceFailedRow(onRetry) - } else if (loading && entries.isEmpty()) { - DeviceLoadingRow() - } else if (entries.isEmpty()) { - Text( - stringResource(R.string.sidebar_empty_workspaces), - fontSize = 14.sp, - color = openBitFunColors.sidebar.muted, - modifier = Modifier.fillMaxWidth().padding(start = 10.dp, top = 6.dp, bottom = 6.dp), - ) - } else { - entries.take(visibleWorkspaceCount).forEach { entry -> - val path = entry.path - val identityKey = entry.key - val workspaceSessions = entry.sessions - val expanded = if (entry.selected) { - identityKey !in collapsedPaths - } else { - identityKey in expandedPaths - } - val collapsed = !expanded - Column(modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) { - Row( - modifier = Modifier - .fillMaxWidth() - .height(46.dp) - .clip(RoundedCornerShape(10.dp)) - .combinedClickable( - role = Role.Button, - onClick = { - if (expanded) { - if (entry.selected) { - collapsedPaths = collapsedPaths + identityKey - } else { - expandedPaths = expandedPaths - identityKey - } - } else { - if (entry.selected) { - collapsedPaths = collapsedPaths - identityKey - } else { - expandedPaths = expandedPaths + identityKey - } - // `list_sessions` answers per workspace, so - // this branch's rows only exist once asked - // for. The store ignores a repeat. - onExpandWorkspace(entry) - } - }, - onLongClick = { onOpenWorkspace(entry) }, - ) - .semantics(mergeDescendants = true) { - contentDescription = entry.name.ifBlank { path.substringAfterLast('/') } - } - .padding(start = 10.dp, end = 6.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_folder), - contentDescription = null, - tint = if (entry.selected) { - openBitFunColors.sidebar.ink - } else { - openBitFunColors.sidebar.muted - }, - modifier = Modifier.size(21.dp), - ) - Text( - entry.name.ifBlank { path.substringAfterLast('/') }, - fontSize = 15.sp, - fontWeight = if (entry.selected) { - FontWeight.Medium - } else { - FontWeight.Normal - }, - color = openBitFunColors.sidebar.ink, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - var createMenuOpen by remember(path) { mutableStateOf(false) } - ProjectCreateControl( - enabled = canActOnSessions && connected, - supportsHarnessProfiles = true, - modesOnly = true, - path = path, - expanded = createMenuOpen, - onToggle = { - if (entry.kind == "assistant") onCreateInWorkspace(entry, "claw") - else createMenuOpen = !createMenuOpen - }, - onDismiss = { createMenuOpen = false }, - onCreateAgent = { agent -> createMenuOpen = false; onCreateInWorkspace(entry, agent) }, - ) - Icon( - painterResource( - if (collapsed) R.drawable.ic_symbol_chevron_right - else R.drawable.ic_symbol_chevron_down, - ), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(13.dp), - ) - } - - if (expanded) { - when (entry.load) { - RemoteSidebarWorkspaceLoad.IDLE, - RemoteSidebarWorkspaceLoad.LOADING, - -> if (workspaceSessions.isEmpty()) DeviceLoadingRow(startPadding = 26.dp) - RemoteSidebarWorkspaceLoad.FAILED -> WorkspaceFailedRow { - onRetryWorkspaceSessions(entry) - } - RemoteSidebarWorkspaceLoad.READY -> if (workspaceSessions.isEmpty()) { - Text( - stringResource(R.string.sidebar_workspace_empty_sessions), - fontSize = 13.sp, - color = openBitFunColors.sidebar.muted, - modifier = Modifier.fillMaxWidth() - .padding(start = 26.dp, top = 6.dp, bottom = 6.dp), - ) - } - } - val limit = if (identityKey in expandedSessionPaths) { - workspaceSessions.size - } else { - SESSIONS_PER_WORKSPACE - } - workspaceSessions.take(limit).forEach { session -> - RemoteSessionRow( - session = session, - selected = session.id == selectedSessionId, - busy = busy, - canActOnSessions = canActOnSessions, - onOpenSession = onOpenSession, - onOpenActions = onOpenActions, - ) - } - if (limit < workspaceSessions.size) { - MoreRow( - hidden = workspaceSessions.size - limit, - startPadding = 26, - onClick = { expandedSessionPaths = expandedSessionPaths + identityKey }, - ) - } - } - } - } - if (visibleWorkspaceCount < entries.size) { - MoreRow( - hidden = entries.size - visibleWorkspaceCount, - startPadding = 10, - onClick = { visibleWorkspaceCount += WORKSPACES_PER_BATCH }, - workspaces = true, - ) - } - if (loading) DeviceLoadingRow() - } -} - -@Composable -private fun DeviceLoadingRow(startPadding: Dp = 10.dp) { - Row( - modifier = Modifier.fillMaxWidth().height(40.dp).padding(start = startPadding, end = 10.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - CircularProgressIndicator( - color = openBitFunColors.sidebar.muted, - strokeWidth = 1.5.dp, - modifier = Modifier.size(14.dp), - ) - Text( - stringResource(R.string.sidebar_device_loading), - fontSize = 13.sp, - color = openBitFunColors.sidebar.muted, - ) - } -} - -/** One workspace whose own session list could not be read, indented under it. */ -@Composable -private fun WorkspaceFailedRow(onRetry: () -> Unit) { - val retryLabel = stringResource(R.string.sidebar_device_retry) - Row( - modifier = Modifier.fillMaxWidth().height(40.dp).padding(start = 26.dp, end = 10.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.sidebar_workspace_load_failed), - fontSize = 13.sp, - color = openBitFunColors.sidebar.muted, - modifier = Modifier.weight(1f), - ) - Text( - retryLabel, - fontSize = 13.sp, - color = openBitFunColors.sidebar.ink, - modifier = Modifier - .clickable(role = Role.Button, onClick = onRetry) - .semantics { contentDescription = retryLabel }, - ) - } -} - -@Composable -private fun DeviceFailedRow(onRetry: () -> Unit) { - val retryLabel = stringResource(R.string.sidebar_device_retry) - Row( - modifier = Modifier - .fillMaxWidth() - .height(40.dp) - .padding(start = 10.dp, end = 10.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stringResource(R.string.sidebar_device_load_failed), - fontSize = 13.sp, - color = openBitFunColors.sidebar.muted, - modifier = Modifier.weight(1f), - ) - Text( - retryLabel, - fontSize = 13.sp, - color = openBitFunColors.sidebar.ink, - modifier = Modifier - .clickable(role = Role.Button, onClick = onRetry) - .semantics { contentDescription = retryLabel }, - ) - } -} - -@Composable -private fun ConnectDesktopRow(onConnect: () -> Unit) { - val connectLabel = stringResource(R.string.sidebar_connect_desktop) - Row( - modifier = Modifier - .fillMaxWidth() - .height(46.dp) - .clip(RoundedCornerShape(10.dp)) - .clickable(role = Role.Button, onClick = onConnect) - .semantics(mergeDescendants = true) { - contentDescription = connectLabel - } - .padding(start = 10.dp, end = 8.dp) - .testTag(SIDEBAR_CODE_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_desktop), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(22.dp), - ) - Text( - connectLabel, - fontSize = 15.sp, - color = openBitFunColors.sidebar.ink, - modifier = Modifier.weight(1f), - ) - Icon( - painterResource(R.drawable.ic_symbol_chevron_right), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(13.dp), - ) - } -} - -@Composable -private fun RemoteSessionRow( - session: RemoteSidebarSessionRow, - selected: Boolean, - busy: Boolean, - canActOnSessions: Boolean, - onOpenSession: (String) -> Unit, - onOpenActions: (RemoteSidebarSessionRow, IntRect) -> Unit, -) { - var anchorBounds by remember { mutableStateOf(IntRect.Zero) } - val sessionTitle = session.title.ifBlank { stringResource(R.string.sidebar_untitled) } - val icon = when (session.agentType.lowercase()) { - "code" -> R.drawable.ic_symbol_code_square - "claw", "assistant", "chat" -> R.drawable.ic_symbol_message - else -> R.drawable.ic_symbol_doc_text - } - Row( - modifier = Modifier - .fillMaxWidth() - .height(44.dp) - .clip(RoundedCornerShape(10.dp)) - .background(if (selected) openBitFunColors.sidebar.selection else openBitFunColors.transparent) - .onGloballyPositioned { coordinates -> - anchorBounds = coordinates.boundsInWindow().toIntRect() - } - .combinedClickable( - enabled = !busy, - role = Role.Button, - onClick = { onOpenSession(session.id) }, - onLongClick = if (canActOnSessions) { - { onOpenActions(session, anchorBounds) } - } else { - null - }, - ) - .semantics(mergeDescendants = true) { - contentDescription = sessionTitle - } - .padding(start = 26.dp, end = 4.dp) - .testTag(SIDEBAR_REMOTE_SESSION_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(icon), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(19.dp), - ) - Text( - sessionTitle, - fontSize = 13.sp, - fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal, - color = openBitFunColors.sidebar.ink, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - if (canActOnSessions) { - IconButton( - enabled = !busy, - onClick = { onOpenActions(session, anchorBounds) }, - ) { - Icon( - painterResource(R.drawable.ic_symbol_ellipsis), - contentDescription = stringResource(R.string.session_actions), - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(18.dp), - ) - } - } - } -} - -private fun Rect.toIntRect(): IntRect = IntRect( - left = left.toInt(), - top = top.toInt(), - right = right.toInt(), - bottom = bottom.toInt(), -) - -@Composable -private fun MoreRow( - hidden: Int, - startPadding: Int, - onClick: () -> Unit, - workspaces: Boolean = false, - devices: Boolean = false, -) { - val moreLabel = stringResource( - when { - devices -> R.string.sidebar_more_devices - workspaces -> R.string.sidebar_more_workspaces - else -> R.string.sessions_show_more - }, - hidden, - ) - Row( - modifier = Modifier - .fillMaxWidth() - .height(40.dp) - .clickable(role = Role.Button, onClick = onClick) - .semantics(mergeDescendants = true) { - contentDescription = moreLabel - } - .padding(start = startPadding.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - moreLabel, - fontSize = 13.sp, - color = openBitFunColors.sidebar.muted, - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarSessionList.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarSessionList.kt deleted file mode 100644 index c49940b49e..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarSessionList.kt +++ /dev/null @@ -1,305 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.layout.boundsInWindow -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.unit.sp -import com.openbitfun.mobile.app.R -import com.openbitfun.mobile.core.feature.shell.SidebarSections -import com.openbitfun.mobile.core.feature.shell.SidebarSessionRow -import com.openbitfun.mobile.app.ui.theme.openBitFunColors - -internal const val SIDEBAR_PINNED_TEST_TAG: String = "app-sidebar-pinned" -internal const val SIDEBAR_ARCHIVED_TEST_TAG: String = "app-sidebar-archived" -internal const val SIDEBAR_MORE_TEST_TAG: String = "app-sidebar-more" - -/** - * The conversation list, ported from `LocalSessionContent` in `AppSidebar.ets`. - * - * Three sections rather than one list: what is held above, what is recent, and - * what has been filed away behind a disclosure that only says how much is in - * there. The archive stays collapsed because its whole point is to be out of the - * way of the list a user actually reads. - */ -@Composable -internal fun SidebarSessionList( - sections: SidebarSections, - selectedSessionId: String?, - activeActionSessionId: String?, - searching: Boolean, - archivedExpanded: Boolean, - onToggleArchived: () -> Unit, - onOpenSession: (SidebarSessionRow) -> Unit, - onOpenActions: (SidebarSessionRow, IntRect) -> Unit, - workspaceContent: @Composable () -> Unit, - footerRoom: Dp = 84.dp, - modifier: Modifier, -) { - LazyColumn( - modifier = modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - if (sections.pinned.isNotEmpty()) { - item(key = "pinned-header") { - SectionLabel( - stringResource(R.string.sidebar_pinned), - Modifier.testTag(SIDEBAR_PINNED_TEST_TAG), - ) - } - items(sections.pinned, key = { "pinned-" + it.id }) { session -> - SessionRow( - session = session, - pinned = true, - selected = session.id == selectedSessionId || - session.id == activeActionSessionId, - onOpen = onOpenSession, - onOpenActions = onOpenActions, - ) - } - } - - item(key = "recent-header") { SectionLabel(stringResource(R.string.sidebar_recent), Modifier) } - - if (sections.recent.isEmpty()) { - item(key = "recent-empty") { - Text( - stringResource( - if (searching) R.string.sidebar_no_search_result else R.string.sidebar_recent_empty, - ), - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.muted, - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), - ) - } - } else { - items(sections.recent, key = { "recent-" + it.id }) { session -> - SessionRow( - session = session, - pinned = false, - selected = session.id == selectedSessionId || - session.id == activeActionSessionId, - onOpen = onOpenSession, - onOpenActions = onOpenActions, - ) - } - } - - if (sections.archivedCount > 0) { - item(key = "archived-disclosure") { - ArchivedDisclosureRow( - count = sections.archivedCount, - expanded = archivedExpanded, - onToggle = onToggleArchived, - ) - } - if (archivedExpanded) { - items(sections.archived, key = { "archived-" + it.id }) { session -> - SessionRow( - session = session, - pinned = false, - selected = session.id == selectedSessionId || - session.id == activeActionSessionId, - onOpen = onOpenSession, - onOpenActions = onOpenActions, - ) - } - } - } - - item(key = "workspace-section") { workspaceContent() } - - // Room for the footer, which floats over the bottom of this list rather - // than pushing it up — the same 84dp the source reserves. - item(key = "footer-room") { Box(Modifier.height(footerRoom)) } - } -} - -@Composable -private fun SectionLabel(text: String, modifier: Modifier) { - Text( - text, - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.muted, - modifier = modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp), - ) -} - -/** - * One conversation. - * - * Long-press opens the same menu as the overflow button: on a list this narrow - * the button is a small target, and holding a row is what a phone user reaches - * for first. - */ -@OptIn(ExperimentalFoundationApi::class) -@Composable -private fun SessionRow( - session: SidebarSessionRow, - pinned: Boolean, - selected: Boolean, - onOpen: (SidebarSessionRow) -> Unit, - onOpenActions: (SidebarSessionRow, IntRect) -> Unit, -) { - val title = session.title.ifBlank { stringResource(R.string.sidebar_untitled) } - var anchorBounds by remember { mutableStateOf(IntRect.Zero) } - Row( - modifier = Modifier - .fillMaxWidth() - .height(44.dp) - .clip(RoundedCornerShape(10.dp)) - .background(if (selected) openBitFunColors.sidebar.selection else openBitFunColors.transparent) - .onGloballyPositioned { coordinates -> - anchorBounds = coordinates.boundsInWindow().toIntRect() - } - .combinedClickable( - role = Role.Button, - onClick = { onOpen(session) }, - onLongClick = { onOpenActions(session, anchorBounds) }, - ) - .semantics { contentDescription = title } - .padding(start = 12.dp, end = 4.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (pinned) { - Icon( - painterResource(R.drawable.ic_symbol_checkmark_circle), - contentDescription = stringResource(R.string.sidebar_pinned), - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(18.dp), - ) - } - Text( - title, - fontSize = 15.sp, - color = openBitFunColors.sidebar.ink, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - Box( - modifier = Modifier - .width(34.dp) - .height(40.dp) - .clip(RoundedCornerShape(8.dp)) - .clickable(role = Role.Button) { onOpenActions(session, anchorBounds) } - .testTag(SIDEBAR_MORE_TEST_TAG), - contentAlignment = Alignment.Center, - ) { - Icon( - painterResource(R.drawable.ic_symbol_ellipsis), - contentDescription = stringResource(R.string.session_actions), - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(18.dp), - ) - } - } -} - -private fun Rect.toIntRect(): IntRect = IntRect( - left = left.toInt(), - top = top.toInt(), - right = right.toInt(), - bottom = bottom.toInt(), -) - -/** The archive, shown as how much is in it rather than as what is in it. */ -@Composable -private fun ArchivedDisclosureRow(count: Int, expanded: Boolean, onToggle: () -> Unit) { - val archivedLabel = stringResource(R.string.sidebar_archived) - Row( - modifier = Modifier - .fillMaxWidth() - .padding(top = 8.dp) - .height(46.dp) - .clip(RoundedCornerShape(10.dp)) - .background(if (expanded) openBitFunColors.sidebar.selection else openBitFunColors.transparent) - .clickable(role = Role.Button, onClick = onToggle) - .semantics(mergeDescendants = true) { - contentDescription = archivedLabel - } - .padding(start = 12.dp, end = 12.dp) - .testTag(SIDEBAR_ARCHIVED_TEST_TAG), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - painterResource(R.drawable.ic_symbol_archivebox), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(20.dp), - ) - Text( - archivedLabel, - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.ink, - modifier = Modifier.weight(1f), - ) - Box( - modifier = Modifier - .width(24.dp) - .height(22.dp) - .clip(RoundedCornerShape(11.dp)) - .background(openBitFunColors.sidebar.selection), - contentAlignment = Alignment.Center, - ) { - Text( - count.toString(), - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - color = openBitFunColors.sidebar.muted, - ) - } - Icon( - painterResource( - if (expanded) { - R.drawable.ic_symbol_chevron_up - } else { - R.drawable.ic_symbol_chevron_down - }, - ), - contentDescription = null, - tint = openBitFunColors.sidebar.muted, - modifier = Modifier.size(16.dp), - ) - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/OpenBitFunMotion.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/OpenBitFunMotion.kt deleted file mode 100644 index cb0f9a26b8..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/OpenBitFunMotion.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.openbitfun.mobile.app.ui.theme - -import androidx.compose.animation.core.CubicBezierEasing -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignMotion - -/** - * Motion contract for the mobile surfaces. - * - * [MotionQuickMillis] and [MotionStructureMillis] consume the generated - * design-system tokens from [MobileDesignMotion]. Compose's composable animation - * APIs and [androidx.compose.animation.core.Animatable.animateTo] honor - * [androidx.compose.animation.core.MotionDurationScale] from the coroutine - * context, and the Android window recomposer derives that scale from the system - * `Settings.Global.ANIMATOR_DURATION_SCALE` ("Remove animations"), so reduced - * motion needs no call-site scaling. The drawer keeps its real durations under - * that scale rather than switching to a different, shorter animation. - * - * The remaining drawer durations mirror the HarmonyOS `AppShell.ets` timings and - * intentionally exceed the minimal Quick/Structure scale; [MotionDrawerHideMillis] - * reuses the structure token because its value is already the same. - */ -internal const val MotionQuickMillis: Int = MobileDesignMotion.Quick -internal const val MotionStructureMillis: Int = MobileDesignMotion.Structure -internal const val MotionDrawerScrimMillis: Int = 210 -internal const val MotionDrawerOpenMillis: Int = 320 -internal const val MotionDrawerCloseMillis: Int = 250 -internal const val MotionDrawerRevealMillis: Int = 300 -internal const val MotionDrawerHideMillis: Int = MotionStructureMillis - -internal val OpenBitFunEaseOut = CubicBezierEasing(0f, 0f, 0.58f, 1f) -internal val OpenBitFunEaseInOut = CubicBezierEasing(0.42f, 0f, 0.58f, 1f) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/Theme.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/Theme.kt deleted file mode 100644 index 678d089ad3..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/Theme.kt +++ /dev/null @@ -1,328 +0,0 @@ -package com.openbitfun.mobile.app.ui.theme - -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.darkColorScheme -import androidx.compose.material3.lightColorScheme -import androidx.compose.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.ReadOnlyComposable -import androidx.compose.runtime.staticCompositionLocalOf -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.unit.Density -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignColors -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignTypography -import com.openbitfun.mobile.app.ui.theme.generated.MobileTextScale - -/** - * The palette, ported from the HarmonyOS client's `Theme.ets` plus its - * `resources/base` and `resources/dark` colour elements. - * - * Stock `lightColorScheme()` / `darkColorScheme()` is Material's purple baseline, - * which is not what the other client looks like: OpenBitFun's is a warm paper-and-ink - * palette. Every screen here already speaks in Material roles rather than - * literals, so aligning the two clients is a matter of what those roles resolve - * to — nothing below this file had to change to get the new colours. - * - * Additional semantic colors cover app-owned surfaces such as media and toasts. - */ -private val LightTokens = MobileDesignColors.Light -private val DarkTokens = MobileDesignColors.Dark -private val InkLight = LightTokens.Ink -private val InkDark = DarkTokens.Ink -private val ContentOnAction = LightTokens.ContentOnAction - -private val LightScheme = lightColorScheme( - primary = LightTokens.PrimaryAction, - onPrimary = ContentOnAction, - primaryContainer = LightTokens.Soft, - onPrimaryContainer = InkLight, - secondary = LightTokens.Accent, - onSecondary = ContentOnAction, - secondaryContainer = LightTokens.Soft, - onSecondaryContainer = InkLight, - // file_link: the one saturated hue in the palette. Material has no link - // role, so it lands on tertiary — which is also the "busy" connection dot. - tertiary = LightTokens.FileLink, - onTertiary = ContentOnAction, - background = LightTokens.PageBg, - onBackground = InkLight, - surface = LightTokens.Card, - onSurface = InkLight, - surfaceVariant = LightTokens.Soft, - onSurfaceVariant = LightTokens.Muted, - // The whole container family, not only the two a card reads. Material fills - // any role left unset from its own purple baseline, and the roles nothing in - // this app names by hand are exactly the ones its components reach for on - // their own — `ModalBottomSheet` takes surfaceContainerLow, elevation takes - // surfaceTint, a snackbar takes inverseSurface. Leaving them out painted a - // lilac sheet under a paper-coloured page. - surfaceContainerLowest = LightTokens.Card, - surfaceContainerLow = LightTokens.FloatingPanelBg, - surfaceContainer = LightTokens.FloatingPanelBg, - surfaceContainerHigh = LightTokens.Soft, - surfaceContainerHighest = LightTokens.Line, - surfaceBright = LightTokens.PageBg, - surfaceDim = LightTokens.Line, - // No tint: the source's cards are flat fills, and a tinted overlay would put - // the ink colour back over every raised surface. - surfaceTint = LightTokens.Card, - inverseSurface = DarkTokens.Soft, - inverseOnSurface = InkDark, - inversePrimary = LightTokens.Line, - outline = LightTokens.Subtle, - outlineVariant = LightTokens.Line, - error = LightTokens.StatusDanger, - onError = ContentOnAction, - // The HarmonyOS palette has no error container; rather than invent a hue, - // a failure card is the same soft surface with the error colour on it. - errorContainer = LightTokens.Soft, - onErrorContainer = LightTokens.StatusDanger, - scrim = LightTokens.Scrim, -) - -private val DarkScheme = darkColorScheme( - primary = DarkTokens.PrimaryAction, - onPrimary = ContentOnAction, - primaryContainer = DarkTokens.Soft, - onPrimaryContainer = InkDark, - secondary = DarkTokens.Accent, - onSecondary = ContentOnAction, - secondaryContainer = DarkTokens.Soft, - onSecondaryContainer = InkDark, - tertiary = DarkTokens.FileLink, - onTertiary = DarkTokens.PageBg, - background = DarkTokens.PageBg, - onBackground = InkDark, - surface = DarkTokens.Card, - onSurface = InkDark, - surfaceVariant = DarkTokens.Soft, - onSurfaceVariant = DarkTokens.Muted, - surfaceContainerLowest = DarkTokens.StartWindowBackground, - surfaceContainerLow = DarkTokens.FloatingPanelBg, - surfaceContainer = DarkTokens.FloatingPanelBg, - surfaceContainerHigh = DarkTokens.Soft, - surfaceContainerHighest = DarkTokens.Line, - surfaceBright = DarkTokens.Accent, - surfaceDim = DarkTokens.PageBg, - surfaceTint = DarkTokens.Card, - inverseSurface = InkDark, - inverseOnSurface = DarkTokens.Card, - inversePrimary = DarkTokens.Line, - outline = DarkTokens.Subtle, - outlineVariant = DarkTokens.Line, - error = DarkTokens.StatusDanger, - onError = ContentOnAction, - errorContainer = DarkTokens.Soft, - onErrorContainer = DarkTokens.StatusDanger, - scrim = DarkTokens.Scrim, -) - -/** - * Palette entries Material has no role for. - * - * [success] is the connection dot's "connected" green — it is not `primary`, - * because primary here is near-black ink and a black dot reads as "off". - */ -internal data class OpenBitFunColors( - val transparent: Color, - val statusSuccess: Color, - val shellScrim: Color, - val mediaBackground: Color, - val mediaScrim: Color, - val mediaControlBackground: Color, - val toastBackground: Color, - val shadowSubtle: Color, - val shadowMedium: Color, - val shadowStrong: Color, - val floatingBorder: Color, - val heroBackground: Color, - val heroSurface: Color, - val heroAccent: Color, - val heroSecondary: Color, - val sidebar: SidebarColors, - val code: CodeSyntaxColors, -) - -/** - * The navigation chrome, held apart from the page palette above. - * - * The desktop client paints its sidebar from a separate family — `surface.chrome` - * one step off the scene, hairlines and selection fills carried as alpha over it - * — so the rail reads as structure rather than as another sheet of paper. These - * are those roles, one for one, and they belong to the sidebar only: a page that - * borrows them stops looking like the desktop, not more like it. - * - * [selection], [line] and [hover] are translucent on purpose. They are meant to - * composite over [background]; flattening them loses the rail's depth. - */ -internal data class SidebarColors( - val background: Color, - val raised: Color, - val line: Color, - val hover: Color, - val selection: Color, - val ink: Color, - val muted: Color, - val subtle: Color, -) - -/** - * What `CodeSyntaxTokenKind` looks like, one entry per kind that is not plain - * text. Straight from the `code_*` colour elements of the HarmonyOS client. - * - * [targetBackground] is not a token colour: it paints behind whichever lines the - * agent's reference named, so a `file.kt:80-92` preview shows *where* rather than - * only *what*. - */ -internal data class CodeSyntaxColors( - val lineNumber: Color, - val keyword: Color, - val string: Color, - val number: Color, - val comment: Color, - val function: Color, - val type: Color, - val constant: Color, - val property: Color, - val targetBackground: Color, -) - -private val LightExtras = OpenBitFunColors( - transparent = LightTokens.Transparent, - statusSuccess = LightTokens.StatusSuccess, - shellScrim = LightTokens.ShellScrim, - mediaBackground = LightTokens.MediaBackground, - mediaScrim = LightTokens.MediaScrim, - mediaControlBackground = LightTokens.MediaControlBackground, - toastBackground = LightTokens.ToastBackground, - shadowSubtle = LightTokens.ShadowSubtle, - shadowMedium = LightTokens.ShadowMedium, - shadowStrong = LightTokens.ShadowStrong, - floatingBorder = LightTokens.FloatingBorder, - heroBackground = LightTokens.ConnectHeroBg, - heroSurface = LightTokens.ConnectHeroSurface, - heroAccent = LightTokens.ConnectHeroAccent, - heroSecondary = LightTokens.ConnectHeroSecondary, - sidebar = SidebarColors( - background = LightTokens.SidebarBg, - raised = LightTokens.SidebarRaised, - line = LightTokens.SidebarLine, - hover = LightTokens.SidebarHover, - selection = LightTokens.SidebarSelection, - ink = LightTokens.SidebarInk, - muted = LightTokens.SidebarMuted, - subtle = LightTokens.SidebarSubtle, - ), - code = CodeSyntaxColors( - lineNumber = LightTokens.CodeLineNumber, - keyword = LightTokens.CodeKeyword, - string = LightTokens.CodeString, - number = LightTokens.CodeNumber, - comment = LightTokens.CodeComment, - function = LightTokens.CodeFunction, - type = LightTokens.CodeType, - constant = LightTokens.CodeConstant, - property = LightTokens.CodeProperty, - targetBackground = LightTokens.CodeTargetBg, - ), -) - -private val DarkExtras = OpenBitFunColors( - transparent = DarkTokens.Transparent, - statusSuccess = DarkTokens.StatusSuccess, - shellScrim = DarkTokens.ShellScrim, - mediaBackground = DarkTokens.MediaBackground, - mediaScrim = DarkTokens.MediaScrim, - mediaControlBackground = DarkTokens.MediaControlBackground, - toastBackground = DarkTokens.ToastBackground, - shadowSubtle = DarkTokens.ShadowSubtle, - shadowMedium = DarkTokens.ShadowMedium, - shadowStrong = DarkTokens.ShadowStrong, - floatingBorder = DarkTokens.FloatingBorder, - heroBackground = DarkTokens.ConnectHeroBg, - heroSurface = DarkTokens.ConnectHeroSurface, - heroAccent = DarkTokens.ConnectHeroAccent, - heroSecondary = DarkTokens.ConnectHeroSecondary, - sidebar = SidebarColors( - background = DarkTokens.SidebarBg, - raised = DarkTokens.SidebarRaised, - line = DarkTokens.SidebarLine, - hover = DarkTokens.SidebarHover, - selection = DarkTokens.SidebarSelection, - ink = DarkTokens.SidebarInk, - muted = DarkTokens.SidebarMuted, - subtle = DarkTokens.SidebarSubtle, - ), - code = CodeSyntaxColors( - lineNumber = DarkTokens.CodeLineNumber, - keyword = DarkTokens.CodeKeyword, - string = DarkTokens.CodeString, - number = DarkTokens.CodeNumber, - comment = DarkTokens.CodeComment, - function = DarkTokens.CodeFunction, - type = DarkTokens.CodeType, - constant = DarkTokens.CodeConstant, - property = DarkTokens.CodeProperty, - targetBackground = DarkTokens.CodeTargetBg, - ), -) - -private val LocalOpenBitFunColors = staticCompositionLocalOf { LightExtras } - -/** - * Harmony's mobile surfaces use a small, explicit type scale rather than the - * platform Material defaults. Keeping the roles here makes every remaining - * Material control start from the same geometry as the ArkUI counterpart. - */ -private val OpenBitFunTypography = androidx.compose.material3.Typography( - displayLarge = MobileDesignTypography.DisplayLarge, - displayMedium = MobileDesignTypography.DisplayMedium, - displaySmall = MobileDesignTypography.DisplaySmall, - headlineLarge = MobileDesignTypography.HeadlineLarge, - headlineMedium = MobileDesignTypography.HeadlineMedium, - headlineSmall = MobileDesignTypography.HeadlineSmall, - titleLarge = MobileDesignTypography.TitleLarge, - titleMedium = MobileDesignTypography.TitleMedium, - titleSmall = MobileDesignTypography.TitleSmall, - bodyLarge = MobileDesignTypography.BodyLarge, - bodyMedium = MobileDesignTypography.BodyMedium, - bodySmall = MobileDesignTypography.BodySmall, - labelLarge = MobileDesignTypography.LabelLarge, - labelMedium = MobileDesignTypography.LabelMedium, - labelSmall = MobileDesignTypography.LabelSmall, -) - -/** The extra palette for the theme in scope. Reads like `MaterialTheme.colorScheme`. */ -internal val openBitFunColors: OpenBitFunColors - @Composable @ReadOnlyComposable get() = LocalOpenBitFunColors.current - -@Composable -internal fun OpenBitFunTheme(dark: Boolean, content: @Composable () -> Unit) { - CompositionLocalProvider( - LocalOpenBitFunColors provides if (dark) DarkExtras else LightExtras, - LocalDensity provides textScaledDensity(), - ) { - MaterialTheme( - colorScheme = if (dark) DarkScheme else LightScheme, - typography = OpenBitFunTypography, - content = content, - ) - } -} - -/** - * The same ramp reads physically larger on a screen whose dp is bigger than the - * reference the sizes were tuned on, so every `sp` under the theme is folded by - * the display's own pitch. It rides on top of the user's font-size preference - * rather than replacing it, and dp geometry is untouched. - */ -@Composable -@ReadOnlyComposable -private fun textScaledDensity(): Density { - val base = LocalDensity.current - val metrics = LocalContext.current.resources.displayMetrics - val factor = MobileTextScale.resolve(xdpi = metrics.xdpi, density = metrics.density) - return if (factor == 1f) base else Density(base.density, base.fontScale * factor) -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/generated/MobileDesignTokens.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/generated/MobileDesignTokens.kt deleted file mode 100644 index 28936f7881..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/theme/generated/MobileDesignTokens.kt +++ /dev/null @@ -1,277 +0,0 @@ -// Generated by scripts/mobile-ui-design-system.mjs. Do not edit. -package com.openbitfun.mobile.app.ui.theme.generated - -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp - -internal object MobileDesignColors { - object Light { - val StartWindowBackground = Color(0xFFFFFFFF) - val Transparent = Color(0x00000000) - val PageBg = Color(0xFFFFFFFF) - val WelcomePageBg = Color(0xFFFFFFFF) - val PageBgFade = Color(0x00FFFFFF) - val PageBgOverlay = Color(0xB8FFFFFF) - val Ink = Color(0xFF171717) - val Muted = Color(0xFF706F6A) - val Subtle = Color(0xFFA5A39B) - val Line = Color(0xFFE9E7E2) - val Card = Color(0xFFFFFFFF) - val CardOverlay = Color(0xCCFFFFFF) - val Accent = Color(0xFF111111) - val FileLink = Color(0xFF2563EB) - val PrimaryAction = Color(0xFF111111) - val ContentOnAction = Color(0xFFFFFFFF) - val ConnectHeroBg = Color(0xFFE6EDFF) - val ConnectHeroAccent = Color(0xFF9DB4FF) - val ConnectHeroSecondary = Color(0xFFC9C5FF) - val ConnectHeroSurface = Color(0xFFF8FAFF) - val ConnectScanAccent = Color(0xFFFFD021) - val Scrim = Color(0x44000000) - val ShellScrim = Color(0x24000000) - val MediaBackground = Color(0xFF000000) - val MediaScrim = Color(0xB8000000) - val MediaControlBackground = Color(0x8C000000) - val ToastBackground = Color(0xD1171717) - val ShadowFaint = Color(0x08000000) - val ShadowSubtle = Color(0x12000000) - val ShadowMedium = Color(0x18000000) - val ShadowStrong = Color(0x24000000) - val FloatingBorder = Color(0x18000000) - val Soft = Color(0xFFF4F3F0) - val FloatingPanelBg = Color(0xFFF7F7F5) - val SidebarBg = Color(0xFFF8F8F9) - val SidebarBgFade = Color(0x00F8F8F9) - val SidebarRaised = Color(0xFFFFFFFF) - val SidebarLine = Color(0x14101A27) - val SidebarHover = Color(0xFFF3F3F5) - val SidebarSelection = Color(0x14000000) - val SidebarInk = Color(0xCC000000) - val SidebarMuted = Color(0x99000000) - val SidebarSubtle = Color(0x66000000) - val StatusSuccess = Color(0xFF27C46A) - val StatusDanger = Color(0xFFE04F4F) - val CodeLineNumber = Color(0xFFAAA69D) - val CodeKeyword = Color(0xFF8F3F71) - val CodeString = Color(0xFF477A4A) - val CodeNumber = Color(0xFF9A5B13) - val CodeComment = Color(0xFF7A8078) - val CodeFunction = Color(0xFF2C6693) - val CodeType = Color(0xFF865A20) - val CodeConstant = Color(0xFFA04444) - val CodeProperty = Color(0xFF466D78) - val CodeTargetBg = Color(0xFFFFF1BE) - val BrandDot = Color(0xFF16B9CE) - val WelcomeDock = Color(0xFF171917) - val WelcomeButton = Color(0xFFFFFFFF) - val WelcomeButtonLabel = Color(0xFF171917) - val WelcomeSecondary = Color(0xFFB9BCB9) - val StatusWarning = Color(0xFFFF8C00) - } - - object Dark { - val StartWindowBackground = Color(0xFF000000) - val Transparent = Color(0x00000000) - val PageBg = Color(0xFF151514) - val WelcomePageBg = Color(0xFF252522) - val PageBgFade = Color(0x00151514) - val PageBgOverlay = Color(0xB8151514) - val Ink = Color(0xFFF4F3EF) - val Muted = Color(0xFFAAA8A0) - val Subtle = Color(0xFF77756E) - val Line = Color(0xFF363531) - val Card = Color(0xFF252522) - val CardOverlay = Color(0xCC252522) - val Accent = Color(0xFF5B5954) - val FileLink = Color(0xFF60A5FA) - val PrimaryAction = Color(0xFF454540) - val ContentOnAction = Color(0xFFFFFFFF) - val ConnectHeroBg = Color(0xFF2B2B29) - val ConnectHeroAccent = Color(0xFF4A4944) - val ConnectHeroSecondary = Color(0xFF3C3B38) - val ConnectHeroSurface = Color(0xFF252522) - val ConnectScanAccent = Color(0xFFFFD021) - val Scrim = Color(0x44000000) - val ShellScrim = Color(0x24000000) - val MediaBackground = Color(0xFF000000) - val MediaScrim = Color(0xB8000000) - val MediaControlBackground = Color(0x8C000000) - val ToastBackground = Color(0xD1171717) - val ShadowFaint = Color(0x08000000) - val ShadowSubtle = Color(0x12000000) - val ShadowMedium = Color(0x18000000) - val ShadowStrong = Color(0x24000000) - val FloatingBorder = Color(0x18000000) - val Soft = Color(0xFF2D2C28) - val FloatingPanelBg = Color(0xFF1E1E1C) - val SidebarBg = Color(0xFF0E0E10) - val SidebarBgFade = Color(0x000E0E10) - val SidebarRaised = Color(0xFF1C1C1F) - val SidebarLine = Color(0x1FFFFFFF) - val SidebarHover = Color(0x0FFFFFFF) - val SidebarSelection = Color(0x1FFFFFFF) - val SidebarInk = Color(0xFFE8E8E8) - val SidebarMuted = Color(0xFFB0B0B0) - val SidebarSubtle = Color(0xFF858585) - val StatusSuccess = Color(0xFF3BD47B) - val StatusDanger = Color(0xFFFF6B6B) - val CodeLineNumber = Color(0xFF77756E) - val CodeKeyword = Color(0xFFD99AC4) - val CodeString = Color(0xFF9BCB9D) - val CodeNumber = Color(0xFFE3B36D) - val CodeComment = Color(0xFF96958D) - val CodeFunction = Color(0xFF8CBCE0) - val CodeType = Color(0xFFD5B27F) - val CodeConstant = Color(0xFFE79A9A) - val CodeProperty = Color(0xFF9CC8D0) - val CodeTargetBg = Color(0xFF5A4E24) - val BrandDot = Color(0xFF16B9CE) - val WelcomeDock = Color(0xFF000000) - val WelcomeButton = Color(0xFFFFFFFF) - val WelcomeButtonLabel = Color(0xFF171917) - val WelcomeSecondary = Color(0xFFB9BCB9) - val StatusWarning = Color(0xFFFF8C00) - } -} - -internal object MobileDesignTypography { - val DisplayLarge = TextStyle(fontSize = 24.sp, lineHeight = 30.sp, fontWeight = FontWeight.Bold) - val DisplayMedium = TextStyle(fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Bold) - val DisplaySmall = TextStyle(fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold) - val HeadlineLarge = TextStyle(fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Bold) - val HeadlineMedium = TextStyle(fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold) - val HeadlineSmall = TextStyle(fontSize = 18.sp, lineHeight = 24.sp, fontWeight = FontWeight.Bold) - val TitleLarge = TextStyle(fontSize = 20.sp, lineHeight = 26.sp, fontWeight = FontWeight.Bold) - val ConversationHeaderTitle = TextStyle(fontSize = 17.sp, lineHeight = 22.sp, fontWeight = FontWeight.Medium) - val TitleMedium = TextStyle(fontSize = 17.sp, lineHeight = 22.sp, fontWeight = FontWeight.Medium) - val TitleSmall = TextStyle(fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.Medium) - val BodyLarge = TextStyle(fontSize = 16.sp, lineHeight = 24.sp, fontWeight = FontWeight.Normal) - val BodyMedium = TextStyle(fontSize = 14.sp, lineHeight = 21.sp, fontWeight = FontWeight.Normal) - val BodySmall = TextStyle(fontSize = 13.sp, lineHeight = 19.sp, fontWeight = FontWeight.Normal) - val LabelLarge = TextStyle(fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.Medium) - val LabelMedium = TextStyle(fontSize = 14.sp, lineHeight = 18.sp, fontWeight = FontWeight.Medium) - val LabelSmall = TextStyle(fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.Normal) - val BrandWordmark = TextStyle(fontSize = 42.sp, lineHeight = 56.sp, fontWeight = FontWeight.Medium) -} - -/** - * Normalises how big one logical unit of type is on the glass. The ramp was - * tuned on 153.3 logical units per inch; a screen whose dp is physically larger - * shrinks its text by the ratio, clamped, so a 16.sp reads as the same - * millimetres. Returns 1 for displays whose xdpi is implausible against their - * nominal 160-per-dp density rather than trusting bad metrics. - */ -internal object MobileTextScale { - const val ReferenceLogicalDpi: Float = 153.3f - const val MinFactor: Float = 0.85f - const val MaxFactor: Float = 1f - - fun resolve(xdpi: Float, density: Float): Float { - if (!(xdpi > 0f) || !(density > 0f)) return 1f - val nominalDpi = density * 160f - if (xdpi < nominalDpi * 0.5f || xdpi > nominalDpi * 2f) return 1f - val factor = (xdpi / density / ReferenceLogicalDpi).coerceIn(MinFactor, MaxFactor) - return Math.round(factor * 1000f) / 1000f - } -} - -internal object MobileDesignGeometry { - val ConversationHeaderHeight = 76.dp - val ConversationHeaderCompactHeight = 64.dp - val ControlTouchSize = 48.dp - val ContentGutter = 16.dp - val ConnectionStripHeight = 48.dp - val TimelineTopPadding = 22.dp - val ConversationOverlaySideInset = 16.dp - val ConversationEdgeFadeHeight = 28.dp - val MessageSpacing = 18.dp - val MessageBubbleMaxWidth = 276.dp - val MessageBubbleHorizontalPadding = 14.dp - val MessageBubbleVerticalPadding = 11.dp - val MessageBubbleRadius = 17.dp - val ComposerActionSize = 48.dp - val ComposerInputHeight = 44.dp - val ComposerExpandedInputHeight = 58.dp - val ComposerCollapsedHeight = 56.dp - val ComposerExpandedInputRowHeight = 60.dp - val ComposerExpandedActionRowHeight = 48.dp - val ComposerExpandedHeight = 120.dp - val ComposerCollapsedRadius = 28.dp - val ComposerExpandedRadius = 18.dp - val ComposerModelSelectorWidth = 330.dp - val ComposerModelSelectorRadius = 14.dp - val ComposerModelSelectorRowHeight = 48.dp - val ComposerModelSelectorRowRadius = 9.dp - val ComposerModelSelectorRowGap = 6.dp - val SheetTopRadius = 28.dp - val LoginSheetMaxWidth = 560.dp - val LoginSheetOuterMargin = 8.dp - val LoginSheetBodyMinHeight = 142.dp - val SheetSideRadius = 28.dp - val SheetHorizontalPadding = 20.dp - val SheetHeaderHeight = 56.dp - val SheetActionHeight = 48.dp - val SelectionTopRadius = 20.dp - val SelectionRowHeight = 64.dp - val SelectionCloseSize = 48.dp - val PopoverWidth = 292.dp - val PopoverRadius = 16.dp - val PopoverPadding = 12.dp - val PopoverVerticalPadding = 10.dp - val PopoverActionHeight = 48.dp - val PopoverShadowRadius = 18.dp - val CompactPopoverWidth = 150.dp - val CompactPopoverRadius = 14.dp - val CompactPopoverActionHeight = 42.dp - val SettingsCompactCardRadius = 12.dp - val SettingsCardRadius = 16.dp - val SettingsProminentCardRadius = 20.dp - val ModelCurrentRowHeight = 64.dp - val ModelSourceRowHeight = 62.dp - val ModelAccountRowHeight = 56.dp - val ModelAccountRowGap = 6.dp - val ModelSectionGap = 20.dp - val ModelOverviewTopPadding = 16.dp - val ModelOverviewBottomPadding = 24.dp - val ModelListTopPadding = 10.dp - val ModelListBottomPadding = 16.dp - val ModelEmptyAccountHeight = 80.dp - val ModelEditorHeight = 560.dp - val WelcomeMaxWidth = 520.dp - val WelcomeGutter = 25.dp - val WelcomeHeaderHeight = 58.dp - val WelcomeButtonHeight = 49.dp - val WelcomeButtonGap = 11.dp - val WelcomeDockRadius = 30.dp - val WelcomeDockBottom = 39.dp - val WelcomeMarkSize = 92.dp - val WelcomeWordSize = 34.dp - val WelcomeStageHeight = 220.dp - val WelcomeHeaderWordSize = 17.dp - val RecentHomeGutter = 24.dp - val RecentHomeMarkSize = 132.dp - val RecentHomeTitleSize = 25.dp - val RecentHomeMaxWidth = 560.dp - val RecentHomeRowPadding = 18.dp - val ApprovalCardRadius = 12.dp - val ApprovalCardPadding = 12.dp - val ApprovalCardGap = 8.dp - val ApprovalActionRadius = 8.dp - val ApprovalActionHeight = 36.dp -} - -internal object MobileDesignBreakpoints { - const val Wide: Int = 600 - const val ExtraWide: Int = 840 - const val Xl: Int = 1440 -} - -internal object MobileDesignMotion { - const val Quick: Int = 180 - const val Structure: Int = 220 - const val StartupBrand: Int = 6800 - const val ColdStartHome: Int = 2400 -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AccountViewModel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AccountViewModel.kt deleted file mode 100644 index 230db1802d..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AccountViewModel.kt +++ /dev/null @@ -1,193 +0,0 @@ -package com.openbitfun.mobile.app.viewmodel - -import android.app.Application -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import com.openbitfun.mobile.app.platform.LogcatCoreLog -import com.openbitfun.mobile.app.platform.LEGACY_MOBILE_DEVICE_NAMES -import com.openbitfun.mobile.app.platform.deviceIdentity -import com.openbitfun.mobile.core.feature.account.AccountIntent -import com.openbitfun.mobile.core.feature.account.AccountStore -import com.openbitfun.mobile.core.feature.account.AccountUiState -import com.openbitfun.mobile.core.feature.account.create -import com.openbitfun.mobile.core.feature.connection.ConnectionPhase -import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent -import com.openbitfun.mobile.core.feature.session.RemoteSessionStore -import com.openbitfun.mobile.core.feature.session.RemoteSessionUiState -import com.openbitfun.mobile.core.feature.session.WorkspaceSessionDirectoryUiState -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceIntent -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceStore -import com.openbitfun.mobile.core.feature.workspace.RemoteWorkspaceUiState -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -internal class AccountViewModel(application: Application) : AndroidViewModel(application) { - private val completionNotifier = com.openbitfun.mobile.app.platform.TaskCompletionNotifier(application) - private var foreground = true - fun setBackground(value: Boolean) { - LogcatCoreLog.info("account host visibility foreground=${!value}") - store.setForeground(!value) - if (!value) store.resumeSessionStreams() - foreground = !value - completionNotifier.setBackground(value) - remoteStore?.dispatch(RemoteSessionIntent.SetForeground(foreground)) - } - private val identity = application.deviceIdentity() - private val store = AccountStore.create( - viewModelScope, - application, - identity.installId, - identity.displayName, - LogcatCoreLog, - LEGACY_MOBILE_DEVICE_NAMES, - ) - val state: StateFlow = store.state - private val _remoteState = MutableStateFlow(RemoteSessionUiState.Idle) - val remoteState: StateFlow = _remoteState.asStateFlow() - private val _connectionPhase = MutableStateFlow(ConnectionPhase.IDLE) - val connectionPhase: StateFlow = _connectionPhase.asStateFlow() - private val _workspaceState = MutableStateFlow(RemoteWorkspaceUiState.Idle) - val workspaceState: StateFlow = _workspaceState.asStateFlow() - private val _workspaceDirectory = MutableStateFlow(WorkspaceSessionDirectoryUiState(emptyList())) - - /** Per-workspace session lists, filled in as the sidebar discloses each branch. */ - val workspaceDirectory: StateFlow = _workspaceDirectory.asStateFlow() - private var remoteStore: RemoteSessionStore? = null - private var workspaceStore: RemoteWorkspaceStore? = null - private var remoteJob: Job? = null - private var connectionJob: Job? = null - private var directoryJob: Job? = null - private var workspaceJob: Job? = null - private var activeTarget: String? = null - // The selected device the user disconnected from. The selection stays so the - // card can offer it again, but account churn must not bind it back. - private var releasedTarget: String? = null - - init { - viewModelScope.launch { - store.state.collect { current -> - val target = (current as? AccountUiState.Ready)?.selectedDeviceId - if (target != releasedTarget) releasedTarget = null - if (target != activeTarget && target != releasedTarget) bindTarget(target) - } - } - store.dispatch(AccountIntent.Restore) - } - - fun dispatch(intent: AccountIntent) { - store.dispatch(intent) - } - - fun notifyAuthorizationCallback() { - LogcatCoreLog.info("account authorization callback wakeup") - store.notifyAuthorizationCallback() - } - - /** The handle General Chat reads the account's synced models through. */ - - fun dispatchSession(intent: RemoteSessionIntent) { - remoteStore?.dispatch(intent) - } - - fun dispatchWorkspace(intent: RemoteWorkspaceIntent) { - workspaceStore?.dispatch(intent) - } - - /** - * Point the session and workspace stores at [deviceId], rebuilding them even - * when it is already the selected device. - * - * The collector above only rebinds when `selectedDeviceId` changes, which is - * right for ordinary account churn but makes the row inert exactly when it - * matters: selecting the device that is already selected produces an - * identical state, so nothing rebinds and a failed load has no way back. - * `canSelectAccountDevice` in `ConnectAccountDevicePage.ets` has no such - * guard, and a row that reads "Controlling" while nothing loaded has to be - * a way back. - */ - fun selectDevice(deviceId: String) { - if (deviceId == activeTarget || deviceId == releasedTarget) { - releasedTarget = null - bindTarget(deviceId) - } else { - // Clear the outgoing projection before publishing the new selection. - // The account collector binds the new target's shared stores. - val ready = state.value as? AccountUiState.Ready ?: return - if (ready.devices.none { it.id == deviceId && it.online }) return - remoteJob?.cancel() - workspaceJob?.cancel() - connectionJob?.cancel() - directoryJob?.cancel() - _workspaceDirectory.value = WorkspaceSessionDirectoryUiState(emptyList()) - _remoteState.value = RemoteSessionUiState.Loading - _workspaceState.value = RemoteWorkspaceUiState.Loading - _connectionPhase.value = ConnectionPhase.IDLE - store.dispatch(AccountIntent.SelectDevice(deviceId)) - } - } - - fun disconnectDevice() { - releasedTarget = activeTarget - bindTarget(null) - } - - private fun bindTarget(target: String?) { - remoteJob?.cancel() - connectionJob?.cancel() - workspaceJob?.cancel() - directoryJob?.cancel() - remoteStore?.dispatch(RemoteSessionIntent.Stop) - workspaceStore?.dispatch(RemoteWorkspaceIntent.Stop) - remoteStore = null - workspaceStore = null - _remoteState.value = RemoteSessionUiState.Idle - _connectionPhase.value = ConnectionPhase.IDLE - _workspaceState.value = RemoteWorkspaceUiState.Idle - _workspaceDirectory.value = WorkspaceSessionDirectoryUiState(emptyList()) - completionNotifier.reset() - activeTarget = target - if (target == null) return - - remoteStore = store.createSessionStore(viewModelScope)?.also { created -> - remoteJob = viewModelScope.launch { created.state.collect { - _remoteState.value = it - completionNotifier.observe(it, target) - } } - connectionJob = viewModelScope.launch { - created.connectionPhase.collect { _connectionPhase.value = it } - } - directoryJob = viewModelScope.launch { - created.workspaceDirectory.collect { _workspaceDirectory.value = it } - } - created.dispatch(RemoteSessionIntent.Load) - created.dispatch(RemoteSessionIntent.SetForeground(foreground)) - } - workspaceStore = store.createWorkspaceStore(viewModelScope)?.also { created -> - workspaceJob = viewModelScope.launch { created.state.collect { _workspaceState.value = it } } - created.dispatch(RemoteWorkspaceIntent.Load) - } - } - - override fun onCleared() { - bindTarget(null) - store.stop() - super.onCleared() - } - - companion object { - val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { - @Suppress("UNCHECKED_CAST") - override fun create( - modelClass: Class, - extras: androidx.lifecycle.viewmodel.CreationExtras, - ): T = AccountViewModel( - extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]!!, - ) as T - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AppSettingsViewModel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AppSettingsViewModel.kt deleted file mode 100644 index 2a386ecabf..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/AppSettingsViewModel.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.openbitfun.mobile.app.viewmodel - -import android.app.Application -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -internal enum class AppThemeMode { - SYSTEM, - LIGHT, - DARK, -} - -internal class AppSettingsViewModel(application: Application) : AndroidViewModel(application) { - private val preferences = application.getSharedPreferences("openbitfun_app_settings", Application.MODE_PRIVATE) - private val _theme = MutableStateFlow( - runCatching { AppThemeMode.valueOf(preferences.getString("theme", null).orEmpty()) } - .getOrDefault(AppThemeMode.SYSTEM), - ) - val theme: StateFlow = _theme.asStateFlow() - - fun setTheme(theme: AppThemeMode) { - preferences.edit().putString("theme", theme.name).apply() - _theme.value = theme - } - - companion object { - val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { - @Suppress("UNCHECKED_CAST") - override fun create( - modelClass: Class, - extras: androidx.lifecycle.viewmodel.CreationExtras, - ): T = AppSettingsViewModel( - extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]!!, - ) as T - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/ComposerAttachmentsViewModel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/ComposerAttachmentsViewModel.kt deleted file mode 100644 index ca51ef5a90..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/ComposerAttachmentsViewModel.kt +++ /dev/null @@ -1,110 +0,0 @@ -package com.openbitfun.mobile.app.viewmodel - -import android.util.AtomicFile -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.mutableStateOf -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.openbitfun.mobile.core.feature.session.ComposerImage -import java.io.File -import java.security.MessageDigest -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withContext -import org.json.JSONArray -import org.json.JSONObject - -/** Native image bytes stay off saved-state Bundles and outside cloud backups. */ -internal class ComposerAttachmentsViewModel : ViewModel() { - private val drafts = mutableMapOf() - - fun forSession(owner: String, directory: File): AttachmentDraft = drafts.getOrPut(owner) { - val name = MessageDigest.getInstance("SHA-256").digest(owner.toByteArray()).joinToString("") { "%02x".format(it) } - AttachmentDraft(AtomicFile(File(directory, "$name.json"))).also { it.restore() } - } - - inner class AttachmentDraft internal constructor(private val file: AtomicFile) { - private val state = mutableStateOf>(emptyList()) - private val mutex = Mutex() - val loading = mutableStateOf(true) - val saving = mutableStateOf(false) - val failed = mutableStateOf(false) - private var loaded = false - @Volatile private var revision = 0 - val images: MutableState> = object : MutableState> { - override var value: List - get() = state.value - set(value) { - if (!loaded || value == state.value) return - state.value = value.toList() - persist() - } - override fun component1() = value - override fun component2(): (List) -> Unit = { value = it } - } - - fun retry() { if (loaded) persist() else restore() } - - internal fun restore() { - loading.value = true - failed.value = false - viewModelScope.launch { - try { - val restored = withContext(Dispatchers.IO) { - mutex.withLock { - if (!file.baseFile.exists() && !File(file.baseFile.path + ".bak").exists()) emptyList() else { - val document = JSONObject(file.openRead().bufferedReader().use { it.readText() }) - require(document.optInt("version", 1) == 1) { "Unsupported attachment draft version" } - val items = document.getJSONArray("images") - List(items.length()) { index -> - val item = items.getJSONObject(index) - ComposerImage(item.getString("id"), item.getString("dataUrl"), item.getString("mimeType")) - } - } - } - } - state.value = restored - loaded = true - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - // Retain unreadable data; retry must never replace it with an empty draft. - failed.value = true - } finally { loading.value = false } - } - } - - private fun persist() { - val requestedRevision = ++revision - val snapshot = state.value - saving.value = true - failed.value = false - viewModelScope.launch { - try { - withContext(Dispatchers.IO) { - mutex.withLock { - if (requestedRevision != revision) return@withLock - val items = JSONArray() - snapshot.forEach { image -> - items.put(JSONObject().put("id", image.id).put("dataUrl", image.dataUrl).put("mimeType", image.mimeType)) - } - val bytes = JSONObject().put("version", 1).put("images", items).toString().toByteArray() - val stream = file.startWrite() - try { stream.write(bytes); file.finishWrite(stream) } - catch (error: Exception) { file.failWrite(stream); throw error } - } - } - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - if (requestedRevision == revision) failed.value = true - } finally { - if (requestedRevision == revision) saving.value = false - } - } - } - } -} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/GeneralChatViewModel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/GeneralChatViewModel.kt deleted file mode 100644 index 24a212860d..0000000000 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/viewmodel/GeneralChatViewModel.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.openbitfun.mobile.app.viewmodel - -import android.app.Application -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import com.openbitfun.mobile.core.feature.CloudSettingsSource -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatIntent -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatStore -import com.openbitfun.mobile.core.feature.generalchat.GeneralChatUiState -import com.openbitfun.mobile.core.feature.generalchat.create -import kotlinx.coroutines.flow.StateFlow - -internal class GeneralChatViewModel(application: Application) : AndroidViewModel(application) { - private val store = GeneralChatStore.create(viewModelScope, application) - val state: StateFlow = store.state - - fun dispatch(intent: GeneralChatIntent) { - store.dispatch(intent) - } - - /** - * Point the model catalog at the signed-in account, or at nothing. - * - * Called on every sign-in change rather than once, because the source is - * bound to one session: passing null on sign-out is what drops the account's - * models, and passing a fresh one on sign-in is what loads the next user's. - */ - fun bindCloudSettings(source: CloudSettingsSource?) { - store.bindCloudSettings(source) - } - - override fun onCleared() { - store.stop() - super.onCleared() - } - - companion object { - val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { - @Suppress("UNCHECKED_CAST") - override fun create( - modelClass: Class, - extras: androidx.lifecycle.viewmodel.CreationExtras, - ): T = GeneralChatViewModel( - extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]!!, - ) as T - } - } -} diff --git a/src/apps/mobile/android/app/src/main/res/.gitkeep b/src/apps/mobile/android/app/src/main/res/.gitkeep deleted file mode 100644 index 8b13789179..0000000000 --- a/src/apps/mobile/android/app/src/main/res/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/apps/mobile/android/app/src/main/res/drawable-nodpi/approval_shield.png b/src/apps/mobile/android/app/src/main/res/drawable-nodpi/approval_shield.png deleted file mode 100644 index 8c0fb2022901ab1225e7d7ed273f97e49423c609..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1324 zcmV+{1=IS8P)g&UE5TM>2u2i3TS2M_VzG7Q0~boG7}AGSORLo*-^|3= zbpDyioquj-Zsx!bfh6BK|C#?e_xmo;ph1Iv24BT_6bw-&JBKkd+jefj#pq{Hv5ty^U6>O!!2t^H zLcf8dxQ2p{x;ExaqdwpWR-iA8QM^gPsT>`jq+)H{CUcl%G2fu#YSamA;Q|Wor(!n+ z|KuDI`zW~bzZe}Xr(%E3|22-C6x?gvs1g`pA&0S)0dA$>NebSl;P@=2%imOV*up?! zY{AytCP!u&_c#?#gqk943wvh>aTXO1$0E94Y@^P6Z=J~GRNPL%4+YmP(>hMU2J1sP z=5%m*c)~5dz#gOG8IIxn+}te;Q1KiUzkA@{Wqm1QP0@&gnH9K7|@D{)BQ;dqyg!rQ#7?gp=pbRtyWuP%A1C2o$Xbj3gV^9VfgZkbeX)dd&XkK^p{R=a}pNS+j z$RUi)PcrDFKN4|#<}{3pP>+l@mia;s;pa=qB+F27SXzxk`%nHz6nh;cYfy1eaGPU_ zec_Kp9Z8pMJc4>;(#VET zitijFXq}JvA*fj7Ooi*JDxJ3?Kv7<5kgsS!O_wPh5nanAYa_M!LM z2;&~ZVk+KE<(}g;F+^CWmHq^+{Yt?@KI$XFx{&}6gfY`OP1Aj-0%#=%*(1rG=x278 z>Y8T+x7b#lgXe^4LY2U1i*?<7W_DnYEv&PQ{c+CN6ZZG0A}Cl!#h1A{5_RTt26!;3 zl+xFa zk>8|ln-%}wj5>nv;2bI*qv99u#zgDg;9Qhmc?Ye6**a6CLh$q>!^Wa7=_(0E#kr4D z@naVw#>{=HFO8WAws3ZMf3j~*NH5T}y84|Aa8Dib07^l4Ww0+Lh`v2xBHq0|4c~ze iV`(|84H`5+HSjM~GsYa4Z9J&}0000 - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_clockwise.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_clockwise.xml deleted file mode 100644 index 4ec726bb9f..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_clockwise.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_down_to_line.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_down_to_line.xml deleted file mode 100644 index f2ca652416..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_down_to_line.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_right_and_square.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_right_and_square.xml deleted file mode 100644 index 892d0ae412..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_right_and_square.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_triangle_merge.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_triangle_merge.xml deleted file mode 100644 index bc56d24d35..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_triangle_merge.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_up.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_up.xml deleted file mode 100644 index b07041c246..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_arrow_up.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle.xml deleted file mode 100644 index 5d9b5e379e..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle_fill.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle_fill.xml deleted file mode 100644 index 651b6ba5d6..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_checkmark_circle_fill.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_down.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_down.xml deleted file mode 100644 index 047662958d..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_down.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left.xml deleted file mode 100644 index 980b110bd8..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left_wide.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left_wide.xml deleted file mode 100644 index d83b1443f4..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_left_wide.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_right.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_right.xml deleted file mode 100644 index 2425278cd6..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_right.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_up.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_up.xml deleted file mode 100644 index 86eca99720..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_chevron_up.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_circle.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_circle.xml deleted file mode 100644 index f8d8abfecd..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_circle.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_cloud.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_cloud.xml deleted file mode 100644 index cb0ceaaca8..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_cloud.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_code_square.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_code_square.xml deleted file mode 100644 index c9ee120b24..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_code_square.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_desktop.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_desktop.xml deleted file mode 100644 index 246060a365..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_desktop.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc.xml deleted file mode 100644 index dc949f8764..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text.xml deleted file mode 100644 index 88d7f7ff94..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_arrow_up.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_arrow_up.xml deleted file mode 100644 index 6cc35d2639..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_arrow_up.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_magnifyingglass.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_magnifyingglass.xml deleted file mode 100644 index 7c93a875e0..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_doc_text_badge_magnifyingglass.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_ellipsis.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_ellipsis.xml deleted file mode 100644 index 37793082f9..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_ellipsis.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye.xml deleted file mode 100644 index be82fe7b64..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye_slash.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye_slash.xml deleted file mode 100644 index a0eb0e4a1c..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_eye_slash.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_folder.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_folder.xml deleted file mode 100644 index 461b878c82..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_folder.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_gearshape.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_gearshape.xml deleted file mode 100644 index 7800cf2aca..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_gearshape.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_info_circle.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_info_circle.xml deleted file mode 100644 index f795bc7d0d..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_info_circle.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_link.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_link.xml deleted file mode 100644 index c3ca1716f3..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_link.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_list_checkmark.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_list_checkmark.xml deleted file mode 100644 index c97dc3b42b..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_list_checkmark.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_magnifyingglass.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_magnifyingglass.xml deleted file mode 100644 index ae861bb727..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_magnifyingglass.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_menu_lines.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_menu_lines.xml deleted file mode 100644 index c9d2d36654..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_menu_lines.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_message.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_message.xml deleted file mode 100644 index c68765bceb..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_message.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_mic.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_mic.xml deleted file mode 100644 index fcb94931dd..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_mic.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_person.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_person.xml deleted file mode 100644 index 79ed5a6c5d..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_person.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_picture.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_picture.xml deleted file mode 100644 index ec61a84c41..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_picture.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_plus.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_plus.xml deleted file mode 100644 index 37f25db6b8..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_plus.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_questionmark_circle.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_questionmark_circle.xml deleted file mode 100644 index 50ecc4f212..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_questionmark_circle.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_rectangle_stack.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_rectangle_stack.xml deleted file mode 100644 index c2d4e2f00c..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_rectangle_stack.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_robot.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_robot.xml deleted file mode 100644 index 41c4efc4b0..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_robot.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_and_pencil.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_and_pencil.xml deleted file mode 100644 index cf732dc17c..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_and_pencil.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_grid_2x2.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_grid_2x2.xml deleted file mode 100644 index 067292085b..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_square_grid_2x2.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_trash.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_trash.xml deleted file mode 100644 index a4d9b5dbaa..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_trash.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_website.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_website.xml deleted file mode 100644 index 79670d5220..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_website.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_wrench_and_screwdriver.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_wrench_and_screwdriver.xml deleted file mode 100644 index 1fcc3ca34e..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_wrench_and_screwdriver.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_xmark.xml b/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_xmark.xml deleted file mode 100644 index 153da459a9..0000000000 --- a/src/apps/mobile/android/app/src/main/res/drawable/ic_symbol_xmark.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/drawable/miniapp_divination_preview.webp b/src/apps/mobile/android/app/src/main/res/drawable/miniapp_divination_preview.webp deleted file mode 100644 index 2bcccda7ed751ca9f29b2e4e2565f8f995b3471e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 79446 zcmV(tK^6YqccJooxn|6i=1`+l{*q<^{pyZQhBXY4Qa zYxi^C&+gx-@9Tf-|8D>9{5}8N{mJ*Q{uBOx?gzjp_V4*W{(BYw(|U~mME{5X z|Nk$yckd7WpOz2pfA;@&zxVu&{^S4u|E2B$|MS~7_y_;~n|~w!!~a{;SIob^|DpMn z;@91?`LEr7ip+2P4}-sSUyuG%_k-dub^lK_7yP^WkNVH>pSwTgenL1~M>hh_37qB1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ByVVE z0}87=tPhsvxZ8R}^}rnS1=fj~njRW04&b-jG8Jzv>y-Ug3`3@^2phF%q<HDggh|Z3{r};OH5mS*X}L!bWRKd z#4RUHJj|y_)eA4_<|17Ye;kmQMksveZ4=!K(A+ivYUe`g`6TyHNfU@m@n8)%pWd=nuoHk*;Q7hj`R*xs<^Fvgy2G90$)*LI7VtLNKg;glxJB-i?WBg#vo#`3>#$|6X`;>XUYTT;+9zkuyRw_WlVcF z-NO>in`wl#4=9(*7NtOoi$5o^R36)DIf@sH888kX~|`x}!8xFYIgVrC`Q|tL!!`BQaZr z$!YzTK0CN%q<*NS+8601<|^KkY0=oB06d%{k~nRzBhi+=?y>KyIxs3f3c~`1(g%6V z1B|Hl8I_NUrKAyhP+9Jjcf)l^qXe7Dg{UNdnH(5{vHZ?qKrQ6WLqncbqODHuj2dG9 ko`~?ajq18a=FWCD3SXPM@S{4C>p7^8{<(7IDQ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/src/apps/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml deleted file mode 100644 index 8ba75ca515..0000000000 --- a/src/apps/mobile/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/src/apps/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index 145142be4c648ffea3baffdf07791cf87111506e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3542 zcmV;{4Jq=8P)-sFvonVI)_fAf2u_j#Uq--p4(jRipAz5u``0DlIs z62Kn-*Z?rNzZwDX0k{F+KLGv(-~@o1;khsX)X5&g0N}#E7XkP?03rNv)d1T4-nF^7 z0UQm_72&!6>WgQ?{}uumHatuQ5CWjw=Rm39IfTMFbr`VM;yly%d*6> zto}E{Fo{;bQ26(*G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H_Rk3)Ce}54#DiTqgcdU8 zDOo;YqG?JsJ(AXS__>wwg0xkiidvZbwKt*de0=u}F5-lBkQeK`zoFbq9|Es+;zk3rVfVAb{PSNVY_QaxD#4y z_)$b-DZ}v$z+QR>J^07RNbcsTjdw|bNeq6y=V5ifUL-cwjx zy>h9RaojJ?qUNDL~ym)$Us&8NQjWH@f_%1&9= ztRi+2HH3J0EC&kQ+Wyk(HYQN5UyQ}$(KQqJvq11{jEH_az4L9~;@?_mw1sffxHlI; zRAvr2vzKSov5oHOr$4Yl9V@_|5i;NUONbZ=2G`o7p~x+7LC!r%9lsw2J*>5^WEm@s zeo(Q$>mY1E&&uoi+q@k;Mr&wGgo#9FLZ(USaLU4SQvF#hFTw(`yK&h7{gqF;>7c)69!yDw;Ro-t`mTmLGMj*UwDj7O~~FUN_NJ??^7C zIutsJ2dQAf-Xk)FA|KuGEF>gkIIaJ22WPz`Ecp>0&o{At{npW1HF_-j_TlHymTBUA zM$gphXfO{SFy^l1Y9R~;A5XDZENa-^#>*$)-?vC=L~(=B%~M6g!!`$F*jIe~lJJ^# zIwL;+m&MH9=Pm*l{taX63*BtkbC@Rz_^K6djS8V^k3OjWKqkK?IUky5B@%RlSRsx5 z**60h)nQjFhdmk0@Vt1?`jm!Lp=-G|4zp`5$oUZC=&0Wk6wZ00Amr)lL{ATDeEet5 zt*~8N+=)E!Ad#SrkdT_gux|i7TOa3|ZRTZPZoEF_jf81O;*04u_0__r3$rCw#S{-O n^B@Y1VDSH4_Bs;Sg;U@T?!7?w!M8W;j|zY^F-KGwJ4O93DK=gz diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png b/src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png deleted file mode 100644 index f0802cfa9335d30608e77cbd4e1c0556e7273b07..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3286 zcmai1`8(A6`+gUPDeFX$r5KZaA4)^EGpZRzANyw%V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S8V^k3OjWKqkK?IUky5B@%RlSRsx5 z**60h)nQjFhdmk0@Vt1?`jm!Lp=-G|4zp`5$oUZC=&0Wk6wZ00Amr)lL{ATDeEet5 zt*~8N+=)E!Ad#SrkdT_gux|i7TOa3|ZRTZPZoEF_jf81O;*04u_0__r3$rCw#S{-O n^B@Y1VDSH4_Bs;Sg;U@T?!7?w!M8W;j|zY^F-KGwJ4O93DK=gz diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/src/apps/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png deleted file mode 100644 index 9d4b03b3cfc091b5396a5ee720b4576e87420c64..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2219 zcmV;c2vqlpP)Y#%9KuIcLtZ z7dz*yU*n9UZvXwkVVJ}F@jUPE&Nj3m zNzztG=;m}106JH_jQP=R8~_s%5?EVX%jxN9lBA|-R1}55V33-oktC<4rg-VnB_<>! ztRWsJfxiHNeX~(#wJDUBmveY{m?Wtv3OybVeLf%kem|F%mgw{O=<#@{C<;k(czBp6 zPMp|^S?SjD0RRH=0xv2mVt02pRaK>;D3oQHi;Ii&cswhf@87@E<%}ZWa|4tuU(?iRg>%MXW2oT-_NN8N7M(CS_SR%w@Bp_i?-3Y;0^~Mn*)5w%9{^xvWCXpvy_lVyg&;&6W`&SMc6K&SpFWM^ z;$i^6#KZ({+_-_x&Q2(b0#Ot}5+pYq3bDrY($Z264i1teeLf!*MPW}*4^vW7jJBIG zMF31mNnv+)Hx)&p&*vja4h{~ow6xS{7sI$4Pm-0D#g2{+27^JWs!FHR$)%+w+H5xN z-Mg0nXfl~7Nz$eslgVU^Z?oCx_xtH|I;pBEgTWvlK77cmtgKiTCo=fV%uEgq4Ur^e zS*FY7qRZtXNmf@^8{p%O=X&4j>S~fS#@BsoXlRIg_Uws9V*U6IfbH$=B+0qCIlA3$ zI-O1`io#c~UKx{bWmnbvnoK4R3=B|F6gr(wy4`Nh&(D)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6 zZiCSIgpfl`r#)dK3 zxZ@qUv)UYS@7~gMPv8M!dM{_5BG6hBrDO#k8Xe7MT0@BR9J>w{=-8HaXAnnvBY+$p zEO;5Eh>6leG+WJKt$-~Eq<19~UNEBs{?v_g2nP8m@CtN`l>z%T;L zJQ3q=H8tg>1rg{ch~GNohC-GAL%<3^MPAtXvKAFA z_w=d^i_~Uy>~T!!-}$V}8hUT!!>n;!e2mkN0+5i9m diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png b/src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png deleted file mode 100644 index 290e99adc093618a8ee67d4d3c79c4760e71f7e0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7041 zcmc&(`#)3vADi+j75j(H0W9=2j$$Av2OYxn(A4 zbIYY%M#JQu>-Y3meD^q)A9l|Bob!6U-p}Xr^?c(j&5h2o3$cShptHs|VF=(n`fq1r z0gkwf3M;_rbihsfU=WCT@!!rwj6`^YK*A7Xn7(z`_)31{^E)HA7g~usx-{KA-A@j` z{fyOm)7&a>tkTvwN&Oi(tqiwriO+^IJ~z9*OG5sOlXS<5y16@`CvYoV!pdCP9`E3& zHPf4k>`AWY2Q4oUjpd%tfF;^FlYI@{emy~6pNuY~5qDndg*=N64c(XRvzaEu+`d!y z$$z?q_JNF~Pk7_cvOT!?f7#~Fq}>Ym*+G(PzVWbj~sFv~t6Tl9s=XD5-2TCnhGk>o61&q$J#0I@`aq9f?Aw4PaV%!9I8*$&^%)j;QU} zR|XluDu_04*)Eb2*N`aa$a`?#WK@PFQ<%xX^F}+#pJnZ0oH|oLph)BQ-S1BYlG#dq z=+{KJH3m0orjMoKa&e2^hq1Pmj|4}Rg|hmRF7hd@GOrOpGSA%Ud6&Ql+6)6)!W&tT z_4r94Yk)AfsHo%{HaC}C-9dQsGabyboo7(cIto+|dM9b@h9_PGM~fX*Qjnd3#Z0wK zQRmwp!oL4LG!1(Ex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UyA`Qie2T4ojb?H97*Zu&dIsZLa%K6F;r}%#Q9(*9$pfJCuVBpKU*0X z%(OSsyp--xb|IvgCurZGhv{`mFu4Iy_69JflsQ_PJo__Ktjj6VSD6et^lx77DHl~k zxt@p6fd)-CaLhBSS%>Yx{RG#ryFNZ7LH9ONpSOvIs_t(^ah#= zVU+G?(#V~lzRP+ALRkelIZWJrFEhicM|6EonrFC(YKFW6%{=VRo-n#`qgyCBA(ZTj zpDl5|%;}SX0AliKVns2m;64LjrWgxZzHPBYM|;5hRMXQ6n(N(G=3s0`A4eC^mH_Un z;cZESkG8foI{8zMr=pKBq`Y~1s>aS34u^{d>;=O<0?_xCR2**(TO7-9N7o?A9C-}6 zS@mZSmx}dSJ|Gn-g(-M9%Q1!u2rvf~GvMEsLd41`=z3FAQ*Ff>E!f-Xikg^D-JAD8 zZ#hLZHwo~v{qF8=#d~VGipJ+nU=jG_m)?^?cmFH!BvRkol;_x#hkiyz(hGDVTfXv) zKV1fl9_Tv3z316&etv#GweF}lj*2N2)|k+9)ga4qN{C>B0yyH8wVV!ARh5#aZNlO6 zZiCSIgpfl`r#)dK3 zxZ@qUv)UYS@7~gMPv8M!dM{_5BG6hBrDO#k8Xe7MT0@BR9J>w{=-8HaXAnnvBY+$p zEO;5Eh>6leG+WJKt$-~Eq<19~UNEBs{?v_g2nP8m@CtN`l>z%T;L zJQ3q=H8tg>1rg{ch~GNohC-GAL%<3^MPAtXvKAFA z_w=d^i_~Uy>~T!!-}$V}8hUT!!>n;!e2mkN0+5i9m diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/src/apps/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png deleted file mode 100644 index 6153a46664a356f0a1dc10018fcd9ae9a5633821..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4797 zcmWldcOaC19LJx_8F%I(*(VBRou9LX?30=7y+=rqnURyd37K_>NN09M_DU{7_9iQP zWn}!G{&?-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P#hrAFPVLaG1q+O+EGPa~XhN7p6yILIPXQ|Z z>?_4X0Eo+gVb!lEEOS@UJK;wEdURxmiiXDTxCVLq_U+MpZIK41dInFTC|u9mPONCi z(8n!lg(7jc!B{|B{b2c#hE=~|V6p+uiWpYiv_|qt*S6NxB|)KdDXe<^fP>$8T^8T9 zS$jy8_x`f&WOhdT7x0X?qfe79N)t#Eyap`L_KcR1gbM!9@Gv6_OYiQ5MB0S?S%ERf zC)lFKMq(;>_SRF_TFcRm$D36?Pt6ROY;DZFu)wMn{eNDy=H7BQAoA3e@z(bCsCH~Jez&f$om7lePD|{%6=n%eFnMUl zM{7zl6!Y~^5~CWikQYy?ksm*B)!G%a;WtRIFj~kyX|i{Q)p=#DX3ikM}q9A|e!2@D2@`AXkhb7a9WkQGTs3 zP^5@?a+i5cpdBrcaecrW0uAZJM}AynZZ0hqo8rl1kPTY_>nLkzTtfL#dwS~}M;JI& z-@C){6`6ke@BNIPpxBCBfkNwepI&FL6#4Pc)<;9$o_`@NS%WdsXzcl7;;^& zY;Z76-l`JZDy#?!mC|59vDR0qf4)yhe+aszIWq3WzwS}SVMWU%2iMBWrOj9%*oYbE z9=&F}uVI5{@<(=iGvzIT6*{XAIc!lyl}33C#6@^R&D~_Z`i+miRz3)YpTO zd(hgx^e``1D?}!T&Bd5D`gw`OnS79aNcz9a1OZi!I>?L(*p?kVb-fXpS{9tcnuS0fCd*{H$|1)Buvs zT@z7Me^JKl=xBs5T`Y{$b%=q*7;JN!$Q;~TJTZnwxCW$3k$lV?!sZp(zXE9Y?<2-_ z6(BXHj?0P{nHRKwB>$Z4>93J~hi&BTO=pAo2k|5cGmq`BToT1|#JzDP|n>KS|aWJOBUy diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/src/apps/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png deleted file mode 100644 index 3646b322400a0396f93f21518ebd080ae645880a..0000000000000000000000000000000000000000 GIT binary patch literal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&Bd5D`gw`OnS79aNcz9a1OZi!I>?L(*p?kVb-fXpS{9tcnuS0fCd*{H$|1)Buvs zT@z7Me^JKl=xBs5T`Y{$b%=q*7;JN!$Q;~TJTZnwxCW$3k$lV?!sZp(zXE9Y?<2-_ z6(BXHj?0P{nHRKwB>$Z4>93J~hi&BTO=pAo2k|5cGmq`BToT1|#JzDP|n>KS|aWJOBUy diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 1c5501a520fc3241583612579db0aacef3be9b82..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10755 zcmW++1z1$w79F~~L*fT%M7kRUq(Qp7l#=d7N+hI9y1S85>68ZP?(Uj*c=LVa%)N8x zoW0jxaU)ceWH3-kQ6UfrhMcUF8u;1u@`a2DzN;;ML;^oh9A$MrLm+UwFJCYX-fDIb z2o*$5O8kSz!cnHDkGg9sbY+LuX0pBDV^9#4{UJjn@*A3Hsz~JJGIv8bH~|4^lB(Gn z7Sute$bh^@eMGC??+57pZdG2PBr4lMRCzf80g-%s-y7-+usOot(DEOQ=ovf*keUOT zR#{YFeXxACjKTvsCNC^RMN0x^aHAJ8^8K~5_iE$=*}IU9-;UQHJXhvyQjLr~dIu_Y zA$8&4ZRkC&l%3H*;Ziz3^NVGAjCq-gLI7qMK_DfhKyk@p;1cFg zjNNhJ^2dk*8>VJ?A!_ibj8(v%SeP74Q|pc~j|NR()f46D4zyat$-|WU0(HBhDp1u# zzlhM?^HhFSz7VSzxtFNyJAC({&QEl6gfq*ixM}E>^Xd>4)R6qEc16pu(=U-6ckI|k z;)@l;3{LjW)3YAiA!2c&pwC@%Nw~027$;ZhR2tU4HS5Eq#eU0=7Az9R5%G5ftK!B5 zavM>R6*(T%^B?qD;TRCy9z3-^MM8Fmq4IbaO}2knWmTdX;HOUtp~#0evdH;}A-{KS z%6L+;m{W{Ygc9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(^(< z8|vGls7Hyko|j@cd2flL)J8q#*@K5O?!6)n3o%Nq(n?BJ%&`kb5~uMAQHXv-a>o&I9x%7-prI;Q^e1?^`YB%!Dbd4cFYbC<(euZkMJoe0>7c}FT}tWv z=J;z5WrY`WWG-5=rrh)laDz54_=(ErUZJp462iR+jr;Craa Ubqr|=jFUn`RTo}%$NKsI1MSNfwEzGB diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png b/src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png deleted file mode 100644 index 046de822a97a814c8845011cc95131e35ea5b17f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17403 zcmchKk78-oX<1&4!ftTPEW&5LqS17 zuW=V{KtXY;;^dE-3LN>UD<%Z~JOB8u8HR#_a{1)%RIQ(Z69vT;3Jtij(UZxI8J{#R z6HkF3n9WjL{Y~VJ`*oG#RP)wX&ZJfdguc>vO2^oKA=&Oqa?dw0Mi#lJCK{IQ>%6*8 z{|T*l!Rx@VcIM+9wf=wF&$C_nM$ye;+5RLRIdiy+Ya|kQEb?Aw&P~o3>^U8_X2vMK z@iS@j-7?vm#SGY=rg(~q!}V_uxc*=~O+j&*4p?~#Sp1ZNl7iw48~F9_L)2p6*MB?2 zXbn#I_gPok!LR>z=%1&j!07+aS$`k+Ul0A;tiNad+pPb&@IMdzH%tEx@!yvI9pZnp z^zW$uZRy`3{->q?%c1`<>+gmCY5f0k=)W2N|2Y}|Y5d>upfg@tooZh#5_)iycrM`M zy!S2PKoqd^=?>kE_!kLc)pRt)kW8oem`i8a+dqi~o~1Ahd2C5M2{f2x?4uHWri`J!G!TVYEVmXs z#$e=$a8fXml+liGcT!&KmMZnFf1dKTQy6oYzmAMFLeyUx zq{S|G!MBIuH310&yoiyr=%ZVZfH&CIkAyvbzFTUqPMxMZMOA@=B;ph^u>E?^*M8f< zyLy5w@^cc&;WFHD#@%dJb8f$OURo1_%&5byuH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lBUsPm}e3ay+idP@I-O{O9c{m<#DwVKn!p<{wz>L%?%& z*~TtNAH8&M@ONvm#ET0&gS!Fm}2e*_yY zNCyJ;?q=0!if#esNr3Yu?Ni_l5|Cq^yo}m54U!f6kUKU(>`UWVI#Wu@q@O#L_g!0d zI3Yex4dzEHfLH+8)sV~Hu+eUm@Me;oA;~f3pB_%khdhHGK&Nx8?i{GzuXAo_J)Vma zJ_TOXyxl~M*_fz)nPdj?r**Rj={q#UX+)lZ!-L|Hix3DR;9gLd+emnBKQ9O3t#}C* zHBQ_6R7}1(vlv-A3DO*O#mu1IXf8QL+sKvd8{A+>6=CZj+l_6DSy*<`P{KFw-$Wq^sJK4;t zgK}WFyNj1}rROOfw(g)=Ua&HTOH(`?X7()<$^`Lf7qG-;)=RW|0A-(ne7zrZ>G?yy z=@u-+=?q=t;C5itsSVNR)`$D$phVO6gyW%Bkq6Bklw4K_?nqnno@T799buxL< zefdH27#ju+npQ@U93zgkHS!9&qaUfFaa5%?^vGfM+nQ@~5E(SObZo8eo}foMCdeI# zh>C9bXfAo#(+Lz5lnE!_1=zZl!?IaKeTNXedTqF7oBb}J{OXK^DluhR@J#Rk69CphDrA9n>c|QzDzTmeQvw_GmAdl5~(`&OQ1pOI0A$vp#;rL(9e7>4#J8`r#)$}IaOko zt$t8PdG3M{=po49g+7oYaz7{y;D=>Gp*xE{T@%;gC~X2kt2;>!zBqa(`!Pl|k(^(< z8|vGls7Hyko|j@cd2flL)J8q#*@K5O?!6)n3o%Nq(n?BJ%&`kb5~uMAQHXv-a>o&I9x%7-prI;Q^e1?^`YB%!Dbd4cFYbC<(euZkMJoe0>7c}FT}tWv z=J;z5WrY`WWG-5=rrh)laDz54_=(ErUZJp462iR+jr;Craa Ubqr|=jFUn`RTo}%$NKsI1MSNfwEzGB diff --git a/src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/src/apps/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png deleted file mode 100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y{W}CoZ$B;`Pn1jne?7fEu^kbq#$~4JXJtGCKq+??$(!C;diiKimK($oO zahNHRQt3}H*5@s0o-iC>m~J~!)0r^E%6W84O9u7CmpmwSar-Q}xyOBMaA8d_{@9{b zRB=L+yS7+I9=n|+5v%{(g}eLH{bl;s5K+FP5j;m;v`u=9xjMEFo@4*z+D{4WKep7p zycaVjt3}keaWmuyP=%d> z@i=*jWi9@T3SOezI(2ziQWREMC0uo~p`(Dm-s7_l-2A1<#bapQz|`8?;Ym6!brT6x zrt%0_y?y+0WK*9yX0xp2YBUcxZLANWs}0TA0jqOj?CsE=sS)y4l4jgphDht6|B!oi z{MTIZT)#cih%blDWPHm=nrMzk@i%#{ZV_`ZhPYzz3YU - - 填入输入框 - OpenBitFun - 聊天 - 远程 - 账号 - 设置 - 设置 - 账号 - 未登录 - 语言 - 通用 - 语言 - 选择语言 - English - 简体中文 - 普通对话 - 关于 - 产品 - OpenBitFun 安卓版 - 版本 - 外观 - 跟随系统 - 浅色 - 深色 - 账号 - 使用邮箱或 GitHub 登录 - 使用邮箱或 GitHub 登录并连接自己的电脑。\n任务和模型配置保留在被控电脑上。 - 登录服务器 - OpenBitFun 用户名 - OpenBitFun 密码 - Relay 地址,例如 https://relay.example.com - 正在登录… - 连接 - 当前控制 - 中继地址 - 用户名 - 密码 - 使用邮箱或 GitHub 登录 - 退出登录 - 离线 - 在线 - 刷新 - 重试 - 正在加载设备… - 账号下还没有其他已注册设备。 - 设备 - 登录云账号后可查看该账号下的所有设备。 - 选择桌面设备 - 远程 - 选择一台在线桌面继续工作。 - 账号设备 - 当前控制 · %1$s - 登录信息无效,请重新登录。 - 登录状态已失效,请重新使用邮箱或 GitHub 登录。 - 登录尝试过多,请稍后再试。 - 登录服务暂时不可用,请稍后重试。 - 暂时无法连接,请检查网络后重试。 - 中继返回了无效的账号响应。 - 无法恢复安全账号会话。 - 连接超时,请检查网络后重试。 - 通用聊天 - 更多 - 复制 Markdown - 删除后将无法恢复这条会话。 - 你 - 助手 - 配置模型服务 - 填写 API URL、模型名称和 API Key 后即可开始对话。 - 请先配置服务商。 - 服务商拒绝了该 API 密钥。 - 模型服务请求过于频繁,请稍后重试。 - 模型服务暂时不可用,请稍后重试。 - 模型服务返回了无法识别的响应。 - 无法连接服务商。 - - 模型 - 本机自定义模型 - 当前使用 - 未配置 - 本机 - 账号同步 - 云端账号模型 - 云端账号 - 已同步 %1$d 个 - 暂无可用的账号模型 - API URL - https://api.example.com - API Key - 输入 API Key - 留空则保留已保存的 Key - 模型名称 - 例如 chat-model - 已安全保存 - 清除已保存的 Key - 保留已保存的 Key - 保存 - API URL 必须以 http:// 或 https:// 开头。 - 请输入模型名称。 - 请输入 API Key。 - 无法访问系统安全存储,请稍后重试。 - 普通对话模型 - 选择账号模型 - 模型来源 - 本机自定义 - 测试连接 - 测试中… - 保留或输入 API Key 后可测试连接。 - 连接测试通过。 - 显示 API Key - 隐藏 API Key - - 取消 - 连接电脑 - - 已连接 - 房间 %1$s… - 工作区:%1$s - 电脑端尚未打开工作区。 - 已登录为 %1$s - 会话 - 正在加载会话… - 重试 - 暂无会话。 - 会话加载失败。 - 桌面端未打开工作区,请先在桌面端打开后刷新。 - 刷新 - 搜索会话 - 搜索 - 全部 - 编码 - 协作 - 新建编码会话 - 新建协作会话 - 加载更多 - 消息已同步 - 选择一个会话 - 从侧边栏打开会话,或新建一个。 - 还没有远程对话 - 新建聊天后,可以从手机继续处理桌面端任务。 - 新建会话 - 项目 - 还有 %1$d 个会话 - 重命名 - 会话标题 - 保存 - 删除 - 会话 - 会话操作 - 已上传的文件 - 当前会话已上传 %1$d 个文件 - 当前会话暂无已上传文件 - 归档 - 置顶 - 取消置顶 - 取消归档 - 查看详情 - 删除后将无法恢复这条会话。 - 会话详情 - 智能体类型 - 工作区 - 工作区路径 - 创建时间 - 更新时间 - 消息数 - 状态 - 未知 - 已归档 - - 刚刚 - %1$d 分钟前 - %1$d 小时前 - %1$d 天前 - - 视图设置 - 调整会话列表的分组和信息密度 - 分组方式 - 筛选 - 显示信息 - 工作区 - 会话类型 - 全部工作区 - 全部类型 - 全部状态 - 更新时间 - 运行状态 - 按项目 - 按时间倒序排列 - 聊天优先 - 聊天 - 今天 - 昨天 - 更早 - 运行中 - 就绪 - 关闭 - 返回 - 打开 - 消息 - 向 OpenBitFun 提问 - 发送 - 停止 - 添加图片 - 语音输入 - 移除图片 - 工具 - 允许 - 拒绝 - 权限模式 - 此设置会同步到当前桌面,并应用于所有新的工具调用。 - 需要确认 - 高风险操作会等待你确认。 - 自动批准 - 原本需要确认的操作会自动通过。 - 完全访问 - 允许所有工具操作,不再请求确认。 - 正在读取桌面权限设置… - 权限设置读取失败,请重试。 - 无法读取桌面端的权限模式,请刷新后重试。 - 权限模式保存失败,桌面端仍是上方显示的模式。 - 连接桌面后可修改权限模式。 - 确认开启完全访问? - 开启后,桌面端工具可以直接执行命令和修改文件。 - 开启完全访问 - 模型 - 未命名模型 - 选择模型 - 本机自定义 - 账号模型 - 暂无可用模型。 - 可用模型加载失败,请重试。 - 当前连接的桌面端不支持从本应用选择模型。 - 重试 - 模型列表刷新失败,正在显示之前加载的列表。 - 工作区 - 工作区信息加载失败。 - 桌面端不支持按 ID 选择工作区,请升级桌面端的 OpenBitFun。 - 桌面端已没有这个工作区。 - 多个已打开的工作区使用同一路径,请从列表中选择。 - 助手 - 远程文件路径 - 在电脑端 - 下载 - 正在读取文件… - %1$s / %2$s - 选择保存位置… - 下载失败 - 已完成 - 打开文件 - 此文件暂不支持预览 - 关闭 - 已显示前 %1$s,下载后可查看完整内容 - 文件不存在或已被移动 - 文件不存在或不在当前工作区 - 无法访问工作区外的文件 - 文件过大,无法在移动端预览 - 读取文件时连接中断。 - 无法打开文件 - 文件预览 - 正在读取文件 - 离线,仅显示已加载内容 - 图片无法解码,请重试或下载文件。 - 适应窗口 - 原始大小 - 刷新 - - 请填写该房间的账号用户名。 - 请填写该房间的账号密码。 - 电脑端拒绝了本设备,请检查用户 ID 与密码。 - 房间不存在,请确认电脑端仍在共享。 - 尝试过于频繁,请稍后再试。 - 中继服务暂时不可用。 - 无法连接到中继服务,请检查网络。 - 电脑端未在规定时间内响应。 - 中继返回了预期之外的内容,电脑端可能需要升级。 - 电脑端拒绝了此次连接。 - - - 连续失败次数过多,请在 %1$d 秒后重试。 - - 搜索 - 搜索对话 - 代码 - 置顶 - 已归档 - 最近对话 - 还没有会话。 - 工作区 - 设备 - 离线 - 加载中... - 这台电脑暂时无法读取 - 重试 - 未连接 - 连接电脑 - 添加连接 - 这台电脑还没有工作区 - 此工作区暂无会话 - 这个工作区暂时无法读取 - 还有 %1$d 个工作区 - 还有 %1$d 台设备 - 在此工作区新建 - 没有匹配的会话 - 未命名会话 - 聊天 - 新聊天 - 使用邮箱或 GitHub 登录 - 打开侧边栏 - 已连接 - 正在重连 - 正在重新连接桌面端 - 连接中 - 连接异常 - 连接不可用,请重新连接 - 已断开 - 与桌面端断开连接 - 等待连接 - 消息已同步 - 正在恢复连接 - OpenBitFun 正在执行... - 正在检测连接…… - 桌面端已停止响应。配对仍然有效,可以重试,或断开后重新配对。 - 重新检测 - 桌面端拒绝了该请求。 - 无法连接中继服务。 - 桌面端没有及时响应。 - 请求过于频繁,请稍后重试。 - 桌面端返回了本应用无法识别的格式,请升级桌面端的 OpenBitFun。 - 该会话已不在桌面端。 - 桌面端不支持按 ID 选择工作区,请升级桌面端的 OpenBitFun。 - 桌面端的 OpenBitFun 版本过旧,不支持按需读取会话内容,请升级桌面端的 OpenBitFun。 - 桌面端已没有这个工作区。 - - 返回会话列表 - 会话设置 - 远程会话 - 还没有消息 - 可以就这个工作区向智能体提问。 - 正在加载对话… - 发送失败,请检查连接后重试 - 回复被中断。 - 重试 - 子智能体 - 展开思考过程 - 收起思考过程 - 正在思考 - 已思考 - 回到最新消息 - 图片 - 复制 - 等待确认 - 执行中 - 已完成 - 已取消 - 失败 - 排队中 - 输入 - 输出 - 错误 - 停止 - 你的回答 - 发送回答 - 其他 - 智能体正在等待你的回答。 - 正在运行“%1$s” - %1$s失败 - %1$s · %2$s - 已运行 %1$d 个工具 - 更新任务列表 - 发起任务 - 读取文件 - 写入文件 - 删除文件 - 查看变更 - 修改文件 - 运行命令 - 网页搜索 - 访问网页 - 搜索代码 - 请求确认 - 新建任务 - 返回 - 告诉 OpenBitFun 要做什么 - 聊天 - 选择工作区 - 没有最近工作区,请先在桌面端打开工作区。 - 没有已连接的桌面设备。 - 创建会话失败。 - 当前远程控制 - 连接来源 - 账号设备 - 未连接 - OpenBitFun 桌面版 - 尚未连接桌面端 - 断开 - 重新连接 - 已认证 - 加载更早消息 - 正在同步 - 打开 OpenBitFun 授权 - 无法处理这张图片,请选择其他图片。 - 极简 - 标准 - 极致 - 任务已完成 - 打开 OpenBitFun 查看结果。 - 开启任务完成提醒 - 稍后 - 开启通知 - 允许 OpenBitFun 在任务完成时发送通知。你可以稍后在系统设置中更改。 - 登录账号 - 干点活儿 - 玩点花样 - 随你发挥 - 今天,想做点什么? - 最近会话 - 浏览工作区 - 全部会话 - 还没有可继续的对话 - 连接电脑后,继续你的对话。 - 受控设备上的路径 - SSH 主机(可选) - 打开工作区 - 受控设备本机 - 无法加载已保存连接,请刷新重试。 - 打开终端 - 终端输入 - 发送 - 关闭终端 - 终端请求失败。 - 浏览文件 - 更多文件 - 文件内容 - 保存文件 - 新目录路径 - 创建目录 - 文件操作失败。 - 新建文件 - 重命名打开的文件 - 删除打开的文件 - 编辑后批准 - 权限请求未能完成,请重试以刷新待审批请求。 - 上传文件 - 无法读取所选文件,请选择本地文件后重试。 - 终端 - 放弃未保存的更改? - 放弃 - 浏览文件夹 - 选择此文件夹 - 上级文件夹 - 名称:升序 - 名称:降序 - 修改时间:最新优先 - 修改时间:最早优先 - 工作区操作 - 工具 - - 计划 - 查看计划 - 执行计划 - 此电脑暂不支持执行计划 - 请等待当前操作完成 - 小应用 - 关闭 - 返回 - 无法恢复或保存图片草稿,点按重试。 - 子任务输出 - 全部应用 - 离线可用 - 无法加载小应用,请重试 - 无法打开授权页面,请重试。 - 旧版设备:显示最近访问的工作区 - 编辑参数 - 收起参数 - 文件名 - 文件操作 - 电脑上的文件已被修改,当前草稿仍保留。请先复制草稿,再重新打开文件以读取最新内容。 - 加载更早消息失败,点按重试。 - 正在加载更早消息… - 任务列表 - 全部任务已完成 - 主力模型 - 快速模型 - 未配置快速模型,使用主力模型 - 主力 - 快速 - 待发送 · %1$d - 长按拖动排序 - 上移 - 下移 - 刷新 - 队列状态已变化或未能确认,请刷新后再操作。 - %1$d 个附件 - 等待执行端处理 - 立即发送 - 消息操作 - 从队列移除 - 升级执行端后可调整消息顺序。 - 此设备暂时无法使用语音输入,请使用文字输入。 - 暂时无法打开照片选择器,请重试或使用其他照片应用。 - diff --git a/src/apps/mobile/android/app/src/main/res/values/ic_launcher_background.xml b/src/apps/mobile/android/app/src/main/res/values/ic_launcher_background.xml deleted file mode 100644 index cedff38687..0000000000 --- a/src/apps/mobile/android/app/src/main/res/values/ic_launcher_background.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - #000000 - diff --git a/src/apps/mobile/android/app/src/main/res/values/strings.xml b/src/apps/mobile/android/app/src/main/res/values/strings.xml deleted file mode 100644 index 4456541efe..0000000000 --- a/src/apps/mobile/android/app/src/main/res/values/strings.xml +++ /dev/null @@ -1,517 +0,0 @@ - - - Use suggestion - OpenBitFun - Chat - Remote - Account - Settings - Settings - Account - Not signed in - Language - General - Language - Choose language - English - Simplified Chinese - - General chat - About - Product - OpenBitFun for Android - Version - Theme - System default - Light - Dark - Account - Sign in with email or GitHub - Sign in with email or GitHub to connect to your computers.\nTasks and model settings stay on the controlled computer. - Sign-in server - OpenBitFun username - OpenBitFun password - Relay URL, for example https://relay.example.com - Signing in… - Connect - Controlling - Relay URL - Username - Password - Sign in with email or GitHub - Sign out - Offline - Online - Refresh - Retry - Loading… - This account has no other registered devices yet. - Devices - Sign in to see every desktop on your account. - Choose a desktop - Remote - Choose an online desktop to continue. - Account devices - - Controlling · %1$s - Sign-in details are invalid. Please sign in again. - Your sign-in has expired. Sign in again with email or GitHub. - Too many sign-in attempts. Try again later. - Sign-in is temporarily unavailable. Try again later. - Unable to connect. Check your connection and try again. - The relay returned an invalid account response. - Connection timed out. Check your connection and try again. - The secure account session could not be restored. - General Chat - More - Copy Markdown - Deleting this conversation cannot be undone. - You - Assistant - Set up the model service - Add an API URL, a model name and an API key to start chatting. - Configure a provider before sending. - The provider rejected the API key. - The model service is rate-limited. Try again later. - The model service is temporarily unavailable. Try again later. - The model service returned an unrecognized response. - Could not reach the provider. - Load earlier messages - Syncing - - Model - Local custom model - In use - Not configured - On this device - Account sync - Account models - Account - %1$d synced - No account models available - API URL - https://api.example.com - API key - Enter the API key - Leave empty to keep the saved key - Model name - e.g. chat-model - Saved securely - Clear the saved key - Keep the saved key - Save - The API URL must start with http:// or https://. - Enter a model name. - Enter an API key. - The system secure storage is unavailable. Try again later. - Chat model - Choose account model - Model sources - Local custom - Test connection - Testing… - Keep or enter an API key to test the connection. - Connection test passed. - Show API key - Hide API key - - Cancel - - Connect to a desktop - - Connected - Room %1$s… - Workspace: %1$s - No workspace is open on the desktop. - Signed in as %1$s - Sessions - Loading sessions… - Try again - No sessions found. - Could not load sessions. - No workspace is open on the desktop. Open one there, then refresh. - Refresh - Search sessions - Search - All - Code - Cowork - New code session - New cowork session - Load more - Messages synced - Choose a session - Open a session from the sidebar, or create one. - No remote chats yet - Start a chat to continue desktop tasks from your phone. - New session - Projects - %1$d more sessions - Rename - Session title - Save - Delete - Session - Session actions - Uploaded files - This session has %1$d uploaded files - No uploaded files in this session - Archive - Pin to top - Unpin - Unarchive - View details - Deleting this session cannot be undone. - Session details - Agent type - Workspace - Workspace path - Created - Updated - Messages - Status - Unknown - Archived - - - Just now - %1$d minutes ago - %1$d hours ago - %1$d days ago - - - View settings - Adjust session grouping and information density - Grouping - Filters - Shown details - Workspace - Session type - All workspaces - All types - All statuses - Updated time - Run status - By project - Newest first - Chats first - Chats - Today - Yesterday - Earlier - Running - Ready - Close - Back - Open - Messages - Ask OpenBitFun - Send - Stop - Attach image - Voice input - Remove image - Tool - Approve - Reject - Permission mode - This setting syncs to the connected desktop and applies to every new tool call. - Ask - High-risk actions wait for your confirmation. - Auto approve - Actions that would ask for confirmation are approved automatically. - Full access - Every tool action is allowed without asking again. - Reading the desktop\'s permission setting… - Could not read the permission setting. Try again. - The desktop\'s permission mode could not be read. Refresh to try again. - Could not save the permission mode. The desktop is still on the mode shown above. - Connect a desktop to change the permission mode. - Turn on full access? - Desktop tools will be able to run commands and change files directly. - Turn on full access - Model - Unnamed model - Choose a model - On this device - Account model - No models are ready to use. - Could not load the available models. Try again. - The connected desktop does not support choosing models from this app. - Retry - The model list could not be refreshed. Showing the previously loaded list. - Workspace - Could not load workspace information. - The desktop does not support selecting workspaces by ID. Update OpenBitFun on the desktop. - The desktop no longer has this workspace. - Several open workspaces share this path. Choose one from the list. - Assistants - Remote file path - - On the desktop - Download - Reading file… - %1$s / %2$s - Choose where to save… - Download failed - Done - Open file - This file type cannot be previewed yet - Close - Showing the first %1$s. Download the file to see all of it. - The file does not exist or was moved - The file does not exist or is outside the current workspace - Cannot access files outside the workspace - The file is too large to preview on mobile - The connection dropped while reading this file. - Could not open the file - File preview - Reading file - Offline. Showing loaded content only. - The image could not be decoded. Retry or download the file. - Fit window - Actual size - Refresh - - - Enter the account user name for this room. - Enter the account password for this room. - The desktop refused this device. Check the user ID and password. - That room is gone. Make sure the desktop is still sharing. - Too many attempts. Wait a moment and try again. - The relay is not responding right now. - Could not reach the relay. Check the network. - The desktop did not answer in time. - Unexpected reply from the relay. The desktop may need updating. - The desktop declined the connection. - - - Too many failed attempts. Try again in %1$d second. - Too many failed attempts. Try again in %1$d seconds. - - Search - Search chats - Code - Pinned - Archived - Recent chats - No conversations yet. - Workspaces - Devices - Offline - Loading... - This computer cannot be read right now - Retry - Disconnected - Connect a computer - Add connection - This computer has no workspaces yet - No chats in this workspace - This workspace cannot be read right now - %1$d more workspaces - %1$d more devices - New in this workspace - No matching sessions - Untitled session - Chat - New chat - Sign in with email or GitHub - Open sidebar - Connected - Reconnecting - Reconnecting to the desktop - Connecting - Connection error - Connection unavailable. Reconnect to continue. - Disconnected - Disconnected from the desktop - Waiting to connect - Messages synced - Restoring connection - OpenBitFun is working... - Checking the connection… - The desktop stopped answering. The pairing is still here, so try again — or disconnect and pair afresh. - Check again - The desktop refused the request. - Could not reach the relay. - The desktop did not answer in time. - Too many requests; try again shortly. - The desktop answered in a format this app does not understand. Update OpenBitFun on the desktop. - That session is no longer on the desktop. - The desktop does not support selecting workspaces by ID. Update OpenBitFun on the desktop. - The desktop runs an older OpenBitFun version that does not support on-demand session streaming. Update OpenBitFun on the desktop to continue. - The desktop no longer has this workspace. - - Back to sessions - Session settings - - Remote session - No messages yet - Ask the agent anything about this workspace. - Loading conversation… - Send failed. Check the connection and retry. - - Reply interrupted. - Retry - - Subagent - Show reasoning - Hide reasoning - Thinking - Thought - Scroll to latest message - Image - Copy - Waiting for you - Running - Done - Cancelled - Failed - Queued - Input - Output - Error - Stop - Your answer - Send answer - Other - The agent is waiting for an answer. - Running \"%1$s\" - %1$s failed - %1$s · %2$s - Ran %1$d tools - Update task list - Start task - Read file - Write file - Delete file - View changes - Edit file - Run command - Search the web - Open page - Search code - Ask for confirmation - New task - Back - Tell OpenBitFun what to do - Chat - Choose a workspace - No recent workspaces. Open one on the desktop first. - No desktop is connected. - Could not create the session. - Current remote control - Connection source - Account device - Not connected - OpenBitFun Desktop - No desktop connected yet - Disconnect - Reconnect - Authenticated - Open OpenBitFun authorization - This image could not be prepared. Choose another image. - Minimal - Standard - Ultimate - Task completed - Open OpenBitFun to view the result. - Task completion notifications - Later - Enable notifications - Allow OpenBitFun to notify you when tasks finish. You can change this later in system settings. - Sign in - Get things done - Try something fun - Make it yours - What would you like to do today? - Recent conversations - Browse workspaces - All conversations - No conversations to continue yet - Connect a computer to continue your conversations. - Path on controlled device - SSH host (optional) - Open workspace - Controlled device - Could not load saved connections. Refresh to retry. - Open terminal - Terminal input - Send - Close terminal - Terminal request failed. - Browse files - More files - File content - Save file - New directory path - Create directory - File operation failed. - Create file - Rename open file - Delete open file - Edit before approval - Permission request could not be completed. Retry to refresh pending requests. - Upload file - Could not read the selected file. Choose a local file and retry. - Discard unsaved changes? - Discard - Browse folders - Choose this folder - Parent folder - Name A–Z - Name Z–A - Newest first - Oldest first - Terminal - Workspace actions - Tools - - Plan - View plan - Build plan - This desktop does not support building plans. - Wait for the current operation to finish. - Mini Apps - Close - Back - Unable to restore or save image drafts. Tap to retry. - Subtask output - All apps - Available offline - Unable to load apps. Please retry. - Unable to open the authorization page. Please retry. - Older device: showing recent workspaces - Edit input - Hide input - File name - File actions - File changed on the computer. Your draft is preserved. Copy it before reopening the file to load the latest version. - Could not load earlier messages. Tap to retry. - Loading earlier messages… - Task list - All tasks completed - Primary model - Fast model - Fast model not configured; using primary - Primary - Fast - Queued messages · %1$d - Hold to reorder - Move up - Move down - Refresh - Queue status changed or could not be confirmed. Refresh before another action. - %1$d attachments - Waiting for host confirmation - Send now - Message actions - Remove from queue - Update the execution host to reorder messages. - Voice input is unavailable on this device. You can continue by typing. - The photo picker is unavailable. Try again or choose a different photo app. - diff --git a/src/apps/mobile/android/app/src/main/res/values/themes.xml b/src/apps/mobile/android/app/src/main/res/values/themes.xml deleted file mode 100644 index 3a0cbe53ad..0000000000 --- a/src/apps/mobile/android/app/src/main/res/values/themes.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/AppLocaleResolverTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/AppLocaleResolverTest.kt deleted file mode 100644 index ff07c5759f..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/AppLocaleResolverTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import org.junit.Assert.assertEquals -import org.junit.Test - -class AppLocaleResolverTest { - @Test - fun resolvesMissingOrUnknownLanguagesToEnglish() { - listOf(null, "", " ", "en", "fr").forEach { language -> - assertEquals(AppLocale.ENGLISH, resolveAppLocale(language)) - } - } - - @Test - fun resolvesChineseLocaleTagsThroughTheirLanguageToken() { - // Android exposes zh-CN and zh-Hans locale tags as the language token zh. - listOf("zh-CN" to "zh", "zh-Hans" to "zh").forEach { (_, language) -> - assertEquals(AppLocale.SIMPLIFIED_CHINESE, resolveAppLocale(language)) - } - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/FoldFactsTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/FoldFactsTest.kt deleted file mode 100644 index df5616e86d..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/platform/FoldFactsTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.openbitfun.mobile.app.platform - -import org.junit.Assert.assertEquals -import org.junit.Test - -class FoldFactsTest { - @Test - fun ordinaryDeviceHasNoFoldFacts() { - assertEquals( - FoldFacts( - hasFoldingFeature = false, - halfOpened = false, - flatOpened = false, - isFolded = false, - isExpandedFoldable = false, - hoverCandidate = false, - ), - reduceFoldFacts(hasHingeSensor = false, features = emptyList()), - ) - } - - @Test - fun flatOpenFeatureIsExpandedButNotFolded() { - assertEquals( - FoldFacts(true, false, true, false, true, false), - reduceFoldFacts( - hasHingeSensor = true, - features = listOf(FoldFeatureFacts(FoldState.FLAT, isHorizontal = false)), - ), - ) - } - - @Test - fun halfOpenHorizontalFeatureIsHoverCandidate() { - assertEquals( - FoldFacts(true, true, false, false, false, true), - reduceFoldFacts( - hasHingeSensor = false, - features = listOf(FoldFeatureFacts(FoldState.HALF_OPENED, isHorizontal = true)), - ), - ) - } - - @Test - fun halfOpenVerticalFeatureIsNotHoverCandidate() { - assertEquals( - FoldFacts(true, true, false, false, false, false), - reduceFoldFacts( - hasHingeSensor = false, - features = listOf(FoldFeatureFacts(FoldState.HALF_OPENED, isHorizontal = false)), - ), - ) - } - - @Test - fun hingeSensorWithoutWindowFeatureMeansCoverFolded() { - assertEquals( - FoldFacts(false, false, false, true, false, false), - reduceFoldFacts(hasHingeSensor = true, features = emptyList()), - ) - } - - @Test - fun unknownFeatureIsNotTreatedAsExpandedOrHovering() { - assertEquals( - FoldFacts(true, false, false, false, false, false), - reduceFoldFacts( - hasHingeSensor = false, - features = listOf(FoldFeatureFacts(FoldState.UNKNOWN, isHorizontal = true)), - ), - ) - } - - @Test - fun mixedFlatAndUnknownFeaturesAreNotFlatOpen() { - assertEquals( - FoldFacts(true, false, false, false, false, false), - reduceFoldFacts( - hasHingeSensor = false, - features = listOf( - FoldFeatureFacts(FoldState.FLAT, isHorizontal = false), - FoldFeatureFacts(FoldState.UNKNOWN, isHorizontal = false), - ), - ), - ) - } - - @Test - fun unknownFeatureSuppressesHoverForMixedHalfOpenFeatures() { - assertEquals( - FoldFacts(true, true, false, false, false, false), - reduceFoldFacts( - hasHingeSensor = false, - features = listOf( - FoldFeatureFacts(FoldState.HALF_OPENED, isHorizontal = true), - FoldFeatureFacts(FoldState.UNKNOWN, isHorizontal = false), - ), - ), - ) - } - - @Test - fun multipleFeaturesRemainHalfOpenAndUseHorizontalHalfOpenForHover() { - assertEquals( - FoldFacts(true, true, false, false, false, true), - reduceFoldFacts( - hasHingeSensor = true, - features = listOf( - FoldFeatureFacts(FoldState.FLAT, isHorizontal = false), - FoldFeatureFacts(FoldState.HALF_OPENED, isHorizontal = true), - ), - ), - ) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt deleted file mode 100644 index 14cebc9ebb..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/state/AppShellStateTest.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.openbitfun.mobile.app.state - -import androidx.compose.runtime.saveable.SaverScope -import org.junit.Assert.* -import org.junit.Test - -class AppShellStateTest { - private fun state() = AppShellState( - MobileSurface.REMOTE, false, false, false, false, "", - ) - - private val scope = object : SaverScope { - override fun canBeSaved(value: Any): Boolean = true - } - - @Test fun disconnectedHomeIsSeparateFromConnectionChooser() { - val shell = state() - assertFalse(shell.remoteConnectOpen) - shell.openRemoteConnect() - assertTrue(shell.remoteConnectOpen) - shell.closeRemoteConnect() - assertFalse(shell.remoteConnectOpen) - } - - @Test fun selectingADeviceOrSessionClosesConnectionFlow() { - val shell = state() - shell.openRemoteConnect() - shell.closeRemoteSession() - assertFalse(shell.remoteConnectOpen) - shell.openRemoteConnect() - shell.openRemoteSession("session") - assertEquals("session", shell.remoteSessionId) - assertEquals("session", shell.pendingRemoteSessionId) - assertFalse(shell.remoteConnectOpen) - } - - @Test fun pendingSessionRoutesBeforeItAppearsInTheCommittedList() { - val shell = state() - shell.openRemoteSession("workspace-session") - - assertEquals( - "workspace-session", - resolveRoutedRemoteSessionId( - pendingSessionId = shell.pendingRemoteSessionId, - requestedSessionId = shell.remoteSessionId, - committedSessionIds = emptySet(), - selectedSessionId = "previous-session", - ), - ) - - shell.observeRemoteSessionOpen("workspace-session", "previous-session", busy = false) - assertEquals("workspace-session", shell.pendingRemoteSessionId) - shell.observeRemoteSessionOpen("workspace-session", "previous-session", busy = true) - shell.observeRemoteSessionOpen("workspace-session", "previous-session", busy = false) - assertEquals(null, shell.pendingRemoteSessionId) - assertEquals( - "previous-session", - resolveRoutedRemoteSessionId( - pendingSessionId = shell.pendingRemoteSessionId, - requestedSessionId = shell.remoteSessionId, - committedSessionIds = emptySet(), - selectedSessionId = "previous-session", - ), - ) - } - - @Test fun successfulPendingOpenFallsBackToTheStoreSelection() { - val shell = state() - shell.openRemoteSession("workspace-session") - shell.observeRemoteSessionOpen("workspace-session", "workspace-session", busy = false) - - assertEquals(null, shell.pendingRemoteSessionId) - assertEquals( - "workspace-session", - resolveRoutedRemoteSessionId( - pendingSessionId = shell.pendingRemoteSessionId, - requestedSessionId = shell.remoteSessionId, - committedSessionIds = emptySet(), - selectedSessionId = "workspace-session", - ), - ) - } - - @Test fun restoreAcceptsOldSavedStateAndRetainsNewConnectionRoute() { - val legacy = listOf("REMOTE", false, "GENERAL", false, false, false, "", null, false, false) - assertFalse(AppShellState.Saver.restore(legacy)!!.remoteConnectOpen) - // Older builds saved a retired connection-overlay request at index 9 - // and nothing after it; the request meant the account device sheet was - // open. - val legacyConnectionOverlay = legacy.dropLast(1) + true - assertTrue(AppShellState.Saver.restore(legacyConnectionOverlay)!!.remoteConnectOpen) - // A build that also wrote index 10 is read from index 10. - val legacyBoth = legacy + false - val closedWithLegacyOverlay = legacyBoth.toMutableList().also { it[9] = true } - assertFalse(AppShellState.Saver.restore(closedWithLegacyOverlay)!!.remoteConnectOpen) - - val shell = state().apply { openRemoteConnect() } - val saved = with(AppShellState.Saver) { scope.save(shell) }!! - assertEquals(12, (saved as List<*>).size) - assertEquals(false, saved[9]) - assertTrue(AppShellState.Saver.restore(saved)!!.remoteConnectOpen) - - val pending = state().apply { openRemoteSession("workspace-session") } - val savedPending = with(AppShellState.Saver) { scope.save(pending) }!! - assertEquals("workspace-session", AppShellState.Saver.restore(savedPending)!!.pendingRemoteSessionId) - } - - @Test fun restoreMapsTheRetiredRemoteSettingsPageToTheOneSettingsPage() { - // Builds with two settings pages saved "REMOTE" at index 2. It must - // still restore, onto the single settings page, rather than throw. - val legacyRemote = listOf("REMOTE", true, "REMOTE", false, false, false, "", null, false, false, false) - val restored = AppShellState.Saver.restore(legacyRemote)!! - assertTrue(restored.showSettings) - assertFalse(restored.showAccount) - - val saved = with(AppShellState.Saver) { scope.save(restored) } as List<*> - assertEquals("GENERAL", saved[2]) - assertTrue(AppShellState.Saver.restore(saved)!!.showSettings) - } - - @Test fun signedInAccountOpensSettingsInsteadOfASeparatePage() { - val shell = state() - shell.openAccount(signedIn = true) - assertTrue(shell.showSettings) - assertFalse(shell.showAccount) - } - - @Test fun signedInAccountKeepsTheSettingsPageAlreadyShowing() { - val shell = state() - shell.openSettings() - shell.openAccount(signedIn = true) - assertTrue(shell.showSettings) - assertFalse(shell.showAccount) - } - - @Test fun signedOutLoginFromSettingsReturnsToSettings() { - val shell = state() - shell.openSettings() - shell.openAccount(signedIn = false) - assertTrue(shell.showAccount) - assertFalse(shell.showSettings) - shell.completeLogin() - assertFalse(shell.showAccount) - assertTrue(shell.showSettings) - } - - @Test fun signedOutLoginFromOutsideSettingsLandsOnSettings() { - val shell = state() - shell.openAccount(signedIn = false) - shell.completeLogin() - assertFalse(shell.showAccount) - assertTrue(shell.showSettings) - } - - @Test fun cancellingLoginRestoresOnlyTheSettingsThatAskedForIt() { - val fromSettings = state().apply { - openSettings() - openAccount(signedIn = false) - dismissAccount() - } - assertTrue(fromSettings.showSettings) - val fromHome = state().apply { - openAccount(signedIn = false) - dismissAccount() - } - assertFalse(fromHome.showSettings) - assertFalse(fromHome.showAccount) - } - - @Test fun completeLoginWithoutAnOpenLoginSheetDoesNothing() { - val shell = state() - shell.completeLogin() - assertFalse(shell.showSettings) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBreakpointTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBreakpointTest.kt deleted file mode 100644 index c6f006c30d..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBreakpointTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import com.openbitfun.mobile.app.ui.theme.generated.MobileDesignBreakpoints -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class ComposerBreakpointTest { - @Test - fun generatedBreakpointTokensRemainStable() { - assertEquals(600, MobileDesignBreakpoints.Wide) - assertEquals(840, MobileDesignBreakpoints.ExtraWide) - assertEquals(1440, MobileDesignBreakpoints.Xl) - } - - @Test - fun composerWideBreakpointHasNoOffByOne() { - assertFalse(composerIsWide(599)) - assertTrue(composerIsWide(600)) - } - - @Test - fun generatedBreakpointBoundariesRemainOrdered() { - assertTrue(839 < MobileDesignBreakpoints.ExtraWide) - assertEquals(MobileDesignBreakpoints.ExtraWide, 840) - assertTrue(1439 < MobileDesignBreakpoints.Xl) - assertEquals(MobileDesignBreakpoints.Xl, 1440) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationComposerDraftTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationComposerDraftTest.kt deleted file mode 100644 index c686d2b559..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationComposerDraftTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import org.junit.Assert.assertEquals -import org.junit.Test - -class ConversationComposerDraftTest { - @Test - fun mergesDictationOntoExistingTextWithASingleSpace() { - assertEquals("existing draft spoken text", mergeComposerDraft("existing draft", "spoken text")) - } - - @Test - fun preservesExistingWhitespaceWhileTrimmingRecognition() { - assertEquals(" existing spoken", mergeComposerDraft(" existing ", " spoken ")) - } - - @Test - fun keepsExistingWhitespaceDraft() { - assertEquals("spoken", mergeComposerDraft("", " spoken ")) - assertEquals(" spoken", mergeComposerDraft(" ", "spoken")) - } - - @Test - fun dropsABlankSpokenFragment() { - assertEquals(" existing ", mergeComposerDraft(" existing ", "")) - assertEquals("existing", mergeComposerDraft("existing", " ")) - } - - @Test - fun blankRecognitionDoesNotEraseDraftWhitespace() { - assertEquals("", mergeComposerDraft("", "")) - assertEquals(" ", mergeComposerDraft(" ", " ")) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationScrollPolicyTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationScrollPolicyTest.kt deleted file mode 100644 index f09c8d08f6..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationScrollPolicyTest.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class ConversationScrollPolicyTest { - @Test - fun sticksWhenReaderIsAtTail() { - assertTrue( - ConversationScrollPolicy.shouldStickToBottom( - currentlySticking = false, - isAtBottom = true, - isScrollInProgress = false, - ), - ) - assertTrue(ConversationScrollPolicy.shouldScrollToBottom(stickToBottom = true, hasRows = true)) - } - - @Test - fun aDragTakesOverBeforeTheFirstMovementAwayFromTheTail() { - assertFalse(ConversationScrollPolicy.shouldStickToBottom( - currentlySticking = true, isAtBottom = true, isScrollInProgress = true, - )) - } - - @Test - fun stopsStickingWhenReaderLeavesTail() { - assertFalse( - ConversationScrollPolicy.shouldStickToBottom( - currentlySticking = true, - isAtBottom = false, - isScrollInProgress = true, - ), - ) - } - - @Test - fun resumesAfterExplicitScrollToBottom() { - assertTrue( - ConversationScrollPolicy.shouldStickToBottom( - currentlySticking = false, - isAtBottom = true, - isScrollInProgress = false, - ), - ) - } - - @Test - fun doesNotScrollWhenDeltaArrivesWhileReaderIsScrolledUp() { - assertFalse( - ConversationScrollPolicy.shouldScrollToBottom( - stickToBottom = false, - hasRows = true, - ), - ) - } - - @Test - fun lastItemIndexAccountsForTheLeadingHeader() { - org.junit.Assert.assertEquals(2, ConversationScrollPolicy.lastItemIndex(rowCount = 3, hasLeadingItem = false)) - org.junit.Assert.assertEquals(3, ConversationScrollPolicy.lastItemIndex(rowCount = 3, hasLeadingItem = true)) - org.junit.Assert.assertEquals(0, ConversationScrollPolicy.lastItemIndex(rowCount = 0, hasLeadingItem = false)) - org.junit.Assert.assertEquals(0, ConversationScrollPolicy.lastItemIndex(rowCount = 0, hasLeadingItem = true)) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/HistoryPageArrivalTrackerTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/HistoryPageArrivalTrackerTest.kt deleted file mode 100644 index 5d8b26a781..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/HistoryPageArrivalTrackerTest.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class HistoryPageArrivalTrackerTest { - @Test fun layoutCannotRequestAndBounceCannotRearmTheSameGesture() { - val tracker = HistoryPageArrivalTracker() - assertFalse(tracker.arrived(true)) - tracker.beginGesture() - assertFalse(tracker.arrived(false)) - assertTrue(tracker.arrived(true)) - repeat(10) { - assertFalse(tracker.arrived(false)) - assertFalse(tracker.arrived(true)) - } - tracker.beginGesture() - assertTrue(tracker.arrived(true)) - tracker.cancelArrival() - assertFalse(tracker.arrived(true)) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ProcessPresentationTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ProcessPresentationTest.kt deleted file mode 100644 index 3f08a1ccff..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/ProcessPresentationTest.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat - -import com.openbitfun.mobile.app.ui.chat.message.* -import com.openbitfun.mobile.core.feature.session.* -import org.junit.Assert.* -import org.junit.Test - -class ProcessPresentationTest { - @Test fun childThinkingOnlyFollowsTheLastVisibleBlock() { - val thought = MessageBlock.Thinking("thought", "Old reasoning", true) - val block = MessageBlock.Subagent("task", "Task", true, "", - listOf(thought, MessageBlock.Text("answer", "Answer", true))) - assertFalse((subagentChildren(block).first() as MessageBlock.Thinking).streaming) - assertTrue((subagentChildren(block.copy(children = listOf(thought))).single() as MessageBlock.Thinking).streaming) - assertFalse((subagentChildren(block.copy(running = false, children = listOf(thought))).single() as MessageBlock.Thinking).streaming) - } - @Test fun outputPreviewKeepsUnicodeAndBoundsLongText() { - val preview = subagentPreview("😀".repeat(400)) - assertEquals(321, preview.codePointCount(0, preview.length)) - assertTrue(preview.endsWith("…")) - assertEquals("answer", subagentPreview(" answer ")) - } - @Test fun statusPreservesFailuresInsteadOfCallingThemDone() { - listOf("failed", "ERROR", "timeout", "cancelled", "canceled", "rejected").forEach { assertTrue(subagentFailed(it)) } - assertFalse(subagentFailed("completed")) - } - private fun tool(id: String, phase: ToolPhase = ToolPhase.COMPLETED) = ToolCard( - id, "Read", phase, ToolKind.DOCUMENT, ToolOperation.READ_FILE, - "file.kt", "", "", "", "", null, emptySet(), - ) - @Test fun completedWorkSummarizesWithoutHidingLiveOrFailedTools() { - val thought = MessageBlock.Thinking("thinking", "Before", false) - val first = MessageBlock.Tools("first", listOf(tool("one"))) - val between = MessageBlock.Thinking("between", "Between", false) - val last = MessageBlock.Tools("last", listOf(tool("two"))) - val answer = MessageBlock.Text("answer", "Answer", false) - val grouped = processGroups(listOf(thought, first, between, last, answer)) - assertTrue(grouped.first().summarized) - assertEquals(listOf("thinking", "tool:one", "between", "tool:two"), grouped.first().blocks.map { it.id }) - assertEquals(answer, grouped.last().blocks.single()) - for (phase in listOf(ToolPhase.RUNNING, ToolPhase.FAILED)) { - val active = MessageBlock.Tools("active", listOf(tool("active", phase))) - val split = processGroups(listOf(thought, first, active, between, last)) - assertEquals(3, split.size) - assertTrue(split.none { it.summarized }) - } - assertEquals(grouped.first().id, processGroups(listOf(thought, first, between, last, - MessageBlock.Tools("more", listOf(tool("three"))))).single().id) - } - @Test fun textAndTaskBoundariesKeepThinkingInOrder() { - val a = MessageBlock.Thinking("a", "First", false) - val b = MessageBlock.Thinking("b", "Second", false) - val answer = MessageBlock.Text("answer", "Answer", false) - val groups = processGroups(listOf(a, b, answer)) - assertEquals(2, groups.size) - assertEquals("First\n\nSecond", (groups[0].blocks.single() as MessageBlock.Thinking).text) - assertEquals(answer, groups[1].blocks.single()) - assertFalse(groups[0].summarized) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanelsTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanelsTest.kt deleted file mode 100644 index 6228ad522c..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/chat/tool/ToolInteractionPanelsTest.kt +++ /dev/null @@ -1,88 +0,0 @@ -package com.openbitfun.mobile.app.ui.chat.tool - -import com.openbitfun.mobile.core.feature.session.QuestionAnswerValue -import com.openbitfun.mobile.core.feature.session.QuestionOption -import com.openbitfun.mobile.core.feature.session.ToolApprovalEditContract -import com.openbitfun.mobile.core.feature.session.ToolApprovalEditSupport -import com.openbitfun.mobile.core.feature.session.ToolQuestion -import org.junit.Assert.assertEquals -import org.junit.Test - -class ToolInteractionPanelsTest { - @Test - fun approvalEditSupportMatchesRuntimeUpdatedInputContract() { - assertEquals(ToolApprovalEditSupport.SUPPORTED, ToolApprovalEditContract.support) - } - - private val questions = listOf( - ToolQuestion(0, "", "Pick one", listOf(QuestionOption("A", null), QuestionOption("B", null)), false), - ToolQuestion(1, "", "Pick many", listOf(QuestionOption("X", null)), true), - ) - - @Test - fun buildStructuredAnswers_mapsSelectionsAndReplacesOther() { - val answers = buildStructuredAnswers( - questions = questions, - selectedByIndex = mapOf(0 to setOf("B"), 1 to setOf("X", "Other")), - customByIndex = mapOf(1 to "custom value"), - otherLabel = "Other", - ) - - assertEquals(QuestionAnswerValue.Text("B"), answers[0].value) - assertEquals(QuestionAnswerValue.Choice(listOf("X", "custom value")), answers[1].value) - } - - @Test - fun buildStructuredAnswers_recognizesWireOtherWithLocalizedOtherLabel() { - val question = ToolQuestion( - 0, - "", - "Pick one", - listOf(QuestionOption("Other", null)), - false, - ) - - val answers = buildStructuredAnswers( - questions = listOf(question), - selectedByIndex = mapOf(0 to setOf("Other")), - customByIndex = mapOf(0 to "custom value"), - otherLabel = "其他", - ) - - assertEquals(QuestionAnswerValue.Text("custom value"), answers.single().value) - val options = effectiveOptions(question, "其他") - assertEquals(1, options.size) - assertEquals(1, options.count { isOtherOption(it.label, "其他") }) - } - - @Test - fun buildStructuredAnswers_recognizesChineseWireOtherWithEnglishOtherLabel() { - val question = ToolQuestion( - 0, - "", - "Pick one", - listOf(QuestionOption("其他", null)), - false, - ) - - val answers = buildStructuredAnswers( - questions = listOf(question), - selectedByIndex = mapOf(0 to setOf("其他")), - customByIndex = mapOf(0 to "custom value"), - otherLabel = "Other", - ) - - assertEquals(QuestionAnswerValue.Text("custom value"), answers.single().value) - val options = effectiveOptions(question, "Other") - assertEquals(1, options.size) - assertEquals(1, options.count { isOtherOption(it.label, "Other") }) - } - - @Test - fun buildStructuredAnswers_keepsEmptyAnswersForUnselectedQuestions() { - val answers = buildStructuredAnswers(questions, emptyMap(), emptyMap(), "Other") - - assertEquals(QuestionAnswerValue.Text(""), answers[0].value) - assertEquals(QuestionAnswerValue.Choice(emptyList()), answers[1].value) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicyTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicyTest.kt deleted file mode 100644 index 6e1a2028f1..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/remote/DocumentExportPolicyTest.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.openbitfun.mobile.app.ui.remote - -import org.junit.Assert.assertEquals -import org.junit.Test - -class DocumentExportPolicyTest { - @Test fun sourceAndExtensionlessFilesDoNotAcquirePlatformExtensions() { - // Android maps .ts to video; unknown source extensions and extensionless - // files have no MIME mapping. text/plain would append .txt in each case. - assertEquals("application/octet-stream", documentExportMimeType("text/plain", "video/mp2t")) - assertEquals("application/octet-stream", documentExportMimeType("text/plain", null)) - assertEquals("image/png", documentExportMimeType("image/png", "image/png")) - assertEquals("application/pdf", documentExportMimeType("application/pdf", "application/pdf")) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/ContentCardCoordinatorTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/ContentCardCoordinatorTest.kt deleted file mode 100644 index a99849f08a..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/ContentCardCoordinatorTest.kt +++ /dev/null @@ -1,100 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell - -import org.junit.Assert.assertEquals -import org.junit.Test - -/** - * Locks the content-card boundary rules for the compact drawer without standing - * up a Compose tree. [ContentCardCoordinator] is the single observable for the - * rounded clip + shadow: [ContentCardPhase.Receded] means the static shadow/clip - * modifier is attached, [ContentCardPhase.Flat] means the full-screen content is - * drawn with neither. - */ -class ContentCardCoordinatorTest { - @Test - fun initialStateReflectsWhetherTheDrawerStartsOpen() { - assertEquals(ContentCardPhase.Flat, ContentCardCoordinator(initialOpen = false).phase) - assertEquals(ContentCardPhase.Receded, ContentCardCoordinator(initialOpen = true).phase) - } - - @Test - fun revealDoesNotRecedeTheFirstFullScreenFrame() { - val coordinator = ContentCardCoordinator(initialOpen = false) - - coordinator.onRevealStarted() - - // The first frame after opening is still the content at rest, full - // screen. The 28dp corner and shadow must not snap onto it. - assertEquals(ContentCardPhase.Flat, coordinator.phase) - } - - @Test - fun zeroProgressNeverRecedes() { - val coordinator = ContentCardCoordinator(initialOpen = false) - - coordinator.onRevealStarted() - coordinator.onContentProgress(0f) - - // progress == 0 means the content is still at rest, full screen; the - // corner/shadow must stay off. This pins the "only progress > 0 may - // recede" invariant directly. - assertEquals(ContentCardPhase.Flat, coordinator.phase) - } - - @Test - fun positiveProgressRecedesTheCard() { - val coordinator = ContentCardCoordinator(initialOpen = false) - - coordinator.onRevealStarted() - coordinator.onContentProgress(0.001f) - - assertEquals(ContentCardPhase.Receded, coordinator.phase) - } - - @Test - fun openThenCloseSettlesBackToFlat() { - val coordinator = ContentCardCoordinator(initialOpen = false) - - coordinator.onRevealStarted() - coordinator.onContentProgress(0.5f) - assertEquals(ContentCardPhase.Receded, coordinator.phase) - - // Close only removes the shadow/clip once the content has settled back - // to full screen — never on an earlier drawer-hide deadline. - coordinator.onContentSettled() - - assertEquals(ContentCardPhase.Flat, coordinator.phase) - } - - @Test - fun rapidOpenCloseConverges() { - val coordinator = ContentCardCoordinator(initialOpen = false) - - coordinator.onRevealStarted() - coordinator.onContentProgress(0.4f) - coordinator.onContentSettled() - coordinator.onRevealStarted() - coordinator.onContentProgress(0.4f) - coordinator.onContentSettled() - - assertEquals(ContentCardPhase.Flat, coordinator.phase) - } - - @Test - fun reducedMotionCollapsesTimingButKeepsTheFinalState() { - val coordinator = ContentCardCoordinator(initialOpen = false) - - // Under "Remove animations" the content animation completes instantly, - // so the first observed progress is already 1f. The boundary events - // still fire in the same order and the final card state must be flat - // with no residual clip/shadow; a repeated settle is a no-op. - coordinator.onRevealStarted() - coordinator.onContentProgress(1f) - assertEquals(ContentCardPhase.Receded, coordinator.phase) - - coordinator.onContentSettled() - coordinator.onContentSettled() - - assertEquals(ContentCardPhase.Flat, coordinator.phase) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicyTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicyTest.kt deleted file mode 100644 index 58db6e573b..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/RemoteWorkspacePathPolicyTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.openbitfun.mobile.app.ui.shell.sidebar - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class RemoteWorkspacePathPolicyTest { - @Test - fun trailingSeparatorsDoNotChangeEquality() { - assertTrue(RemoteWorkspacePathPolicy.equal("/workspace", "/workspace/")) - assertTrue(RemoteWorkspacePathPolicy.equal("/workspace///", "/workspace")) - assertTrue(RemoteWorkspacePathPolicy.equal("/workspace\\", "/workspace")) - } - - @Test - fun surroundingWhitespaceIsIgnored() { - assertTrue(RemoteWorkspacePathPolicy.equal(" /workspace ", "/workspace")) - } - - @Test - fun rootEmptyBlankAndSingleCharacterEdgesArePreserved() { - assertEquals("/", RemoteWorkspacePathPolicy.normalize("///")) - assertEquals("\\", RemoteWorkspacePathPolicy.normalize("\\\\")) - assertEquals("", RemoteWorkspacePathPolicy.normalize(" ")) - assertEquals("/", RemoteWorkspacePathPolicy.normalize("/")) - assertTrue(RemoteWorkspacePathPolicy.equal("", " ")) - assertFalse(RemoteWorkspacePathPolicy.equal("/", "")) - } - - @Test - fun realWorkspacePathWithTrailingSlashEqualsCanonicalPath() { - val path = "/home/user/project/src" - assertTrue(RemoteWorkspacePathPolicy.equal(path, "$path/")) - } - - @Test - fun distinctPathsRemainUnequal() { - assertFalse(RemoteWorkspacePathPolicy.equal("/home/user/project", "/home/user/other")) - assertFalse(RemoteWorkspacePathPolicy.equal("/workspace/a", "/workspace/ab")) - } -} diff --git a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/theme/MobileTextScaleTest.kt b/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/theme/MobileTextScaleTest.kt deleted file mode 100644 index a7ab833fd6..0000000000 --- a/src/apps/mobile/android/app/src/test/kotlin/com/openbitfun/mobile/app/ui/theme/MobileTextScaleTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.openbitfun.mobile.app.ui.theme - -import com.openbitfun.mobile.app.ui.theme.generated.MobileTextScale -import org.junit.Assert.assertEquals -import org.junit.Test - -class MobileTextScaleTest { - @Test - fun referenceClassStaysUnscaled() { - // 460 ppi at 3x is the ramp's reference; anything denser per dp caps at 1. - assertEquals(1f, MobileTextScale.resolve(xdpi = 460f, density = 3f), 0.0001f) - assertEquals(1f, MobileTextScale.resolve(xdpi = 489f, density = 3f), 0.0001f) - } - - @Test - fun largerDpShrinksText() { - // HUAWEI Mate X7 outer screen: 415.6 xdpi at density 3.125. - assertEquals(0.868f, MobileTextScale.resolve(xdpi = 415.636f, density = 3.125f), 0.0001f) - } - - @Test - fun neverDropsBelowFloor() { - assertEquals(0.85f, MobileTextScale.resolve(xdpi = 300f, density = 3f), 0.0001f) - } - - @Test - fun implausibleMetricsFallBackToUnscaled() { - assertEquals(1f, MobileTextScale.resolve(xdpi = 0f, density = 3f), 0.0001f) - assertEquals(1f, MobileTextScale.resolve(xdpi = 96f, density = 3f), 0.0001f) - assertEquals(1f, MobileTextScale.resolve(xdpi = 2000f, density = 3f), 0.0001f) - assertEquals(1f, MobileTextScale.resolve(xdpi = 415f, density = 0f), 0.0001f) - } -} diff --git a/src/apps/mobile/android/build.gradle.kts b/src/apps/mobile/android/build.gradle.kts deleted file mode 100644 index 020183f6cc..0000000000 --- a/src/apps/mobile/android/build.gradle.kts +++ /dev/null @@ -1,4 +0,0 @@ -plugins { - alias(libs.plugins.android.application) apply false - alias(libs.plugins.kotlin.compose) apply false -} diff --git a/src/apps/mobile/android/gradle.properties b/src/apps/mobile/android/gradle.properties deleted file mode 100644 index 82bae8dc45..0000000000 --- a/src/apps/mobile/android/gradle.properties +++ /dev/null @@ -1,11 +0,0 @@ -org.gradle.jvmargs=-Xmx3g -XX:MaxMetaspaceSize=1g -org.gradle.parallel=true -org.gradle.caching=true - -android.useAndroidX=true -android.nonTransitiveRClass=true - -kotlin.code.style=official - -# Enabled parallel sync for Gradle 9.4+ -org.gradle.tooling.parallel=true diff --git a/src/apps/mobile/android/gradle/wrapper/gradle-wrapper.jar b/src/apps/mobile/android/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index eddabd2eef8d94a5437d6168ff9c87a78ff725b3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 47505 zcma%jV|XRZx@BzJPRF)w+qP|W2RrDP9UC1d9oxo^)3I%LIQh<*=g!Qz_k45q^VI&e z|5VkgwQ8;Rt*tBv4uJsz0|NsB0z&#Z{?7*m1QtX=LS2MGMp2SUUPeqpQB6Wa9TEie zub-^z>bb3QVg*ju^jKS3o#9H#w4Yxz1*n>pYH+2nC3dC@ic(OUh@sI7>n^@O3t+EN zk19TR2&69-M23X8{h9JYx|8)kwwf7ttr>teD4+VN#nkbK$s(IG`^odY38j0~G5LYI zE8yj!-3t3WJpbc*GP8f1Ijv!GZFxNt(Cq4DxZU@%dVh&ur@bEGnl2N^*QNXDgt%%uIzL8-|f9*0a_P$gWq1W= zyYFqsd}OSk24kb~1dN}B%z?^{HGmwKoogz&O?>^nlNT;9zKwXe(^*#}CA6|3JU~$) z84gW6*^!J(I2cJ6Fex`F@*8Z;s#mTo^y2AJ6hSf>Ei3lYhvt>4{wrqH*`8wlt+NqV zs$Y#ZDUzSWF!beISEBi0Dvx#amw4A=5p>tM)l(wMg*GU=hp|-Z=aZM_pw^OegdgFE z#1Jtd_&p~_;Lb@JjM5MZdJErBWf7~hq^IxX89(}?*<2v)uDSTyr#g{7fM4R;@KjPU zef+&aPhcAskT5|z_09<(`3G^SKwJ0e=Q(TjU}<2E7jh(ZoiwT{!}jl%GU(rNo2?a! zx2+TFX}Pt%EZ7ohNMI$bpk|IVcQ3Z2tWLJSZtq)*Im<#WBDYEfci;r(!~8KiUAI2I z+)9QJ;|lF-J*nrrVRIf{Rt}tBY`7YBW#R+!Qox8y99}8lf<@)9znd`>8Q;dY znEDDc?e6`E=jWxW%O= z*dn!&=MGIsRTcKy#$f?nc7NBdssxcHDt6p!g8h@bt@_P63RGK`SeA81RG5nyyn|pn zh5?evjH@qk|v=A$Ff0_lB8|p@3G{6%UYG`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5GQjh zzG|CYxM@?dHVc%Y3IIpv^VG;b1nQo!)`Toj36NwO9`dz~uBTY{v(9Fkl{a)cc?MrL zG&|LOQud7KIzd%k(g7}bA}&&^2WQ2NF@Jz}RF81KID^_gunIaLlk^UXIz!oOwUyj) z^+LFYc3qAMTacfK6krSYC5w+K!}1m7y$P{71~+3rm-PqDl4Ffj7kXRkoE0c}Q6Fxd0JzFy#jzttYd5r2)Z**Zu6(rTZo z#JUzXt2$RM*)J-lT7#v>@uYnyC*q|CF&7pP)ewcxhAv%~I$edQrHQ7{yi#F-c7NS| zA@la$-Q7NgLAu}|gt>6_FXjUDJxnM}C`3dE914mI>O)l?@g@osR3kMM6guRJ`J>5- zDhn}6%84<{ND7O}DT%5m!$CprLhlxPKf1B(@77F&d|m^2VgBHT1=6JH|J=w5$w`Wd zDk(F`iv3qtM4@h}cb#R_Ag{ZgJl_l*4GPNE!Hn7LU+tTijjS!0zr*1QIhZ-yKzfct zkX0sjzgSEDe8^N|&?OF#RYW>u6>*2#{bmv9ztj08FY;&SQSWJQB_Yn!AdBNWyx}*~ z#Q2@_zX`wx_!o0!@ zhJR1zPjwtWOAZQ?S`9$r$qaI8pZy@YiuVVS(f|nI;jh8{HCzbE!^z|yG_9x05;!3f z8UUHlABRax_6M4>7LJY(p4nfjkVyFxNw99gQWHdy9@3lp$6*dr{DI`(TCN5TCVxIm zz3W43S4iMc+V&iDsHDgdkhpYZ&i>iy%7 z2?xtRtNz2>eb2i6(Rl{Pe>nfwO#KEE{_~gldqnFUF87@w`o4YS9bMs@6)F8z>K{V=`&NT@+g{&n#qgJY|DYA+&&U3K`@J874c+878h>wm z{Pz}yKkIy7^?cXN@0;nH{+Z4{OxE`W!*|8g-|U6^F9rTvDfQ1s{(UX$k7vQvYMdv{Mz{+ '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/src/apps/mobile/android/gradlew.bat b/src/apps/mobile/android/gradlew.bat deleted file mode 100644 index a51ec4f588..0000000000 --- a/src/apps/mobile/android/gradlew.bat +++ /dev/null @@ -1,82 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem gradlew startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables, and ensure extensions are enabled -setlocal EnableExtensions - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -"%COMSPEC%" /c exit 1 - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -"%COMSPEC%" /c exit 1 - -:execute -@rem Setup the command line - - - -@rem Execute gradlew -@rem endlocal doesn't take effect until after the line is parsed and variables are expanded -@rem which allows us to clear the local environment before executing the java command -endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel - -:exitWithErrorLevel -@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts -"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/src/apps/mobile/android/settings.gradle.kts b/src/apps/mobile/android/settings.gradle.kts deleted file mode 100644 index 73f93f937b..0000000000 --- a/src/apps/mobile/android/settings.gradle.kts +++ /dev/null @@ -1,34 +0,0 @@ -pluginManagement { - repositories { - google() - mavenCentral() - gradlePluginPortal() - } -} - -plugins { - id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" -} - -dependencyResolutionManagement { - repositories { - google() - mavenCentral() - } - // One catalog for the whole mobile stack. The app cannot drift onto a - // different Kotlin or AGP than the modules it links against, because there - // is no second place to write a version down. - versionCatalogs { - create("libs") { - from(files("../shared/gradle/libs.versions.toml")) - } - } -} - -rootProject.name = "openbitfun-android" - -// The dependency points this way and only this way: the app includes the -// shared build, the shared build knows nothing about the app. -includeBuild("../shared") - -include(":app") diff --git a/src/apps/mobile/design-system/README.md b/src/apps/mobile/design-system/README.md deleted file mode 100644 index 9af6d2d43a..0000000000 --- a/src/apps/mobile/design-system/README.md +++ /dev/null @@ -1,227 +0,0 @@ -# OpenBitFun Mobile Design System - -This directory is the source-neutral visual contract for the native HarmonyOS, -Android, and iOS applications. It owns stable visual facts and deterministic -preview scenarios; it does not implement a cross-platform renderer. - -## Ownership - -- `tokens/mobile-tokens.json`: the single source for semantic colors, - typography, shared geometry, breakpoints, and motion durations. -- `components/mobile-components.json`: component anatomy, states, and the token - roles each native implementation must consume. -- `scenarios/mobile-preview-scenarios.json`: deterministic states rendered by - native preview galleries and the desktop comparison tool. -- `preview/`: the local three-column inspection surface. It can show the - contract fallback immediately and accepts native screenshots for overlay or - side-by-side inspection. - -Generated platform files are checked in so IDE previews and native builds do -not require Node.js. Change the contract, then run: - -```bash -pnpm run mobile:ui:generate -pnpm run mobile:ui:check -pnpm run mobile:ui:preview -``` - -Do not edit generated files by hand. Native components remain responsible for -safe areas, keyboard behavior, accessibility bridges, navigation gestures, and -platform presentation primitives. - -## Typography - -- Product text consumes the semantic roles in `tokens/mobile-tokens.json`; - native components must not introduce literal text sizes. -- Keep the hierarchy shallow: display and page titles use the display/headline - roles, row titles use title roles, reading text uses body roles, and compact - metadata uses label roles. The smallest product-text role is `label_small` - at 12 units; icon glyph sizing is independent of text sizing. -- Native hosts follow the system font-size preference with a documented maximum - scale. Validate the standard size and at least one enlarged accessibility size - without changing display zoom, and prefer wrapping or ellipsis over clipping. -- The ramp's sizes were tuned on the iPhone Pro class, where one logical unit is - 1/153.3 inch (460 ppi at 3x). A screen whose logical unit is physically larger - renders the same `16` visibly bigger, so `text_scale` normalises it: the host - computes `xdpi / density / reference_logical_dpi`, clamps it to - `[min_factor, max_factor]`, and applies it to text only, on top of the user's - font-size preference. HarmonyOS folds it into the generated typography roles - (`MobileTextScale.apply` at ability start, so every role getter returns the - scaled value); Android folds it into the theme's `Density.fontScale` so every - `sp` under `OpenBitFunTheme` follows. iOS is the reference and stays at 1. - Symbol glyph and `dp`/`vp` geometry never scale. A HUAWEI Mate X7 - (415.6 dpi at density 3.125) resolves to 0.868, so its `16` reads as 14 vp — - the same millimetres as 16 pt on the iPhone. -- Inline Markdown runs (`**strong**`, `*emphasis*`, `` `code` ``) change only - weight, slant, or family; they inherit the paragraph role's size on all three - hosts. - -The native role names map to the product's formal content purposes as follows: - -| Content purpose | Native role | -| --- | --- | -| Page title | `display_large`, or `headline_large` in a compact container | -| Section title | `headline_small` | -| Card or row title | `title_small` / `title_medium` | -| Body copy | `body_medium`, with `body_large` for reading emphasis | -| Supporting text | `body_small` | -| Control label | `label_medium` / `label_large` | -| Compact metadata | `label_small` | - -Platform renderers may choose the listed size variant for available width, but -must not substitute a different content purpose merely to obtain a preferred -metric. - -## Sidebar chrome - -The left sidebar is chrome, not another page. The desktop client paints it with -its own surface family — one step off the scene the conversation sits on — so -the mobile clients carry a dedicated `sidebar_*` token family rather than -reusing the page roles (`page_bg`, `card`, `soft`, `line`, `ink`, `muted`, -`subtle`). Those page roles stay exactly as they were for conversations, -sheets, and action surfaces; only the rail moved. - -Each token maps one-to-one onto a desktop semantic role from -`design-system/packages/theme-openbitfun`: - -| Mobile token | Desktop role | Used for | -| --- | --- | --- | -| `sidebar_bg` | `color.surface.chrome` | the rail itself, and the pane behind it | -| `sidebar_bg_fade` | same hue at zero alpha | the top stop of the footer fade | -| `sidebar_raised` | `color.surface.raised` | circle buttons, the quiet footer action | -| `sidebar_line` | `color.border.subtle` | hairlines and control borders | -| `sidebar_hover` | `color.action.quiet.hover` | the search field fill | -| `sidebar_selection` | `color.selection.surface` | the selected row and device fills | -| `sidebar_ink` | `color.content.primary` | titles, row labels, icon tint | -| `sidebar_muted` | `color.content.secondary` | supporting row text | -| `sidebar_subtle` | `color.content.caption` | placeholders and offline devices | - -`sidebar_line`, `sidebar_hover` (dark), and `sidebar_selection` are stored as -`#AARRGGBB` on purpose: desktop defines them as alpha over the chrome surface, -and keeping the alpha lets them composite the same way instead of baking a -flattened value that drifts the moment the surface changes. - -Sidebar components shared with page surfaces take their layer from the caller -rather than assuming it — Android's `SidebarCircleButton` and -`SignedOutConnectionActions` both expose background/border/content parameters, -and the sheet presented from the sidebar (the workspace picker) stays on page -roles because a sheet is not chrome. - -## Simulator captures - -The native galleries can be launched without changing the normal app path: - -```bash -# Android (after installing the debug APK) -adb shell am force-stop com.openbitfun.mobile.debug -adb shell am start \ - -n com.openbitfun.mobile.debug/com.openbitfun.mobile.app.MainActivity \ - --ez openbitfun.design_preview true \ - --es openbitfun.design_scenario connected-conversation - -# iOS Simulator (after installing the simulator app) -xcrun simctl launch booted com.openbitfun.mobile.ios \ - --design-preview connected-conversation - -# HarmonyOS emulator (after installing a locally signed debug HAP) -hdc -t shell aa force-stop -hdc -t shell aa start \ - -a EntryAbility -b \ - --ps openbitfunDesignPreview connected-conversation -``` - -Valid scenario ids come from `scenarios/mobile-preview-scenarios.json`. Save -captures using the convention documented in `preview/snapshots/README.md`, then -open the desktop comparison surface to inspect them beside the HarmonyOS -baseline. - -## Cold-start brand motion - -HarmonyOS, Android and iOS render `startup_brand_reveal` natively. The 6.8-second -sequence uses the `brand_wordmark` artwork typography and the dedicated -`brand_dot` cyan, distinct from action and status colors. Platform soft sans -fonts are used; the HTML prototype's macOS fonts are not redistributed. This -decorative wordmark scales with its 280-unit stage, rather than Dynamic Type; -normal app text continues to respect accessibility sizing. - -The cyan dot hops with the letter reveals, returns to the dotless i, then the -shared contour mark expands above the word. Cold-launch presentation is -independent of account and network readiness. Backgrounding removes it without -replay, and system reduced-motion skips it. Notification onboarding waits until -the overlay finishes. Design-preview launches bypass the startup overlay. - -Validate on a compact and wide native window, including a live resize where -available, and check a background/foreground cycle during the reveal. - -## Signed-out welcome home - -The disconnected, signed-out home uses the A welcome composition with the C -staggered-slide phrase animation: a fixed brand mark, desktop-derived localized -short phrases, and equally weighted sign-in and scan actions in a dark dock. -This is the signed-out home itself, not an onboarding layer before another -landing page. Compact and wide hosts use the same entry on all three platforms: -without a control target, show the welcome composition; account identity only -changes its primary action from sign-in to connect. Connect opens the existing -device chooser and scan opens the existing scanner. With a retained target, -disconnect/reconnect preserves session context and retry controls instead of -returning to welcome. An account reset can leave HarmonyOS disconnected rather -than idle; either state leads to welcome once the control target is cleared. -`welcome_*` geometry tokens own the compact dimensions and a 520-unit wide -content cap. The four dedicated welcome colors keep the dark dock and white -buttons stable in both appearance modes; normal page/action tokens invert or -change surfaces and cannot express this fixed brand treatment. - -Each phrase enters with 55 ms per-glyph staggering and an 800 ms cubic ease-out, -then leaves over 650 ms. Reduced motion renders a static wordmark. Background -or invisible hosts suspend presentation work. Native safe-area and accessibility -behavior remain platform-owned; these are logical layout units, not a promise -of identical font rasterization on different systems. - -HarmonyOS exposes the bundled MiniApp destination. Android and iOS preserve the -reserved footer area until they own that capability, rather than presenting an -inert MiniApp action. QR actions still use the existing account-device protocol; -this UI change does not add guest credentials or bypass server authorization. -HarmonyOS can render the isolated surface with the existing design-preview -launch parameter `openbitfunDesignPreview=welcome-home`, without logging out an -active account or loading its connection state. - -The welcome and startup marks share the desktop AboutBrandMark contour geometry: -15 rounded hexagonal paths with three low-opacity highlights traveling around -each contour over 18 seconds. `assets/welcome-brand-contours.json` records the -256-unit paths and lengths; native renderers own their drawing and lifecycle. -The startup keeps its existing entrance choreography; the welcome mark stays -in place while the highlights and short phrases loop. Reduced motion keeps the -contours static. No microphone or voice-service dependency is introduced. - -### Recent-conversation home - -Signed-in home shows up to three non-archived sessions from the current remote -device, ordered by valid update timestamp (creation time is the fallback). It -labels the device and workspace without treating a loaded catalog as an active -workspace selection. All conversations opens the existing sidebar; creation -stays in the workspace-owned sidebar action. Signed-in users without a remote -target see the same home with a connection entry, while signed-out users retain -the welcome page. Loading and offline states never erase retained sessions. -The mark uses a five-second diagonal highlight sweep; reduced motion uses a -static contour. Native hosts retain their own lifecycle and adaptive layout. - -The recent-home brand and headline are centered above the leading-aligned session list. The mark retains its original silhouette and uses the same diagonal sweep across native surfaces. HarmonyOS uses a 156vp mark and 21fp headline for its optical balance; other hosts use the shared geometry. - -HarmonyOS welcome occupies the full window when signed out without an active remote target. It suppresses the workspace sidebar without changing retained selection. At 600vp and above, the brand, phrase and constrained action group are centered without the compact dock; smaller windows retain the stacked dock. The welcome mark is 156vp compact and 184vp wide, using the diagonal sweep. Size changes update this layout in place. - -For HarmonyOS welcome windows at least 840vp wide with width/height at least 1.2, a centered composition capped at 1000vp places the brand and actions side by side. This follows available window geometry rather than a device model or fold count. - -### Authenticated cold-start home transition - -After the persisted first-install reveal has already been claimed, an -authenticated process launch uses `cold_start_home` (2400 ms). The home shell -mounts immediately so restoration and remote loading continue underneath the -cover. The contour mark starts at 56 logical units, then moves to the mark's -measured native bounds during 16%–68% of the timeline; the cover fades from -68%–100%. Each platform measures the actual compact or wide home layout, so -safe-area insets, split windows, and foldable posture changes do not rely on a -fixed coordinate. Signed-out restore, manual login after launch, activity or -scene recreation, foreground resume, and a second root do not claim the -transition. If the home mark is unavailable, the mark remains centered and the -cover still fades on the same clock. Reduced motion finishes immediately, and -accessibility and pointer interaction stay with the cover until it completes. diff --git a/src/apps/mobile/design-system/assets/approval-shield.svg b/src/apps/mobile/design-system/assets/approval-shield.svg deleted file mode 100644 index 3194e2b785..0000000000 --- a/src/apps/mobile/design-system/assets/approval-shield.svg +++ /dev/null @@ -1,43 +0,0 @@ - - diff --git a/src/apps/mobile/design-system/assets/welcome-brand-contours.json b/src/apps/mobile/design-system/assets/welcome-brand-contours.json deleted file mode 100644 index 6e5727b483..0000000000 --- a/src/apps/mobile/design-system/assets/welcome-brand-contours.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "viewBox": 256, - "cycleMs": 18000, - "source": "Desktop AboutBrandMark rounded six-corner ribbon, 15 fixed contours.", - "contours": [ - { - "path": "M154.860 59.584 Q167.500 59.584 173.820 70.531 L200.680 117.053 Q207.000 128.000 200.680 138.947 L173.820 185.469 Q167.500 196.416 154.860 196.416 L101.140 196.416 Q88.500 196.416 82.180 185.469 L55.320 138.947 Q49.000 128.000 55.320 117.053 L82.180 70.531 Q88.500 59.584 101.140 59.584 Z", - "length": 460.63326438618736 - }, - { - "path": "M152.788 57.185 Q165.682 56.702 172.547 67.628 L201.722 114.060 Q208.586 124.985 202.557 136.392 L176.934 184.875 Q170.905 196.282 158.011 196.765 L103.212 198.815 Q90.318 199.298 83.453 188.372 L54.278 141.940 Q47.414 131.015 53.443 119.608 L79.066 71.125 Q85.095 59.718 97.989 59.235 Z", - "length": 470.2124371537121 - }, - { - "path": "M150.574 54.847 Q163.702 53.863 171.119 64.741 L202.639 110.973 Q210.056 121.851 204.343 133.713 L180.066 184.126 Q174.353 195.988 161.224 196.972 L105.426 201.153 Q92.298 202.137 84.881 191.259 L53.361 145.027 Q45.944 134.149 51.657 122.287 L75.934 71.874 Q81.647 60.012 94.776 59.028 Z", - "length": 479.79160992123684 - }, - { - "path": "M148.218 52.578 Q161.562 51.074 169.537 61.879 L203.427 107.798 Q211.401 118.603 206.031 130.911 L183.208 183.221 Q177.838 195.529 164.494 197.032 L107.782 203.422 Q94.438 204.926 86.463 194.121 L52.573 148.202 Q44.599 137.397 49.969 125.089 L72.792 72.779 Q78.162 60.471 91.506 58.968 Z", - "length": 489.3707826887615 - }, - { - "path": "M145.724 50.384 Q159.263 48.344 167.799 59.048 L204.079 104.542 Q212.616 115.246 207.614 127.991 L186.355 182.157 Q181.353 194.902 167.814 196.943 L110.276 205.616 Q96.737 207.656 88.201 196.952 L51.921 151.458 Q43.384 140.754 48.386 128.009 L69.645 73.843 Q74.647 61.098 88.186 59.057 Z", - "length": 498.94995545628615 - }, - { - "path": "M143.094 48.274 Q156.805 45.680 165.907 56.257 L204.592 101.209 Q213.694 111.786 209.085 124.957 L189.498 180.935 Q184.889 194.106 171.178 196.700 L112.906 207.726 Q99.195 210.320 90.093 199.743 L51.408 154.791 Q42.306 144.214 46.915 131.043 L66.502 75.065 Q71.111 61.894 84.822 59.300 Z", - "length": 508.5291282238109 - }, - { - "path": "M140.330 46.254 Q154.191 43.091 163.861 53.512 L204.959 97.806 Q214.629 108.227 210.439 121.813 L192.629 179.551 Q188.438 193.137 174.578 196.301 L115.670 209.746 Q101.809 212.909 92.139 202.488 L51.041 158.194 Q41.371 147.773 45.561 134.187 L63.371 76.449 Q67.562 62.863 81.422 59.699 Z", - "length": 518.1083009913356 - }, - { - "path": "M137.437 44.331 Q151.423 40.584 161.662 50.823 L205.177 94.338 Q215.416 104.577 211.669 118.563 L195.741 178.007 Q191.993 191.993 178.007 195.741 L118.563 211.669 Q104.577 215.416 94.338 205.177 L50.823 161.662 Q40.584 151.423 44.331 137.437 L60.259 77.993 Q64.007 64.007 77.993 60.259 Z", - "length": 527.6874737588603 - }, - { - "path": "M134.416 42.513 Q148.504 38.167 159.311 48.195 L205.242 90.813 Q216.049 100.840 212.769 115.214 L198.826 176.300 Q195.545 190.673 181.458 195.019 L121.584 213.487 Q107.496 217.833 96.689 207.805 L50.758 165.187 Q39.951 155.160 43.231 140.786 L57.174 79.700 Q60.455 65.327 74.542 60.981 Z", - "length": 537.2666465263849 - }, - { - "path": "M131.272 40.805 Q145.436 35.849 156.810 45.637 L205.149 87.237 Q216.523 97.025 213.733 111.769 L201.877 174.431 Q199.087 189.175 184.923 194.131 L124.728 215.195 Q110.564 220.151 99.190 210.363 L50.851 168.763 Q39.477 158.975 42.267 144.231 L54.123 81.569 Q56.913 66.825 71.077 61.869 Z", - "length": 546.8458192939097 - }, - { - "path": "M128.010 39.216 Q142.223 33.637 154.160 43.157 L204.895 83.616 Q216.832 93.136 214.556 108.234 L204.885 172.401 Q202.609 187.499 188.396 193.077 L127.990 216.784 Q113.777 222.363 101.840 212.843 L51.105 172.384 Q39.168 162.864 41.444 147.766 L51.115 83.599 Q53.391 68.501 67.604 62.923 Z", - "length": 556.4249920614343 - }, - { - "path": "M124.633 37.750 Q138.869 31.539 151.365 40.762 L204.475 79.959 Q216.972 89.182 215.233 104.616 L207.842 170.209 Q206.103 185.643 191.868 191.854 L131.367 218.250 Q117.131 224.461 104.635 215.238 L51.525 176.041 Q39.028 166.818 40.767 151.384 L48.158 85.791 Q49.897 70.357 64.132 64.146 Z", - "length": 566.004164828959 - }, - { - "path": "M121.147 36.415 Q135.377 29.562 148.427 38.459 L203.889 76.272 Q216.938 85.169 215.758 100.920 L210.742 167.858 Q209.562 183.608 195.331 190.461 L134.853 219.585 Q120.623 226.438 107.573 217.541 L52.111 179.728 Q39.062 170.831 40.242 155.080 L45.258 88.142 Q46.438 72.392 60.669 65.539 Z", - "length": 575.5833375964837 - }, - { - "path": "M117.556 35.216 Q131.752 27.713 145.348 36.256 L203.131 72.563 Q216.727 81.106 216.127 97.152 L213.575 165.347 Q212.975 181.393 198.778 188.896 L138.444 220.784 Q124.248 228.287 110.652 219.744 L52.869 183.437 Q39.273 174.894 39.873 158.848 L42.425 90.653 Q43.025 74.607 57.222 67.104 Z", - "length": 585.1625103640084 - }, - { - "path": "M113.866 34.160 Q128.000 26.000 142.134 34.160 L202.201 68.840 Q216.335 77.000 216.335 93.320 L216.335 162.680 Q216.335 179.000 202.201 187.160 L142.134 221.840 Q128.000 230.000 113.866 221.840 L53.799 187.160 Q39.665 179.000 39.665 162.680 L39.665 93.320 Q39.665 77.000 53.799 68.840 Z", - "length": 594.7416831315331 - } - ] -} diff --git a/src/apps/mobile/design-system/components/mobile-components.json b/src/apps/mobile/design-system/components/mobile-components.json deleted file mode 100644 index 202a5d960f..0000000000 --- a/src/apps/mobile/design-system/components/mobile-components.json +++ /dev/null @@ -1,300 +0,0 @@ -{ - "version": 1, - "components": { - "shell_header_alignment": { - "purpose": "Keep sidebar search and conversation menu controls on one horizontal centerline.", - "anatomy": ["sidebar_header", "conversation_header"], - "states": ["drawer_open", "drawer_closed", "wide", "with_subtitle", "without_subtitle"], - "tokens": ["conversation_header_height"], - "platformNotes": "Both signed-in header rows use conversationHeaderHeight from the same safe-area origin, without a sidebar-only top inset. Preserve this height when a subtitle appears or disappears. Anchor drawer content scaling vertically at half the header height so reveal animation cannot shift its control centerline." - }, - "sidebar_chrome": { - "purpose": "Give the workspace sidebar the desktop client's structural chrome instead of the conversation page surface.", - "anatomy": ["chrome_surface", "header_row", "scroll_fade", "raised_control", "hairline"], - "states": ["light", "dark", "signed_out", "signed_in"], - "tokens": ["sidebar_bg", "sidebar_bg_fade", "sidebar_raised", "sidebar_line", "sidebar_hover", "sidebar_selection", "sidebar_ink", "sidebar_muted", "sidebar_subtle"], - "platformNotes": "The family mirrors the desktop semantic theme one role at a time: sidebar_bg is surface.chrome, sidebar_raised is surface.raised, sidebar_line is border.subtle, sidebar_hover is action.quiet.hover, sidebar_selection is selection.surface, and sidebar_ink / sidebar_muted / sidebar_subtle are content.primary / content.secondary / content.caption. The sidebar therefore sits one step away from the conversation surface in both appearance modes, as the desktop navigation panel does beside the scene. Alpha roles composite over sidebar_bg and must not be flattened into opaque literals. Conversation, sheet and action surfaces keep the paper-and-ink page tokens; only sidebar chrome uses this family." - }, - "sidebar_device_selector": { - "purpose": "Select one remote device and show its workspace panel below the device list, matching mobile web.", - "anatomy": ["device_icon", "device_name", "connection_indicator", "selected_workspace_panel"], - "states": ["selected", "online", "offline", "loading"], - "tokens": ["sidebar_selection", "sidebar_ink", "sidebar_muted", "status_success"], - "platformNotes": "Device rows have no disclosure chevron. Re-selecting the current device does not collapse its workspaces or restart a healthy connection. Use the sidebar selection surface and normal ink for device identity; only the separate status indicator expresses reachability. Do not add a connection status text row or recovery banner below the device. Automatic reconnect stays quiet; tapping the selected failed or disconnected device retries the connection. Workspace disclosure remains independent and survives refresh and device switching. Compact and wide layouts use the same selection semantics." - }, - "sidebar_tools_footer": { - "purpose": "Open controlled-device tools without creating a chat; keep settings separately reachable.", - "anatomy": ["tools_icon_and_label", "flexible_gap", "settings_button"], - "states": ["enabled", "disabled", "pressed"], - "tokens": ["sidebar_raised", "sidebar_line", "sidebar_ink"], - "platformNotes": "Use Tools / 工具 for both the sidebar entry and destination title. Render a native wrench-and-screwdriver symbol (or the existing platform vector) in a 24-unit slot, 8-unit label gap, 15-unit medium text, 14-unit horizontal padding and a minimum 104 by 48 pill. Keep the 48-unit settings action separate. Use a quiet surface and outline without raised shadows. Compact and wide sidebars reuse a pure footer component with state and callbacks; create-session validation must not affect tools appearance." - }, - "circle_control": { - "purpose": "A compact navigation or overflow control with a full-size touch target.", - "anatomy": ["touch_target", "centered_glyph", "optional_pressed_surface"], - "states": ["enabled", "pressed", "disabled", "focused"], - "tokens": ["control_touch_size", "card", "line", "ink"], - "platformNotes": "Keep the glyph's optical box separate from the touch target. Header and sidebar controls stay visually transparent at rest; reserve borders and elevation for the containing surface." - }, - "interaction_question": { - "purpose": "Answer a runtime mailbox question independently of transcript tool state.", - "anatomy": ["question_heading", "choice_or_text_input", "submit_action", "failure_feedback"], - "states": ["pending", "editing", "submitting", "failed"], - "tokens": ["content_gutter", "body_medium", "body_small", "ink", "muted", "card", "primary_action", "content_on_action"], - "platformNotes": "Render a direct question form in the scrollable mailbox. Tool execution headers, result expansion and stop actions stay in the transcript or composer. Retain draft values through submission failure and queue reordering; remove the form only when authoritative mailbox state removes it." - }, - "runtime_file_browser": { - "purpose": "Browse and manage files on the selected controlled runtime without changing the active chat workspace.", - "anatomy": ["runtime_location", "path_caption", "single_row_navigation_sort_create_toolbar", "scrolling_file_rows", "row_overflow", "contextual_transfer_feedback", "on_demand_action_sheet"], - "states": ["loading", "ready", "empty", "failed", "action_draft", "action_busy", "action_failed", "editor"], - "tokens": ["control_touch_size", "content_gutter", "body_medium", "body_small", "ink", "muted", "line", "card", "primary_action", "content_on_action"], - "platformNotes": "Parent, refresh, sort and create share one toolbar row. Rows show file or folder glyphs and an overflow menu; mutation forms are not permanently visible. Compact forms use a bottom sheet with submit and cancel reachable while the native keyboard is open. Preserve failed drafts and route every action to the captured runtime provider. Native adapters own keyboard avoidance and file pickers." - }, - "action_button": { - "purpose": "Expresses one primary, secondary, quiet, or destructive workflow action with consistent emphasis.", - "anatomy": ["touch_target", "action_label", "semantic_surface", "optional_hairline_border"], - "states": ["primary", "secondary", "quiet", "destructive", "disabled", "busy"], - "tokens": ["sheet_action_height", "primary_action", "content_on_action", "card", "soft", "line", "status_danger", "label_large"], - "platformNotes": "The semantic style is shared; a workflow may override height when its context requires a larger target, while preserving typography, radius, color, and disabled treatment." - }, - "conversation_header": { - "purpose": "Identifies the active conversation and the device or workspace answering it.", - "anatomy": ["leading_control", "title", "context_subtitle", "trailing_control"], - "states": ["single_line", "with_context", "renaming", "actions_open"], - "tokens": ["conversation_header_height", "conversation_header_compact_height", "conversation_header_title", "content_gutter", "control_touch_size"], - "platformNotes": "Compact and wide layouts preserve the same control geometry and action meaning." - }, - "message_bubble": { - "purpose": "Presents one user or assistant message in the conversation timeline.", - "anatomy": ["message_text", "role_surface", "hairline_border", "message_timestamp"], - "states": ["user", "assistant"], - "tokens": ["body_large", "message_bubble_max_width", "message_bubble_horizontal_padding", "message_bubble_vertical_padding", "message_bubble_radius", "message_spacing", "timeline_top_padding"], - "platformNotes": "The maximum width is the 276-unit compact HarmonyOS baseline; wide layouts may use a separate responsive policy. Show each available host message time below its content in localized short date/time with muted label-small text, right aligned for users and left aligned for assistants. Omit unavailable or invalid legacy timestamps. Ordinary failed tool calls share the neutral collapsed activity presentation; their actual failure details remain expandable. Questions, approvals and failed replies retain their attention states." - }, - "conversation_overlay": { - "purpose": "Lets the transcript own the whole pane while the header and composer stay reachable above it.", - "anatomy": [ - "top_overlay", - "top_edge_fade", - "timeline", - "bottom_overlay_fade" - ], - "states": [ - "at_rest", - "scrolled", - "composer_expanded", - "mailbox_open", - "keyboard_open" - ], - "tokens": [ - "conversation_overlay_side_inset", - "conversation_edge_fade_height" - ], - "platformNotes": "The timeline fills the pane and scrolls beneath both overlays; its content insets are measured from the live overlay heights rather than fixed, and are applied with each platform's content-inset primitive \u2014 Compose contentPadding, SwiftUI safeAreaInset, ArkUI contentStartOffset/contentEndOffset \u2014 never with padding, which would shrink the viewport and stop the transcript at the overlay instead of letting it run underneath, because the composer grows with multiline text and attachments and the mailbox appears without warning. The top layer is an opaque band with a short fade carrying it into the transcript; the bottom layer has no strip of its own \u2014 its whole background is the fade, because the transcript runs behind the composer and a short strip would leave a line of text crisp beside the pill after it had already faded out higher up. Fades never take touches. Blur is the platform's own: iOS ultraThinMaterial, HarmonyOS backgroundBlurStyle. Compose has no first-party backdrop blur, so Android uses a high-opacity band instead and reads the same at a glance." - }, - "composer_bar": { - "purpose": "Collects the next instruction and exposes one unambiguous primary action.", - "anatomy": ["attachment_action", "text_input", "model_control", "primary_action"], - "states": ["empty", "draft", "focused", "streaming", "disconnected", "with_attachments"], - "tokens": ["composer_action_size", "composer_collapsed_height", "composer_expanded_height", "composer_collapsed_radius", "composer_expanded_radius"], - "platformNotes": "Keyboard, dictation, and attachment pickers remain native adapters. The focused two-row form stays compact and exists to expose message context controls; multiline content and attachments may grow it further. The trailing action is the single filled action for Send, Dictate, or Stop." - }, - "prompt_suggestion": { - "purpose": "Offer the host's next-input suggestion above the remote conversation composer.", - "anatomy": ["suggestion_text", "full_width_touch_target"], - "states": ["available", "draft_hidden", "busy_hidden", "disconnected_hidden", "retired"], - "tokens": ["body_medium", "muted", "control_touch_size", "conversation_overlay_side_inset"], - "platformNotes": "Compact and wide layouts use a quiet, leading-aligned button with wrapping text and a minimum 48-unit touch target. Show only for the latest completed turn when the draft is empty and the session is idle and connected. Tapping copies the exact text into the native editor and focuses it without sending. New turns, session changes and host stream gaps retire the hint. Suggestions stay outside persisted transcripts; older hosts need no fallback request." - }, - "composer_model_selector": { - "purpose": "Changes the model for the message being composed without leaving the conversation or creation flow.", - "anatomy": ["optional_modal_header", "selected_mark", "primary_label", "supporting_label", "scrolling_model_rows"], - "states": ["compact_bottom", "wide_popover", "selected", "empty", "scrolling"], - "tokens": ["composer_model_selector_width", "composer_model_selector_radius", "composer_model_selector_row_height", "composer_model_selector_row_radius", "composer_model_selector_row_gap", "selection_top_radius", "selection_close_size", "floating_panel_bg", "card", "soft", "line", "ink", "muted"], - "platformNotes": "Compact layouts use a native bottom surface with a closeable header; wide layouts use an arrowless anchored surface without a redundant header. The selected model is first, uses the soft surface and a leading check mark, and all platform-specific provider glyphs and row dividers are omitted." - }, - "adaptive_modal_surface": { - "purpose": "Hosts settings, connection, creation, selection, and detail flows without crossing a physical fold or obscuring more of the workspace than necessary.", - "anatomy": ["scrim", "paper_surface", "header", "scroll_content", "action_rail"], - "states": ["compact_bottom", "wide_side", "fold_operate", "busy", "error"], - "tokens": ["scrim", "sheet_top_radius", "sheet_side_radius", "sheet_horizontal_padding", "sheet_header_height", "sheet_action_height", "card", "line", "structure"], - "platformNotes": "Use each platform's native modal lifecycle, accessibility focus, and back gesture; placement comes from the shared adaptive policy and visual geometry comes from these tokens." - }, - "account_login_sheet": { - "purpose": "Offers GitHub sign-in in a compact bottom sheet without empty full-screen space.", - "anatomy": ["close_header", "title", "supporting_copy", "optional_error", "primary_action"], - "states": ["signed_out", "authorizing", "error"], - "tokens": ["sheet_top_radius", "sheet_horizontal_padding", "sheet_header_height", "sheet_action_height", "display_medium", "body_medium"], - "platformNotes": "Use a bottom-aligned modal paper on compact and wide hosts: width min(available width - 16, 560), 8-unit margins outside system safe areas, 28-unit circular corners, no button or panel shadow. Header 56, top-aligned body at least 142, footer 10 + 48 + 24 give a 280-unit default height. Body grows for localized text, accessibility text and errors; oversized content scrolls. Close glyph uses round-capped 1.5-unit diagonal strokes from (2,2) to (16,16) and (16,2) to (2,16) within an 18-unit box, centered in a 48-unit target. Account profiles retain their separate adaptive settings presentation." - }, - "action_popover": { - "purpose": "Presents a short, anchored set of conversation, session, model, or project actions.", - "anatomy": ["section_label", "action_rows", "optional_divider", "anchored_paper_surface"], - "states": ["open", "compact_two_action", "selected", "destructive", "disabled"], - "tokens": ["popover_width", "popover_radius", "popover_padding", "popover_vertical_padding", "popover_action_height", "compact_popover_width", "compact_popover_radius", "compact_popover_action_height", "floating_panel_bg", "line", "quick"], - "platformNotes": "Wide action sets use the standard arrowless anchored paper surface. The project-row Code/Cowork shortcut remains an anchored two-action popover on every size because its trigger already lives inside the session list; it uses the compact popover geometry." - }, - "session_action_surface": { - "purpose": "Presents actions for a session row without stacking confirmation UI.", - "anatomy": ["optional_drag_handle", "session_identity", "action_rows", "in_place_confirmation"], - "states": ["compact_bottom", "wide_popover", "confirming_delete", "busy"], - "tokens": ["sheet_action_height", "popover_radius", "card", "line", "soft", "status_danger"], - "platformNotes": "Compact session lists use a transparent native sheet hosting the same 16-unit paper surface that wide lists anchor as a popover; deletion confirmation replaces the action rows in place. This is distinct from the active conversation header's action_popover." - }, - "selection_surface": { - "purpose": "Lets the user choose a language, model, device, workspace, or assistant from one consistent modal pattern.", - "anatomy": ["modal_header", "selection_rows", "selected_mark", "optional_supporting_text"], - "states": ["loading", "ready", "selected", "empty", "failed"], - "tokens": ["selection_top_radius", "selection_row_height", "selection_close_size", "sheet_header_height", "sheet_horizontal_padding", "card", "soft", "line"], - "platformNotes": "A compact standalone picker uses one native bottom surface and a wide picker anchors one arrowless paper popover to its trigger. When selection starts inside another modal, it replaces that modal's content rather than stacking another modal or scrim. The picker mechanism may be native, but row height, selected treatment, header chrome, and dismissal affordance stay aligned." - }, - "confirmation_surface": { - "purpose": "Confirms destructive or high-impact actions inside the surface that initiated them.", - "anatomy": ["specific_consequence", "cancel_action", "destructive_action"], - "states": ["idle", "confirming", "submitting", "failed"], - "tokens": ["sheet_action_height", "status_danger", "soft", "line"], - "platformNotes": "Prefer an in-place confirmation step over stacking a second modal and a second scrim." - }, - "settings_card": { - "purpose": "Groups related settings into a stable paper card within an adaptive modal surface.", - "anatomy": ["section_heading", "card", "entry_rows", "dividers", "inline_controls"], - "states": ["navigable", "editable", "loading", "failed", "disabled"], - "tokens": ["settings_compact_card_radius", "settings_card_radius", "settings_prominent_card_radius", "card", "line", "muted", "body_medium"], - "platformNotes": "A chevron means navigation; controls that mutate in place do not use one." - }, - "session_view_settings_surface": { - "purpose": "Controls how the connected desktop's sessions are grouped, filtered, and annotated without changing remote session data.", - "anatomy": ["modal_header", "grouping_card", "workspace_filter_card", "agent_filter_card", "status_filter_card", "metadata_card"], - "states": ["project_grouping", "time_grouping", "chat_first", "filtered", "metadata_visible"], - "tokens": ["sheet_header_height", "settings_compact_card_radius", "card", "soft", "line", "muted", "body_medium", "label_small"], - "platformNotes": "Open from the session-list overflow inside the shared adaptive modal. Choices update local view state only; compact, wide, and fold-operate placements use the same cards and never stack native pickers or alerts." - }, - "model_service_surface": { - "purpose": "Manages the active chat model, account-synced choices, and the local provider editor as one replace-in-place settings flow.", - "anatomy": ["modal_header", "current_model_card", "source_group", "account_model_rows", "local_provider_form", "feedback", "actions"], - "states": ["overview", "account_selection", "local_editor", "testing", "saving", "failed"], - "tokens": ["sheet_header_height", "model_current_row_height", "model_source_row_height", "model_account_row_height", "model_section_gap", "settings_compact_card_radius", "card", "soft", "line"], - "platformNotes": "Overview, account selection, and local editing replace each other inside the existing adaptive modal. Never stack another sheet or system picker; account rows select immediately, while the local row selects a complete configuration and its chevron always opens the editor." - }, - "pairing_surface": { - "purpose": "Guides desktop pairing from preparation through scanning, with a manual-code fallback that stays inside the connect surface.", - "anatomy": ["hero_wash", "back_control", "desktop_or_scanner_glyph", "instructions", "primary_action", "manual_pairing_overlay", "conditional_account_credentials", "status_feedback"], - "states": ["intro", "scan", "manual", "account_auth", "connecting", "failed", "paired"], - "tokens": ["connect_hero_bg", "connect_hero_surface", "scrim", "sheet_side_radius", "primary_action", "card", "soft", "line"], - "platformNotes": "Camera capture and permission prompts remain native. The manual form is an in-surface overlay with the shared scrim and 34-unit card, not a second system sheet. Account-protected links add username and password fields in that same card; passwords remain transient view state and are cleared on submit or dismiss." - }, - "remote_create_surface": { - "purpose": "Creates a remote session from one instruction while making the target desktop, workspace, and model explicit.", - "anatomy": ["back_control", "empty_focus_region", "device_context", "workspace_context", "create_composer", "selection_surface"], - "states": ["ready", "selecting_device", "selecting_workspace", "selecting_model", "listening", "submitting", "disconnected"], - "tokens": ["composer_expanded_height", "composer_expanded_radius", "selection_row_height", "popover_width", "card", "soft", "line", "accent"], - "platformNotes": "This is a conversation route, not a form modal: title and agent type are inferred from the first instruction and selected workspace. Compact selectors use one bottom selection surface; wide selectors use the same rows in an arrowless anchored popover." - }, - "remote_control_settings_surface": { - "purpose": "Explains which desktop is being controlled, how it is connected, and which permission policy that desktop applies.", - "anatomy": ["modal_header", "profile_entry", "current_control_card", "connection_source", "alternate_connection_entry", "permission_mode_card", "in_place_full_access_confirmation"], - "states": ["disconnected", "connecting", "connected_by_account", "connected_by_pairing", "permission_loading", "permission_failed", "confirming_full_access", "account_page"], - "tokens": ["sheet_header_height", "settings_prominent_card_radius", "settings_compact_card_radius", "scrim", "card", "soft", "line", "status_danger"], - "platformNotes": "The account page replaces this page inside the same adaptive modal. Full-access confirmation replaces content inside the permission card; it never opens a system alert or a second sheet." - }, - "file_preview_surface": { - "purpose": "Shows a remote file as a compact full-page modal or as a wide companion pane.", - "anatomy": ["file_header", "download_action", "close_action", "content_viewport", "truncation_notice"], - "states": ["loading", "text", "markdown", "image", "unsupported", "failed", "truncated"], - "tokens": ["sheet_header_height", "file_link", "card", "line", "soft"], - "platformNotes": "Placement is shared policy; rendering, file export, and platform-safe dismissal remain native adapters." - }, - "miniapp_navigation": { - "purpose": "Opens locally bundled tools from primary sidebar navigation, without requiring account or device access.", - "anatomy": ["outlined_apps_glyph", "leading_aligned_label", "full_row_touch_target"], - "states": ["idle", "pressed", "focused", "signed_out", "connected"], - "tokens": ["ink", "body_large", "control_touch_size"], - "platformNotes": "Use a quiet 48vp icon-and-label row in compact and wide sidebars, with 16vp medium-weight navigation text, a 24vp icon slot and a 14vp gap. In the sidebar the row keeps 4vp above and 8vp below itself, and the device section header keeps 10vp above it, inside the shared 76vp header frame: the header control sits 20vp above the row and the Devices label 18vp below it. A platform whose header control is not 44vp inherits that difference instead of adding a second gap, and no column-level spacing is layered around the row. HarmonyOS uses the native outlined sys.symbol.square_grid_2x2 at 24vp, centered in its slot and tinted with the semantic ink color. Render the catalog inside the shell content pane so selecting it slides the right pane left as the drawer closes, using the existing 250ms ease-out shell motion. Sidebar session selection uses the same shell motion without a second route-push animation. Do not promote this navigation destination to a primary action on remote home." - }, - "miniapp_catalog": { - "purpose": "Presents bundled apps with large visual previews that open each app directly.", - "anatomy": ["back_control", "centered_page_title", "offline_caption", "square_preview", "app_title"], - "states": ["catalog", "loading", "error", "app_open", "light", "dark"], - "tokens": ["page_bg", "ink", "muted", "soft", "body_large", "title_small", "body_medium", "label_small"], - "platformNotes": "Use a two-column library of square previews on compact screens and three columns when the gallery reaches 600vp. Clip previews to 24vp corners with 14vp column and 20vp row gaps; keep app names below images. The centered gallery caps at 1000vp, while open apps use full width. Reuse established showcase assets. Resize the grid without reloading an open app." - }, - "welcome_home": { - "purpose": "Signed-out disconnected home: fixed brand mark, looping desktop phrases, equal login and QR actions.", - "anatomy": ["wordmark_header", "fixed_brand_mark", "sliding_phrase", "dark_action_dock", "login", "scan", "optional_bundled_miniapps"], - "states": ["signed_out", "reduce_motion", "compact", "wide"], - "tokens": ["welcome_max_width", "welcome_gutter", "welcome_header_height", "welcome_button_height", "welcome_button_gap", "welcome_dock_radius", "welcome_dock_bottom", "welcome_mark_size", "welcome_word_size", "welcome_stage_height", "welcome_header_word_size", "welcome_dock", "welcome_button", "welcome_button_label", "welcome_secondary", "brand_dot"], - "platformNotes": "A layout with C staggered slide motion. Mark never animates. Per-glyph entry: 180ms + index*55ms, 800ms cubic ease-out, 38px slide with 5px settling overshoot. Exit is 650ms, 30px left. Respect reduced motion and stop work offscreen. Retain real account/scan routing; only show MiniApps on hosts that implement them. Safe-area insets remain native." - }, - "startup_brand_reveal": { - "purpose": "Provides a desktop-inspired identity transition on the first normal launch of an installation without waiting for network or account loading.", - "anatomy": ["theme_background", "bouncing_brand_dot", "staggered_wordmark", "desktop_contour_brand_mark"], - "states": ["first_launch", "already_shown", "reduced_motion", "backgrounded"], - "tokens": ["page_bg", "ink", "brand_dot", "startup_brand"], - "platformNotes": "Native first-launch-only overlay on HarmonyOS, Android and iOS. Claim a persisted installation-local flag before playback; account changes, process restarts and upgrades do not reset it. Design previews do not consume it. Existing installs without the flag show it once after upgrade; 6800ms timeline independent of network readiness. A cyan dot hops ahead of ten 42-unit letters with subtle letter bounce. At normalized text time 0.70–0.86 it arcs back to the dotless i, settling at 7.35 units diameter with one fading halo. Text time is min(progress / 0.65 * 0.9, 0.9). Logo expands from 0.65 to 1 with a small overshoot during progress 0.66–0.85 as the word moves down 42 units. Use a centered 280×240 stage, scaled down for narrow windows, 92-unit contour mark on Android/iOS and a 156vp mark on HarmonyOS, with platform-native soft sans typography. HarmonyOS positions the mark at (62, -34) to preserve separation from the settled wordmark. Fade the overlay over the last 3%. Reserve full glyph slots; no layout changes during reveal. Remove on completion or background and do not replay on activity recreation/foreground. Skip for reduced motion. Notification onboarding follows completion. The dedicated brand_dot token preserves identity independently of action/status colors." - }, - "cold_start_home_transition": { - "purpose": "Covers a normal authenticated process launch while the measured home brand mark moves into its final position and the page fades in.", - "anatomy": ["home_surface", "moving_contour_brand_mark", "measured_home_mark_anchor", "page_fade"], - "states": ["authenticated_process_launch", "signed_out", "background_resume", "reduce_motion", "compact", "wide"], - "tokens": ["page_bg", "recent_home_mark_size", "cold_start_home"], - "platformNotes": "Only the first authenticated restore in a new process may claim this presentation. The existing installation-local startup_brand_reveal takes precedence and remains unchanged. The home shell mounts underneath; no network request gates the 2400ms timeline. Start the mark at 56 logical units, measure the rendered home mark in the native layout, and interpolate to that measured rect so compact, wide, safe-area, and foldable layouts share the same endpoint. Move through the measured target during 16%–68% of the timeline, then fade the cover from 68%–100%. Signed-out restore, later manual login, foreground resume, activity recreation, and a second scene root do not replay it. Reduced motion completes immediately. If the target is unavailable, keep the mark centered and fade the cover without inventing an endpoint. Hide the underlying shell from accessibility while the cover is active; preserve pointer blocking until completion." - }, - "permission_request_panel": { - "purpose": "Answers an independent runtime permission request below the conversation header, outside the transcript, matching mobile-web.", - "anatomy": [ - "warning_glyph_and_action", - "optional_source_identity", - "neutral_resource_preview", - "collapsed_input_editor", - "trailing_reject_and_allow_actions" - ], - "states": [ - "pending", - "editing", - "busy", - "failed" - ], - "tokens": [ - "approval_card_radius", - "approval_card_padding", - "approval_card_gap", - "approval_action_radius", - "approval_action_height", - "status_warning", - "card", - "soft", - "line", - "primary_action", - "content_on_action" - ], - "platformNotes": "Reference: desktop ChatInputApprovalBand and @openbitfun/ui raised Card, neutral resource Card, fill reject Button and primary allow Button. Preserve desktop 12-unit card radius/padding and 8-unit gaps, with 36-unit mobile actions. Resource content scrolls within the band; actions do not stretch across the card. JSON editing remains a quiet, collapsed mobile-web capability. status_warning ports desktop amber.550 for the short shield glyph: neither success/danger nor the blue file-link accent communicates pending approval." - }, - "message_queue": { - "purpose": "Manage the execution host’s pending messages without leaving the composer.", - "anatomy": [ - "count_disclosure", - "drag_handle", - "preview_and_attachments", - "send_now", - "actions_menu", - "inset_separator" - ], - "states": [ - "queued", - "blocked", - "steering_pending", - "reordering", - "offline", - "legacy_host" - ], - "tokens": [ - "content_gutter", - "control_touch_size", - "ink", - "muted", - "line" - ], - "platformNotes": "No enclosing border. Each 48pt row starts with a hairline inset by 8pt on both sides. The last row has no bottom separator and touches the composer without an extra gap. Attachments follow text. Native drag handles and accessible Move up/Move down actions commit through the host queue revision; incoming host changes cancel the gesture. Never present a local-only order as execution order." - } - } -} diff --git a/src/apps/mobile/design-system/preview/generated/mobile-design-data.js b/src/apps/mobile/design-system/preview/generated/mobile-design-data.js deleted file mode 100644 index 807e3c77a3..0000000000 --- a/src/apps/mobile/design-system/preview/generated/mobile-design-data.js +++ /dev/null @@ -1,1526 +0,0 @@ -// Generated by scripts/mobile-ui-design-system.mjs. Do not edit. -export const mobileTokens = { - "version": 1, - "identity": { - "name": "OpenBitFun Mobile", - "signature": "Paper-and-ink conversation chrome with a single blue information accent" - }, - "colors": { - "start_window_background": { - "light": "#FFFFFF", - "dark": "#000000" - }, - "transparent": { - "light": "#00000000", - "dark": "#00000000" - }, - "page_bg": { - "light": "#FFFFFF", - "dark": "#151514" - }, - "welcome_page_bg": { - "light": "#FFFFFF", - "dark": "#252522" - }, - "page_bg_fade": { - "light": "#00FFFFFF", - "dark": "#00151514" - }, - "page_bg_overlay": { - "light": "#B8FFFFFF", - "dark": "#B8151514" - }, - "ink": { - "light": "#171717", - "dark": "#F4F3EF" - }, - "muted": { - "light": "#706F6A", - "dark": "#AAA8A0" - }, - "subtle": { - "light": "#A5A39B", - "dark": "#77756E" - }, - "line": { - "light": "#E9E7E2", - "dark": "#363531" - }, - "card": { - "light": "#FFFFFF", - "dark": "#252522" - }, - "card_overlay": { - "light": "#CCFFFFFF", - "dark": "#CC252522" - }, - "accent": { - "light": "#111111", - "dark": "#5B5954" - }, - "file_link": { - "light": "#2563EB", - "dark": "#60A5FA" - }, - "primary_action": { - "light": "#111111", - "dark": "#454540" - }, - "content_on_action": { - "light": "#FFFFFF", - "dark": "#FFFFFF" - }, - "connect_hero_bg": { - "light": "#E6EDFF", - "dark": "#2B2B29" - }, - "connect_hero_accent": { - "light": "#9DB4FF", - "dark": "#4A4944" - }, - "connect_hero_secondary": { - "light": "#C9C5FF", - "dark": "#3C3B38" - }, - "connect_hero_surface": { - "light": "#F8FAFF", - "dark": "#252522" - }, - "connect_scan_accent": { - "light": "#FFD021", - "dark": "#FFD021" - }, - "scrim": { - "light": "#44000000", - "dark": "#44000000" - }, - "shell_scrim": { - "light": "#24000000", - "dark": "#24000000" - }, - "media_background": { - "light": "#FF000000", - "dark": "#FF000000" - }, - "media_scrim": { - "light": "#B8000000", - "dark": "#B8000000" - }, - "media_control_background": { - "light": "#8C000000", - "dark": "#8C000000" - }, - "toast_background": { - "light": "#D1171717", - "dark": "#D1171717" - }, - "shadow_faint": { - "light": "#08000000", - "dark": "#08000000" - }, - "shadow_subtle": { - "light": "#12000000", - "dark": "#12000000" - }, - "shadow_medium": { - "light": "#18000000", - "dark": "#18000000" - }, - "shadow_strong": { - "light": "#24000000", - "dark": "#24000000" - }, - "floating_border": { - "light": "#18000000", - "dark": "#18000000" - }, - "soft": { - "light": "#F4F3F0", - "dark": "#2D2C28" - }, - "floating_panel_bg": { - "light": "#F7F7F5", - "dark": "#1E1E1C" - }, - "sidebar_bg": { - "light": "#F8F8F9", - "dark": "#0E0E10" - }, - "sidebar_bg_fade": { - "light": "#00F8F8F9", - "dark": "#000E0E10" - }, - "sidebar_raised": { - "light": "#FFFFFF", - "dark": "#1C1C1F" - }, - "sidebar_line": { - "light": "#14101A27", - "dark": "#1FFFFFFF" - }, - "sidebar_hover": { - "light": "#F3F3F5", - "dark": "#0FFFFFFF" - }, - "sidebar_selection": { - "light": "#14000000", - "dark": "#1FFFFFFF" - }, - "sidebar_ink": { - "light": "#CC000000", - "dark": "#E8E8E8" - }, - "sidebar_muted": { - "light": "#99000000", - "dark": "#B0B0B0" - }, - "sidebar_subtle": { - "light": "#66000000", - "dark": "#858585" - }, - "status_success": { - "light": "#27C46A", - "dark": "#3BD47B" - }, - "status_danger": { - "light": "#E04F4F", - "dark": "#FF6B6B" - }, - "code_line_number": { - "light": "#AAA69D", - "dark": "#77756E" - }, - "code_keyword": { - "light": "#8F3F71", - "dark": "#D99AC4" - }, - "code_string": { - "light": "#477A4A", - "dark": "#9BCB9D" - }, - "code_number": { - "light": "#9A5B13", - "dark": "#E3B36D" - }, - "code_comment": { - "light": "#7A8078", - "dark": "#96958D" - }, - "code_function": { - "light": "#2C6693", - "dark": "#8CBCE0" - }, - "code_type": { - "light": "#865A20", - "dark": "#D5B27F" - }, - "code_constant": { - "light": "#A04444", - "dark": "#E79A9A" - }, - "code_property": { - "light": "#466D78", - "dark": "#9CC8D0" - }, - "code_target_bg": { - "light": "#FFF1BE", - "dark": "#5A4E24" - }, - "brand_dot": { - "light": "#16B9CE", - "dark": "#16B9CE" - }, - "welcome_dock": { - "light": "#171917", - "dark": "#000000" - }, - "welcome_button": { - "light": "#FFFFFF", - "dark": "#FFFFFF" - }, - "welcome_button_label": { - "light": "#171917", - "dark": "#171917" - }, - "welcome_secondary": { - "light": "#B9BCB9", - "dark": "#B9BCB9" - }, - "status_warning": { - "light": "#FF8C00", - "dark": "#FF8C00" - } - }, - "typography": { - "display_large": { - "size": 24, - "lineHeight": 30, - "weight": 700 - }, - "display_medium": { - "size": 22, - "lineHeight": 28, - "weight": 700 - }, - "display_small": { - "size": 20, - "lineHeight": 26, - "weight": 700 - }, - "headline_large": { - "size": 22, - "lineHeight": 28, - "weight": 700 - }, - "headline_medium": { - "size": 20, - "lineHeight": 26, - "weight": 700 - }, - "headline_small": { - "size": 18, - "lineHeight": 24, - "weight": 700 - }, - "title_large": { - "size": 20, - "lineHeight": 26, - "weight": 700 - }, - "conversation_header_title": { - "size": 17, - "lineHeight": 22, - "weight": 600 - }, - "title_medium": { - "size": 17, - "lineHeight": 22, - "weight": 500 - }, - "title_small": { - "size": 15, - "lineHeight": 20, - "weight": 500 - }, - "body_large": { - "size": 16, - "lineHeight": 24, - "weight": 400 - }, - "body_medium": { - "size": 14, - "lineHeight": 21, - "weight": 400 - }, - "body_small": { - "size": 13, - "lineHeight": 19, - "weight": 400 - }, - "label_large": { - "size": 15, - "lineHeight": 20, - "weight": 500 - }, - "label_medium": { - "size": 14, - "lineHeight": 18, - "weight": 500 - }, - "label_small": { - "size": 12, - "lineHeight": 16, - "weight": 400 - }, - "brand_wordmark": { - "size": 42, - "lineHeight": 56, - "weight": 500 - } - }, - "text_scale": { - "reference_logical_dpi": 153.3, - "min_factor": 0.85, - "max_factor": 1 - }, - "geometry": { - "conversation_header_height": 76, - "conversation_header_compact_height": 64, - "control_touch_size": 48, - "content_gutter": 16, - "connection_strip_height": 48, - "timeline_top_padding": 22, - "conversation_overlay_side_inset": 16, - "conversation_edge_fade_height": 28, - "message_spacing": 18, - "message_bubble_max_width": 276, - "message_bubble_horizontal_padding": 14, - "message_bubble_vertical_padding": 11, - "message_bubble_radius": 17, - "composer_action_size": 48, - "composer_input_height": 44, - "composer_expanded_input_height": 58, - "composer_collapsed_height": 56, - "composer_expanded_input_row_height": 60, - "composer_expanded_action_row_height": 48, - "composer_expanded_height": 120, - "composer_collapsed_radius": 28, - "composer_expanded_radius": 18, - "composer_model_selector_width": 330, - "composer_model_selector_radius": 14, - "composer_model_selector_row_height": 48, - "composer_model_selector_row_radius": 9, - "composer_model_selector_row_gap": 6, - "sheet_top_radius": 28, - "login_sheet_max_width": 560, - "login_sheet_outer_margin": 8, - "login_sheet_body_min_height": 142, - "sheet_side_radius": 28, - "sheet_horizontal_padding": 20, - "sheet_header_height": 56, - "sheet_action_height": 48, - "selection_top_radius": 20, - "selection_row_height": 64, - "selection_close_size": 48, - "popover_width": 292, - "popover_radius": 16, - "popover_padding": 12, - "popover_vertical_padding": 10, - "popover_action_height": 48, - "popover_shadow_radius": 18, - "compact_popover_width": 150, - "compact_popover_radius": 14, - "compact_popover_action_height": 42, - "settings_compact_card_radius": 12, - "settings_card_radius": 16, - "settings_prominent_card_radius": 20, - "model_current_row_height": 64, - "model_source_row_height": 62, - "model_account_row_height": 56, - "model_account_row_gap": 6, - "model_section_gap": 20, - "model_overview_top_padding": 16, - "model_overview_bottom_padding": 24, - "model_list_top_padding": 10, - "model_list_bottom_padding": 16, - "model_empty_account_height": 80, - "model_editor_height": 560, - "welcome_max_width": 520, - "welcome_gutter": 25, - "welcome_header_height": 58, - "welcome_button_height": 49, - "welcome_button_gap": 11, - "welcome_dock_radius": 30, - "welcome_dock_bottom": 39, - "welcome_mark_size": 92, - "welcome_word_size": 34, - "welcome_stage_height": 220, - "welcome_header_word_size": 17, - "recent_home_gutter": 24, - "recent_home_mark_size": 132, - "recent_home_title_size": 25, - "recent_home_max_width": 560, - "recent_home_row_padding": 18, - "approval_card_radius": 12, - "approval_card_padding": 12, - "approval_card_gap": 8, - "approval_action_radius": 8, - "approval_action_height": 36 - }, - "breakpoints": { - "wide": 600, - "extra_wide": 840, - "xl": 1440 - }, - "motion": { - "quick": 180, - "structure": 220, - "startup_brand": 6800, - "cold_start_home": 2400 - } -}; -export const mobileComponents = { - "version": 1, - "components": { - "shell_header_alignment": { - "purpose": "Keep sidebar search and conversation menu controls on one horizontal centerline.", - "anatomy": [ - "sidebar_header", - "conversation_header" - ], - "states": [ - "drawer_open", - "drawer_closed", - "wide", - "with_subtitle", - "without_subtitle" - ], - "tokens": [ - "conversation_header_height" - ], - "platformNotes": "Both signed-in header rows use conversationHeaderHeight from the same safe-area origin, without a sidebar-only top inset. Preserve this height when a subtitle appears or disappears. Anchor drawer content scaling vertically at half the header height so reveal animation cannot shift its control centerline." - }, - "sidebar_chrome": { - "purpose": "Give the workspace sidebar the desktop client's structural chrome instead of the conversation page surface.", - "anatomy": [ - "chrome_surface", - "header_row", - "scroll_fade", - "raised_control", - "hairline" - ], - "states": [ - "light", - "dark", - "signed_out", - "signed_in" - ], - "tokens": [ - "sidebar_bg", - "sidebar_bg_fade", - "sidebar_raised", - "sidebar_line", - "sidebar_hover", - "sidebar_selection", - "sidebar_ink", - "sidebar_muted", - "sidebar_subtle" - ], - "platformNotes": "The family mirrors the desktop semantic theme one role at a time: sidebar_bg is surface.chrome, sidebar_raised is surface.raised, sidebar_line is border.subtle, sidebar_hover is action.quiet.hover, sidebar_selection is selection.surface, and sidebar_ink / sidebar_muted / sidebar_subtle are content.primary / content.secondary / content.caption. The sidebar therefore sits one step away from the conversation surface in both appearance modes, as the desktop navigation panel does beside the scene. Alpha roles composite over sidebar_bg and must not be flattened into opaque literals. Conversation, sheet and action surfaces keep the paper-and-ink page tokens; only sidebar chrome uses this family." - }, - "sidebar_device_selector": { - "purpose": "Select one remote device and show its workspace panel below the device list, matching mobile web.", - "anatomy": [ - "device_icon", - "device_name", - "connection_indicator", - "selected_workspace_panel" - ], - "states": [ - "selected", - "online", - "offline", - "loading" - ], - "tokens": [ - "sidebar_selection", - "sidebar_ink", - "sidebar_muted", - "status_success" - ], - "platformNotes": "Device rows have no disclosure chevron. Re-selecting the current device does not collapse its workspaces or restart a healthy connection. Use the sidebar selection surface and normal ink for device identity; only the separate status indicator expresses reachability. Do not add a connection status text row or recovery banner below the device. Automatic reconnect stays quiet; tapping the selected failed or disconnected device retries the connection. Workspace disclosure remains independent and survives refresh and device switching. Compact and wide layouts use the same selection semantics." - }, - "sidebar_tools_footer": { - "purpose": "Open controlled-device tools without creating a chat; keep settings separately reachable.", - "anatomy": [ - "tools_icon_and_label", - "flexible_gap", - "settings_button" - ], - "states": [ - "enabled", - "disabled", - "pressed" - ], - "tokens": [ - "sidebar_raised", - "sidebar_line", - "sidebar_ink" - ], - "platformNotes": "Use Tools / 工具 for both the sidebar entry and destination title. Render a native wrench-and-screwdriver symbol (or the existing platform vector) in a 24-unit slot, 8-unit label gap, 15-unit medium text, 14-unit horizontal padding and a minimum 104 by 48 pill. Keep the 48-unit settings action separate. Use a quiet surface and outline without raised shadows. Compact and wide sidebars reuse a pure footer component with state and callbacks; create-session validation must not affect tools appearance." - }, - "circle_control": { - "purpose": "A compact navigation or overflow control with a full-size touch target.", - "anatomy": [ - "touch_target", - "centered_glyph", - "optional_pressed_surface" - ], - "states": [ - "enabled", - "pressed", - "disabled", - "focused" - ], - "tokens": [ - "control_touch_size", - "card", - "line", - "ink" - ], - "platformNotes": "Keep the glyph's optical box separate from the touch target. Header and sidebar controls stay visually transparent at rest; reserve borders and elevation for the containing surface." - }, - "interaction_question": { - "purpose": "Answer a runtime mailbox question independently of transcript tool state.", - "anatomy": [ - "question_heading", - "choice_or_text_input", - "submit_action", - "failure_feedback" - ], - "states": [ - "pending", - "editing", - "submitting", - "failed" - ], - "tokens": [ - "content_gutter", - "body_medium", - "body_small", - "ink", - "muted", - "card", - "primary_action", - "content_on_action" - ], - "platformNotes": "Render a direct question form in the scrollable mailbox. Tool execution headers, result expansion and stop actions stay in the transcript or composer. Retain draft values through submission failure and queue reordering; remove the form only when authoritative mailbox state removes it." - }, - "runtime_file_browser": { - "purpose": "Browse and manage files on the selected controlled runtime without changing the active chat workspace.", - "anatomy": [ - "runtime_location", - "path_caption", - "single_row_navigation_sort_create_toolbar", - "scrolling_file_rows", - "row_overflow", - "contextual_transfer_feedback", - "on_demand_action_sheet" - ], - "states": [ - "loading", - "ready", - "empty", - "failed", - "action_draft", - "action_busy", - "action_failed", - "editor" - ], - "tokens": [ - "control_touch_size", - "content_gutter", - "body_medium", - "body_small", - "ink", - "muted", - "line", - "card", - "primary_action", - "content_on_action" - ], - "platformNotes": "Parent, refresh, sort and create share one toolbar row. Rows show file or folder glyphs and an overflow menu; mutation forms are not permanently visible. Compact forms use a bottom sheet with submit and cancel reachable while the native keyboard is open. Preserve failed drafts and route every action to the captured runtime provider. Native adapters own keyboard avoidance and file pickers." - }, - "action_button": { - "purpose": "Expresses one primary, secondary, quiet, or destructive workflow action with consistent emphasis.", - "anatomy": [ - "touch_target", - "action_label", - "semantic_surface", - "optional_hairline_border" - ], - "states": [ - "primary", - "secondary", - "quiet", - "destructive", - "disabled", - "busy" - ], - "tokens": [ - "sheet_action_height", - "primary_action", - "content_on_action", - "card", - "soft", - "line", - "status_danger", - "label_large" - ], - "platformNotes": "The semantic style is shared; a workflow may override height when its context requires a larger target, while preserving typography, radius, color, and disabled treatment." - }, - "conversation_header": { - "purpose": "Identifies the active conversation and the device or workspace answering it.", - "anatomy": [ - "leading_control", - "title", - "context_subtitle", - "trailing_control" - ], - "states": [ - "single_line", - "with_context", - "renaming", - "actions_open" - ], - "tokens": [ - "conversation_header_height", - "conversation_header_compact_height", - "conversation_header_title", - "content_gutter", - "control_touch_size" - ], - "platformNotes": "Compact and wide layouts preserve the same control geometry and action meaning." - }, - "message_bubble": { - "purpose": "Presents one user or assistant message in the conversation timeline.", - "anatomy": [ - "message_text", - "role_surface", - "hairline_border", - "message_timestamp" - ], - "states": [ - "user", - "assistant" - ], - "tokens": [ - "body_large", - "message_bubble_max_width", - "message_bubble_horizontal_padding", - "message_bubble_vertical_padding", - "message_bubble_radius", - "message_spacing", - "timeline_top_padding" - ], - "platformNotes": "The maximum width is the 276-unit compact HarmonyOS baseline; wide layouts may use a separate responsive policy. Show each available host message time below its content in localized short date/time with muted label-small text, right aligned for users and left aligned for assistants. Omit unavailable or invalid legacy timestamps. Ordinary failed tool calls share the neutral collapsed activity presentation; their actual failure details remain expandable. Questions, approvals and failed replies retain their attention states." - }, - "conversation_overlay": { - "purpose": "Lets the transcript own the whole pane while the header and composer stay reachable above it.", - "anatomy": [ - "top_overlay", - "top_edge_fade", - "timeline", - "bottom_overlay_fade" - ], - "states": [ - "at_rest", - "scrolled", - "composer_expanded", - "mailbox_open", - "keyboard_open" - ], - "tokens": [ - "conversation_overlay_side_inset", - "conversation_edge_fade_height" - ], - "platformNotes": "The timeline fills the pane and scrolls beneath both overlays; its content insets are measured from the live overlay heights rather than fixed, and are applied with each platform's content-inset primitive — Compose contentPadding, SwiftUI safeAreaInset, ArkUI contentStartOffset/contentEndOffset — never with padding, which would shrink the viewport and stop the transcript at the overlay instead of letting it run underneath, because the composer grows with multiline text and attachments and the mailbox appears without warning. The top layer is an opaque band with a short fade carrying it into the transcript; the bottom layer has no strip of its own — its whole background is the fade, because the transcript runs behind the composer and a short strip would leave a line of text crisp beside the pill after it had already faded out higher up. Fades never take touches. Blur is the platform's own: iOS ultraThinMaterial, HarmonyOS backgroundBlurStyle. Compose has no first-party backdrop blur, so Android uses a high-opacity band instead and reads the same at a glance." - }, - "composer_bar": { - "purpose": "Collects the next instruction and exposes one unambiguous primary action.", - "anatomy": [ - "attachment_action", - "text_input", - "model_control", - "primary_action" - ], - "states": [ - "empty", - "draft", - "focused", - "streaming", - "disconnected", - "with_attachments" - ], - "tokens": [ - "composer_action_size", - "composer_collapsed_height", - "composer_expanded_height", - "composer_collapsed_radius", - "composer_expanded_radius" - ], - "platformNotes": "Keyboard, dictation, and attachment pickers remain native adapters. The focused two-row form stays compact and exists to expose message context controls; multiline content and attachments may grow it further. The trailing action is the single filled action for Send, Dictate, or Stop." - }, - "prompt_suggestion": { - "purpose": "Offer the host's next-input suggestion above the remote conversation composer.", - "anatomy": [ - "suggestion_text", - "full_width_touch_target" - ], - "states": [ - "available", - "draft_hidden", - "busy_hidden", - "disconnected_hidden", - "retired" - ], - "tokens": [ - "body_medium", - "muted", - "control_touch_size", - "conversation_overlay_side_inset" - ], - "platformNotes": "Compact and wide layouts use a quiet, leading-aligned button with wrapping text and a minimum 48-unit touch target. Show only for the latest completed turn when the draft is empty and the session is idle and connected. Tapping copies the exact text into the native editor and focuses it without sending. New turns, session changes and host stream gaps retire the hint. Suggestions stay outside persisted transcripts; older hosts need no fallback request." - }, - "composer_model_selector": { - "purpose": "Changes the model for the message being composed without leaving the conversation or creation flow.", - "anatomy": [ - "optional_modal_header", - "selected_mark", - "primary_label", - "supporting_label", - "scrolling_model_rows" - ], - "states": [ - "compact_bottom", - "wide_popover", - "selected", - "empty", - "scrolling" - ], - "tokens": [ - "composer_model_selector_width", - "composer_model_selector_radius", - "composer_model_selector_row_height", - "composer_model_selector_row_radius", - "composer_model_selector_row_gap", - "selection_top_radius", - "selection_close_size", - "floating_panel_bg", - "card", - "soft", - "line", - "ink", - "muted" - ], - "platformNotes": "Compact layouts use a native bottom surface with a closeable header; wide layouts use an arrowless anchored surface without a redundant header. The selected model is first, uses the soft surface and a leading check mark, and all platform-specific provider glyphs and row dividers are omitted." - }, - "adaptive_modal_surface": { - "purpose": "Hosts settings, connection, creation, selection, and detail flows without crossing a physical fold or obscuring more of the workspace than necessary.", - "anatomy": [ - "scrim", - "paper_surface", - "header", - "scroll_content", - "action_rail" - ], - "states": [ - "compact_bottom", - "wide_side", - "fold_operate", - "busy", - "error" - ], - "tokens": [ - "scrim", - "sheet_top_radius", - "sheet_side_radius", - "sheet_horizontal_padding", - "sheet_header_height", - "sheet_action_height", - "card", - "line", - "structure" - ], - "platformNotes": "Use each platform's native modal lifecycle, accessibility focus, and back gesture; placement comes from the shared adaptive policy and visual geometry comes from these tokens." - }, - "account_login_sheet": { - "purpose": "Offers GitHub sign-in in a compact bottom sheet without empty full-screen space.", - "anatomy": [ - "close_header", - "title", - "supporting_copy", - "optional_error", - "primary_action" - ], - "states": [ - "signed_out", - "authorizing", - "error" - ], - "tokens": [ - "sheet_top_radius", - "sheet_horizontal_padding", - "sheet_header_height", - "sheet_action_height", - "display_medium", - "body_medium" - ], - "platformNotes": "Use a bottom-aligned modal paper on compact and wide hosts: width min(available width - 16, 560), 8-unit margins outside system safe areas, 28-unit circular corners, no button or panel shadow. Header 56, top-aligned body at least 142, footer 10 + 48 + 24 give a 280-unit default height. Body grows for localized text, accessibility text and errors; oversized content scrolls. Close glyph uses round-capped 1.5-unit diagonal strokes from (2,2) to (16,16) and (16,2) to (2,16) within an 18-unit box, centered in a 48-unit target. Account profiles retain their separate adaptive settings presentation." - }, - "action_popover": { - "purpose": "Presents a short, anchored set of conversation, session, model, or project actions.", - "anatomy": [ - "section_label", - "action_rows", - "optional_divider", - "anchored_paper_surface" - ], - "states": [ - "open", - "compact_two_action", - "selected", - "destructive", - "disabled" - ], - "tokens": [ - "popover_width", - "popover_radius", - "popover_padding", - "popover_vertical_padding", - "popover_action_height", - "compact_popover_width", - "compact_popover_radius", - "compact_popover_action_height", - "floating_panel_bg", - "line", - "quick" - ], - "platformNotes": "Wide action sets use the standard arrowless anchored paper surface. The project-row Code/Cowork shortcut remains an anchored two-action popover on every size because its trigger already lives inside the session list; it uses the compact popover geometry." - }, - "session_action_surface": { - "purpose": "Presents actions for a session row without stacking confirmation UI.", - "anatomy": [ - "optional_drag_handle", - "session_identity", - "action_rows", - "in_place_confirmation" - ], - "states": [ - "compact_bottom", - "wide_popover", - "confirming_delete", - "busy" - ], - "tokens": [ - "sheet_action_height", - "popover_radius", - "card", - "line", - "soft", - "status_danger" - ], - "platformNotes": "Compact session lists use a transparent native sheet hosting the same 16-unit paper surface that wide lists anchor as a popover; deletion confirmation replaces the action rows in place. This is distinct from the active conversation header's action_popover." - }, - "selection_surface": { - "purpose": "Lets the user choose a language, model, device, workspace, or assistant from one consistent modal pattern.", - "anatomy": [ - "modal_header", - "selection_rows", - "selected_mark", - "optional_supporting_text" - ], - "states": [ - "loading", - "ready", - "selected", - "empty", - "failed" - ], - "tokens": [ - "selection_top_radius", - "selection_row_height", - "selection_close_size", - "sheet_header_height", - "sheet_horizontal_padding", - "card", - "soft", - "line" - ], - "platformNotes": "A compact standalone picker uses one native bottom surface and a wide picker anchors one arrowless paper popover to its trigger. When selection starts inside another modal, it replaces that modal's content rather than stacking another modal or scrim. The picker mechanism may be native, but row height, selected treatment, header chrome, and dismissal affordance stay aligned." - }, - "confirmation_surface": { - "purpose": "Confirms destructive or high-impact actions inside the surface that initiated them.", - "anatomy": [ - "specific_consequence", - "cancel_action", - "destructive_action" - ], - "states": [ - "idle", - "confirming", - "submitting", - "failed" - ], - "tokens": [ - "sheet_action_height", - "status_danger", - "soft", - "line" - ], - "platformNotes": "Prefer an in-place confirmation step over stacking a second modal and a second scrim." - }, - "settings_card": { - "purpose": "Groups related settings into a stable paper card within an adaptive modal surface.", - "anatomy": [ - "section_heading", - "card", - "entry_rows", - "dividers", - "inline_controls" - ], - "states": [ - "navigable", - "editable", - "loading", - "failed", - "disabled" - ], - "tokens": [ - "settings_compact_card_radius", - "settings_card_radius", - "settings_prominent_card_radius", - "card", - "line", - "muted", - "body_medium" - ], - "platformNotes": "A chevron means navigation; controls that mutate in place do not use one." - }, - "session_view_settings_surface": { - "purpose": "Controls how the connected desktop's sessions are grouped, filtered, and annotated without changing remote session data.", - "anatomy": [ - "modal_header", - "grouping_card", - "workspace_filter_card", - "agent_filter_card", - "status_filter_card", - "metadata_card" - ], - "states": [ - "project_grouping", - "time_grouping", - "chat_first", - "filtered", - "metadata_visible" - ], - "tokens": [ - "sheet_header_height", - "settings_compact_card_radius", - "card", - "soft", - "line", - "muted", - "body_medium", - "label_small" - ], - "platformNotes": "Open from the session-list overflow inside the shared adaptive modal. Choices update local view state only; compact, wide, and fold-operate placements use the same cards and never stack native pickers or alerts." - }, - "model_service_surface": { - "purpose": "Manages the active chat model, account-synced choices, and the local provider editor as one replace-in-place settings flow.", - "anatomy": [ - "modal_header", - "current_model_card", - "source_group", - "account_model_rows", - "local_provider_form", - "feedback", - "actions" - ], - "states": [ - "overview", - "account_selection", - "local_editor", - "testing", - "saving", - "failed" - ], - "tokens": [ - "sheet_header_height", - "model_current_row_height", - "model_source_row_height", - "model_account_row_height", - "model_section_gap", - "settings_compact_card_radius", - "card", - "soft", - "line" - ], - "platformNotes": "Overview, account selection, and local editing replace each other inside the existing adaptive modal. Never stack another sheet or system picker; account rows select immediately, while the local row selects a complete configuration and its chevron always opens the editor." - }, - "pairing_surface": { - "purpose": "Guides desktop pairing from preparation through scanning, with a manual-code fallback that stays inside the connect surface.", - "anatomy": [ - "hero_wash", - "back_control", - "desktop_or_scanner_glyph", - "instructions", - "primary_action", - "manual_pairing_overlay", - "conditional_account_credentials", - "status_feedback" - ], - "states": [ - "intro", - "scan", - "manual", - "account_auth", - "connecting", - "failed", - "paired" - ], - "tokens": [ - "connect_hero_bg", - "connect_hero_surface", - "scrim", - "sheet_side_radius", - "primary_action", - "card", - "soft", - "line" - ], - "platformNotes": "Camera capture and permission prompts remain native. The manual form is an in-surface overlay with the shared scrim and 34-unit card, not a second system sheet. Account-protected links add username and password fields in that same card; passwords remain transient view state and are cleared on submit or dismiss." - }, - "remote_create_surface": { - "purpose": "Creates a remote session from one instruction while making the target desktop, workspace, and model explicit.", - "anatomy": [ - "back_control", - "empty_focus_region", - "device_context", - "workspace_context", - "create_composer", - "selection_surface" - ], - "states": [ - "ready", - "selecting_device", - "selecting_workspace", - "selecting_model", - "listening", - "submitting", - "disconnected" - ], - "tokens": [ - "composer_expanded_height", - "composer_expanded_radius", - "selection_row_height", - "popover_width", - "card", - "soft", - "line", - "accent" - ], - "platformNotes": "This is a conversation route, not a form modal: title and agent type are inferred from the first instruction and selected workspace. Compact selectors use one bottom selection surface; wide selectors use the same rows in an arrowless anchored popover." - }, - "remote_control_settings_surface": { - "purpose": "Explains which desktop is being controlled, how it is connected, and which permission policy that desktop applies.", - "anatomy": [ - "modal_header", - "profile_entry", - "current_control_card", - "connection_source", - "alternate_connection_entry", - "permission_mode_card", - "in_place_full_access_confirmation" - ], - "states": [ - "disconnected", - "connecting", - "connected_by_account", - "connected_by_pairing", - "permission_loading", - "permission_failed", - "confirming_full_access", - "account_page" - ], - "tokens": [ - "sheet_header_height", - "settings_prominent_card_radius", - "settings_compact_card_radius", - "scrim", - "card", - "soft", - "line", - "status_danger" - ], - "platformNotes": "The account page replaces this page inside the same adaptive modal. Full-access confirmation replaces content inside the permission card; it never opens a system alert or a second sheet." - }, - "file_preview_surface": { - "purpose": "Shows a remote file as a compact full-page modal or as a wide companion pane.", - "anatomy": [ - "file_header", - "download_action", - "close_action", - "content_viewport", - "truncation_notice" - ], - "states": [ - "loading", - "text", - "markdown", - "image", - "unsupported", - "failed", - "truncated" - ], - "tokens": [ - "sheet_header_height", - "file_link", - "card", - "line", - "soft" - ], - "platformNotes": "Placement is shared policy; rendering, file export, and platform-safe dismissal remain native adapters." - }, - "miniapp_navigation": { - "purpose": "Opens locally bundled tools from primary sidebar navigation, without requiring account or device access.", - "anatomy": [ - "outlined_apps_glyph", - "leading_aligned_label", - "full_row_touch_target" - ], - "states": [ - "idle", - "pressed", - "focused", - "signed_out", - "connected" - ], - "tokens": [ - "ink", - "body_large", - "control_touch_size" - ], - "platformNotes": "Use a quiet 48vp icon-and-label row in compact and wide sidebars, with 16vp medium-weight navigation text, a 24vp icon slot and a 14vp gap. In the sidebar the row keeps 4vp above and 8vp below itself, and the device section header keeps 10vp above it, inside the shared 76vp header frame: the header control sits 20vp above the row and the Devices label 18vp below it. A platform whose header control is not 44vp inherits that difference instead of adding a second gap, and no column-level spacing is layered around the row. HarmonyOS uses the native outlined sys.symbol.square_grid_2x2 at 24vp, centered in its slot and tinted with the semantic ink color. Render the catalog inside the shell content pane so selecting it slides the right pane left as the drawer closes, using the existing 250ms ease-out shell motion. Sidebar session selection uses the same shell motion without a second route-push animation. Do not promote this navigation destination to a primary action on remote home." - }, - "miniapp_catalog": { - "purpose": "Presents bundled apps with large visual previews that open each app directly.", - "anatomy": [ - "back_control", - "centered_page_title", - "offline_caption", - "square_preview", - "app_title" - ], - "states": [ - "catalog", - "loading", - "error", - "app_open", - "light", - "dark" - ], - "tokens": [ - "page_bg", - "ink", - "muted", - "soft", - "body_large", - "title_small", - "body_medium", - "label_small" - ], - "platformNotes": "Use a two-column library of square previews on compact screens and three columns when the gallery reaches 600vp. Clip previews to 24vp corners with 14vp column and 20vp row gaps; keep app names below images. The centered gallery caps at 1000vp, while open apps use full width. Reuse established showcase assets. Resize the grid without reloading an open app." - }, - "welcome_home": { - "purpose": "Signed-out disconnected home: fixed brand mark, looping desktop phrases, equal login and QR actions.", - "anatomy": [ - "wordmark_header", - "fixed_brand_mark", - "sliding_phrase", - "dark_action_dock", - "login", - "scan", - "optional_bundled_miniapps" - ], - "states": [ - "signed_out", - "reduce_motion", - "compact", - "wide" - ], - "tokens": [ - "welcome_max_width", - "welcome_gutter", - "welcome_header_height", - "welcome_button_height", - "welcome_button_gap", - "welcome_dock_radius", - "welcome_dock_bottom", - "welcome_mark_size", - "welcome_word_size", - "welcome_stage_height", - "welcome_header_word_size", - "welcome_dock", - "welcome_button", - "welcome_button_label", - "welcome_secondary", - "brand_dot" - ], - "platformNotes": "A layout with C staggered slide motion. Mark never animates. Per-glyph entry: 180ms + index*55ms, 800ms cubic ease-out, 38px slide with 5px settling overshoot. Exit is 650ms, 30px left. Respect reduced motion and stop work offscreen. Retain real account/scan routing; only show MiniApps on hosts that implement them. Safe-area insets remain native." - }, - "startup_brand_reveal": { - "purpose": "Provides a desktop-inspired identity transition on the first normal launch of an installation without waiting for network or account loading.", - "anatomy": [ - "theme_background", - "bouncing_brand_dot", - "staggered_wordmark", - "desktop_contour_brand_mark" - ], - "states": [ - "first_launch", - "already_shown", - "reduced_motion", - "backgrounded" - ], - "tokens": [ - "page_bg", - "ink", - "brand_dot", - "startup_brand" - ], - "platformNotes": "Native first-launch-only overlay on HarmonyOS, Android and iOS. Claim a persisted installation-local flag before playback; account changes, process restarts and upgrades do not reset it. Design previews do not consume it. Existing installs without the flag show it once after upgrade; 6800ms timeline independent of network readiness. A cyan dot hops ahead of ten 42-unit letters with subtle letter bounce. At normalized text time 0.70–0.86 it arcs back to the dotless i, settling at 7.35 units diameter with one fading halo. Text time is min(progress / 0.65 * 0.9, 0.9). Logo expands from 0.65 to 1 with a small overshoot during progress 0.66–0.85 as the word moves down 42 units. Use a centered 280×240 stage, scaled down for narrow windows, 92-unit contour mark on Android/iOS and a 156vp mark on HarmonyOS, with platform-native soft sans typography. HarmonyOS positions the mark at (62, -34) to preserve separation from the settled wordmark. Fade the overlay over the last 3%. Reserve full glyph slots; no layout changes during reveal. Remove on completion or background and do not replay on activity recreation/foreground. Skip for reduced motion. Notification onboarding follows completion. The dedicated brand_dot token preserves identity independently of action/status colors." - }, - "cold_start_home_transition": { - "purpose": "Covers a normal authenticated process launch while the measured home brand mark moves into its final position and the page fades in.", - "anatomy": [ - "home_surface", - "moving_contour_brand_mark", - "measured_home_mark_anchor", - "page_fade" - ], - "states": [ - "authenticated_process_launch", - "signed_out", - "background_resume", - "reduce_motion", - "compact", - "wide" - ], - "tokens": [ - "page_bg", - "recent_home_mark_size", - "cold_start_home" - ], - "platformNotes": "Only the first authenticated restore in a new process may claim this presentation. The existing installation-local startup_brand_reveal takes precedence and remains unchanged. The home shell mounts underneath; no network request gates the 2400ms timeline. Start the mark at 56 logical units, measure the rendered home mark in the native layout, and interpolate to that measured rect so compact, wide, safe-area, and foldable layouts share the same endpoint. Move through the measured target during 16%–68% of the timeline, then fade the cover from 68%–100%. Signed-out restore, later manual login, foreground resume, activity recreation, and a second scene root do not replay it. Reduced motion completes immediately. If the target is unavailable, keep the mark centered and fade the cover without inventing an endpoint. Hide the underlying shell from accessibility while the cover is active; preserve pointer blocking until completion." - }, - "permission_request_panel": { - "purpose": "Answers an independent runtime permission request below the conversation header, outside the transcript, matching mobile-web.", - "anatomy": [ - "warning_glyph_and_action", - "optional_source_identity", - "neutral_resource_preview", - "collapsed_input_editor", - "trailing_reject_and_allow_actions" - ], - "states": [ - "pending", - "editing", - "busy", - "failed" - ], - "tokens": [ - "approval_card_radius", - "approval_card_padding", - "approval_card_gap", - "approval_action_radius", - "approval_action_height", - "status_warning", - "card", - "soft", - "line", - "primary_action", - "content_on_action" - ], - "platformNotes": "Reference: desktop ChatInputApprovalBand and @openbitfun/ui raised Card, neutral resource Card, fill reject Button and primary allow Button. Preserve desktop 12-unit card radius/padding and 8-unit gaps, with 36-unit mobile actions. Resource content scrolls within the band; actions do not stretch across the card. JSON editing remains a quiet, collapsed mobile-web capability. status_warning ports desktop amber.550 for the short shield glyph: neither success/danger nor the blue file-link accent communicates pending approval." - }, - "message_queue": { - "purpose": "Manage the execution host’s pending messages without leaving the composer.", - "anatomy": [ - "count_disclosure", - "drag_handle", - "preview_and_attachments", - "send_now", - "actions_menu", - "inset_separator" - ], - "states": [ - "queued", - "blocked", - "steering_pending", - "reordering", - "offline", - "legacy_host" - ], - "tokens": [ - "content_gutter", - "control_touch_size", - "ink", - "muted", - "line" - ], - "platformNotes": "No enclosing border. Each 48pt row starts with a hairline inset by 8pt on both sides. The last row has no bottom separator and touches the composer without an extra gap. Attachments follow text. Native drag handles and accessible Move up/Move down actions commit through the host queue revision; incoming host changes cancel the gesture. Never present a local-only order as execution order." - } - } -}; -export const mobilePreviewScenarios = { - "version": 1, - "scenarios": [ - { - "id": "connected-conversation", - "title": "Connected conversation", - "description": "A remote desktop is answering and the composer is ready.", - "appearance": "light", - "viewport": { - "width": 390, - "height": 844 - }, - "header": { - "title": "统一移动端设计系统", - "subtitle": "DESKTOP-KM3L4UI" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "可以。共享视觉契约,三端继续使用原生渲染。" - } - ], - "composer": { - "draft": "", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - }, - { - "id": "streaming-dark", - "title": "Streaming in dark mode", - "description": "An active turn exercises dark surfaces and the stop action.", - "appearance": "dark", - "viewport": { - "width": 390, - "height": 844 - }, - "header": { - "title": "跨端视觉校验", - "subtitle": "正在由 MacBook Pro 运行" - }, - "messages": [ - { - "role": "user", - "text": "比较三端的输入框、消息气泡和标题栏。" - }, - { - "role": "assistant", - "text": "正在生成原生截图,并按相同基线并排展示。" - } - ], - "composer": { - "draft": "检查深色模式下的边框对比度", - "placeholder": "输入消息", - "phase": "connected", - "streaming": true - } - }, - { - "id": "reconnecting-wide", - "title": "Reconnecting on a wide viewport", - "description": "A tablet-sized viewport keeps remote blocking states answerable.", - "appearance": "light", - "viewport": { - "width": 1024, - "height": 768 - }, - "header": { - "title": "远程会话", - "subtitle": "正在恢复连接" - }, - "messages": [ - { - "role": "assistant", - "text": "连接暂时中断。恢复后会从上次游标继续。" - } - ], - "composer": { - "draft": "", - "placeholder": "等待重新连接", - "phase": "reconnecting", - "streaming": false - } - }, - { - "id": "narrow-multiline", - "title": "Narrow phone with a multiline draft", - "description": "Narrow phone with a multiline draft", - "appearance": "light", - "viewport": { - "width": 360, - "height": 800 - }, - "header": { - "title": "检查移动端长标题、正文与控制目标的可读性", - "subtitle": "远程开发工作站 · OpenBitFun / feature/mobile-reading" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "可以。共享视觉契约,三端继续使用原生渲染。" - } - ], - "composer": { - "draft": "请检查输入框是否能保留多行中文草稿。\n模型选择后内容应继续保留。\n附件与文本应各自成行。", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - }, - { - "id": "fold-context", - "title": "Foldable with long remote context", - "description": "Foldable with long remote context", - "appearance": "light", - "viewport": { - "width": 700, - "height": 840 - }, - "header": { - "title": "检查移动端长标题、正文与控制目标的可读性", - "subtitle": "远程开发工作站 · OpenBitFun / feature/mobile-reading" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "可以。共享视觉契约,三端继续使用原生渲染。" - } - ], - "composer": { - "draft": "请保留当前会话与控制目标。", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - }, - { - "id": "long-reading", - "title": "Long reading content", - "description": "Long reading content", - "appearance": "light", - "viewport": { - "width": 430, - "height": 932 - }, - "header": { - "title": "检查移动端长标题、正文与控制目标的可读性", - "subtitle": "远程开发工作站 · OpenBitFun / feature/mobile-reading" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "移动端的阅读层级需要清晰,正文应该舒适地换行,辅助说明保留足够对比度。\n\n当内容变长时,消息区滚动,输入框仍然可以操作。请在系统大字体设置下检查这一场景。" - } - ], - "composer": { - "draft": "", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - } - ] -}; diff --git a/src/apps/mobile/design-system/preview/index.html b/src/apps/mobile/design-system/preview/index.html deleted file mode 100644 index 2c4c7e49fe..0000000000 --- a/src/apps/mobile/design-system/preview/index.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - OpenBitFun Mobile Parity Bench - - - - - -

-
-
-

OPENBITFUN MOBILE · NATIVE PARITY

-

三端视觉校准台

-

HarmonyOS 是基准。Android 与 iOS 使用同一契约、同一场景,各自保持原生渲染。

-
-
HarmonyOS baseline
-
- -
- - - - -
- -
- - -
- -
-
- - - diff --git a/src/apps/mobile/design-system/preview/preview-scenarios.smoke.test.mjs b/src/apps/mobile/design-system/preview/preview-scenarios.smoke.test.mjs deleted file mode 100644 index 97cda051ee..0000000000 --- a/src/apps/mobile/design-system/preview/preview-scenarios.smoke.test.mjs +++ /dev/null @@ -1,66 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; - -import { mobilePreviewScenarios } from './generated/mobile-design-data.js'; - -const expectedScenarioIds = [ - 'connected-conversation', - 'streaming-dark', - 'reconnecting-wide', - 'narrow-multiline', - 'fold-context', - 'long-reading', -]; -const requiredScenarioFields = [ - 'id', - 'title', - 'appearance', - 'header.title', - 'header.subtitle', - 'composer.phase', - 'composer.streaming', -]; -const sensitiveContentPatterns = [ - /akid/i, - /sk-/i, - /-----begin/i, - /password/i, - /secret/i, - /token/i, - /[A-Za-z0-9+/=]{40,}/, -]; - -const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key); - - -test('mobile preview scenarios satisfy the deterministic contract', () => { - const scenarios = mobilePreviewScenarios.scenarios; - - assert.equal(scenarios.length, expectedScenarioIds.length); - assert.deepEqual( - scenarios.map((scenario) => scenario.id), - expectedScenarioIds, - ); - - for (const scenario of scenarios) { - for (const field of requiredScenarioFields) { - const [root, nested] = field.split('.'); - const value = nested === undefined ? scenario : scenario[root]?.[nested]; - assert.ok( - nested === undefined ? hasOwn(scenario, root) : hasOwn(scenario[root], nested), - `scenario ${scenario.id} is missing ${field}`, - ); - assert.notEqual(value, undefined, `scenario ${scenario.id} has undefined ${field}`); - } - - assert.ok(hasOwn(scenario.viewport, 'width')); - assert.ok(hasOwn(scenario.viewport, 'height')); - assert.ok(Array.isArray(scenario.messages)); - assert.ok(scenario.messages.length > 0); - } - - const serializedScenarios = JSON.stringify(mobilePreviewScenarios); - for (const pattern of sensitiveContentPatterns) { - assert.doesNotMatch(serializedScenarios, pattern); - } -}); diff --git a/src/apps/mobile/design-system/preview/preview.css b/src/apps/mobile/design-system/preview/preview.css deleted file mode 100644 index 743ba103a9..0000000000 --- a/src/apps/mobile/design-system/preview/preview.css +++ /dev/null @@ -1,412 +0,0 @@ -:root { - color-scheme: light; - font-family: var(--openbitfun-font-family-sans); - background: var(--openbitfun-color-surface-workbench); - color: var(--openbitfun-color-content-primary); -} - -* { box-sizing: border-box; } - -body { - margin: 0; - min-width: 1040px; - min-height: 100vh; - background: - linear-gradient(transparent 31px, color-mix(in srgb, var(--openbitfun-color-content-primary) 3.5%, transparent) 32px), - var(--openbitfun-color-surface-workbench); - background-size: 100% 32px; -} - -button, input, select { font: inherit; } - -.bench-shell { - max-width: 1640px; - margin: 0 auto; - padding: 38px 34px 54px; -} - -.bench-header { - display: flex; - align-items: flex-end; - justify-content: space-between; - gap: 32px; - padding: 0 4px 28px; -} - -.eyebrow { - margin: 0 0 11px; - color: var(--openbitfun-color-content-muted); - font: 600 11px/1.2 var(--openbitfun-font-family-mono); - letter-spacing: 0.13em; -} - -h1 { - margin: 0; - font-size: clamp(30px, 3vw, 48px); - line-height: 1; - letter-spacing: -0.045em; -} - -.intro { - max-width: 720px; - margin: 13px 0 0; - color: var(--openbitfun-color-content-secondary); - font-size: 14px; - line-height: 1.7; -} - -.baseline-key { - display: flex; - align-items: center; - gap: 9px; - padding: 9px 12px; - border: 1px solid var(--openbitfun-color-border-default); - border-radius: 999px; - background: var(--openbitfun-color-surface-panel); - color: var(--openbitfun-color-content-secondary); - font: 600 11px/1 var(--openbitfun-font-family-mono); -} - -.baseline-key span { - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--openbitfun-color-link-default); - box-shadow: 0 0 0 4px color-mix(in srgb, var(--openbitfun-color-link-default) 13%, transparent); -} - -.toolbar { - display: grid; - grid-template-columns: minmax(230px, 1.5fr) minmax(150px, 0.7fr) minmax(260px, 1fr) auto; - gap: 18px; - align-items: end; - padding: 18px 20px; - border: 1px solid var(--openbitfun-color-border-default); - border-radius: 18px 18px 0 0; - background: color-mix(in srgb, var(--openbitfun-color-surface-panel) 90%, transparent); - backdrop-filter: blur(16px); -} - -.toolbar label:not(.check-control) { - display: grid; - gap: 7px; -} - -.toolbar label > span { - color: var(--openbitfun-color-content-muted); - font: 600 11px/1.2 var(--openbitfun-font-family-mono); - letter-spacing: 0.05em; -} - -select { - width: 100%; - height: 38px; - padding: 0 34px 0 12px; - border: 1px solid var(--openbitfun-color-field-border); - border-radius: 10px; - background: var(--openbitfun-color-field-background); - color: var(--openbitfun-color-content-primary); -} - -.range-control { - grid-template-columns: 1fr auto; -} - -.range-control span { grid-column: 1 / -1; } -.range-control input { width: 100%; accent-color: var(--openbitfun-color-accent-default); } -.range-control output { color: var(--openbitfun-color-content-muted); font: 12px var(--openbitfun-font-family-mono); } - -.check-control { - display: flex; - align-items: center; - gap: 9px; - height: 38px; - white-space: nowrap; -} - -.check-control input { width: 16px; height: 16px; accent-color: var(--openbitfun-color-accent-default); } - -.scenario-note { - display: flex; - gap: 12px; - align-items: baseline; - min-height: 46px; - padding: 14px 20px; - border: 1px solid var(--openbitfun-color-border-default); - border-top: 0; - background: var(--openbitfun-color-surface-panel); - color: var(--openbitfun-color-content-muted); - font-size: 12px; -} - -.scenario-note strong { color: var(--openbitfun-color-content-primary); } - -.platform-grid { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 14px; - padding-top: 14px; -} - -.platform-card { - min-width: 0; - overflow: hidden; - border: 1px solid var(--openbitfun-color-border-default); - border-radius: 20px; - background: var(--openbitfun-color-surface-panel); - box-shadow: var(--openbitfun-shadow-overlay); -} - -.platform-card[data-platform="harmonyos"] { border-top: 3px solid var(--openbitfun-color-link-default); } - -.platform-heading { - display: flex; - align-items: center; - gap: 10px; - min-height: 62px; - padding: 12px 15px; - border-bottom: 1px solid var(--openbitfun-color-border-subtle); -} - -.platform-mark { - display: grid; - place-items: center; - width: 34px; - height: 34px; - border-radius: 10px; - background: var(--openbitfun-color-action-primary-background); - color: var(--openbitfun-color-action-primary-content); - font: 700 12px/1 var(--openbitfun-font-family-mono); -} - -.platform-card[data-platform="harmonyos"] .platform-mark { background: var(--openbitfun-color-link-default); } - -.platform-title { min-width: 0; } -.platform-title strong { display: block; font-size: 13px; } -.platform-title span { display: block; margin-top: 3px; color: var(--openbitfun-color-content-muted); font-size: 10px; } - -.capture-button { - margin-left: auto; - padding: 8px 10px; - border: 1px solid var(--openbitfun-color-border-default); - border-radius: 9px; - background: var(--openbitfun-color-field-background); - color: var(--openbitfun-color-content-secondary); - cursor: pointer; - font-size: 11px; -} - -.capture-button:hover { border-color: var(--openbitfun-color-field-border-hover); } -.capture-button input { display: none; } - -.viewport-stage { - position: relative; - display: grid; - place-items: center; - min-height: 690px; - padding: 22px; - overflow: hidden; - background: var(--openbitfun-color-surface-subtle); -} - -.device-screen { - --screen-scale: 1; - position: relative; - width: min(100%, 390px); - aspect-ratio: var(--viewport-width) / var(--viewport-height); - max-height: 646px; - overflow: hidden; - border: 1px solid color-mix(in srgb, var(--openbitfun-color-content-primary) 25%, transparent); - border-radius: 28px; - background: var(--mobile-page-bg); - color: var(--mobile-ink); - box-shadow: var(--openbitfun-shadow-overlay); - container-type: inline-size; -} - -.device-screen.wide { - width: 100%; - max-height: 500px; - border-radius: 18px; -} - -.platform-card[data-platform="harmonyos"] .device-screen { font-family: "HarmonyOS Sans", system-ui, sans-serif; } -.platform-card[data-platform="android"] .device-screen { font-family: Roboto, system-ui, sans-serif; } -.platform-card[data-platform="ios"] .device-screen { font-family: -apple-system, BlinkMacSystemFont, sans-serif; } - -.contract-render { - position: absolute; - inset: 0; - display: flex; - flex-direction: column; -} - -.screen-meta { - display: flex; - align-items: center; - gap: 6px; - height: calc(var(--mobile-connection-strip-height) * 1px); - padding: 0 calc(var(--mobile-content-gutter) * 1px); - border-bottom: 1px solid var(--mobile-line); - font-size: 11px; -} - -.screen-meta strong { font-size: 12px; } -.screen-meta span { margin-left: auto; color: var(--mobile-muted); font-family: ui-monospace, monospace; font-size: 9px; } - -.conversation-header { - display: grid; - grid-template-columns: calc(var(--mobile-control-touch-size) * 1px) 1fr calc(var(--mobile-control-touch-size) * 1px); - align-items: center; - gap: 8px; - height: calc(var(--mobile-conversation-header-height) * 1px); - padding: 8px calc(var(--mobile-content-gutter) * 1px); -} - -.circle-control { - display: grid; - place-items: center; - width: calc(var(--mobile-control-touch-size) * 1px); - height: calc(var(--mobile-control-touch-size) * 1px); - border: 1px solid var(--mobile-line); - border-radius: 50%; - background: var(--mobile-card); - box-shadow: 0 3px 10px var(--mobile-shadow-medium); - color: var(--mobile-ink); - font-size: 18px; -} - -.header-copy { min-width: 0; text-align: center; } -.header-copy strong, .header-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.header-copy strong { - font-size: calc(var(--mobile-conversation-header-title-size) * 1px); - line-height: calc(var(--mobile-conversation-header-title-line-height) * 1px); - font-weight: var(--mobile-conversation-header-title-weight); -} -.header-copy span { - margin-top: 3px; - color: var(--mobile-muted); - font-size: calc(var(--mobile-label-medium-size) * 1px); - line-height: calc(var(--mobile-label-medium-line-height) * 1px); - font-weight: var(--mobile-label-medium-weight); -} - -.timeline { - flex: 1; - display: flex; - flex-direction: column; - gap: calc(var(--mobile-message-spacing) * 1px); - min-height: 0; - padding: calc(var(--mobile-timeline-top-padding) * 1px) calc(var(--mobile-content-gutter) * 1px); -} - -.message { - max-width: calc(var(--mobile-message-bubble-max-width) * 1px); - padding: - calc(var(--mobile-message-bubble-vertical-padding) * 1px) - calc(var(--mobile-message-bubble-horizontal-padding) * 1px); - border: 1px solid var(--mobile-line); - border-radius: calc(var(--mobile-message-bubble-radius) * 1px); - background: var(--mobile-card); - font-size: calc(var(--mobile-body-medium-size) * 1px); - line-height: calc(var(--mobile-body-medium-line-height) * 1px); - font-weight: var(--mobile-body-medium-weight); -} - -.message.user { align-self: flex-end; background: var(--mobile-soft); } - -.connection-note { - align-self: center; - padding: 5px 9px; - border-radius: 999px; - background: var(--mobile-soft); - color: var(--mobile-muted); - font: 10px/1.2 ui-monospace, monospace; -} - -.composer-zone { padding: 8px calc(var(--mobile-content-gutter) * 1px) 14px; } - -.composer { - display: grid; - grid-template-columns: calc(var(--mobile-composer-action-size) * 1px) 1fr calc(var(--mobile-composer-action-size) * 1px); - align-items: center; - gap: 5px; - min-height: calc(var(--mobile-composer-collapsed-height) * 1px); - padding: 0 8px; - border: 0; - border-radius: calc(var(--mobile-composer-collapsed-radius) * 1px); - background: var(--mobile-card); - box-shadow: 0 2px 10px var(--mobile-shadow-medium); -} - -.composer.has-draft { min-height: 76px; border-radius: calc(var(--mobile-composer-expanded-radius) * 1px); } -.composer button { width: 40px; height: 40px; border: 0; background: transparent; color: var(--mobile-ink); font-size: 19px; } -.composer-copy { - min-width: 0; - color: var(--mobile-muted); - font-size: calc(var(--mobile-body-large-size) * 1px); - line-height: calc(var(--mobile-body-large-line-height) * 1px); - font-weight: var(--mobile-body-large-weight); -} -.composer.has-draft .composer-copy { color: var(--mobile-ink); } -.composer .primary { border-radius: 50%; background: var(--mobile-primary-action); color: var(--mobile-content-on-action); } - -.native-shot { - position: absolute; - inset: 0; - z-index: 3; - display: none; - width: 100%; - height: 100%; - object-fit: contain; - background: var(--mobile-media-background); - opacity: var(--native-opacity); -} - -.device-screen.has-native .native-shot { display: block; } - -.alignment-grid { - pointer-events: none; - position: absolute; - inset: 0; - z-index: 5; - display: none; - background-image: - linear-gradient(color-mix(in srgb, var(--openbitfun-color-link-default) 20%, transparent) 1px, transparent 1px), - linear-gradient(90deg, color-mix(in srgb, var(--openbitfun-color-link-default) 14%, transparent) 1px, transparent 1px); - background-size: 8px 8px; -} - -.show-grid .alignment-grid { display: block; } - -.capture-status { - display: grid; - grid-template-columns: auto 1fr; - gap: 12px; - padding: 10px 15px; - border-top: 1px solid var(--openbitfun-color-border-subtle); - color: var(--openbitfun-color-content-muted); - font: 10px/1.4 var(--openbitfun-font-family-mono); -} - -.capture-status strong { color: var(--openbitfun-color-content-secondary); } -.capture-status span { text-align: right; } -.capture-status em { - grid-column: 1 / -1; - color: var(--openbitfun-color-content-muted); - font-style: normal; - text-align: right; -} -.capture-aspect-warning .capture-status strong { color: var(--openbitfun-color-status-warning-content); } - -@media (max-width: 1180px) { - .bench-shell { padding-inline: 20px; } - .viewport-stage { min-height: 620px; padding-inline: 12px; } -} - -@media (prefers-reduced-motion: no-preference) { - .platform-card { animation: settle 360ms ease-out both; } - .platform-card:nth-child(2) { animation-delay: 45ms; } - .platform-card:nth-child(3) { animation-delay: 90ms; } - @keyframes settle { from { opacity: 0; transform: translateY(8px); } } -} diff --git a/src/apps/mobile/design-system/preview/preview.js b/src/apps/mobile/design-system/preview/preview.js deleted file mode 100644 index f9d4e4002f..0000000000 --- a/src/apps/mobile/design-system/preview/preview.js +++ /dev/null @@ -1,220 +0,0 @@ -import { mobilePreviewScenarios, mobileTokens } from './generated/mobile-design-data.js'; - -const platforms = [ - { id: 'harmonyos', captureId: 'harmony', name: 'HarmonyOS', mark: 'H', note: 'ArkUI · baseline' }, - { id: 'android', name: 'Android', mark: 'A', note: 'Jetpack Compose' }, - { id: 'ios', name: 'iOS', mark: 'i', note: 'SwiftUI' }, -]; - -const scenarioSelect = document.querySelector('#scenario-select'); -const appearanceSelect = document.querySelector('#appearance-select'); -const opacityControl = document.querySelector('#opacity-control'); -const opacityOutput = document.querySelector('#opacity-output'); -const gridControl = document.querySelector('#grid-control'); -const platformGrid = document.querySelector('#platform-grid'); -const nativeCaptures = new Map(); - -for (const scenario of mobilePreviewScenarios.scenarios) { - const option = document.createElement('option'); - option.value = scenario.id; - option.textContent = scenario.title; - scenarioSelect.append(option); -} - -scenarioSelect.addEventListener('change', render); -appearanceSelect.addEventListener('change', render); -gridControl.addEventListener('change', () => { - platformGrid.classList.toggle('show-grid', gridControl.checked); -}); -opacityControl.addEventListener('input', () => { - const opacity = Number(opacityControl.value) / 100; - opacityOutput.textContent = `${opacityControl.value}%`; - document.documentElement.style.setProperty('--native-opacity', String(opacity)); -}); - -render(); - -function render() { - nativeCaptures.clear(); - const scenario = mobilePreviewScenarios.scenarios.find((item) => item.id === scenarioSelect.value) - ?? mobilePreviewScenarios.scenarios[0]; - const appearance = appearanceSelect.value === 'scenario' ? scenario.appearance : appearanceSelect.value; - document.querySelector('#scenario-title').textContent = scenario.title; - document.querySelector('#scenario-description').textContent = scenario.description; - platformGrid.replaceChildren(...platforms.map((platform) => platformCard(platform, scenario, appearance))); - platformGrid.classList.toggle('show-grid', gridControl.checked); -} - -function platformCard(platform, scenario, appearance) { - const card = document.createElement('article'); - card.className = 'platform-card'; - card.dataset.platform = platform.id; - card.innerHTML = ` -
- -
- -
-
-
-
-
-
-
☰
-
-
•••
-
-
-
-
- -
- -
-
-
- -
-
-
-
CONTRACT RENDER等待原生截图
- `; - - card.querySelector('.platform-title strong').textContent = platform.name; - card.querySelector('.platform-title span').textContent = platform.note; - - const screen = card.querySelector('.device-screen'); - applyTokens(screen, appearance); - screen.style.setProperty('--viewport-width', String(scenario.viewport.width)); - screen.style.setProperty('--viewport-height', String(scenario.viewport.height)); - screen.classList.toggle('wide', scenario.viewport.width >= mobileTokens.breakpoints.wide); - - card.querySelector('.screen-meta strong').textContent = platform.name; - card.querySelector('.screen-meta span').textContent = `${scenario.viewport.width} × ${scenario.viewport.height}`; - card.querySelector('.header-copy strong').textContent = scenario.header.title; - card.querySelector('.header-copy span').textContent = scenario.header.subtitle; - - const timeline = card.querySelector('.timeline'); - for (const message of scenario.messages) { - const bubble = document.createElement('div'); - bubble.className = `message ${message.role}`; - bubble.textContent = message.text; - timeline.append(bubble); - } - if (scenario.composer.phase === 'reconnecting') { - const note = document.createElement('div'); - note.className = 'connection-note'; - note.textContent = 'RECONNECTING · CURSOR PRESERVED'; - timeline.append(note); - } - - const composer = card.querySelector('.composer'); - const hasDraft = scenario.composer.draft.length > 0; - composer.classList.toggle('has-draft', hasDraft); - card.querySelector('.composer-copy').textContent = scenario.composer.draft || scenario.composer.placeholder; - card.querySelector('.composer .primary').textContent = scenario.composer.streaming ? '■' : hasDraft ? '↑' : '●'; - - const fileInput = card.querySelector('input[type="file"]'); - fileInput.addEventListener('change', () => { - const [file] = fileInput.files; - if (file) useNativeShot(card, URL.createObjectURL(file), file.name); - }); - tryConventionalScreenshot(card, platform.captureId ?? platform.id, scenario.id); - return card; -} - -function applyTokens(element, appearance) { - for (const [name, pair] of Object.entries(mobileTokens.colors)) { - element.style.setProperty(`--mobile-${name.replaceAll('_', '-')}`, mobileColorToCss(pair[appearance])); - } - for (const [name, value] of Object.entries(mobileTokens.geometry)) { - element.style.setProperty(`--mobile-${name.replaceAll('_', '-')}`, String(value)); - } - for (const [name, token] of Object.entries(mobileTokens.typography)) { - const prefix = `--mobile-${name.replaceAll('_', '-')}`; - element.style.setProperty(`${prefix}-size`, String(token.size)); - element.style.setProperty(`${prefix}-line-height`, String(token.lineHeight)); - element.style.setProperty(`${prefix}-weight`, String(token.weight)); - } -} - -function tryConventionalScreenshot(card, platform, scenario) { - const path = `./snapshots/${scenario}/${platform}.png`; - const image = new Image(); - image.onload = () => useNativeShot(card, path, `${platform}.png`); - image.src = path; -} - -function useNativeShot(card, source, label) { - const screen = card.querySelector('.device-screen'); - const image = card.querySelector('.native-shot'); - image.addEventListener('load', () => { - const expectedAspect = Number(screen.style.getPropertyValue('--viewport-width')) - / Number(screen.style.getPropertyValue('--viewport-height')); - const captureAspect = image.naturalWidth / image.naturalHeight; - const aspectDelta = Math.abs(captureAspect / expectedAspect - 1) * 100; - card.querySelector('.capture-status span').textContent = - `${label} · ${image.naturalWidth}×${image.naturalHeight} · 画幅差 ${aspectDelta.toFixed(1)}%`; - card.classList.toggle('capture-aspect-warning', aspectDelta >= 1); - if (card.isConnected) { - nativeCaptures.set(card.dataset.platform, { card, image }); - updatePixelDeltas(); - } - }, { once: true }); - image.src = source; - image.alt = `${card.dataset.platform} native screenshot`; - screen.classList.add('has-native'); - card.querySelector('.capture-status strong').textContent = 'NATIVE CAPTURE'; - card.querySelector('.capture-status span').textContent = `${label} · 读取尺寸…`; -} - -function updatePixelDeltas() { - const baseline = nativeCaptures.get('harmonyos'); - if (!baseline) return; - baseline.card.querySelector('.capture-delta, .capture-status em').textContent = 'PIXEL BASELINE'; - for (const platform of ['android', 'ios']) { - const capture = nativeCaptures.get(platform); - if (!capture) continue; - const delta = significantPixelDelta(baseline.image, capture.image); - capture.card.querySelector('.capture-delta, .capture-status em').textContent = `全帧像素差 ${delta.toFixed(1)}%`; - } -} - -function significantPixelDelta(baseline, candidate) { - const width = 195; - const height = 422; - const referencePixels = containedPixels(baseline, width, height); - const candidatePixels = containedPixels(candidate, width, height); - let changed = 0; - const pixelCount = width * height; - for (let index = 0; index < referencePixels.length; index += 4) { - const channelDelta = ( - Math.abs(referencePixels[index] - candidatePixels[index]) - + Math.abs(referencePixels[index + 1] - candidatePixels[index + 1]) - + Math.abs(referencePixels[index + 2] - candidatePixels[index + 2]) - ) / 3; - if (channelDelta >= 16) changed += 1; - } - return changed / pixelCount * 100; -} - -function containedPixels(image, width, height) { - const canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - const context = canvas.getContext('2d', { willReadFrequently: true }); - context.fillStyle = mobileColorToCss(mobileTokens.colors.media_background.dark); - context.fillRect(0, 0, width, height); - const scale = Math.min(width / image.naturalWidth, height / image.naturalHeight); - const drawWidth = image.naturalWidth * scale; - const drawHeight = image.naturalHeight * scale; - context.drawImage(image, (width - drawWidth) / 2, (height - drawHeight) / 2, drawWidth, drawHeight); - return context.getImageData(0, 0, width, height).data; -} - -function mobileColorToCss(value) { - if (!/^#[0-9A-F]{8}$/i.test(value)) return value; - const alpha = value.slice(1, 3); - const rgb = value.slice(3); - return `#${rgb}${alpha}`; -} diff --git a/src/apps/mobile/design-system/preview/snapshots/.gitignore b/src/apps/mobile/design-system/preview/snapshots/.gitignore deleted file mode 100644 index e33609d251..0000000000 --- a/src/apps/mobile/design-system/preview/snapshots/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.png diff --git a/src/apps/mobile/design-system/preview/snapshots/README.md b/src/apps/mobile/design-system/preview/snapshots/README.md deleted file mode 100644 index cb4b282392..0000000000 --- a/src/apps/mobile/design-system/preview/snapshots/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Native preview captures - -The desktop comparison tool looks for optional PNG captures at: - -```text -snapshots//.png -``` - -`platform` is `harmony`, `android`, or `ios`. For example: - -```text -snapshots/connected-conversation/harmony.png -snapshots/connected-conversation/android.png -snapshots/connected-conversation/ios.png -``` - -Use the matching generated native preview gallery and the same scenario id. -Captures can also be selected directly from each column in the browser. Local -captures are visual evidence and should not be committed unless they are being -reviewed as deliberate regression fixtures. - -Android capture evidence is produced by on-device instrumentation tests, not -committed PNGs. HarmonyOS captures remain unproven until a device and toolchain -are available. diff --git a/src/apps/mobile/design-system/scenarios/mobile-preview-scenarios.json b/src/apps/mobile/design-system/scenarios/mobile-preview-scenarios.json deleted file mode 100644 index e5218787f1..0000000000 --- a/src/apps/mobile/design-system/scenarios/mobile-preview-scenarios.json +++ /dev/null @@ -1,181 +0,0 @@ -{ - "version": 1, - "scenarios": [ - { - "id": "connected-conversation", - "title": "Connected conversation", - "description": "A remote desktop is answering and the composer is ready.", - "appearance": "light", - "viewport": { - "width": 390, - "height": 844 - }, - "header": { - "title": "统一移动端设计系统", - "subtitle": "DESKTOP-KM3L4UI" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "可以。共享视觉契约,三端继续使用原生渲染。" - } - ], - "composer": { - "draft": "", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - }, - { - "id": "streaming-dark", - "title": "Streaming in dark mode", - "description": "An active turn exercises dark surfaces and the stop action.", - "appearance": "dark", - "viewport": { - "width": 390, - "height": 844 - }, - "header": { - "title": "跨端视觉校验", - "subtitle": "正在由 MacBook Pro 运行" - }, - "messages": [ - { - "role": "user", - "text": "比较三端的输入框、消息气泡和标题栏。" - }, - { - "role": "assistant", - "text": "正在生成原生截图,并按相同基线并排展示。" - } - ], - "composer": { - "draft": "检查深色模式下的边框对比度", - "placeholder": "输入消息", - "phase": "connected", - "streaming": true - } - }, - { - "id": "reconnecting-wide", - "title": "Reconnecting on a wide viewport", - "description": "A tablet-sized viewport keeps remote blocking states answerable.", - "appearance": "light", - "viewport": { - "width": 1024, - "height": 768 - }, - "header": { - "title": "远程会话", - "subtitle": "正在恢复连接" - }, - "messages": [ - { - "role": "assistant", - "text": "连接暂时中断。恢复后会从上次游标继续。" - } - ], - "composer": { - "draft": "", - "placeholder": "等待重新连接", - "phase": "reconnecting", - "streaming": false - } - }, - { - "id": "narrow-multiline", - "title": "Narrow phone with a multiline draft", - "description": "Narrow phone with a multiline draft", - "appearance": "light", - "viewport": { - "width": 360, - "height": 800 - }, - "header": { - "title": "检查移动端长标题、正文与控制目标的可读性", - "subtitle": "远程开发工作站 · OpenBitFun / feature/mobile-reading" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "可以。共享视觉契约,三端继续使用原生渲染。" - } - ], - "composer": { - "draft": "请检查输入框是否能保留多行中文草稿。\n模型选择后内容应继续保留。\n附件与文本应各自成行。", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - }, - { - "id": "fold-context", - "title": "Foldable with long remote context", - "description": "Foldable with long remote context", - "appearance": "light", - "viewport": { - "width": 700, - "height": 840 - }, - "header": { - "title": "检查移动端长标题、正文与控制目标的可读性", - "subtitle": "远程开发工作站 · OpenBitFun / feature/mobile-reading" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "可以。共享视觉契约,三端继续使用原生渲染。" - } - ], - "composer": { - "draft": "请保留当前会话与控制目标。", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - }, - { - "id": "long-reading", - "title": "Long reading content", - "description": "Long reading content", - "appearance": "light", - "viewport": { - "width": 430, - "height": 932 - }, - "header": { - "title": "检查移动端长标题、正文与控制目标的可读性", - "subtitle": "远程开发工作站 · OpenBitFun / feature/mobile-reading" - }, - "messages": [ - { - "role": "user", - "text": "三端的组件和样式可以保持一致吗?" - }, - { - "role": "assistant", - "text": "移动端的阅读层级需要清晰,正文应该舒适地换行,辅助说明保留足够对比度。\n\n当内容变长时,消息区滚动,输入框仍然可以操作。请在系统大字体设置下检查这一场景。" - } - ], - "composer": { - "draft": "", - "placeholder": "向 OpenBitFun 提问", - "phase": "connected", - "streaming": false - } - } - ] -} diff --git a/src/apps/mobile/design-system/tokens/mobile-tokens.json b/src/apps/mobile/design-system/tokens/mobile-tokens.json deleted file mode 100644 index d81f3b2d6f..0000000000 --- a/src/apps/mobile/design-system/tokens/mobile-tokens.json +++ /dev/null @@ -1,440 +0,0 @@ -{ - "version": 1, - "identity": { - "name": "OpenBitFun Mobile", - "signature": "Paper-and-ink conversation chrome with a single blue information accent" - }, - "colors": { - "start_window_background": { - "light": "#FFFFFF", - "dark": "#000000" - }, - "transparent": { - "light": "#00000000", - "dark": "#00000000" - }, - "page_bg": { - "light": "#FFFFFF", - "dark": "#151514" - }, - "welcome_page_bg": { - "light": "#FFFFFF", - "dark": "#252522" - }, - "page_bg_fade": { - "light": "#00FFFFFF", - "dark": "#00151514" - }, - "page_bg_overlay": { - "light": "#B8FFFFFF", - "dark": "#B8151514" - }, - "ink": { - "light": "#171717", - "dark": "#F4F3EF" - }, - "muted": { - "light": "#706F6A", - "dark": "#AAA8A0" - }, - "subtle": { - "light": "#A5A39B", - "dark": "#77756E" - }, - "line": { - "light": "#E9E7E2", - "dark": "#363531" - }, - "card": { - "light": "#FFFFFF", - "dark": "#252522" - }, - "card_overlay": { - "light": "#CCFFFFFF", - "dark": "#CC252522" - }, - "accent": { - "light": "#111111", - "dark": "#5B5954" - }, - "file_link": { - "light": "#2563EB", - "dark": "#60A5FA" - }, - "primary_action": { - "light": "#111111", - "dark": "#454540" - }, - "content_on_action": { - "light": "#FFFFFF", - "dark": "#FFFFFF" - }, - "connect_hero_bg": { - "light": "#E6EDFF", - "dark": "#2B2B29" - }, - "connect_hero_accent": { - "light": "#9DB4FF", - "dark": "#4A4944" - }, - "connect_hero_secondary": { - "light": "#C9C5FF", - "dark": "#3C3B38" - }, - "connect_hero_surface": { - "light": "#F8FAFF", - "dark": "#252522" - }, - "connect_scan_accent": { - "light": "#FFD021", - "dark": "#FFD021" - }, - "scrim": { - "light": "#44000000", - "dark": "#44000000" - }, - "shell_scrim": { - "light": "#24000000", - "dark": "#24000000" - }, - "media_background": { - "light": "#FF000000", - "dark": "#FF000000" - }, - "media_scrim": { - "light": "#B8000000", - "dark": "#B8000000" - }, - "media_control_background": { - "light": "#8C000000", - "dark": "#8C000000" - }, - "toast_background": { - "light": "#D1171717", - "dark": "#D1171717" - }, - "shadow_faint": { - "light": "#08000000", - "dark": "#08000000" - }, - "shadow_subtle": { - "light": "#12000000", - "dark": "#12000000" - }, - "shadow_medium": { - "light": "#18000000", - "dark": "#18000000" - }, - "shadow_strong": { - "light": "#24000000", - "dark": "#24000000" - }, - "floating_border": { - "light": "#18000000", - "dark": "#18000000" - }, - "soft": { - "light": "#F4F3F0", - "dark": "#2D2C28" - }, - "floating_panel_bg": { - "light": "#F7F7F5", - "dark": "#1E1E1C" - }, - "sidebar_bg": { - "light": "#F8F8F9", - "dark": "#0E0E10" - }, - "sidebar_bg_fade": { - "light": "#00F8F8F9", - "dark": "#000E0E10" - }, - "sidebar_raised": { - "light": "#FFFFFF", - "dark": "#1C1C1F" - }, - "sidebar_line": { - "light": "#14101A27", - "dark": "#1FFFFFFF" - }, - "sidebar_hover": { - "light": "#F3F3F5", - "dark": "#0FFFFFFF" - }, - "sidebar_selection": { - "light": "#14000000", - "dark": "#1FFFFFFF" - }, - "sidebar_ink": { - "light": "#CC000000", - "dark": "#E8E8E8" - }, - "sidebar_muted": { - "light": "#99000000", - "dark": "#B0B0B0" - }, - "sidebar_subtle": { - "light": "#66000000", - "dark": "#858585" - }, - "status_success": { - "light": "#27C46A", - "dark": "#3BD47B" - }, - "status_danger": { - "light": "#E04F4F", - "dark": "#FF6B6B" - }, - "code_line_number": { - "light": "#AAA69D", - "dark": "#77756E" - }, - "code_keyword": { - "light": "#8F3F71", - "dark": "#D99AC4" - }, - "code_string": { - "light": "#477A4A", - "dark": "#9BCB9D" - }, - "code_number": { - "light": "#9A5B13", - "dark": "#E3B36D" - }, - "code_comment": { - "light": "#7A8078", - "dark": "#96958D" - }, - "code_function": { - "light": "#2C6693", - "dark": "#8CBCE0" - }, - "code_type": { - "light": "#865A20", - "dark": "#D5B27F" - }, - "code_constant": { - "light": "#A04444", - "dark": "#E79A9A" - }, - "code_property": { - "light": "#466D78", - "dark": "#9CC8D0" - }, - "code_target_bg": { - "light": "#FFF1BE", - "dark": "#5A4E24" - }, - "brand_dot": { - "light": "#16B9CE", - "dark": "#16B9CE" - }, - "welcome_dock": { - "light": "#171917", - "dark": "#000000" - }, - "welcome_button": { - "light": "#FFFFFF", - "dark": "#FFFFFF" - }, - "welcome_button_label": { - "light": "#171917", - "dark": "#171917" - }, - "welcome_secondary": { - "light": "#B9BCB9", - "dark": "#B9BCB9" - }, - "status_warning": { - "light": "#FF8C00", - "dark": "#FF8C00" - } - }, - "typography": { - "display_large": { - "size": 24, - "lineHeight": 30, - "weight": 700 - }, - "display_medium": { - "size": 22, - "lineHeight": 28, - "weight": 700 - }, - "display_small": { - "size": 20, - "lineHeight": 26, - "weight": 700 - }, - "headline_large": { - "size": 22, - "lineHeight": 28, - "weight": 700 - }, - "headline_medium": { - "size": 20, - "lineHeight": 26, - "weight": 700 - }, - "headline_small": { - "size": 18, - "lineHeight": 24, - "weight": 700 - }, - "title_large": { - "size": 20, - "lineHeight": 26, - "weight": 700 - }, - "conversation_header_title": { - "size": 17, - "lineHeight": 22, - "weight": 600 - }, - "title_medium": { - "size": 17, - "lineHeight": 22, - "weight": 500 - }, - "title_small": { - "size": 15, - "lineHeight": 20, - "weight": 500 - }, - "body_large": { - "size": 16, - "lineHeight": 24, - "weight": 400 - }, - "body_medium": { - "size": 14, - "lineHeight": 21, - "weight": 400 - }, - "body_small": { - "size": 13, - "lineHeight": 19, - "weight": 400 - }, - "label_large": { - "size": 15, - "lineHeight": 20, - "weight": 500 - }, - "label_medium": { - "size": 14, - "lineHeight": 18, - "weight": 500 - }, - "label_small": { - "size": 12, - "lineHeight": 16, - "weight": 400 - }, - "brand_wordmark": { - "size": 42, - "lineHeight": 56, - "weight": 500 - } - }, - "text_scale": { - "reference_logical_dpi": 153.3, - "min_factor": 0.85, - "max_factor": 1 - }, - "geometry": { - "conversation_header_height": 76, - "conversation_header_compact_height": 64, - "control_touch_size": 48, - "content_gutter": 16, - "connection_strip_height": 48, - "timeline_top_padding": 22, - "conversation_overlay_side_inset": 16, - "conversation_edge_fade_height": 28, - "message_spacing": 18, - "message_bubble_max_width": 276, - "message_bubble_horizontal_padding": 14, - "message_bubble_vertical_padding": 11, - "message_bubble_radius": 17, - "composer_action_size": 48, - "composer_input_height": 44, - "composer_expanded_input_height": 58, - "composer_collapsed_height": 56, - "composer_expanded_input_row_height": 60, - "composer_expanded_action_row_height": 48, - "composer_expanded_height": 120, - "composer_collapsed_radius": 28, - "composer_expanded_radius": 18, - "composer_model_selector_width": 330, - "composer_model_selector_radius": 14, - "composer_model_selector_row_height": 48, - "composer_model_selector_row_radius": 9, - "composer_model_selector_row_gap": 6, - "sheet_top_radius": 28, - "login_sheet_max_width": 560, - "login_sheet_outer_margin": 8, - "login_sheet_body_min_height": 142, - "sheet_side_radius": 28, - "sheet_horizontal_padding": 20, - "sheet_header_height": 56, - "sheet_action_height": 48, - "selection_top_radius": 20, - "selection_row_height": 64, - "selection_close_size": 48, - "popover_width": 292, - "popover_radius": 16, - "popover_padding": 12, - "popover_vertical_padding": 10, - "popover_action_height": 48, - "popover_shadow_radius": 18, - "compact_popover_width": 150, - "compact_popover_radius": 14, - "compact_popover_action_height": 42, - "settings_compact_card_radius": 12, - "settings_card_radius": 16, - "settings_prominent_card_radius": 20, - "model_current_row_height": 64, - "model_source_row_height": 62, - "model_account_row_height": 56, - "model_account_row_gap": 6, - "model_section_gap": 20, - "model_overview_top_padding": 16, - "model_overview_bottom_padding": 24, - "model_list_top_padding": 10, - "model_list_bottom_padding": 16, - "model_empty_account_height": 80, - "model_editor_height": 560, - "welcome_max_width": 520, - "welcome_gutter": 25, - "welcome_header_height": 58, - "welcome_button_height": 49, - "welcome_button_gap": 11, - "welcome_dock_radius": 30, - "welcome_dock_bottom": 39, - "welcome_mark_size": 92, - "welcome_word_size": 34, - "welcome_stage_height": 220, - "welcome_header_word_size": 17, - "recent_home_gutter": 24, - "recent_home_mark_size": 132, - "recent_home_title_size": 25, - "recent_home_max_width": 560, - "recent_home_row_padding": 18, - "approval_card_radius": 12, - "approval_card_padding": 12, - "approval_card_gap": 8, - "approval_action_radius": 8, - "approval_action_height": 36 - }, - "breakpoints": { - "wide": 600, - "extra_wide": 840, - "xl": 1440 - }, - "motion": { - "quick": 180, - "structure": 220, - "startup_brand": 6800, - "cold_start_home": 2400 - } -} diff --git a/src/apps/mobile/docs/remote-session-lifecycle.md b/src/apps/mobile/docs/remote-session-lifecycle.md deleted file mode 100644 index 0ffc01ab8e..0000000000 --- a/src/apps/mobile/docs/remote-session-lifecycle.md +++ /dev/null @@ -1,38 +0,0 @@ -# Remote session lifecycle guidance - -Android, iOS, and HarmonyOS should follow the same MVVM shape for remote -sessions. The native surfaces may use different language and UI primitives, but -the ViewModel layer should keep the same responsibilities and update order. - -## Create - -Every create entry point dispatches one create operation with the selected -device and workspace identity. After success, the ViewModel should generally: - -1. select the returned session id and route to its conversation surface; -2. discard the previous session's draft, transcript, active turn, and file - preview state; -3. open or subscribe to the returned session on the remote host; -4. publish the hydrated timeline, including an empty timeline for a new session; -5. send the optional first instruction and start live polling/stream replay. - -The route should not wait for a non-empty transcript. An empty session is a -successful open and the conversation View owns its loading state. - -## Open an existing session - -Opening an existing row follows the same steps from selection onward. The -selected session id is the navigation identity; a stale timeline from another -session should not be rendered while the open request is pending. - -## Ownership by platform - -- Android and iOS receive most session state from the shared KMP session store. - Shell state controls containers, drawers, and transient route presentation; - it should not become a second session store. -- HarmonyOS keeps its native ViewModel and controller, but their responsibilities - should mirror the KMP store and use the same remote command shapes. -- Transport, relay, and desktop behavior are not owned by a mobile surface. - -Failures after the create commit should leave the created session visible and -route to its conversation surface with an explicit loading or error state. diff --git a/src/apps/mobile/harmonyos/.gitignore b/src/apps/mobile/harmonyos/.gitignore deleted file mode 100644 index 63b8fc71c1..0000000000 --- a/src/apps/mobile/harmonyos/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -/node_modules -/oh_modules -/local.properties -/.idea -.DS_Store -**/build -/.hvigor -**/.hvigor -.cxx -/.clangd -/.clang-format -/.clang-tidy -**/.test -/.appanalyzer - -# Local emulator verification artifacts -/openbitfun_*.jpeg -/openbitfun_*_layout.json -/openbitfun_layout*.json -.openbitfun/ -/.openbitfun/search/flashgrep-index/ - -# Signing credentials and installable artifacts -/signing.local.json5 -*.cer -*.key -*.p12 -*.p7b -*.pem -*.hap -*.app - -# Generated from shared desktop MiniApp sources by entry/hvigorfile.ts -/entry/src/main/resources/rawfile/miniapps/ - -# Generated from en_US/zh_CN element string catalogs by entry/hvigorfile.ts -/entry/src/main/resources/rawfile/string.json diff --git a/src/apps/mobile/harmonyos/AGENTS.md b/src/apps/mobile/harmonyos/AGENTS.md deleted file mode 100644 index 0766797ad7..0000000000 --- a/src/apps/mobile/harmonyos/AGENTS.md +++ /dev/null @@ -1,221 +0,0 @@ -# HarmonyOS App Instructions - -These rules apply to all changes under `src/apps/mobile/harmonyos`. - -## Controller product boundary - -Phone, tablet, and foldable entrypoints are remote controllers. They must not -instantiate a local Agent Runtime, model provider, local chat command owner, or -model configuration store. OpenBitFun account identity and the authenticated device directory -are the authority for selection and reconnect; QR data supplies only a device id. -Keep old persisted records readable and retained without activating legacy room -credentials or local execution. Compact and wide hosts enforce the same boundary. - -## MVVM Refactor Boundaries - -This app has one `entry` module, so MVVM is the file-organization boundary for -the module. Keep the official responsibilities explicit: - -- Model/services own data access, persistence, transport, and business logic; - they do not import views or page components. -- Views own presentation and user input; they consume projected state and emit - intents/events rather than calling services directly. -- ViewModels bridge services and views by owning feature state, projecting data, - and handling intents. ViewModels must not import components. -- Shared conversation presentation DTOs (`ChatSurface`, `ChatComposerCapabilities`, - `ConversationUiModels`) live in `pages/state/`. State must not import - `pages/components`. - -The following constraints are enforced incrementally by -`pnpm run harmony:architecture` (the runtime behavior checks remain in -`entry/src/test/ArchitectureUnit.test.ets`): - -1. `services/**` must not import `../pages/`. -2. `pages/state/**` must not import `pages/components/`. -3. `pages/components/**` must not import `pages/viewmodel/`; imports of - `pages/state/` and `pages/policy/` are allowed for observable state and pure - policies. -4. The page dependency graph must remain acyclic; ViewModels must not depend on - components. -5. Actions and Hooks use typed interfaces with object literals. Do not add - position-dependent callback constructors. -6. New components use `@ComponentV2`; do not add V1 `@Component`, `@State`, - `@Prop`, `@Link`, or `@Watch` declarations. `@BuilderParam` remains supported. -7. General Chat and Remote Chat shared observable fields belong to - `pages/state/ConversationCoreState.ets`. Page-specific state objects compose - that core and must not redeclare the shared `@Trace` fields. -8. Keep files focused by ownership, not by a hard line count. When a file - starts mixing unrelated concerns, extract the new owner. Do not cram or - flatten structure just to stay under a number. -9. Components must not import permission, scanner, input-method, or other - side-effectful platform kits directly. Put platform lifecycle and error - handling behind a service or a focused platform leaf component, then expose - typed state and events to the presentation tree. -10. Long, unbounded timelines use `Repeat.virtualScroll()` with stable identity - keys. V2 message rows must remain reusable, and mutable render content must - not be embedded in the identity key. -11. CPU-bound native work must not execute synchronously on the ArkTS caller - thread. Expose it through Node-API async work (or an equivalent TaskPool / - Worker owner), return a Promise, and bound the ArkTS wait with an explicit - timeout. -12. `ConversationView` consumes grouped presentation state/options and emits a - typed `ConversationIntent`. Do not reintroduce one public parameter or event - per projected field/action. - -User-facing copy lives in `entry/src/main/ets/i18n`. Keep `zh-CN` and `en-US` -catalogs in key lockstep, use canonical locale ids, and route language changes -through `LocaleController`. Do not import Web UI or mobile-web locale catalogs. - -The current local HarmonyOS verification loop is: - -```bash -node --test tools/tests/*.test.cjs # host stream paging/hints/restart gaps, catalog, terminal, identity checks -node --test miniapps/*.test.cjs # bundled sources, browser bridge, and local storage compatibility -source scripts/ohos-env.sh -"$HVIGORW" --mode module -p product=default -p module=entry@default assembleHap --no-daemon -"$HVIGORW" --mode module -p module=entry@default -p ohos.test.type=LocalTest test --no-daemon -``` - -Relay Zstd encode/decode uses N-API async work through -`services/RelayMessageEncoding.ets`. The wrapper bounds the worker wait, and -compressed messages retain their capability generation until submission. Verify -presence changes during upload, settled replies, and codec waits with -`node --test tools/tests/relay-message-generation.test.cjs`. - -For window inset subscription lifecycle and late completion regressions, run -`node --test tools/tests/window-insets-lifecycle.test.cjs tools/tests/immersive-bottom.test.cjs`. -The lifecycle tests run the production service with deferred platform window -reads; device rotation and folding still require native verification. - -For language-refresh and literal-parameter regressions, run -`node --test tools/tests/host-text-retranslator.test.cjs`. This exercises the -production retranslator and RemoteI18n with real element catalogs; platform -resource access is mocked and does not replace native resource/device checks. - -For workspace/session catalog rendering, install the debug HAP and run -`python3 tools/check-catalog-refresh.py --hdc "$HDC"` (add `--dark` for dark -mode). Run in compact and wide postures. The isolated fixture replaces objects -while preserving IDs and checks titles and click payloads in the sidebar, -recent sessions, time/project lists, and workspace picker. The script restores -the normal App even on assertion failure; it does not modify remote data. - -For composer submission timing and draft ownership, run -`node --test tools/tests/composer-submit.test.cjs`. The native preview scenario -`composer-submit` uses the real composer and command controller with a pending -fake RPC: send must clear the input before pressing **Acknowledge**, and a -**Next draft** entered while pending must survive acknowledgment. Exercise both -compact and wide layouts and return to normal `EntryAbility` afterward. - -For rollback reply ownership and session switching, run -`node --test tools/tests/rollback-session-isolation.test.cjs`. -In the `copy-rollback` native preview, stage a rollback, use **Resize**, and verify -the preview remains for the same session. Use **Switch session** and verify the -staging bar and full-text panel close while `SESSION-B-DRAFT` remains untouched. -Exercise compact and wide widths in light and dark modes, then restore normal -`EntryAbility`. Deferred-response unit tests cover switching while rollback, -send acknowledgment, and voice shutdown are pending; the preview uses a mock -host and is not evidence of live relay or physical fold behavior. -After installing the debug HAP on a wide device/emulator, run -`python3 tools/check-rollback-session-isolation.py --hdc "$HDC" --device ` -for compact/wide, light/dark and live resize checks with layout/screenshot evidence. - -For history loading and explicit jump-to-bottom navigation, install the debug -HAP and run `python3 tools/check-history-scroll.py --hdc "$HDC"`. The -`history-scroll` preview holds a mock history response while the production -ChatTimeline handles the jump. It covers success/failure at wide and compact -content widths with a live resize and restores the normal App afterward. -This is native controller UI coverage, not remote transport or physical fold -coverage; exercise those separately when their behavior changes. - -For durable transcript projection, run -`node --test tools/tests/session-record.test.cjs tools/tests/host-stream.test.cjs tools/tests/streaming-markdown.test.cjs`. -The `durable-timeline` native preview uses the -production reducer, timeline store and rows. **Next replay** exercises late tool -insertion, 30 identical publications, text correction, deletion and completion; -block counts must be 2, 3, 3, 3, 2, 2, with one visible answer. Verify compact, -wide and live fold transitions, then return to normal `EntryAbility`. - -For chat Markdown tildes, escapes, streaming prefixes and plain/rich copy, run -`node --test tools/tests/markdown-html-serializer.test.cjs tools/tests/streaming-markdown.test.cjs`. -These host tests execute the production parser and serializer; they do not -replace native rendering checks. -For a parser-only ArkTS compile without packaging/signing, source -`scripts/ohos-env.sh`, then run -`"$HVIGORW" --mode module -p product=default -p module=entry@default 'default@CompileArkTS' --no-daemon`. - -For host shutdown/restart handling, run -`node --test tools/tests/connection-health.test.cjs tools/tests/session-record.test.cjs tools/tests/host-stream.test.cjs`. -In `durable-timeline`, **Host offline** must retain content and disable Stop; -**Host returned** publishes an interrupted turn, preserving its output and -removing the running action. Test both postures and restore normal App afterward. - -## Visual reference fidelity - -- Before drawing a system glyph, text approximation, or new bitmap, search the existing HarmonyOS media resources and the approved desktop reference images. Reuse the established asset when one exists. -- Conversation header controls must use the approved `remote_ref_back` and `remote_ref_more` assets. Do not replace them with a system chevron or text such as `...` / bullet characters. Compact top-left open-sidebar uses `CompactMenuButton` (`gpt_home_menu_glyph`). Wide restore/collapse uses `SidebarToggleButton` (the sidebar-pane glyph). -- Render monochrome reference assets in template mode and tint them with semantic theme colors such as `INK`. Never rely on the bitmap's original black or white pixels; the same control must remain legible in light and dark themes. -- Keep paired header controls on the same fixed touch-target size and optical alignment. A responsive layout may reposition a control, but must not silently change its icon geometry or visual weight. -- Keep `SymbolGlyph` geometry separate from its touch target. When a glyph is clickable or sits in a decorated control, wrap it in `Stack({ alignContent: Alignment.Center })` (or use a centered `Button`) that carries the touch-target size, and size the glyph with `.fontSize()` only. Do not stretch the glyph itself to the full 32vp/40vp/44vp target. -- Prefer `.fontSize()` over `.width()`/`.height()` on a `SymbolGlyph`. Measured on device: a glyph's natural advance box is `fontSize * 1.013` square for most symbols, but `chevron_left` and `chevron_right` are only `fontSize * 0.507` wide. Ink is drawn **left-anchored** inside any box forced wider than the natural box (vertically it stays centered, so only the horizontal axis is affected), and a box forced *smaller* than the natural box makes the glyph overflow rather than scale. So `.width(N)` on a chevron shifts it left of its container's center by `(N - fontSize * 0.507) / 2`. -- A collapse indicator that swaps between `chevron_right` and `chevron_down` still needs a fixed slot so the adjacent label does not jump between states. Put the fixed size on a wrapping `Stack({ alignContent: Alignment.Center })` and select the symbol with a ternary on one unsized `SymbolGlyph`; see `SubagentTaskCard.ets`. Never put the slot size on the glyph itself. -- The one place a forced width is correct is a leading icon slot in a list row: because ink is left-anchored, a shared `.width()` is what keeps icon and text left edges aligned down a column of rows whose `fontSize` values differ. Leave those alone. - -## Responsive interaction semantics - -- Every HarmonyOS change that can affect presentation or interaction — including - state, actions, ViewModels, and components — must treat compact phones, wide - screens, and foldables in both folded and unfolded postures as first-class - targets. Do not implement or review a feature against only the currently - visible layout. -- Before editing, search for every responsive host and presentation branch that - exposes the affected action or state (for example compact overlays, wide - master/detail hosts, sidebars, routed destinations, sheets, and popovers). - Keep their behavior and capability gating aligned; a fix is incomplete while - an equivalent wide or compact entry point still uses legacy behavior. -- Do not infer device class from a single width captured at startup. Layout must - remain correct when a foldable changes posture or window size while the app is - running, preserving state, selection, and interaction meaning across the - transition. -- For UI changes, verify at minimum one compact layout and one wide layout. When - a foldable or resizable emulator/device is available, also exercise a live - folded/unfolded or resize transition. Record any unverified posture explicitly - in the handoff instead of treating a phone-only check as sufficient evidence. -- Wide and compact layouts must keep the same interaction meaning. Responsive presentation may change spacing and available width, but it must not turn a lightweight anchored action menu into a bottom sheet by default. -- Conversation-header overflow actions open from the top-right trigger as an anchored popover on both compact and wide layouts. Use a bottom sheet only when the content is a genuinely large or multi-step mobile workflow and the design explicitly calls for it. -- Anchor popovers to their actual trigger with `bindPopup` or the equivalent platform API. Do not emulate the anchor with unrelated page-level absolute positioning. -- Preserve auto-dismiss, outside-tap handling, accessibility labels, and a short enter/exit transition for anchored menus. - -## Theme and device verification - -For cold-start home animation geometry, launch the isolated design preview with -`hdc shell aa start -a EntryAbility -b --ps openbitfunDesignPreview cold-start-home` -(or `cold-start-home-dark`). Use **Replay** to run the production 2400 ms -transition over the production recent-home component and **Resize** during -playback to remeasure its anchor. This fixture does not load account or remote -state. Check compact and wide windows separately, then force-stop and start the -normal EntryAbility without preview arguments. A fixture check does not replace -authenticated cold-process, signed-out, and background/foreground verification. - -- Use existing semantic colors from `Theme.ets`; do not hard-code a light-only foreground or surface color. -- For changes to navigation controls, menus, or responsive presentation, verify compact and wide behavior, light and dark theme legibility, and capture a real-device screenshot before completion when a device is connected. -- Run the smallest matching HarmonyOS build/check plus `pnpm run theme:color-audit:all` for theme or color-related changes. - -For the bundled native file editor renderer (read-only mode, horizontal lines, -line-number scroll alignment, and edit bridge), run from the repository root: - -```bash -node --test src/mobile-web/tests/harmony-file-editor-browser.test.mjs -node --test src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs -``` - -The Chrome renderer test does not replace Harmony device-level keyboard and -sheet-layout checks. - -For queue capability negotiation, session isolation and mutation/read races: - -```bash -node --test tools/tests/message-queue.test.cjs -``` - -The fixture uses the production queue store with a simulated host. Native drag -presentation and live remote dispatch need separate device verification. diff --git a/src/apps/mobile/harmonyos/AppScope/app.json5 b/src/apps/mobile/harmonyos/AppScope/app.json5 deleted file mode 100644 index 75bf7f95e1..0000000000 --- a/src/apps/mobile/harmonyos/AppScope/app.json5 +++ /dev/null @@ -1,14 +0,0 @@ -{ - "app": { - // Package identity is intentionally stable across the OpenBitFun rename so - // upgrades retain encrypted sessions, preferences, and watch handoff data. - "bundleName": "com.bitfun.app", - "vendor": "OpenBitFun", - "versionCode": 9, - "versionName": "1.0.0", // x-release-please-version - "buildVersion": "1", - "icon": "$media:openbitfun_app_icon", - "label": "$string:app_name", - "configuration": "$profile:configuration" - } -} diff --git a/src/apps/mobile/harmonyos/AppScope/resources/base/element/string.json b/src/apps/mobile/harmonyos/AppScope/resources/base/element/string.json deleted file mode 100644 index 44a03dc857..0000000000 --- a/src/apps/mobile/harmonyos/AppScope/resources/base/element/string.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "string": [ - { - "name": "app_name", - "value": "OpenBitFun" - } - ] -} diff --git a/src/apps/mobile/harmonyos/AppScope/resources/base/media/openbitfun_app_icon.png b/src/apps/mobile/harmonyos/AppScope/resources/base/media/openbitfun_app_icon.png deleted file mode 100644 index 2cfdd17e9453d91c999c9c7d046dbc650abf89e8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 104027 zcmaI82Ut^G*DbmeI--DxGzCSa2uhPCRm4VD6i|AX-g`-~f{KWU(!l~qM|uZEKrnz( zrAMmt-XXa&;&;Du&VTOpd3?+ZJA1Fa)?9OrImTFTh?d5c{j}_~2!iatc2)TXf{?>U za)g=^{=pm-xDWr(IA6W(h9G2rNPkgcG-B3Awj{L^G35#2xk$0TpT@qLH zSlYhTcrDPf`P znA6#)_*rEsFQy_;?o?84_S@Gtq<>#}l6>6fT719c2ZJeXp3Ss39n49a**C3iSRZH5fb8NbdVYbtWRyvB2kFNh6hx0LfPf;ha z<9qw7dAYio6AP@~FL$>1Hk~M_;Ojji;!&ZSXhq$nws_acF9yH6M~z5dJ6Z05dvuRJ zNT$YrX}Y*ZvJoScUYf**9DAtqJi319L3Dcc=KSkXqFke@?co|L9&C#kEEOZ8z2!dH zYmMlum9i>EfmbQXsu~1&H#qZAZ{Y=BzOhX@`bV>rJV+jQi(s`sJQ)65y)LV&u{IHu z6U5Q@UC=5;QR(7IT7+8S{A%%{`THs>9CIMCC=#P!6@a<_NR2eK4^x>Cps6JXK9zqxb6NZP72iW5#46Mi(MP93{>J}E#sKVP;*xmMhDUV`9bq5Ir z31RgckJSk5k3b_|s%Cq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d;*Z+KPCe4nPa!aB@;Fg$I$Bj>{DtXJljB;M!p4j$H zI+Z7mjl304lHHza@x@KYc`u-Ob*#jA;Q8zS-8$h!+rBpWBTFu@)>-+GU$i>f>Pc0B z|C>Rkmgj)WaKWWMRWp-pA8VR2wSdi((!k?OzRNnXxRtFfO7&_%xlayLh7!GGj9-y* zH@Ie4b)U+^+3}}$ePGd=ncMtKi7Y9Wr#A{&X|C$to5Sxv$xE_t53njYI?ewMon`B^fS3zPRXtZns*fvL>UtB}Ro}SxlkF-V4 zUfFA2wOgDPELq7vv#H$6g!u_WGp!FxXdQIUCx`GyBl_d)eKllR;Cm%auX!j~N%Hl+Ui37=|Ph{xV zXyk2)4HCk@ee)b7I{V#kQ^w)!vdf)babQ_aCHh`l|lp zHFL$09%U<6+`Z6zp|5*2xz>wutXTV;%G((=y6`FcI{eP+C^mCeLH6@MvMEh#wf}Mq zPlZ3m4fj8mopY4svd>XwAY$?g@84v;SKV^++(4qb|Zm7w1dkfh1uEm?Va_rLz{5AH`TRfck*KoLWrb)E+e`duoO81{thp@$ZCsc%% zbZIIT9(0*e_vU;eqas6DRpaoXjrZiUw%t!|ng50^!`|w8h7e!HdRJ-B9MdQI#Qw7Nt;L^Jf4Lohj{mWi^~3jguIqB^&rE%V;pFA* zaubyv1yplUrZH~)bH<%?3(@GaQgwTc*VG;R+oG$n`1SJbh3~ZfJ=SdcB|HX8aSWzlut|jFQj!A5T&_n4Bb`@6hd_n`~izkWur+=AaaQ{99_o zh=42WY za%O8Bo3~ScEw{ds?==;hX@*eXm{|}k84}bsw diff --git a/src/apps/mobile/harmonyos/AppScope/resources/base/profile/configuration.json b/src/apps/mobile/harmonyos/AppScope/resources/base/profile/configuration.json deleted file mode 100644 index f300d62def..0000000000 --- a/src/apps/mobile/harmonyos/AppScope/resources/base/profile/configuration.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "configuration": { - "fontSizeScale": "followSystem", - "fontSizeMaxScale": "1.75" - } -} diff --git a/src/apps/mobile/harmonyos/README.md b/src/apps/mobile/harmonyos/README.md deleted file mode 100644 index 48e1295b46..0000000000 --- a/src/apps/mobile/harmonyos/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# OpenBitFun HarmonyOS - -Native HarmonyOS controller for OpenBitFun desktop and CLI hosts on phones, -foldables, and tablets. Sign in with GitHub, select an account device, then send -tasks and view results from that host. The phone does not run an Agent Runtime or -store model-provider configuration. Model selection applies to the selected host. - -Device QR codes identify a target; the authenticated account directory authorizes -access. Old room records and local conversation data remain on disk during an -upgrade, but do not automatically reconnect or start a local runtime. - -GitHub usernames and avatars are presentation metadata loaded from GitHub's public -user-by-ID API without forwarding account credentials. The phone caches them for -24 hours in its encrypted account store, scoped to the authenticated GitHub ID. -Existing signed-in installs are enriched on startup. Offline or rate-limited -profile requests retain the session and cached display; device authorization -continues to use the immutable ID issued by Relay. - -## Project Layout - -- `AppScope/`: application metadata and shared resources. -- `entry/src/main/ets/`: ArkTS application code. -- `entry/src/main/resources/`: entry-module resources. -- `entry/src/test/`: local unit tests. -- `entry/src/ohosTest/`: device tests. -- `tools/fake-relay.mjs`: local relay simulator for UI and protocol testing. - -## Development - -Open this directory as a project in DevEco Studio. Install dependencies through -OHPM before building the `entry` module. - -On macOS with DevEco Studio installed in its default location: - -```bash -source scripts/ohos-env.sh -"$OHPM" install -"$HVIGORW" --mode module -p module=entry assembleHap --no-daemon -``` - -Signing configuration is intentionally not stored in the repository. Configure -a local signing identity in DevEco Studio when installing the app on a device. - -The current project targets HarmonyOS `6.1.1(24)` and supports -`6.0.1(21)` or newer on phone and tablet devices. - -## Built-in MiniApps - -Choose **MiniApps** from the sidebar to open Gomoku, Regex Playground, -or Daily Divination. The gallery uses two columns of rounded showcase previews -on phones and three on wide screens; tapping a preview opens the app directly. -Showcase images reuse the existing desktop artwork under -`src/web-ui/src/assets/miniapps/showcases/`. Navigation typography follows the -shared mobile body role, with the same proportions on compact and wide hosts. - -These bundled pages run locally in ArkWeb without signing -in, pairing, a desktop connection, or internet access. Storage and clipboard -writes use the phone. Data is isolated by app and retained across app upgrades; -it is not synchronized with desktop MiniApps. Closing a page discards its -unsaved page state. Changing desktop targets has no effect on these local tools. - -Every IDE/CLI HAP build runs `miniapps/generate.cjs` through -`entry/hvigorfile.ts`. It packages the existing shared MiniApp sources and -canonical appearance tokens into generated raw resources; do not edit those -outputs. `miniapps/mobile.css` owns phone-only layout adaptation. The pages -follow the app language and system light/dark appearance. They resize in place -for compact, wide, and folded/unfolded layouts. - -The sandboxed iframe has no network access or local-file access. The native -bridge permits only per-app storage keys and clipboard writes; it has no generic -invoke, Worker, shell, workspace, AI, or Agent API. Local records are replaced -atomically, and malformed records are retained and return an error. These local -tools do not read any remote workspace or peer content, and do not execute jobs -on CLI/Detached Dispatch hosts. Existing Remote Connect protocols are unchanged. -Desktop catalogs, page transfer, and remote MiniApp execution are deferred. - -Run the local test and HAP build commands in `AGENTS.md`, plus: - -```bash -node --test miniapps/*.test.cjs -``` - -Before claiming device verification, exercise local/offline launches, saved data -after relaunch, clipboard, keyboard input, compact/wide layouts, light/dark -appearance, and a live resize/fold transition on supported hardware. - -### Home and launch presentation - -Cold launches reuse the desktop contour mark and reveal the OpenBitFun wordmark -letter by letter in approximately 1.3 seconds. This presentation does not wait -for network/account initialization, is dismissed when backgrounded, and does not -replay on foreground. The system reduced-motion preference skips it where the -platform exposes that preference (API 23+). Native launch artwork and the app -surface both follow the system light/dark theme. - -The welcome surface keeps connection actions at the bottom and offers bundled -MiniApps without a desktop connection. Connected, connecting, and empty wide -surfaces retain their existing remote capability and session routing behavior. diff --git a/src/apps/mobile/harmonyos/build-profile.json5 b/src/apps/mobile/harmonyos/build-profile.json5 deleted file mode 100644 index b8ab714e5f..0000000000 --- a/src/apps/mobile/harmonyos/build-profile.json5 +++ /dev/null @@ -1,56 +0,0 @@ -{ - "app": { - "products": [ - { - "name": "default", - "signingConfig": "default", - "targetSdkVersion": "26.0.0", - "compatibleSdkVersion": "6.0.1(21)", - "runtimeOS": "HarmonyOS", - "buildOption": { - "strictMode": { - "caseSensitiveCheck": true, - "useNormalizedOHMUrl": true - } - } - } - ], - "buildModeSet": [ - { - "name": "debug" - }, - { - "name": "release" - } - ], - "signingConfigs": [ - { - "name": "default", - "type": "HarmonyOS", - "material": { - "certpath": "/Users/user/.ohos/config/default_harmonyos_B3rUxpnSPfGXXWmdMOYVoc7TUzJDbROQp3p6n39Q8qQ=.cer", - "keyAlias": "debugKey", - "keyPassword": "0000001A391869B09E80CE6A66CFA3F3864C8F321A69398D55D1CD0AD84D6EA98C4F835AF200151DB198", - "profile": "/Users/user/.ohos/config/default_harmonyos_B3rUxpnSPfGXXWmdMOYVoc7TUzJDbROQp3p6n39Q8qQ=.p7b", - "signAlg": "SHA256withECDSA", - "storeFile": "/Users/user/.ohos/config/default_harmonyos_B3rUxpnSPfGXXWmdMOYVoc7TUzJDbROQp3p6n39Q8qQ=.p12", - "storePassword": "0000001A975FC127975033425E725D1E55324204FF1C28601D5B38A9E066DFDD16F320DA9D97F3D83071" - } - } - ] - }, - "modules": [ - { - "name": "entry", - "srcPath": "./entry", - "targets": [ - { - "name": "default", - "applyToProducts": [ - "default" - ] - } - ] - } - ] -} diff --git a/src/apps/mobile/harmonyos/code-linter.json5 b/src/apps/mobile/harmonyos/code-linter.json5 deleted file mode 100644 index 073990fa45..0000000000 --- a/src/apps/mobile/harmonyos/code-linter.json5 +++ /dev/null @@ -1,32 +0,0 @@ -{ - "files": [ - "**/*.ets" - ], - "ignore": [ - "**/src/ohosTest/**/*", - "**/src/test/**/*", - "**/src/mock/**/*", - "**/node_modules/**/*", - "**/oh_modules/**/*", - "**/build/**/*", - "**/.preview/**/*" - ], - "ruleSet": [ - "plugin:@performance/recommended", - "plugin:@typescript-eslint/recommended" - ], - "rules": { - "@security/no-unsafe-aes": "error", - "@security/no-unsafe-hash": "error", - "@security/no-unsafe-mac": "warn", - "@security/no-unsafe-dh": "error", - "@security/no-unsafe-dsa": "error", - "@security/no-unsafe-ecdsa": "error", - "@security/no-unsafe-rsa-encrypt": "error", - "@security/no-unsafe-rsa-sign": "error", - "@security/no-unsafe-rsa-key": "error", - "@security/no-unsafe-dsa-key": "error", - "@security/no-unsafe-dh-key": "error", - "@security/no-unsafe-3des": "error" - } -} \ No newline at end of file diff --git a/src/apps/mobile/harmonyos/docs/adaptive-sheet-placement-design.md b/src/apps/mobile/harmonyos/docs/adaptive-sheet-placement-design.md deleted file mode 100644 index 72956d72b9..0000000000 --- a/src/apps/mobile/harmonyos/docs/adaptive-sheet-placement-design.md +++ /dev/null @@ -1,366 +0,0 @@ -# 折叠屏与宽屏的 Sheet 放置统一设计 - -Date: 2026-08-19 - -Scope: `src/apps/mobile/harmonyos` 的全部覆盖式 Sheet(设置、连接、会话详情、远程视图设置)在窄屏、宽屏、双折叠、三折叠和悬停态下的放置。不改会话 master-detail 几何、文件预览分栏、relay 协议和桌面端。 - -## 问题 - -这个 App 现在跑着**两套布局语言**。 - -会话面用的是一套成熟的折痕引擎:`ConversationLayoutPolicy` 读 `display.getCurrentFoldCreaseRegion()`,区分合盖、悬停、单折展开、双折展开、三折展开、无折痕宽屏六档,`FilePreviewPlacementPolicy` 还能让预览分界对齐第二道折痕。 - -Sheet 面用的是一个布尔: - -```ts -// AppShell.ets:203 -private shouldUseWideSheetLayout(): boolean { - return this.useWideLayout; -} -``` - -由此产生三个实际缺陷。 - -### 1. 540vp 宽度地板在折叠屏上必然溢出 - -```ts -// AppShell.ets:175 -private settingsSheetWidth(): number { - return Math.min(680, Math.max(540, Math.round(this.shellWidth * 0.48))); -} -``` - -`0.48` 的比例本身没问题:平板 1440vp 得 680,占 47%。出事的是 `540` 这个下限。Mate X7 展开态约 630–740vp,比例算出来是 302–355,被地板顶到 540 —— 占窗口 73%–86%,配合 `wideSheetHeight()` 的 `Math.max(560, h - 80)` 再占掉约 90% 的高度。一个「设置面板」变成了近乎全屏的遮挡。 - -**任何最小宽度在折叠屏上都是一个待触发的跨铰链缺陷。** 折痕围出来的物理叶片宽度不受设计意愿支配,视觉最佳宽度必须让位给物理边界。 - -### 2. `SheetType.CENTER` 把内容居中到铰链上 - -会话面花了很大力气让 master/detail 分界对齐折痕、让点击热区避开折痕安全区。Sheet 面则把一个 540vp 宽的面板**居中**到一块中间有铰链的屏幕上 —— 正好让分割线穿过面板正中。 - -这不是设置页独有的。现存 4 个函数、5 个 Sheet 全部如此: - -``` -AppShell.ets:167 wideCenterSheetOptions → 设置 Sheet + 连接 Sheet -AppSidebar.ets:678 sessionDetailsSheetOptions → 560 × 560 -RemoteSessionList.ets:750 sessionDetailsSheetOptions → 560 × 560 -AppRootPresentation:452 remoteViewSettingsSheetOptions → 560 × 520 -``` - -五个 Sheet 的宽度都 ≥ 540vp,都居中,在任何双折/三折展开态上都骑折痕。 - -(`AppSidebar.ets:668` 与 `RemoteSessionList.ets:740` 的 `sessionActionSheetOptions` 是 380/300 的普通底部 Sheet,不在此列。) - -### 3. 悬停态的底部 Sheet 横跨折痕 - -`useHoverOperate()` 判定悬停后 `largeScreenLayout` 为 false,Sheet 走 `bottomSheetOptions()` 的 `SheetSize.LARGE`(`AppShell.ets:159`),从屏幕底部一直铺到顶部,横穿那道横向折痕。 - -会话面对同一问题已有解: - -```ts -// ConversationView.ets:138-155 -FolderStack() { - Column() { this.ConversationBody() } // 第一个子节点 → 上半 display - Column() { this.Composer() } // 第二个子节点 → 下半 operate -} -.alignContent(Alignment.Bottom).enableAnimation(true).autoHalfFold(true) -``` - -上半显示、下半操作。Settings 全部是点击、选择、进二级页,是彻头彻尾的 operate 内容,应该落在下半屏。但那个 `FolderStack` 长在 `ConversationView` 里,而 Settings 是 `AppShell` 根上的 `bindSheet`,在它外面。 - -## 目标 - -1. 所有覆盖式 Sheet 的放置由**折痕数量与折叠姿态**决定,不由单一宽度布尔决定。 -2. 存在可用折痕时,Sheet 完整落在一块物理叶片内,不跨铰链。 -3. 悬停态 Sheet 完整落在 operate(下半)区,不横跨折痕。 -4. 放置决策收敛到一个可单测的纯 Policy,四处调用点共用同一个实现。 -5. 折叠形态切换时,Sheet 的当前子页与草稿不丢失。 - -## 非目标 - -- 不建注入式 `AdaptiveLayoutContext`。布局上下文是 Policy 的**入参值对象**,组件永远拿不到它。理由见「设计 / 为什么不注入」。 -- 不引入 `safeAreaInsets` 字段。`bindSheet` 与 `FolderStack` 自行处理安全区,当前无消费者;每多一个字段就多一个重建触发源。 -- 不为「物理 pane 小到放不下最低内容布局」设降级档位。720vp 三折的右叶约 352vp,与手机宽度同量级,现有紧凑行布局原样可用,加了是死代码。 -- 不把 Settings 塞进 `ConversationView` 的 `FolderStack`,也不为此重排根布局。 -- 不在本设计内改 `ConversationLayoutPolicy.useMasterDetail()` 的六参签名。参数摊平确实是技术债,但收编它会把会话布局的回归风险带进 Sheet 改动。等新 Policy 稳定后单独处理。 -- 不改会话 master-detail 几何、文件预览三栏分界、单屏抽屉动画。 - -## 当前逻辑 - -### 折痕探测已经集中,不需要重建 - -一个常见的误判是「折痕探测分散在各处,需要统一」。实际上探测只在一处: - -``` -AppRootPresentation.currentVerticalCreases() // :416 - └─ ConversationLayoutPolicy.verticalCreasesFromRects() // :124 -``` - -`ConversationLayoutPolicy` 和 `FilePreviewPlacementPolicy` 都是接收参数的纯函数,没有各自读 display。**分叉不在探测层。** - -真正的问题是参数摊平: - -```ts -useMasterDetail(viewportWidth, mediaQueryMatched, isFolded, creases, isExpandedFoldable, isHover) -``` - -六个位置参数,中间四个是布尔和数组。再加一个 `SettingsPlacementPolicy` 就是第三份同样的实参列表,任何一处传反编译器都不会报错。抽入参值对象的价值在这里。 - -### `AppShell` 拿不到几何 - -```ts -// AppRootPresentation.ets:113 -AppShell({ shellState: this.shellState, useWideLayout: this.isWideLayout(), ... }) -``` - -`AppShell` 只收到一个布尔。`viewportWidth`、`verticalCreases`、`foldStatus`、`isHoverLayout()` 全部停在 `AppRootPresentation` 里没往下传。 - -### 没有真正的横折痕概念 - -```ts -// ConversationLayoutPolicy.ets:143-145 -if (!spansViewportWidth && spansViewportHeight) { - mapped.push(new ConversationLayoutCrease(rect.top, rect.height)); -} -``` - -横向 rect 的 `top/height` 被塞进同一个「纵向折痕」数组,随后交给按宽度过滤的 `visibleCreases()`。这是一段旋转补偿启发式,不是横折痕支持。要算 operate 区高度必须拆出独立通路。 - -另外 `currentVerticalCreases()` 在合盖或悬停时直接返回 `[]`(`:417`),所以横折痕不能挂在同一个早退分支下。 - -## 设计 - -### 分档矩阵 - -| 环境 | 形态 | 尺寸来源 | -| --- | --- | --- | -| 窄屏竖屏 / 合盖 | Bottom Sheet | 现状 `SheetSize.LARGE` | -| 窄屏横屏 | Side Sheet | 约 45% | -| 平板宽屏,无折痕 | Side Sheet | `clamp(400, 0.32w, 520)` | -| 双折展开,一道纵向折痕 | Side Sheet | `w - c1.left - c1.width`,**无下限** | -| 三折展开,两道纵向折痕 | Side Sheet | `w - c2.left - c2.width`,**无下限** | -| 悬停 / 半折,有可用横折痕 | Bottom Sheet(FoldOperate) | `height = kindOperateHeight(h - (横折痕.top + 横折痕.height))`,UI 必须用 `height` 而不是未封顶的 `maxHeight` | -| 悬停 / 半折,只有可用纵折痕(书本折) | Side Sheet | 与展开态同一公式:`w - lastCrease.left - lastCrease.width`,**无下限**。书本折悬停的铰链仍是竖的,底部限高挡不住跨铰链 | -| 悬停 / 半折,折痕不可观察 | Bottom Sheet | 用当前窗口高度,**禁止** `floor(h/2)`。编造中线比诚实退回窗口更糟 | -| 折痕数据非法 | 当作没有折痕,走上面的无折痕决策树 | 不是「强制平板 400」。窄窗口配异常折痕必须仍能进 Bottom,不得溢出 | - -窄屏横屏固定 45%:横屏是唯一高度稀缺的场景,宽度多给没有收益。 - -### 入参值对象 - -新增 `pages/policy/AdaptiveLayoutInput.ets`: - -```ts -export class AdaptiveLayoutInput { - readonly viewportWidth: number; - readonly viewportHeight: number; - readonly foldStatus: number; - readonly isFolded: boolean; - readonly isExpandedFoldable: boolean; - readonly isHoverOperate: boolean; - readonly wideLayoutMatched: boolean; - readonly verticalCreases: ConversationLayoutCrease[]; - readonly horizontalCreases: ConversationLayoutCrease[]; -} -``` - -由 `AppRootPresentation.refreshWideGeometry()`(`:354`)一次构造,喂给 Policy,**只把解析结果往下传**。 - -#### 为什么不注入 - -ComponentV2 里把类实例作为 `@Param` 广泛注入有两个后果: - -1. 字段级变更不触发重渲染,必须整体替换对象,任何遗漏都是静默失效。 -2. 过度失效。一个含 `safeAreaInsets` 的上下文会让键盘弹起重建所有持有它的组件。 - -本仓库已经吃过一次这个亏: - -```ts -// AppShell.ets:26-32 -// ... this copy stayed mounted behind an opacity of 0 — invisible, but -// rebuilt on every selection change, which on a tablet doubled the cost -// of switching sessions. -``` - -所以:上下文是 Policy 的入参,不是组件的注入上下文。 - -### 放置 Policy - -新增 `pages/policy/SettingsPlacementPolicy.ets`,沿用 `FilePreviewPlacementPolicy` 的房规(枚举 + 全字段 readonly 类): - -```ts -export enum SettingsPlacementMode { Bottom, Side, FoldOperate } - -export enum SettingsSheetKind { Settings, Connect, SessionDetails, RemoteViewSettings } - -export class SettingsPlacement { - readonly mode: SettingsPlacementMode; - readonly width: number; // Side - readonly height: number; - readonly maxHeight: number; // FoldOperate -} - -static resolve(input: AdaptiveLayoutInput, kind: SettingsSheetKind): SettingsPlacement -``` - -ArkTS 不支持 TS 判别联合(`{ mode: 'side'; width: number } | { mode: 'bottom' }`),也不支持推断类型的对象字面量入参,因此不采用那种签名。 - -Policy 不引用任何 ArkUI 类型,`SheetOptions` 的组装留在组件里。 - -### 悬停态:限高,不改 FolderStack - -让 Settings 落进 `ConversationView` 的 `FolderStack` operate 半区,要么把全局 Settings 塞进会话组件(层级反了),要么为一个瞬态面板重排根布局。 - -等效且低一个量级的做法:**底部 Sheet 不动,把高度压进 operate 区。** - -`height ≤ viewportHeight - (横折痕.top + 横折痕.height)` 的底部 Sheet 物理上就完整落在下半屏,上半屏会话原样保留。视觉结果与 FolderStack 方案一致,实现只是一个高度数字。 - -这也是 `horizontalCreases` 字段存在的主要理由 —— 不是用来识别悬停态(`useHoverOperate()` 已经解决),而是在**铰链已经横过来**时算 operate 区高度。 - -书本折(Mate X7)展开态把铰链报成宽扁 rect(hidumper `0, 1064, 2496, 171` px,vp 约 `0,340,799x55`)。`classifyCreaseRects` 一次分类:能映射成纵折痕的 rect 不再进横向。否则同一道铰链在悬停态会被当成假横折痕,走出 FoldOperate 矮底栏,而不是右叶 Side。Sheet 入参必须使用探测到的原始纵折痕,不能复用 `currentVerticalCreases()` 的悬停清空。没有可用横折痕时不得把 `floor(viewportHeight / 2)` 当成 operate 区。 - -### 缺陷修复(2026-08-19) - -评审里有一条「测试通过但行为不存在」:`kindOperateHeight()` 写入了 `placement.height`,`AdaptiveSheetOptions` 的 FoldOperate 分支却把 `placement.maxHeight` 交给 `bindSheet`。会话详情 / 远程视图设置的 560 / 520 封顶永远到不了 UI。修复后 FoldOperate 与 Side、Bottom 一样只把 `placement.height` 写进 `SheetOptions.height`;`maxHeight` 只表达 operate 区天花板,供策略与测试断言。 - -非法折痕回退「无折痕宽屏档」的含义是:**假装折痕不存在,再走无折痕决策树**。宽视口才进 `clamp(400, 0.32w, 520)`;窄视口进 Bottom。`tabletSidePlacement` 额外把宽度 `min` 到 `viewportWidth`,任何 Side 宽度都不得大于窗口。 - -`SheetType.SIDE` 的贴边由 ArkUI 决定,API 20 文档写明:LTR 从右侧进、RTL 从左侧进,没有左/右开关。交叉检测用 trailing edge(`sheetLeft(placement, viewportWidth, isRtl)`),禁止写死 `right`。Side 宽度也按 trailing 叶:LTR 用最后一道折痕之后的剩余宽度,RTL 用第一道折痕的 `left`。窗口宽度 < 600vp 时 ArkUI 根本不接受 SIDE,策略不得在这种窗口返回 Side。 - -设置首页分组标题改用 `settings.general.section`(通用 / General)。`settings.language.section` 已无引用,删除。`settings.modelService.*` 只留给模型子页。 - -## 实施顺序 - -``` -T0 ─┬─→ T1 ─┬─→ T2 - │ └─→ T3(需 T3.1 先落地) - └───────────→ T4(T2 / T3 各自的验收门) -T5 独立 -``` - -### T0:止血,设置与连接 Sheet 不再骑折痕 - -- `AppShell` 新增 `@Param viewportCreaseLeft: number` / `@Param viewportCreaseWidth: number`(0 表示无折痕),由 `AppRootPresentation.ets:113` 从第一道可用纵向折痕传入。 -- 宽度:有折痕 → `shellWidth - creaseLeft - creaseWidth`,**不套最小宽度**;无折痕 → `clamp(400, 0.32 × shellWidth, 520)`。 -- `WIDE_SETTINGS_SHEET_MAX_WIDTH` / `WIDE_CONNECT_SHEET_MAX_WIDTH` / `WIDE_SHEET_MIN_WIDTH` 三个常量退役。 -- **暂不动 `SheetType.CENTER`**。宽度等于叶片宽度后,居中造成的偏差只剩半个铰链宽(8vp 量级),不再劈内容。SIDE 留到 T2 统一换。 - -可独立提交、独立上真机。 - -### T1:Policy 与入参对象 - -1. `AdaptiveLayoutInput.ets`。 -2. `SettingsPlacementPolicy.ets`,T0 的算式原样搬入,补齐窄屏横屏与悬停两档。 -3. `AppShell` 删除 `shouldUseWideSheetLayout()`(`:203`)、`settingsSheetWidth()`(`:175`)、`connectSheetWidth()`(`:185`)、`wideSheetHeight()`(`:192`)及相关常量,改收 `@Param placement: SettingsPlacement`,整体替换。 -4. 单测见「测试要求」。 - -### T2:`SheetType.CENTER` → `SheetType.SIDE`,四处统一 - -- Policy 返回 `Side` 时,四处 `SheetOptions` 一并换 `preferType: SheetType.SIDE`。 -- `AppSidebar.ets:678` 与 `RemoteSessionList.ets:750` 的两份 `sessionDetailsSheetOptions` 是重复代码,合并为共用实现。 -- `AppRootPresentation.ets:452` 的 560×520 同样接入。 -- `SheetType.SIDE` 为 `@since 20`,项目 `compatibleSdkVersion 6.0.1(21)` 满足。真机需确认贴边方向;不要把 `right` 写死,为将来的 RTL 留出口。 - -### T3:悬停态限高 - -1. **T3.1** `ConversationLayoutPolicy` 新增 `horizontalCreasesFromRects()`,与纵向通路分离。倾向新建一个横向折痕类而非复用 `ConversationLayoutCrease`:复用会让 `visibleCreases()` 这类按宽度过滤的工具在错误的轴上被误用。 -2. **T3.2** `AppRootPresentation` 用独立方法暴露横折痕,不受 `currentVerticalCreases():417` 悬停早退分支影响。 -3. **T3.3** Policy 返回 `FoldOperate` 与 `maxHeight`,`AppShell.bottomSheetOptions()` 用它替掉 `SheetSize.LARGE`。 - -### T4:形态切换连续性 - -见「风险与未知」。这不是一个独立步骤,而是 T2 与 T3 各自必须通过的验收门。 - -### T5:信息架构收敛(纯视觉,可任意时机插入) - -- 设置分三组:账号 / 通用(语言 + 模型)/ 关于。 -- 设置首页分组标题用 `settings.general.section`(通用 / General),不再复用 `settings.modelService.section`。同步改 `ZhCnMessages` / `EnUsMessages`,`I18nUnit.test.ets` 的键对齐测试兜底。 -- 关闭按钮从 50×50 带阴影降为 40×40 无阴影(`SettingsSheet.ets:109-124`)。 -- **不需要**移除「个人资料」分组标题 —— 该标题本就不存在,`SettingsHome()` 中 `AccountEntry()`(`:91`)直接跟在大标题之后。 - -## 风险与未知 - -### 形态切换时 `preferType` 变更的行为未知 - -用户在展开态打开 SIDE Sheet,随后合盖:`largeScreenLayout` 翻转,placement 由 `Side` 变 `Bottom`。`bindSheet` 的 `preferType` 在已呈现状态下变更,可能闪烁、可能保持旧形态、可能直接关闭。**当前无任何依据可以预判。** - -这不是理论风险。`wide-conversation-navigation-design.md` 的「待验证」已经挂着「三屏与双屏之间的真实折叠切换连续性」,会话层自己尚未验证;Sheet 层引入同样的形态切换,是同一个洞的第二个入口。 - -必须在真机上验三条: - -1. 展开态 SIDE Sheet → 合盖。 -2. 悬停态限高 Sheet → 完全展开。 -3. 双折 ↔ 三折切换。 - -若观察到闪烁或残留,回退方案是**形态切换时先关闭 Sheet、再按新形态重开**,代价是必须把状态提升。该决定等真机结果,不预设。 - -### Sheet 状态在重建时会丢 - -`SettingsSheet.@Local page`(`:49`)与三个 `savedGeneralChat*`(`:50-52`)都是组件内状态。Sheet 一旦重建,用户当前停在概览 / 账号列表 / 本机编辑器哪一页、以及本机编辑器里的草稿,全部丢失。 - -无论 T4 的结论如何,这两项都必须在形态切换后保留,作为 T1 的验收项,不等真机撞出来再补。 - -## 验收矩阵 - -| 场景 | 预期结果 | -| --- | --- | -| 窄屏竖屏,打开设置 | 与改动前完全一致的底部 Sheet | -| 窄屏横屏,打开设置 | 侧边 Sheet,约 45% 宽 | -| 平板无折痕(MatePad Pro 1440vp) | 侧边 Sheet,461vp,比改前的 680 窄 | -| 双折展开(Mate X7),打开设置 | Sheet 左缘 ≥ 折痕右缘,完整落在右叶。2026-08-19 真机:`rects=[0,340.48,798.72x54.72]` → `side 312x627`,`SheetPage [1235,122][2210,2416]`,左缘贴折痕右缘 1235px | -| 双折展开,打开连接 Sheet | 同上 | -| 双折展开,打开会话详情 | 同上,不再是居中的 560×560 | -| 双折展开,打开远程视图设置 | 同上,不再是居中的 560×520 | -| 三折完整展开(两道折痕) | Sheet 完整落在第二道折痕之后的右屏 | -| 悬停态,有横折痕,打开设置 | Sheet 高度为 `placement.height`(kind 封顶后的 operate 区),上半会话可见 | -| 悬停态,只有竖折痕(书本折) | Side Sheet 落在 trailing 叶:LTR 为最后一道折痕之后,RTL 为第一道折痕之前。分类必须走真实 rect 管线,不得手填 `horizontalCreases: []` | -| 折叠单屏,全部 Sheet | 与改动前完全一致 | -| 展开态开着设置 → 合盖 | 不闪烁、不残留;当前子页与草稿保留 | -| 悬停态开着设置 → 展开 | 同上 | -| 双折 ↔ 三折切换,Sheet 开启中 | 同上 | -| 折痕数据缺失 / 非法 | 回退到无折痕宽屏档,不阻断渲染 | - -## 测试要求 - -### 自动化 - -在 `ArchitectureUnit.test.ets` 为 `SettingsPlacementPolicy` 增加纯逻辑测试,覆盖八档: - -1. 窄屏竖屏 -2. 窄屏横屏 -3. 无折痕宽屏(平板) -4. 一道纵向折痕 -5. 两道纵向折痕 -6. 折痕偏到极端位置(叶片极窄) -7. 折痕数据非法(负宽、越界、坐标在内容区外) -8. 悬停态(横折痕限高、无折痕不编造、书本折走纵折痕 Side) - -对齐现有 `ConversationLayoutPolicy` 的标准:新增行、函数、分支覆盖率均为 100%。 - -另需断言:任一档位下 Policy 的返回宽度都不与折痕区间相交。 - -### 构建 - -```bash -source scripts/ohos-env.sh -"$OHPM" install -"$HVIGORW" --mode module -p module=entry assembleHap --no-daemon -``` - -### 真机手工验证 - -在 HUAWEI Mate X7(`DEL-AL10`)覆盖双折展开、折叠单屏、悬停三态;在 HUAWEI MatePad Pro(`WEB-W00`)覆盖无折痕宽屏。三折两道折痕的完整展开态目前无对应真机,与 `wide-conversation-navigation-design.md` 的同一项一并挂起。 - -浅色与深色均需验证。 - -## 完成标准 - -只有同时满足以下条件才视为完成: - -- 五个 Sheet 全部通过同一个 `SettingsPlacementPolicy` 决定放置。 -- `AppShell.shouldUseWideSheetLayout()` 及三个宽度常量已删除。 -- 存在可用折痕时,任一 Sheet 的边界都不与折痕区间相交。 -- 悬停态 Sheet 完整落在 operate 区。 -- 折叠形态切换时 Sheet 的当前子页与草稿不丢失。 -- 窄屏与折叠单屏验收矩阵全部与改动前一致。 -- 八档单测通过,覆盖率达标;HarmonyOS 构建通过;两台真机手工验证有记录。 diff --git a/src/apps/mobile/harmonyos/docs/harmonyos-i18n-design.md b/src/apps/mobile/harmonyos/docs/harmonyos-i18n-design.md deleted file mode 100644 index 30a2ff5698..0000000000 --- a/src/apps/mobile/harmonyos/docs/harmonyos-i18n-design.md +++ /dev/null @@ -1,52 +0,0 @@ -# HarmonyOS 手机端 i18n 设计 - -Date: 2026-08-18 - -Status: Implementation - -Scope: `src/apps/mobile/harmonyos` - -## 问题 - -鸿蒙手机端已有 `RemoteI18n.t/f/f2`,但只有一份写死的简体中文词表,没有语言状态、没有持久化、设置页也没有入口。因此界面无法切换中英文。 - -## 目标 - -- 产品内支持规范 locale:`zh-CN`、`en-US`。 -- 设置页可显式切换,切换后当前界面立即刷新。 -- 用户选择写入本机 preferences,冷启动恢复;首次启动按系统语言解析,解析不到则用 `zh-CN`。 -- 系统权限文案、语音识别语言、相对/绝对时间、错误分类都跟随当前语言。 -- 不引入 Web UI / mobile-web 的词库。locale id 与别名规则对齐共享合同。 - -## 结构 - -| 单元 | 职责 | -|---|---| -| `i18n/AppLocale` | 规范 id、别名解析、fallback、展示名 | -| `i18n/ZhCnMessages` / `EnUsMessages` | 各语言完整 key 词表,key 必须一对一 | -| `i18n/AppLocaleState` | `@ObservedV2` 语言身份,供 ArkUI V2 订阅 | -| `i18n/RemoteI18n` | 查找、插值、跨语言匹配、日期格式;`t()` 读取 `@Trace language` | -| `services/LocalePreferenceStore` | preferences 持久化、系统语言探测、`setAppPreferredLanguage` | -| `pages/viewmodel/LocaleController` | 初始化与切换;切换后刷新已落地的连接/服务状态文案 | -| `pages/components/LanguageSettingsPanel` | 设置里的中/英选择面板 | - -## 数据流 - -1. `AppRootRuntime.aboutToAppear` 先初始化 `LocaleController`。 -2. 已保存的语言优先生效;否则解析系统语言并写入。 -3. `RemoteI18n.setLanguage` 更新 `AppLocaleState.language/revision`,UI 通过 `t()` 的 `@Trace` 读取重建。 -4. 设置页调用 `onSetLanguage` → `LocaleController.setLanguage` → 持久化 + 应用首选语言 + 刷新派生状态文案。 - -## 错误匹配 - -`ConnectionErrorPolicy` / `GeneralChatServiceStatus` 不得只对比当前语言译文。用 `RemoteI18n.textEquals` / `textContains` 对 `zh-CN` 与 `en-US` 同时匹配,避免切换语言后把旧错误文案认丢。 - -## 远程场景 - -本能力是控制器本机 UI 语言,不代理到桌面、不随 Peer/Dispatch 同步。远程工作区路径、协议字段保持不变。语音识别语言跟随本机 UI locale。 - -## 验证 - -- 词表 key 对等、别名解析、切换/回退、跨语言错误匹配、时间格式的本地单测。 -- `pnpm run harmony:architecture` -- HarmonyOS LocalTest + `assembleHap` diff --git a/src/apps/mobile/harmonyos/docs/mobile-control-console-design.md b/src/apps/mobile/harmonyos/docs/mobile-control-console-design.md deleted file mode 100644 index ca7af5acfe..0000000000 --- a/src/apps/mobile/harmonyos/docs/mobile-control-console-design.md +++ /dev/null @@ -1,329 +0,0 @@ -# HarmonyOS 侧栏跨设备工作区设计 - -Date: 2026-08-18 - -Scope: `src/apps/mobile/harmonyos`。不改 relay、桌面端、CLI 和 -`src/crates/services/services-integrations/src/remote_connect.rs` 的远程命令合同。 - -## 实施状态 - -截至 2026-08-18:五阶段代码已接到侧栏两个宿主与冷启动回填;`harmony:architecture`、 -`assembleHap`、LocalTest、`theme:color-audit:all`(浅色深色)全部通过,并已装到真机 -`5ZU0226202001116`。「验证要求」里的六项真机手测在两台在线桌面上全部走过并通过。 - -2026-08-25 补齐二维码与账号设备的统一投影:二维码目标也固定画设备头;目标 `deviceId` -已在账号目录时复用该真实设备行,不在目录时作为临时设备置顶,同时保留账号下其他电脑。 -鸿蒙仍是单活动控制目标,这次只统一导航树,不改变传输拓扑。 - -第 4 项(跨设备打开会话)第一次跑是失败的,成因和修法记在这里,因为它牵出的是一处传输层 -缺陷而不是 UI 疏漏:目标桌面不应答时,`AccountDeviceCommandTransport.send` 把调用方给的 -timeout 整个丢掉,一律吃 `deviceRpc` 写死的 130 秒,于是一次失败的设备切换要挂满两分钟, -其间既没有等待态、失败后也没有把控制目标退回原设备。三处修完:timeout 从 -`AccountDeviceCommandTransport` 一路传到 `deviceRpc`;`connectAccountDevice` 的握手单独用 -`ACCOUNT_HANDSHAKE_TIMEOUT_MS = 15000`(握手的沉默意味着桌面没了,不是桌面忙); -`RemoteCreateFlowController.ensureRemoteControlTarget` 在切换点弹一次 -`remote.settings.deviceSwitching` 吐司,`SettingsController` 在切换失败后调 -`restoreControlTarget()` 回到切换前那台(`restorableControlTarget()` 必须在 teardown -清空状态**之前**取快照)。复验用 `kill -STOP` 冻住 Mac 桌面制造「relay 仍报在线、桌面不 -应答」这一模一样的条件:T+4 s 屏上是「正在恢复连接 · 正在连接」,T+16 s 头部退回原设备。 -日志的三行时间戳对得上——`device rpc cmd=get_workspace_info` 15:33:32.534、 -`account device handshake failed … Operation timeout` 15:33:47.547(15.0 秒,不是 130)、 -`control target restored device=3fa42461…` 15:33:48.576。 - -第 5 项(在第二台新建会话不搬动那台桌面的工作区)在真机上验了,通过,四条证据互相独立: -桌面日志只有 `Session created`,没有任何 `open_workspace`;`workspace_data.json` 虽在同一秒 -被改写,但 `current_workspace_id` 内容没变(**看内容不看 mtime**,只看 mtime 会误判成失败); -新会话落在被点的那个工作区目录下,说明测试不是空转;手机侧 `get_workspace_info` → -`create_session` 全程 0.5 秒,中间没有 `set_workspace`。 - -同一轮真机验证暴露并已修的是在线判定,共三处:relay 的 presence 会谎报离线、宽屏根本不刷新 -presence(见「4. 拉取策略」后两条),以及 `ForEach` 键撞车导致活动设备那一行永远渲染摊平占位 -对象(见「3. 每台设备一个组件实例」末段)。第三处才是「明明连着却灰着」的直接原因——前两处修完, -模型里 `online` 已经是 `true`,画面照旧是灰的。冷启动复验:活动桌面亮起并默认展开,列出自己的 -工作区与会话。 - -## 背景 - -手机端今天是"多设备可切换,单设备活动":整个远控界面在任意时刻只面向一台桌面。侧栏的 -工作区分区因此只能展示**当前那一台**机器的工作区;想看另一台上的东西,必须先把全局控制 -目标切过去,切过去之后前一台就从视野里消失了。 - -这不是中控。中控的最低要求是:**账号下所有桌面上的工作区和会话,同时可见。** - -导航面本身已经具备承载这件事的形状。`dd0d89dfe` 把侧栏从"先选来源(本地 / Remote)再看 -内容"的分段选择器,重构成了一条统一的滚动流——上半是会话时间线,下半是工作区分区,工作 -区分区由宿主通过 `@BuilderParam` 注入,侧栏本身不认识远程状态。`107cac595` 又把"连接电脑" -这一行从 `AppRoute.RemoteHome` 改接到连接面板上,因为那个路由的宽屏详情面只是一块没有任何 -控件的占位。 - -所以本设计不新增页面。**多设备这一层长在既有的 `SidebarWorkspaceSection` 上**:设备成为 -工作区之上的一层分组。分区标题一律为「设备」;账号设备和二维码配对都画设备头,优先使用 -`listDevices` 的真名,不用「未连接」这种连接状态顶替设备名。二维码目标按 `deviceId` 与账号 -目录合并;目录里没有它时保留为临时设备行。离线设备默认收成灰行,缓存只在用户展开后出现。 - -## 目标 - -- 侧栏工作区分区呈现账号下**所有**桌面设备的工作区与会话,层级为「设备 > 工作区 > 会话」。 -- 展开一层只预览 3 条:点开设备不列出全量工作区,点开工作区不列出全量会话;「还有 N 个」每次再展开 3 条,不一次铺开。 -- 浏览另一台设备的内容不需要任何显式的"切换控制设备"动作。 -- 浏览和创建都不改变被观察那台桌面自己正在打开的工作区。 -- 账号桌面与二维码桌面都画设备头;同 `deviceId` 合并,异 `deviceId` 并存。 - -## 非目标 - -- **不做跨设备运行状态**。见下表:远端会话列表协议不携带执行状态,做"运行中 / 待授权 / - 失败"必须先改后端。会话行的绿点继续只表示**当前活动设备**正在跑的那一轮,因为那是手机 - 唯一真知道的事。 -- **本轮不做 Detached Dispatch**,它需要新增跨端命令族,超出这份文档「不改远程命令合同」 - 的范围。手机怎么从中控位置上把一台机器的活派到另一台去,见 - [`mobile-detached-dispatch-design.md`](mobile-detached-dispatch-design.md)。 -- **不做多设备并发对话**。对话面仍然一次一台:点开另一台的会话时自动切换控制目标,切换 - 是隐式的,但仍然是切换。 -- 不改 relay、不改桌面/Android/iOS、不新增或放宽任何远程命令。 - -## 已核实的基线事实 - -这一节是后续裁决的依据,每条都对应可复查的代码位置,按当前 `main` 核对。 - -| 事实 | 依据 | 对设计的影响 | -|---|---|---| -| 账号设备传输已经是无状态、按设备寻址的一次性加密 HTTPS RPC | `services/CloudAccountClient.ets:264` `deviceRpc(relayUrl, session, targetDeviceId, command)` | 跨设备并行观察不需要新传输,也不需要 relay 改动 | -| 账号设备"连接"没有服务端状态,只是构造 transport 后发两条 RPC | `services/RemoteSessionManager.ets:115` `connectAccountDevice` | "连接一台设备"是 UI 概念,不是资源占用 | -| 单设备约束落在一个字段上 | `services/RemoteSessionManager.ets:33` `private transport?` | 解除单活动设备是手机端重构,不是协议问题 | -| 全局只有一个控制目标 | `pages/state/RemotePageState.ets:30` `controlTargetDeviceId` | 该字段的语义要收窄为"我正在对话的那台",而不是"手机现在归谁" | -| 切换设备会停轮询、清空 workspace / session / timeline 再连新设备 | `pages/viewmodel/SettingsController.ets:426` `selectCloudAccountDevice` | 跨设备打开会话可直接复用它,不需要新写连接逻辑 | -| 设备列表已携带在线状态 | `services/CloudAccountClient.ets:247` `listDevices`,`:259` 逐台带出 `online` | 离线设备可以只画不拨,避免一串 130s 超时 | -| 跨工作区扇出已存在,并已做并发上限 | `services/ConcurrentWorkspaceListing.ets:14` `CONCURRENT_WORKSPACE_LISTINGS = 4`、`services/RemoteWorkspaceCoordinator.ets:41` `sessionsForWorkspaces` | 加设备维度是复用这套批量语义,不是新写扇出 | -| 会话列表和聊天记录的本地库已按 `device_key` 分区 | `services/RemoteSessionListRdbStore.ets:26`、`services/RemoteChatLocalRdbStore.ets:30` | 多设备缓存不需要迁移主键,今天只是从没写过第二行 | -| `CreateSession` 直接绑定入参 `workspace_path`,不依赖宿主活动工作区 | `remote_connect.rs:1295` 的 `binding_workspace` | 手机建会话时的 `set_workspace` 是手机端遗留,可以去掉 | -| 手机建会话会先切换宿主活动工作区(本轮已修,此行记录改前基线) | 改前 `pages/viewmodel/RemoteSessionViewModel.ets` 的 `createSessionInWorkspace` 调 `onSelectWorkspace`;修后见 `:147`,该分支已删除(`316f66d5b`) | 会打扰坐在那台机器前的人,中控前必须先修 | -| 新建流程里"选设备"实际是切换全局控制目标,且提交时要求所选设备等于当前活动设备 | `pages/viewmodel/RemoteCreateFlowController.ets:186`、`:211` | 设备选择被当成了主导航,这正是要消除的 | -| 远端会话摘要不含执行状态 | `remote_connect.rs:1827` `SessionInfo` 无 status 字段;`services/RemoteResponseMapper.ets:67` 因此一律填 `'idle'` | 跨设备"在跑什么"做不了,必须先改后端,本轮排除 | -| `ListSessions` 强制要求非空 `workspace_path` | `remote_connect.rs:1252` | 没有设备级列表,只能按工作区扇出 | -| 侧栏会话投影缓存是**单槽**的 | `pages/policy/SessionListProjection.ets:304` | 一个实例服务多台设备会每次 rebuild 都 miss,必须一设备一实例 | -| 工作区分区由宿主注入,侧栏不认识远程状态 | `pages/components/AppSidebar.ets:56` `@BuilderParam contentSlot` | 加设备层不会把远程状态漏进 `AppSidebar` | -| 同一个工作区分区被两个宿主复用 | `pages/components/AppRootOverlaySurfaces.ets:58`、`pages/components/WideConversationHost.ets:184` | 改参数必须两处同步,窄屏和宽屏语义一致 | - -## 设计 - -### 1. 观察面按设备扇出,对话面仍单设备 - -关键事实是 `deviceRpc` 本来就是无状态的:每次调用自带 relayUrl、账号 session 和目标 -deviceId,直接 POST 到 `/api/devices/{id}/rpc`。今天的跨工作区扇出之所以要经过 -`RemoteSessionManager`,只是因为它恰好握着那唯一一个 transport,而不是因为列工作区、列会话 -需要连接状态。 - -因此**不动** `RemoteSessionManager` 的单 transport 模型。它同时拥有 `this.workspace`、轮询 -和聊天,把它改成 transport 表会让一条读路径的改动波及所有写路径。取而代之,新增一个只读的 -目录服务,按设备现场构造 `AccountDeviceCommandTransport`,只发两条只读命令 -(`list_recent_workspaces`、`list_sessions`),与活动连接完全隔离。 - -```mermaid -flowchart LR - S["SidebarWorkspaceSection
设备 > 工作区 > 会话"] - V["DeviceDirectoryViewModel
展开 / 折叠 / 重试"] - C["DeviceDirectoryCoordinator
懒加载扇出 · 批量并发 · 每设备容错"] - D["AccountDeviceDirectory
按 deviceId 建只读 transport"] - A["活动设备
RemotePageState"] - B["其他在线设备
deviceRpc"] - O["离线设备
只画不拨"] - - S --> V --> C --> D - C -->|"零 RPC,直接读"| A - D -->|"list_recent_workspaces
list_sessions"| B - D -.->|"不发起"| O -``` - -分工上,**活动设备**那一组的数据仍旧来自 `RemotePageState`(它已经加载好了,且要跟着轮询 -实时更新),目录服务只负责其余设备。这样活动设备不会出现两份互相打架的副本。 - -### 2. 分层 - -| 文件 | 动作 | 职责 | -|---|---|---| -| `services/AccountDeviceDirectory.ets` | 新增 | 按 deviceId 建只读 transport,只发 `list_recent_workspaces` / `list_assistants` / `list_sessions` | -| `services/DeviceDirectoryCoordinator.ets` | 新增 | 懒加载扇出、批量并发、每设备与每工作区各自容错 | -| `pages/state/DeviceDirectoryState.ets` | 新增 | `@ObservedV2`,与 `RemotePageState` 并列的目录快照 | -| `pages/viewmodel/DeviceDirectoryViewModel.ets` | 新增 | 展开 / 折叠 / 重试意图 | -| `pages/components/SidebarDeviceGroup.ets` | 新增 | 一台设备一个组件实例 | -| `pages/components/SidebarWorkspaceSection.ets` | 改 | 顶层从工作区列表变为设备列表 | - -`RemotePageState` 的语义**不变**:它继续表示"我现在正在对话的那台设备"。目录是另一个状态 -对象,而不是往一个 per-active-device 的类里塞 per-device 缓存——那会让每个既有字段都要重新 -回答"这是哪台机器的"。 - -### 3. 每台设备一个组件实例 - -`SessionListProjectionCache`(`pages/policy/SessionListProjection.ets:304`)是**单槽**缓存: -它只记得上一次的标量键与两个数组的引用/指纹,命中才返回同一个投影实例。而标量键里就含 -`workspacePath` / `workspaceName`,所以一个实例轮流服务多台设备必然每次都 miss,退回全量 -`SessionListProjector.project()`。按它自己的注释,这个缓存存在的理由正是让"选中一个会话" -这种不改输入的重建退化成属性 diff,而不是重算整棵列表。 - -所以把设备组抽成 `SidebarDeviceGroup` 这个 `@ComponentV2`,每个实例持有自己的 -`projectionCache`,天然做到一设备一缓存。`WorkspaceGroup` / `SessionRow` / `MoreSessionsRow` -三个 `@Builder` 从 `SidebarWorkspaceSection` 原样平移进来,逻辑不变,只多一级缩进。 - -**`ForEach` 的键必须区分临时设备行**。`ForEach` 把子组件绑定在它**首次创建时**的那个 item 上, -只有键变了才会重新读 item。二维码刚连上而账号目录尚未返回时使用 `transientEntry`;它带的正是 -控制目标自己的 deviceId,所以无前缀会与稍后落地的真实设备行撞键。`deviceKey()` 给临时行加 -`transient:` 前缀;同一设备进入账号目录后键发生变化,子组件才能重建到账号持有的可观察对象上。 -注意这类失效只发生在 **`ForEach` 里实例化的子组件**上;`@Builder` 渲染的行随父组件重建, -不受影响。 - -`SidebarWorkspaceSection` 退化为"设备列表 + 分区头"。所有桌面都画设备头;账号目录是基础列表, -活动控制目标不在目录时作为临时设备置顶,在目录中时直接复用真实行。这样账号状态与二维码通道 -可以并存,但同一台电脑不会重复出现,用户也始终能看见工作区属于哪台机器。 - -### 4. 拉取策略:展开才拉,离线不拨 - -- 离线设备默认只画一个带真名的灰行,永不发 RPC。`deviceRpc` 的读超时是 130 秒 - (`CloudAccountClient.ets:291`),一台离线机器就足以让整个分区看起来是坏的。 -- **活动设备**默认展开,数据来自 `RemotePageState`,零额外 RPC。 -- 在线状态本身也要刷新,而且**不能只靠事件驱动**。设备列表过去只在冷启动拉一次,于是启动 - 之后才上线的桌面会一直灰着,直到 app 被杀掉重启。回到前台与打开侧栏各触发一次 - `refreshAccountDevicesIfStale`(15 秒内的答案视为仍然新鲜——够短,让一台刚上线的桌面在同一 - 次使用里就变亮;够长,让冷启动时同时发生的两个事件只花一次请求)。但「打开侧栏」这个事件 - 只存在于窄屏:宽屏把 `AppSidebar` 常驻在 `WideConversationHost` 的主栏里,`openAppSidebar` - 永远不会触发,于是最需要它的那块屏反而一次都不刷新。relay 也没有推送 presence 的通道。 - 因此另加一个前台轮询 `SettingsController.startPresencePolling()`(`PRESENCE_POLL_INTERVAL_MS` - = 20 秒一拍,复用 `RemoteHeartbeatController` 的丢重叠语义),由 `AppRootRuntime` 的 - `onPageShow` 起、`onPageHide` / `aboutToDisappear` 停——页面不在屏上就没有东西会过期。 - 轮询器放在 `SettingsController` 而不是 `AppRootRuntime`:presence 的其余部分本来就归它, - 而 `AppRootRuntime` 只剩 5 行预算(上限 500),把定时器塞进去会顶破架构检查。 -- **有活链路时不听 relay 的**。relay 的 `online` 是内存连接注册表的投影 - (`relay-service/src/db.rs:251`),会滞后、也会丢条目:真机上出现过 `/api/devices` 报 - `online=false`,而同一台桌面每 15 秒的 `cmd=ping` 都返回 200。手机对「我正连着的那台」有 - 第一手证据,所以 `syncDevices` 里活链路压过 relay 的答案。这条规则求值于**列表被发布的那 - 一刻**,因此链路刚变活时必须重新发布一次(`SettingsController.resyncAccountDevicePresence()`, - 不发请求,只是把缓存的同一份列表再读一遍)——冷启动的设备列表往往先于重连落地,那一次拉回 - 来的答案正是「离线」。发布点唯一,视图层不复制这条规则,否则两处会各自腐烂。 -- 其他在线设备默认折叠。首次展开触发 `list_recent_workspaces` + `list_assistants`,再对该 - 设备的工作区路径批量 `list_sessions`。磁盘回填是 `cached`:先画出来,展开后仍要被 RPC - 覆盖,不能把缓存当成已经加载完。 -- 数据可以一次拉全,画面不能一次铺开。点开设备只预览 3 个工作区(工作区行默认收起), - 点开工作区只预览 3 条会话;「还有 N 个」每次再展开 3 条。活动设备默认展开。 - 磁盘缓存仍存该设备的完整工作区/会话快照,不按预览窗口裁切;「还有 N 个」和继续展开 - 都靠这份全量,预览游标只活在组件 `@Local` 里,冷启动回到第一批 3 条。 -- 批量并发复用 `RemoteWorkspaceCoordinator` 已有的形状(一次 4 个,按给定顺序合并,因此 - 调宽批量只改耗时不改结果)。把那段循环提成共享 helper 由两边调用,而不是复制一份。 -- 容错分两级,与既有实现一致:一个工作区读不出来只丢那一个工作区(既有注释:一个读不了的 - 工作区不构成丢掉另外二十个的理由);整台设备失败只把该设备标为 `failed` 并给一行重试, - 不影响其余设备。**失败必须可见**——设备从聚合结果里静默消失,比报错更糟。 - -### 5. 打开另一台设备上的会话 - -`RemoteSession` 增加可选字段 `deviceId?`,由目录协调器在映射之后盖章,`RemoteResponseMapper` -不用改(它映射的是线上报文,而设备身份是调用方才知道的事)。侧栏的打开动作变为:会话属于 -非活动设备时,先复用 `selectCloudAccountDevice` 完成整套连接与状态置换,再打开会话; -`navigateHome` 传 `false`,因为路由由打开会话本身负责。 - -这条边界要在文案上说清楚:**看是多设备的,聊是单设备的**。点开另一台机器上的会话会把手机 -的对话通道移过去,这是真实发生的事,不能假装没有。 - -切换要有始有终,两头都要有交代。**开头**:`ensureRemoteControlTarget` 是唯一的切换缝 -(打开会话与工作区内新建都走它),在那里弹一次 `remote.settings.deviceSwitching`,否则 -用户面对的是一段没有任何解释的静止界面。**结尾**:切换失败必须回到切换前那台,而不是把 -手机留在一个既没连上新设备、也不再轮询旧设备的悬空态。快照要在 teardown 清状态之前取 -(`restorableControlTarget()`),恢复本身带一个 `restoringControlTarget` 重入位——要恢复 -的那台也死了时不能来回互拨;恢复也不关用户自己打开的面板,只有用户主动选设备的那条路径 -才走 `navigateHome`。 - -**握手的超时必须自己给**。`AccountDeviceCommandTransport` 过去把调用方的 timeout 丢了, -一律用 `deviceRpc` 的 130 秒;那是给「桌面在唤醒冷进程」留的耐心,不该套在握手上——握手 -沉默说明桌面不在了。所以 `connectAccountDevice` 的第一条 `get_workspace_info` 用 -`ACCOUNT_HANDSHAKE_TIMEOUT_MS = 15000`,失败经 `handshakeFailure()` 归一成 -`remote.settings.deviceUnavailable`,原始报文只进日志。这条尤其容易复发:relay 的 -`online` 在桌面进程被冻住时仍然报 `true`(socket 没断),所以「设备在线」永远不能当成 -「设备会应答」的保证。 - -`AppRootRuntimeComposition` 中按 `item.id` 去重的两处要改成按 `deviceId + id` 去重——不同机器 -上的会话 id 理论上可以撞,撞上时静默丢一条是最难查的那类 bug。 - -### 6. 持久化 - -会话列表的本地表已经是 `device_key TEXT PRIMARY KEY`,存 N 行不需要改主键。需要新增的只有 -工作区快照: - -```sql -CREATE TABLE IF NOT EXISTS remote_device_workspaces ( - device_key TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER NOT NULL) -``` - -并把 `RemoteSessionListRdbStore` 的 `SCHEMA_VERSION` 从 1 提到 2。缓存按定义可重建,提版本 -会丢掉旧的 `remote_session_list`——这正是那个常量注释所说的用法,代价是一次冷启动多拉一遍。 - -冷启动时按已知设备逐个回填,让展开过的设备先显示缓存、再被 RPC 覆盖。缓存回填把 -状态标成 `cached`,不是 `ready`:`ready` 只表示这一轮 RPC 已经结束。浏览另一台桌面 -时走 `saveObservedList`,**不得**改写 `last_device_key`——那个指针只属于当前控制目标, -冷启动 `restoreLast()` 必须和自动重连瞄准同一台机器。 - -切换控制目标前,必须在 teardown 清空 live 列表之前把当前工作区/会话快照写进该设备的 -目录行(`captureLive`);空列表不能覆盖已有快照。活动设备的目录行不再被标成 -`ready` + 空数组,否则它一旦不再活动就会永远跳过拉取。 - -## 前置修复:创建会话不该改动宿主的活动工作区 - -`createSessionInWorkspace` 在目标工作区与当前工作区不同时,会先 `onSelectWorkspace(path)`, -也就是**手机改掉了那台桌面正在打开的工作区**。而 `CreateSession` 本来就直接绑定入参 -`workspace_path`,这次 `set_workspace` 是多余的。 - -单设备下这只是有点粗鲁;多设备中控下它是错的——在 B 机器上开个会话不该把 B 的界面挪走。 - -修法:`CreateSessionOptions` 增加 `workspacePath?`;`RemoteSessionManager.createSession` 用 -`options.workspacePath` 兜底到当前工作区(`RemoteCommandFactory.createSession` 本来就收路径 -参数,不用改);`createSessionInWorkspace` 删掉切换工作区的分支及其后的 -`workspacePath === path` 守卫,失败恢复路径相应简化。 - -这一步独立可验收,先做。 - -## 阶段划分 - -**阶段一:前置修复。** 创建不搬工作区。改动三个文件,独立验收。 - -**阶段二:目录服务与状态。** `AccountDeviceDirectory`、`DeviceDirectoryCoordinator`、 -`DeviceDirectoryState`、`DeviceDirectoryViewModel`;抽出共享的批量 helper; -`RemoteSession.deviceId`。此阶段无 UI 变化,由单元测试覆盖。 - -**阶段三:侧栏设备层。** 抽出 `SidebarDeviceGroup`;`SidebarWorkspaceSection` 顶层改为设备 -列表,账号桌面无论几台都画设备头;两个宿主同步改参数;新增设备离线、加载失败重试、"还有 N 台设备" -的文案键。 - -**阶段四:跨设备打开会话。** 打开前置切换;去重键改为 `deviceId + id`;工作区内新建同样带上 -设备身份。 - -**阶段五:持久化。** 新增工作区表、`SCHEMA_VERSION` 提到 2、冷启动逐设备回填。 - -## 验证要求 - -各阶段标记完成前至少需要: - -- 架构检查:`pnpm run harmony:architecture` 通过。新增文件必须守住既有边界——`services/**` - 不 import `../pages/`;`pages/components/**` 不 import `pages/viewmodel/`(设备组只吃 - `@Param` 与 `@Event`);新组件用 `@ComponentV2`;Actions / Hooks 用具名接口加对象字面量。 -- 单元测试(`entry/src/test`,LocalTest):一台设备抛错时其余设备结果完整返回;批量 helper - 的合并顺序与批宽无关;离线设备不产生任何 RPC;`deviceId + id` 去重下两台设备的同 id 会话 - 都保留。 -- 构建与本地测试: - - ```bash - source scripts/ohos-env.sh - "$HVIGORW" --mode module -p product=default -p module=entry@default assembleHap --no-daemon - "$HVIGORW" --mode module -p module=entry@default -p ohos.test.type=LocalTest test --no-daemon - ``` - -- 真机手工验证(需要账号下至少两台桌面): - 1. 只有一台账号桌面时仍画设备头,名称是桌面真名,不是「未连接」; - 2. 两台在线时,展开第二台能列出它的工作区与会话,第一台不受影响; - 3. 第二台离线时是灰行,不转圈、不超时; - 4. 从第二台打开一个会话,自动切换控制目标并进入会话,消息可收发; - 5. 在第二台的某个工作区新建会话,该桌面**当前打开的工作区不变**; - 6. 杀进程重启后,展开过的设备先出缓存再刷新。 -- 主题:`pnpm run theme:color-audit:all`。设备行只用 `Theme.ets` 的语义色,浅色深色都要看。 - -## 与既有文档的关系 - -`wide-conversation-navigation-design.md` 的"已实现"一节仍在描述宽屏左栏的"本地 / Remote" -分段选择器。该选择器已随 `dd0d89dfe` 删除(`ConversationSource` 与 `ConversationSourceSwitcher` -一并移除,路由合同改为 `isRemoteRoute` / `remoteSurfaceDestination`)。那份文档的更新不在本轮 -范围内,此处记一笔,避免下一个读者把它当作现状。 diff --git a/src/apps/mobile/harmonyos/docs/mobile-detached-dispatch-design.md b/src/apps/mobile/harmonyos/docs/mobile-detached-dispatch-design.md deleted file mode 100644 index 8deaef082a..0000000000 --- a/src/apps/mobile/harmonyos/docs/mobile-detached-dispatch-design.md +++ /dev/null @@ -1,251 +0,0 @@ -# 鸿蒙端 Detached Dispatch:手机是中控 - -Date: 2026-08-18 - -Scope: `src/apps/mobile/harmonyos`,外加为它新增的一族 `RemoteCommand`。本设计**必须**改 -`src/crates/services/services-integrations/src/remote_connect.rs` 与桌面端的远程命令路由,理由见 -「为什么这次躲不开后端」。不改 relay,不改 CLI 的 dispatch 目标端,不改 -[`docs/architecture/detached-task-dispatch.md`](../../../../../docs/architecture/detached-task-dispatch.md) -定义的协议版本 4。 - -## 原则 - -**手机是中控。任务不在手机上执行,但手机可以控制一切。** - -这条原则划的是「决定」与「干活」的界,不是「手机能做」与「手机不能做」的界。它给出本设计的 -两条判据,全文每一处取舍都由它们裁定: - -1. **凡是决定,手机都要能做。**派给谁、拿什么派、批不批权限、要不要停、要不要把结果收回来—— - 缺一个,就是设计没做完,不是「留待后续」。 -2. **凡是干活,手机一件都不做。**Git 基线工作树、bundle 传输、worker 进程、目标工作树, - 全在机器上发生。 - -第 2 条不是对手机的限制。手机不建 Git 基线,是因为那是干活,不是因为手机没资格。把执行的 -限制写成权限的限制,会把整份设计带偏成「手机只能当只读观察者」——这是本设计最容易走错的一步, -写在最前面。 - -## 主用例:手机远控 A,把 A 上的活派到 B - -协议原生就是这个形状:A 是 controller(它有仓库、有工作树服务),B 是 target(它有 worker -和权限信箱),**手机是下决定的那个**。三者各就各位,谁也没越界。 - -目标 B 可以是同账号的另一台桌面:`DispatchTargetRequest`(`service/dispatch/target.rs:50`) -有 `Device { deviceId, workspacePath }` 这一支,走账号设备 RPC,`device_controller.rs` 已经实现。 -也就是说 A→B 这条路今天在桌面 UI 上就能走通,缺的只是手机上的那个决定入口。 - -**一处必须说清的边界**:能派出去的是「活」,不是「这个会话」。`DispatchSubmitRequest` -(`service/dispatch/controller.rs:60`)带的是 target、base_ref、`include_uncommitted`、prompt、 -审批策略、模型、附件——**没有任何携带对话历史的字段**。所以: - -- ✅ A 上干到一半的活,**连未提交的改动一起**(`include_uncommitted`),派给 B 接着跑; -- ❌ 手机正和 A 进行的这个会话,整个搬到 B 续上。 - -后者协议里根本不存在,桌面 UI 上同样搬不了,不是手机的短板。想把上下文带过去,只能由手机把 -它拼进 `prompt`——那是手机在组织一段提示词,不是协议在接力会话,文档和 UI 都不许把它说成接力。 - -## 中控要能控什么 - -这张表是第 1 条判据的展开,也是本设计的验收清单。左列是决定,中列是谁去干活,右列是手机上 -必须存在的入口。**右列不允许有空格。** - -| 决定 | 谁执行 | 手机侧动词 | 桌面对应 | -|---|---|---|---| -| 派给哪台机器 | — | 复用侧栏设备列表 + `dispatch_probe_target` | `dispatch_api.rs:85` / `:119` | -| 拿哪个工作区的活派、带不带未提交改动 | A | `dispatch_submit`(含 `includeUncommitted`) | `:271` | -| 批一条待决权限 | target | `dispatch_answer` | `:488` | -| 给正在跑的这一轮插话 | target | `dispatch_append` | `:516` | -| 排下一轮 | target | `dispatch_continue` | `:371` | -| 停 | target | `dispatch_cancel` | `:427` | -| 把结果收回 A | A | `dispatch_sync_result` | `:338` | -| 看有哪些活、跑到哪了 | — | `dispatch_list_jobs` / `dispatch_job_status` | `:455` / `:304` / `:399` | - -对照方式是逐条比 `src/apps/desktop/src/api/dispatch_api.rs` 的命令表:桌面上能做的每一个 -**决定**,手机上都要有入口;桌面上剩下的那些(`dispatch_provision_target`、 -`dispatch_install_cli_*`、`dispatch_sync_model_config`、`dispatch_save_transcript`)属于干活、 -SSH 目标的准备工作或本机存储,手机不做,且要在「手机不执行的东西」里逐条说明为什么不做—— -**不写理由的缺席等同于遗漏**。`dispatch_query` 是单个 job 的详情读取,与 status 同属观察, -合并在最后一行里。 - -```mermaid -flowchart LR - P["手机 · 中控
派发 · 批权限 · 转向 · 停 · 收回"] - A["机器 A · controller
Git 基线 · 提交 · 结果回传"] - B["机器 B · target
worker · 会话 · 权限信箱"] - - P -->|"RemoteCommand
dispatch_*"| A - A -->|"HostInvoke
dispatch_target_*"| B - P -.->|"永不直连"| B -``` - -## 为什么这次躲不开后端 - -前几轮的规矩是「跨端的我们不管,先完整实现鸿蒙」。那条规矩成立,是因为侧栏要的命令 -`RemoteCommand` 里全都有。Dispatch 不一样:那个枚举(`remote_connect.rs:2144`)里**没有任何一个 -dispatch 动词**。手机对外只有这一个通道,所以「手机能控制 dispatch」和「不改后端」不可能同时 -成立——这不是取舍,是算术。 - -好消息是要加的很薄。桌面的 `dispatch_api.rs` 本身就是一层壳:每个命令只做「挑传输(SSH 还是 -账号设备)」然后调 `service/dispatch` 里的核心函数。手机的动词打在**同一批核心函数**上,新增的 -是路由,不是第二套 dispatch 实现。这是本设计成立的前提,也是它的自检线:**一旦发现要为手机 -新写 job 状态机、新写存储、新写重试语义,说明设计错了,停下来重来。** - -## 已核实的基线事实 - -| 事实 | 依据 | 对设计的影响 | -|---|---|---| -| `RemoteCommand` 里没有任何 dispatch 动词 | `remote_connect.rs:2144` | 手机要控制 dispatch,必然改这个枚举 | -| 枚举没有 `#[serde(other)]` 兜底 | 同文件全文无 `serde(other)`;解析失败见 `service/remote_connect/remote_server.rs:331` | 老桌面只会回 `parse command: unknown variant`,与「参数拼错了」不可区分——能力协商必须另走一条路 | -| 目标可以是同账号的另一台桌面 | `service/dispatch/target.rs:50` `DispatchTargetRequest::Device` | A→B 走账号设备 RPC,今天就能跑 | -| 提交请求不携带对话历史 | `service/dispatch/controller.rs:60` `DispatchSubmitRequest` 全字段 | 能派「活」,不能接力「会话」;上下文只能进 prompt | -| job 本身是多轮会话 | 规范 Conversation model:`append` steer 当前轮,`continue` 排下一轮,worker 恢复目标会话 | 派出去不是一锤子买卖,手机要能持续插话 | -| 结果回传是 controller 侧的 Git 快进 | 规范 Synchronization semantics 第 4 步:fetch 后 `--ff-only` 推进基线工作树 | 手机能**下令**同步,同步本身在 A 上发生;用户的 checkout 永不被改 | -| 桌面 dispatch API 是薄层 | `dispatch_api.rs:271` / `:338` / `:455` / `:488` 等各自只做传输选择后调核心函数 | 手机动词复用同一批核心函数 | -| 出站记录只存在 controller 本机 | `service/dispatch/mod.rs:93` `OutboundDispatchRecord`,落盘于 `~/.openbitfun/dispatch/outbound/` | 手机问 A,列到的是 **A 派出去的** job,不是账号级全集 | -| 账号设备通道上 `dispatch_target_*` 是保留名 | 规范 Protocol:这些名字先于 Peer Host 桥直接路由到 target CLI | 手机的动词不能用这个前缀 | -| 光标每观察者独立,target 无 controller 租约 | 规范 Event and observer contract | 手机与桌面可同时观察同一个 job,互不干扰 | -| 光标不能单独还原画面 | 同上:光标只记录读到哪,不记录画了什么 | 投影 + 光标 + 完整性事实必须原子地写在一起 | -| 权限回复与追加消息是 target 侧幂等信箱 | 规范 Approval and supervision | 手机批与桌面批不冲突,重试安全 | -| relay 不排队 job | 规范 Failure rules 第一条 | 目标离线就是提交失败,手机不做假排队 | -| 工作区交付是 Git-only | 规范 Workspace delivery;非 UI 调用方由 controller 再校验一次 | 非 Git 工作区在手机上就要禁掉派发入口,并说明原因 | - -## 设计 - -### 1. 派发:手机选,A 做 - -`dispatch_submit` 的语义是「**你**(A)以 controller 身份,在**你**的这个工作区上,向这个目标 -提交一个 job」。手机提供的全是决定:目标、工作区路径、提示词、审批策略、要不要带未提交改动、 -模型与附件。Git 基线、bundle、worker,一件都不经过手机。 - -这正好接上已经做完的侧栏:「设备 > 工作区 > 会话」让手机能看见每台桌面上的每个工作区,派发需要 -的两个坐标(哪台机器出活、哪台机器干活)在侧栏里本来就是选好的。入口就长在工作区行上。 - -**失败必须直说。**relay 不排队 job,目标离线就是提交失败,不存在「先收下,回头替你发」。响应 -丢失时 job 处于 `submission_unknown`,靠 status 或幂等重试与 target 的持久事实对账——手机不得 -自己猜一个状态填上去。非 Git 工作区不给派发入口,并明写原因,而不是让它点下去再报错。 - -### 2. 命令族叫 `dispatch_*`,不叫 `dispatch_target_*` - -新动词全部落在**桌面的 controller 角色**上,前缀必须是 `dispatch_`。`dispatch_target_*` 在账号 -设备传输上是保留名,规范写明它们**先于** Peer Host 桥直接路由到 target CLI——手机若用那个前缀, -请求会被送到 target 角色,而手机要说话的对象是 controller。 - -这个错不会立刻炸:A 和 B 常常是同一类机器,甚至同一台,所以它会一直看起来是对的,直到某天 -目标是第三台机器才现形。这是本设计里最容易写错、最难查的一处,名字必须一眼可辨。 - -### 3. 能力协商:老桌面必须能被认出来 - -枚举没有兜底分支,一台没升级的 A 收到 `dispatch_submit` 只会回 `parse command: unknown variant`, -这串字符和「手机把参数拼错了」长得一模一样。靠它判断对面支不支持,结果就是把某天的真 bug -常年显示成「该桌面版本较低」。 - -**能力要搭在一条老桌面本来就会答的响应上。**`get_workspace_info` 是账号设备连接的第一条命令, -给它的响应加一个可选能力数组:老桌面不认识这个字段、压根不产出,手机读到的是缺失——**缺失即 -不支持**,这是不会误判的信号。手机据此决定画不画派发入口。按 AGENTS.md 的规矩这叫 degrade -loudly:不支持就收起入口或明写不支持,绝不静默失败,更不许假装成功。 - -### 4. 派出去之后:批权限是手机最不可替代的那件事 - -`remote` 审批策略下,worker 把安全的展示 DTO 持久化,status 暴露它,`answer` 记下用户来源的 -回复后执行才继续。也就是:**一个跑在 B 上的长任务卡着等人点「允许」,而那个人不在任何一台 -电脑前。**这是中控原则最硬的一次兑现——决定权在人身上,人在手机上。 - -信箱是 target 拥有的、幂等的,不依赖最初提交它的 controller,所以手机批和桌面批不冲突。手机 -侧只有两条硬要求:待决权限要能推到用户眼前,不能只在打开某个页面时才被发现;待决项必须显示 -**它属于哪台机器上的哪个 job**——同时看着多台机器时,一个没有出处的「允许写入文件?」是不能 -批的。 - -### 5. 收回来:手机下令,A 执行 - -同步在 job 运行中和终态后都可用。target 提交自己工作树上的改动、造 `..` 的 -增量 bundle,controller 验签后 fetch 进基线并 `--ff-only` 推进。**用户在 A 上的 checkout 永远 -不被改**,基线工作树才是审阅边界。 - -手机在这里只出一个决定(「把结果收回来」)和一个显示(同步到了哪个分支的哪个 commit、几个文件、 -有没有失败)。规范要求任一侧离开 job 分支、基线被删或有分叉提交时**可见地失败**,不做重置或 -改写——手机侧同理,失败就说失败,不给「已同步」的错觉。 - -### 6. 光标与转录缓存:一起写,不然会撒谎 - -规范对观察者的要求很硬:status 要报下一个字节光标、请求的光标是否被重置、更老的历史是否被截断、 -多少超大事件被省略标记替换、以及返回的转录**能否被视为完整**;轮转与超大事件绝不可被表示为 -完整转录。 - -光标只记录读到哪、不记录画了什么,所以光标单独存不足以还原画面。**投影、产生它的光标、当时 -适用的完整性事实,三者必须写在同一条记录里**——只有一起写下的这一组才自洽。落到鸿蒙端就是在 -`RemoteSessionListRdbStore`(现 `SCHEMA_VERSION` = 2,`services/RemoteSessionListRdbStore.ets:15`) -加一张表,一 job 一行,整行原子写,行上带投影规则版本号;缺失、损坏、版本不匹配、超体积上限, -一律从字节 0 重放,不做修补。 - -被截断的历史在手机上必须**看得见**是截断的。这不是文案偏好:把省略画成完整,会让人根据一段 -没发生过的历史去批一条权限。 - -### 7. 任务不是会话 - -规范要求 controller **不得**把 target 会话建进自己的正常会话库,观察记录只是 observer-only 的 -路由记录。手机照办:job 不进 `remote_session_list`,不进侧栏会话时间线,不参与 `deviceId + id` -那套会话去重。它是与「设备 > 工作区 > 会话」并列的另一层,共用设备这一维,不共用会话这一维。 - -混进去两边都会坏:会话列表的每一行都假设自己能被打开成一个对话,而 job 不能;job 的每一行都 -带着目标机器、审批策略、完整性事实,而会话行没有位置放它们。 - -## 手机不执行的东西 - -以下都不是「手机做不到」,是按原则第 2 条**不该由手机做**,且每一条的决定权仍在手机上: - -- **Git 基线工作树、bundle 的制作与分块传输**——A 干。手机决定派不派、带不带未提交改动。 -- **worker 进程与目标工作树**——B 干。手机决定停不停、下一轮跑什么。 -- **同步时的 fetch 与 `--ff-only`**——A 干。手机决定什么时候收。 -- **CLI 安装与目标 provision**(`dispatch_api.rs:138` / `:197`)——SSH 目标的准备工作,涉及签名 - 校验与安装器,属于干活;账号设备目标不走这条路。手机不做,本轮也不代理。 -- **向 SSH 目标同步模型配置**(`dispatch_api.rs:257`)——只对 SSH 连接成立(它取的是 - `ssh_manager`),账号设备目标没有这一步。手机的目标是账号设备,不涉及。 -- **转录的本机保存**(`dispatch_save_transcript`)——那是 controller 的本地缓存实现细节,手机 - 有自己的缓存表,不是同一份东西。 - -另有一条是协议层面的空缺,不是分工问题:**会话接力不存在**。提交请求不带历史,任何一端都搬不 -了一个正在进行的会话。 - -## 阶段划分 - -按「决定的完整性」推进,不按「哪个好做」推进。 - -**阶段一 — 派得出去、看得见。**能力协商字段;`dispatch_submit` + `dispatch_list_jobs` + -`dispatch_job_status`;转录缓存表落地。派出去却看不到状态等于没派,所以这两件必须同一阶段交付。 - -**阶段二 — 管得住。**`dispatch_answer` / `dispatch_append` / `dispatch_continue` / -`dispatch_cancel`。到这一步手机开始改变别的机器上的状态,每个动词都按幂等重试来测。 - -**阶段三 — 收得回。**`dispatch_sync_result` 与同步结果的显示;目标选择接上 -`dispatch_probe_target` 的能力检查。 - -三阶段做完,「中控要能控什么」那张表的右列不应再有空格。 - -## 验证要求 - -- 架构检查 `pnpm run harmony:architecture` 通过;新增文件守住既有边界(`services/**` 不 import - `../pages/`,`pages/components/**` 不 import `pages/viewmodel/`,新组件 `@ComponentV2`)。 -- Rust 侧:新动词要有 `remote_connect` 路由测试,并且**必须**有一条断言老桌面路径——没有能力 - 字段时手机不发这些命令。 -- 单元测试(`entry/src/test`,LocalTest):转录缓存版本不匹配时从零重放;截断的历史不会被投影 - 成完整;同一条权限回复重复提交是幂等的;离线设备不产生任何 dispatch RPC;非 Git 工作区不出现 - 派发入口。 -- 真机验证(账号下至少两台桌面): - 1. 老桌面上派发入口不出现,且不产生任何失败请求; - 2. **手机远控 A,把 A 上一个工作区的活(含未提交改动)派给 B,B 上确实起了 job**; - 3. `remote` 策略下 job 卡在待决权限,**从手机批准后任务继续**,待决项显示了机器与 job; - 4. 手机 `append` 一条转向消息,B 的当前轮收到;`continue` 排出下一轮且带着上文; - 5. 从手机下令同步,结果落回 A 的基线工作树,**A 上用户自己的 checkout 未被改动**; - 6. 目标离线时派发失败并明说,本地不留任何「排队中」; - 7. 杀进程重启后,转录从缓存光标续上,截断标记仍在。 -- 主题:`pnpm run theme:color-audit:all`,任务行只用 `Theme.ets` 语义色,深浅色都看。 - -## 与既有文档的关系 - -[`mobile-control-console-design.md`](mobile-control-console-design.md) 的「非目标」原本写着 -「不做 Detached Dispatch」,已改为指向这里。那份文档「不改远程命令合同」的范围声明仍适用于它 -自己描述的侧栏工作,不适用于本文档。 - -协议本体以 -[`docs/architecture/detached-task-dispatch.md`](../../../../../docs/architecture/detached-task-dispatch.md) -为准。本文档不复述协议,只记录手机在其中的位置——它是下决定的那个——以及为此要新增什么。两者 -冲突时以协议文档为准。 diff --git a/src/apps/mobile/harmonyos/docs/model-service-settings-sheet-design.md b/src/apps/mobile/harmonyos/docs/model-service-settings-sheet-design.md deleted file mode 100644 index 11b4fea025..0000000000 --- a/src/apps/mobile/harmonyos/docs/model-service-settings-sheet-design.md +++ /dev/null @@ -1,84 +0,0 @@ -# 普通对话模型设置:bindSheet 与模型选择 - -Date: 2026-08-19 - -Scope: `src/apps/mobile/harmonyos` 设置里的「普通对话 / 模型」面板,以及同一套手搓蒙层的语言面板。不改 ComposerBar 选择器、relay、桌面端。 - -## 问题 - -`ModelServiceSettingsPanel` 不是系统 Sheet,而是塞进 `SettingsSheet` Stack 的手搓蒙层(`78%` 死高度 + 自绘圆角 + 自绘 ×)。设置页那个 × 是同一个 Stack 的 overlay,所以两个 × 同时出现;内容只有三行,底下是大片空白。 - -`checkmark_circle_fill` 在「当前使用 / 账号同步 / 本机自定义」上各出现一次。后两个表达的是来源归属,和「当前使用」那一行重复。 - -账号同步行没有 `onClick`。用户看见「已同步 12 个」却进不去、也换不了模型。真正的切换只在 ComposerBar 的 `bindSheet` 里。语言面板是同一套手搓蒙层,同样会和设置页 × 叠在一起。 - -## 目标 - -1. 设置子面板收敛到和 `ComposerBar` 一样的 `bindSheet`(`showClose: false`、`dragBar: true`、高度按内容算)。一次去掉双 ×、死高度空白、手搓蒙层。 -2. `✓` 只表示「当前选中的模型」。来源行不再带 ✓。 -3. 账号同步行可点,带 `>`,打开真实的账号模型列表,点一项即 `SettingsController.selectModel`。 -4. 信息架构收成两组:「当前使用」+「模型来源」。账号同步和本机自定义是同级入口,放在同一分组容器里,中间一条 divider;分组标题和行文字共用 16vp 水平边距。 - -语言面板做同一套 `bindSheet` 收敛,不再单独留一手搓模态。 - -## 非目标 - -- 不改 ComposerBar 里那套对话中模型选择器。 -- 不改账号模型的同步/拉取合同。 -- 不把设置面板做成 ComposerBar 选择器的第二份拷贝;设置侧分「状态 / 来源 / 本机配置」三层,选择器只负责挑一个 id。 - -## 交互 - -设置页「模型」行 → `bindSheet` 打开概览。 - -``` -[普通对话模型 ×] - -当前使用 -[ ✓ deepseek-v4-pro ] -[ 云端账号 ] - -模型来源 -[ ☁ 云端账号模型 > ] -[ 已同步 12 个 ] -[ ------------------------------- ] -[ 🔧 本机模型名 > ] -[ 本机 ] -``` - -- 账号行 → 再挂一层 `bindSheet`,列表高度按 `min(条数, 7)` 算,和 ComposerBar 同一公式。点一项调用 `selectModel`,关掉列表,概览上的「当前使用」跟着变。0 条也进得去,显示空态。 -- 本机行 `>` → 再挂一层 `bindSheet` 打开本机 API 编辑器(自适应/固定表单高度,保留键盘避让)。已配置时,点行主体会选中本机模型;未配置时点整行进编辑器。保存成功后沿用现有 `save` 路径。 -- 概览「当前使用」只读。`✓` 只出现在这里,以及账号列表里当前那一项。 - -设置页「语言」行同样改 `bindSheet`,高度按语言条数算。 - -## 结构 - -| 单元 | 职责 | -|---|---| -| `ModelServiceSettingsPolicy` | 当前模型解析、账号模型过滤、来源分组、三页 Sheet 高度。组件不内嵌这些规则。 | -| `SettingsSheet` | 在根节点上 `bindSheet` 语言 / 概览 / 账号列表 / 本机编辑器。不再把子面板叠进 Stack。 | -| `ModelServiceSettingsPanel` | 只画当前页:`overview` / `account` / `local`。发出 `onOpenAccountModels` / `onOpenLocalEditor` / `onSelectModel`。 | -| `LanguageSettingsPanel` | 只画语言列表,不再自绘蒙层。 | -| `SettingsPresentationActions.selectGeneralModel` | 接到 `SettingsController.selectModel`。 | - -设置页本身已经是 `AppShell` 上的 `bindSheet`。子面板再 `bindSheet` 一次,真机上点击会改状态但第二张 Sheet 不会出现(`5ZU0226202001116` 上点「模型」后仍只有一张 `SheetPage`)。因此语言 / 概览 / 账号列表 / 本机编辑器改为**替换设置列表**,不嵌套系统 Sheet。设置页的 × 只在主列表显示,避免双 ×。 - -## 高度 - -公式放在 policy 里,组件只读数字: - -- 概览:header + 「当前使用」一行 + 「模型来源」两行分组,约 345vp。 -- 账号列表:`min(480, chrome + min(n, 7) * row + 行距)`,空态用一行占位高。 -- 本机编辑器:560vp,够放下三字段、测试/保存和反馈;聚焦时仍走现有 `KeyboardAvoidMode.RESIZE`。 -- 语言:`chrome + 条数 * 64`。 - -三页各绑一张 Sheet,打开时按当时内容算高度,避免同一张 Sheet 切页后高度不刷新。 - -## 测试 - -`ModelServiceSettingsPolicy` 覆盖:当前模型解析顺序、只把 `cloud:` 且 `enabled` 的项算进账号列表、来源行不承担选中语义、三页高度随内容变且账号列表封顶 7 行。`ArchitectureUnit` 不应被这次改动破坏。i18n 中英 key 锁步。 - -## 远程场景 - -这次只动本机设置壳。账号模型数据仍来自已有云端同步;选择写进 `GeneralChatConfigStore`,和 ComposerBar 走同一条 `selectModel`。不新增远程命令,也不把本机 API Key 泄漏到远端控制器。 diff --git a/src/apps/mobile/harmonyos/docs/mvvm-architecture-refactor-design.md b/src/apps/mobile/harmonyos/docs/mvvm-architecture-refactor-design.md deleted file mode 100644 index fafe0b7db0..0000000000 --- a/src/apps/mobile/harmonyos/docs/mvvm-architecture-refactor-design.md +++ /dev/null @@ -1,575 +0,0 @@ -# HarmonyOS 端 MVVM 架构重构设计 - -Date: 2026-08-06 - -Status: Implementation in progress; S0-S5 and S7 are complete, while S6 component decomposition and the wide-screen visual matrix remain pending - -Scope: `src/apps/mobile/harmonyos/entry/src/main/ets` - -Baseline: commit `6c35485bb`(窄屏 Local/Remote 统一完成后) - -Reference: 华为官方文档 -[MVVM模式(状态管理V2)](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V13/arkts-mvvm-v2-V13)、 -[MVVM模式(V1)](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-mvvm)、 -[状态管理(V1)](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-state-management-v1) - -Related designs: - -- [`adaptive-conversation-ui-redesign.md`](adaptive-conversation-ui-redesign.md) -- [`wide-conversation-navigation-design.md`](wide-conversation-navigation-design.md) -- [`responsive-file-preview-design.md`](responsive-file-preview-design.md) -- [`native-code-preview-implementation-design.md`](native-code-preview-implementation-design.md) - -本文只负责**代码结构**,不改变任何用户可见行为。上述四篇设计继续负责路由合同、折痕几何、文件预览 placement 和会话 UI/UX;本文的每一个阶段都以"这些文档描述的行为在真机上完全不变"为验收前提。发生冲突时,以现有行为文档为准,重构方案让路。 - ---- - -## 0. 结论摘要 - -- **架构基准**:MVVM 是鸿蒙官方文档明确定义的模式,官方把它定位为**单模块内的文件组织方式**;整个应用的模块化官方推荐三层架构(products / features / commons)。本项目 `build-profile.json5` 只有一个 `entry` 模块,正落在 MVVM 覆盖的范围内——**MVVM 是本次重构正确且足够的框架,三层架构不在本次范围**。 -- **好消息**:ViewModel 层已经是干净的。7 个 `*ViewModel` 共 1379 行,**没有任何一个 import `components/`**。MVVM 里最难守住的一条,这里已经守住了。 -- **重构结果**:`services/` → `pages/`、`components` → `viewmodel`、`viewmodel` → `components` 当前均为零;运行时组合根已拆为 `AppRootRuntime` 与 `AppRootRuntimeComposition`,特性行为由四个 Controller 持有。 -- **一条被更正的判断**:初版诊断把"10 个 `components/*` import `../state/`"列为分层违规,**这是错的**,详见 §3.4。 -- **状态管理范式统一到 V2**:基线有 15 个 V1 struct(5114 行)与 19 个 V2 struct 混用;S5 已将这 15 个组件全部迁移到 V2。V2 是官方对新项目的推荐范式,也是官方 MVVM 示例的形式,详见 §2.8 与 §5 的 S5 阶段。 -- **实施方式**:S0–S7 八个阶段,每个阶段独立可发布、可回滚,前三个阶段零行为变更。 - ---- - -## 1. 架构基准 - -### 1.1 官方 MVVM 的三条职责界定 - -引自华为官方文档: - -- **model** —— 负责数据的获取和存储以及业务逻辑,**不与 view 关联**; -- **view** —— 负责界面展现和用户输入,**不与 model 关联**; -- **viewmodel** —— 作为连接二者的桥梁,负责将 model 数据转为 view 数据并管理界面状态。 - -官方 V2 示例的绑定形式是 `@ComponentV2` + `@Local` 持有 ViewModel 实例。 - -本文后续所有"违规"判定,都直接引用上面三句,不引入本文自创的架构偏好。 - -### 1.2 范围界定:MVVM vs 三层架构 - -官方对二者的分工是明确的: - -> MVVM 的目录组织方式一般适用于**单个模块内**的文件组织;为了更好地适配复杂应用开发,建议采用**三层架构**对**整个应用**功能进行模块化。 - -| 层级 | 编译产物 | 依赖约束 | -| --- | --- | --- | -| products(产品定制层) | Entry HAP | 可依赖 features / commons,禁止横向调用 | -| features(基础特性层) | HAR / HSP | 可依赖 commons,避免反向依赖 products | -| commons(公共能力层) | HAR / HSP | 不可依赖上层 | - -**本项目现状**:`build-profile.json5` 的 `modules` 只有 `entry` 一项,`compatibleSdkVersion 6.0.1(21)` / `targetSdkVersion 6.1.1(24)`。单模块 = MVVM 的适用范围。 - -**三层架构的引入时机**(记录,本次不做):当需要为不同设备形态提供差异化入口(折叠屏 / 平板 / 车机各自的 Entry HAP),或 `services/` 需要被鸿蒙端之外复用时,才是把 `services/` 抽成 commons HAR、把会话/Remote 抽成 features HSP 的时机。在只有一个 entry 的现在做这件事,只增加构建复杂度,不带来收益。 - -### 1.3 ArkTS/ArkUI 层面必须遵守的既有教训 - -这些是本模块已经付出过代价的约束,重构中任何一步都不得违反: - -1. **`@Builder` 的值参数不具备响应式**。只有按引用传入的单个对象参数才会驱动重渲染;builder 内部读 `this.` 才是可靠的。拆分 builder 时,凡是原先从父 builder 传入的宽度、来源等标量,一律改为在子 builder 内部读状态。 -2. **`NavPathStack` 不可观测**。任何存活于 `Navigation` 之外的界面(抽屉是典型)都不能靠它驱动刷新,必须消费 `AppShellState.activeRoute` 这个 `@Trace` 镜像。该镜像由 `AppShellViewModel.syncActiveRoute()` 统一维护,**新增导航路径必须经由 `AppShellViewModel`**。 -3. **V1 / V2 混用现状**:`@Component/@State/@Prop` 与 `@ComponentV2/@Local/@Param/@Event` 并存。本次**全量迁移到 V2**,范式统一后 §1.3.1 和 §1.3.2 两条约束的心智负担也随之下降(V2 的观测边界比 V1 明确)。分布数据见 §2.8,实施见 §5 的 S5 阶段。 - ---- - -## 2. 现状测量 - -以下全部为实测值,非估算。 - -### 2.1 规模基线 - -| 目录 | 文件数 | 行数 | -| --- | --- | --- | -| `pages/components` | 39 | 14518 | -| `services`(含 `general-chat` 21 / 3296) | 51 | 7492 | -| `pages/state` | 21 | 5645 | -| `i18n` | — | 581 | -| `model` | — | 465 | -| `pages/navigation` | — | 110 | -| 测试 `entry/src/test` | 8 | 6612 | - -### 2.2 `pages/state/` 的真实构成(一个目录装了三层) - -| 类别 | 文件 | 行数 | -| --- | --- | --- | -| ViewModel | `AppShellViewModel` 98、`ConversationViewModel` 22、`GeneralChatConversationViewModel` 336、`RemoteActivityViewModel` 163、`RemoteConnectionViewModel` 353、`RemoteSessionViewModel` 236、`RemoteWorkspaceViewModel` 171 | 1379 | -| State(`@ObservedV2` 绑定对象) | `AppShellState` 58、`ConversationViewState` 120、`FilePreviewState` 107、`GeneralChatPageState` 200、`RemoteCreateSessionState` 113、`RemotePageState` 373 | 971 | -| Policy(纯逻辑,零 `@Trace`) | `ConversationLayoutPolicy` 156、`FilePreviewPlacementPolicy` 185、`ConversationModelPresentationPolicy` 82、`ConversationSessionFilterPolicy` 51、`SessionActionPolicy` 31 | 505 | -| God Facade | `AppRootRuntime` | 2608 | -| 其他 | `ConversationIntentDispatcher`、`FilePreviewTarget` 等 | 约 182 | - -### 2.3 两个引力井的内部构成 - -**`AppRootPresentation.ets`(1449 行)**——可分离,各段落关注点互不相干: - -| 段落 | 行数 | 性质 | -| --- | --- | --- | -| 7 个 action DTO 定义(L62–270) | 209 | 属于 model 定义,不该在 view 文件里 | -| Remote UI builders | 305 | 一个独立特性面 | -| Remote 辅助方法 | 143 | 同上 | -| 宽屏几何计算 | 179 | 纯计算,可脱离 UI,当前零单测覆盖 | -| 宽屏 builders | 275 | 一个独立布局面 | - -共 25 个 `@Builder`、约 50 个私有方法、21 个 `@Local`(其中 13 个属于宽屏几何、8 个属于 Remote 过滤/元数据)。两组 `@Local` 混在同一 struct 内,意味着改宽屏分栏宽度会连带触发 Remote 过滤区重算。 - -**`AppRootRuntime.ets`(2608 行)**——性质不同,是"所有特性的门面开在同一个类上": - -- 183 个方法级条目,约 101 个 public,其中 **45 个是一行转发**; -- 75 个 import; -- 字段初始化块从 L140 延伸到 L761(621 行); -- 单个方法最长 `selectCloudAccountDevice` 91 行。 - -### 2.4 接线代码 - -12 个 `*Hooks` / `*Actions` 类:定义 412 行,在 `AppRootRuntime` 中的构造点 235 行,合计约 **650 行纯接线**。 - -其中 7 个定义在 `AppRootPresentation.ets` 内(L62–270,209 行)。构造点规模:`AppRootPresentationActions` 96 行、`RemoteSessionViewModelHooks` 46 行、`ConversationIntentDispatcherHooks` 39 行、两个 Hooks 各 23 行、一个 8 行。 - -全部为**位置参数构造**: - -```ts -new AppRootPresentationActions(a, b, c, d, /* …共 96 行实参 */) -``` - -代价不只是行数——新增一个回调要同步改三处(DTO 定义、构造点、消费点),且位置参数在 ArkTS 里没有编译期的名字保护:两个相邻的同签名回调若被调换顺序,编译通过、运行时行为错乱。这是本模块唯一一类"改对了也无法在编译期确认"的修改。 - -### 2.5 会话状态的重复 - -`GeneralChatPageState`(200)与 `RemotePageState`(373)有**约 15 个字段同名同义**。为了让上层统一消费,又长出两层扇入扇出: - -- `services/AppRootRouteState.ets`(88 行)——存在的唯一理由是在两者之间搬数据; -- `ConversationViewState.project(route, remote, general, …)`——再做一遍同样的归约; -- 分散各处的 `compact` 布尔与 `if (source === General)` 分支。 - -后果:每新增一项会话能力(附件、引用、重发……),要在两个 State 各写一次,再在两个投影层各接一次。 - -### 2.6 组件层 - -内联 glyph / icon builder 共 **538 行**,分布在 10 个文件:`AppSidebar` 179、`ConnectView` 99、`ToolStatusList` 91、`ConversationView` 61、`ChatMessageBubble` 35、`SessionActionSurface` 19、`CreateSessionSheet` 18,`ComposerBar` / `RemoteCreateSessionView` / `ChatTimeline` 各 12。 - -第二梯队大结构体:`ToolStatusList` 1442 行 / 16 builders、`ConnectView` 1344 / 24、`ChatMessageBubble` 1246 / 18、`AppSidebar` 908 / 29。 - -### 2.7 现有安全网 - -`entry/src/test/` 共 6612 行 hypium 用例: - -| 文件 | 行数 | -| --- | --- | -| `RemoteControllersUnit` | 2177 | -| `TransportAndGeneralChatUnit` | 1255 | -| `LocalTestFixtures` | 1078 | -| `ConversationStateUnit` | 1057 | -| `LifecycleUnit` | 748 | -| `AppRootLifecycleUnit` | 129 | -| `ArchitectureUnit` | 95 | -| `AppRootRuntimeStartupUnit` | 51 | - -本地运行方式(已实测通过,BUILD SUCCESSFUL 11s,报告落在 `entry/.test/default/outputs/test/reports/`): - -```bash -source scripts/ohos-env.sh -"$HVIGORW" --mode module -p module=entry@default -p ohos.test.type=LocalTest test --no-daemon -``` - -注:现有 `ArchitectureUnit`(95 行)测的是**行为**(生成号失效、时间线归约、路由栈不变量),不是分层。分层目前无任何自动化约束。 - -### 2.8 V1 / V2 范式分布(重构前基线) - -**结构体**:V1(`@Component`)15 个,共 **5114 行**;V2(`@ComponentV2`)19 个。 - -**装饰器用量**: - -| V1 | 次数 | V2 | 次数 | -| --- | --- | --- | --- | -| `@Prop` | 79 | `@Param` | 155 | -| `@State` | 53 | `@Local` | 62 | -| `@BuilderParam` | 7 | `@Event` | 104 | -| `@Watch` | 4 | `@Trace` | 99 | -| `@Link` | 2 | `@ObservedV2` | 5 | -| `@Observed` / `@ObjectLink` / `@Provide` / `@Consume` / `@StorageLink` / `@StorageProp` | 0 | `@Monitor` | 4 | - -(`@BuilderParam` 在 V1 与 V2 中均受支持,不属于迁移面。) - -**V1 文件清单与迁移面**: - -| 文件 | 行数 | `@State` | `@Prop` | `@Link` | `@Watch` | -| --- | --- | --- | --- | --- | --- | -| `ConnectView.ets` | 1344 | 12 | 16 | — | — | -| `AppSidebar.ets` | 908 | 7 | 11 | — | — | -| `RemoteControlSettingsSheet.ets` | 872 | 13 | 12 | — | 1 | -| `ModelServiceSettingsPanel.ets` | 662 | 10 | 5 | — | — | -| `SettingsSheet.ets` | 297 | 4 | 8 | — | — | -| `CreateSessionSheet.ets` | 226 | — | 4 | 2 | — | -| `MarkdownContent.ets` | 199 | — | 1 | — | — | -| `OpenBitFunAccountLoginPage.ets` | 146 | 5 | — | — | — | -| `StreamingMarkdownContent.ets` | 142 | 1 | 3 | — | 3 | -| `FileReferenceCard.ets` | 85 | — | 8 | — | — | -| `ThinkingBlock.ets` | 67 | 1 | 5 | — | — | -| `ChatStatusBar.ets` | 60 | — | 4 | — | — | -| `AppRoot.ets` | 48 | — | — | — | — | -| `ConversationSourceSwitcher.ets` | 40 | — | 1 | — | — | -| `DefaultAccountAvatar.ets` | 18 | — | 1 | — | — | - -**集中度**:前 4 个文件占 3786 行(V1 总量的 74%)、86 个 V1 状态装饰器(占 65%)。其中 `ConnectView` 与 `AppSidebar` 同时也是 S6 拆分的目标,可就近编排。 - -**当前是否已有跨范式错误用法**:已逐文件核查,**没有**。5 个 `@ObservedV2` 类(`AppShellState`、`RemotePageState`、`GeneralChatPageState`、`RemoteCreateSessionState`、`FilePreviewState`)**没有任何一处被 V1 的 `@State` / `@Prop` / `@Link` 持有**——官方不支持 `@ObservedV2` 对象走 V1 观测机制,这条目前没有被踩到。 - -所以全量迁移 V2 **不是在修复既有 bug,而是在消除一类风险**:只要 V1 struct 还在,任何一次后续改动都可能把某个 `@ObservedV2` 对象传进 V1 的 `@Prop`,届时得到的是"编译通过、界面不刷新"——与本模块此前踩过的抽屉不刷新(§1.3.2)完全同型、且同样难以定位的故障。 - ---- - -## 3. 诊断 - -### 3.1 符合官方定义的部分 - -- **ViewModel 层是干净的**:7 个 VM 共 1379 行,零 import `components/`。ViewModel 完全不知道 UI 存在。 -- **Policy 层是纯的**:5 个 Policy 共 505 行,零 `@Trace` / 零 `@ObservedV2`,可直接单测。 -- **已有一处标准 MVVM 三件套**:`ConversationViewState`(投影,120)→ `ConversationViewHost`(哑视图,91)→ `ConversationIntent` / `ConversationIntentDispatcher`(意图,120)。**这是本次重构要推广的形状,不需要发明新范式。** - -### 3.2 硬违规(按 §1.1 官方定义判定) - -| 官方职责 | 违规 | 证据 | -| --- | --- | --- | -| model **不与 view 关联** | `services/` → `pages/` 反向依赖 | `AppRootRouteState`、`FileTargetResolver`、`RemoteFilePreviewController`、`MessageFileReferenceProjector` 共 4 个文件 import `../pages/` | -| view **不与 model 关联** | view 文件持有 model 定义,导致真实模块环 | `AppRootPresentation.ets` L62–270 定义 209 行 action DTO → `AppRootRuntime` 反向 import `AppRootPresentation` | -| viewmodel 是**桥梁** | `AppRootRuntime` 不是桥梁,是 God Facade | 2608 行 / 101 public / 45 一行转发 / 621 行字段初始化块;所有 view 绑到同一个巨型对象,而非各自绑到所属特性的 VM | - -### 3.3 结构性问题(不算违规,但是主要成本来源) - -1. **接线子系统化**(§2.4,约 650 行)——位置参数构造带来无编译期保护的修改风险。 -2. **会话状态双份实现**(§2.5)——每项能力写四遍。 -3. **目录命名说谎**(§2.2)——`pages/state/` 一个目录装了 ViewModel / State / Policy / God Facade 四类东西,"这个文件属于哪一层"无法从路径判断,也导致分层断言写不出来。 -4. **组件层关注点混合**(§2.6)——538 行内联图标 + 四个千行级结构体。 - -### 3.4 更正:一条被推翻的初版判断 - -初版诊断把 **"10 个 `components/*` import `../state/`" 列为分层被打穿。这个判断是错的**,此处保留记录以免后续重复犯错。 - -逐文件查证结果——这 10 个文件 import 的**全部是 State 类与 Policy 类,没有一个 import `*ViewModel`**: - -``` -AppShell.ets → AppShellState -AppSidebar.ets → SessionActionPolicy -ConversationViewHost.ets → ConversationViewState -ComposerBar.ets → ConversationModelPresentationPolicy -FilePreviewSurface.ets → FilePreviewState -ConversationIntent.ets → FilePreviewTarget -ConversationViewSettings → ConversationSessionFilterPolicy -RemoteSessionList.ets → SessionActionPolicy, ConversationSessionFilterPolicy -RemoteCreateSessionView → RemoteCreateSessionState -AppRootPresentation.ets → AppShellState 等 6 个 State/Policy -``` - -View 持有 `@ObservedV2` 状态对象**正是 ArkUI V2 官方推荐的绑定方式**,不是违规。真正的问题是 §3.3 第 3 条:目录名叫 `state`,内容却是四层,让合规的 import 看起来像违规。 - -**因此 S6 的目标已相应修正**:从"切断 `components → state` 的 import"改为"消除内联图标与多关注点混合"。 - ---- - -## 4. 目标结构 - -依赖单向向下,`pages/state/` 按真实层次拆开: - -``` -pages/ - ├─ AppRoot.ets @Entry,组合根 - ├─ actions/ 所有 Actions/Hooks 接口定义(从 view 文件搬出,环即断) - ├─ viewmodel/ 7 个 *ViewModel + 按特性拆出的 Controller - ├─ state/ 纯 @ObservedV2 绑定对象 - ├─ policy/ 纯逻辑,无装饰器,全部可单测 - ├─ layout/ WideLayoutGeometry 等纯几何计算 - ├─ navigation/ AppRouteContract(叶子) - └─ components/ 哑视图 + Glyphs 图标库 -services/ model 层:领域与传输,禁止 import ../pages -model/ i18n/ 叶子 -``` - -**五条硬约束**(S0 写入 `AGENTS.md` 并以"已知清单"模式开始由 `ArchitectureUnit` 拦截新增违规;第 5 条在 S5 完成后转为强制,第 1–3 条在 S7 完成后转为强制): - -1. `services/**` 不得 import `../pages/`; -2. `pages/components/**` 不得 import `pages/viewmodel/`(import `state/` `policy/` 合法); -3. 不存在任何模块环,`viewmodel → components` 方向禁止; -4. Actions/Hooks 一律 `interface` + 对象字面量,禁止位置参数构造; -5. **组件一律 `@ComponentV2`**,禁止新增 `@Component` / `@State` / `@Prop` / `@Link` / `@Watch`(`@BuilderParam` 不在此列,V2 亦支持)。 - -**每个特性面的标准形状**(推广 §3.1 已有的三件套): - -``` -XxxViewState 投影:把 model 数据转成 view 数据 -XxxHost 哑视图:只接 @Param 和回调 -XxxIntent 意图:view 向上表达"用户想做什么" -XxxViewModel 桥梁:持有 state、消费 services、处理 intent -``` - ---- - -## 5. 分阶段方案 - -按"风险调整后收益"排序。S0–S2 零行为变更。每阶段独立可发布、可回滚。 - -### S0 · 立规则与护栏(0.5 天,零行为变更) - -**做什么** - -1. 把 §1.1 官方三条职责、§1.2 范围界定、§4 五条硬约束写入 `src/apps/mobile/harmonyos/AGENTS.md`; -2. 把 §2.7 的本地测试命令补进 `AGENTS.md`(目前未文档化); -3. 扩展 `ArchitectureUnit.test.ets`,新增两组源文件扫描断言,均采用**"已知清单"模式**——断言"当前违规集合 == 登记清单",从此新增违规立即失败,存量按阶段递减: - - 分层断言:登记当前 5 处(`services → pages` 4 处 + `runtime → presentation` 1 处),S7 清零; - - **范式断言**:登记当前 15 个 V1 文件(§2.8 清单),S5 清零。这一条从 S0 当天起就阻止新增 V1 组件,避免迁移期间边迁边长。 - -**为什么先做**:规则来自官方文档,不需要团队内部论证;两份清单让后续每阶段的进度可测,且"只减不增"是机器保证的。 - -**风险**:无。不触碰产物代码。 - ---- - -### S1 · 从 view 中取出 model 定义,断环 + 拆分引力井(1–2 天,零行为变更) - -**做什么** - -1. **7 个 action DTO(L62–270,209 行)→ `pages/actions/`**。单独这一步就消掉硬违规 ② 与循环依赖,建议独立成第一个 commit。 -2. Remote builders + helpers(448 行)→ `pages/components/remote/RemoteSurfaceHost.ets`,带走 8 个 Remote `@Local`。 -3. 宽屏几何(179 行)→ `pages/layout/WideLayoutGeometry.ets`,纯函数,**顺带补单测**(当前零覆盖)。宽屏 builders 带走 13 个几何 `@Local`。 -4. `pages/state/` 按 §4 拆成 `viewmodel/` `state/` `policy/`——纯改目录与 import 路径,零逻辑改动,但让 S0 的断言写得出来。 - -目标:`AppRootPresentation.ets` 从 1449 行收敛到约 300 行的装配壳。 - -**实际结果(2026-08-07)**:7 组 action DTO 已迁入 `pages/actions/`;Remote、 -窄屏路由、宽屏会话与根级 overlay 分别由 `RemoteSurfaceHost`、 -`ConversationRouteSurface`、`WideConversationHost`、`AppRootOverlaySurfaces` -持有。宽屏几何已迁入 `pages/layout/WideLayoutGeometry.ets`,并由 -`ArchitectureUnit` 覆盖关键几何约束。`AppRootPresentation.ets` 从基线 1449 行 -收敛到 406 行,保留响应式测量、`Navigation`、compact preview overlay、Remote -settings sheet 与顶层装配。架构门禁要求该文件不超过 500 行,并要求上述拆分文件 -持续存在。 - -HAP、LocalTest 与窄屏真机 Local → Remote → Local 往返均通过。真机 smoke 曾发现 -`@BuilderParam` slot 内直接构造 V2 组件会触发 `class constructor cannot called without -'new'`;现已改为由 `@Builder` 方法承接 slot,并复验进程在完整往返中持续存活。 -当前两个 target 分别为 1080 × 2444 真机和 466 × 466 模拟器,均不能提供宽屏三栏 -验收条件,因此 S1 的宽屏视觉复验仍记为待办。 - -**风险点(本阶段唯一)**:`@Builder` 值参数不响应式(§1.3.1)。拆分后凡是原先由父 builder 传入的标量,必须改为子 builder 内读状态——`wideMasterPaneCurrentWidth()` 就是这个坑的既有修复案例。 - -**验证**:完整验证回路 + **必须真机复验宽屏三栏与窄屏抽屉来源切换**。 - ---- - -### S2 · 消灭位置参数接线(2–3 天,零行为变更) - -**做什么**:12 个 `*Hooks` / `*Actions` 由 `class` + 位置构造改为 `interface` + 对象字面量。 - -```ts -// before —— 96 行实参,顺序错了编译期无感 -new AppRootPresentationActions(onA, onB, onC, /* … */) - -// after —— 字段名保护,新增回调只改两处 -const actions: AppRootPresentationActions = { - onA: () => { /* … */ }, - onB: () => { /* … */ }, - onC: () => { /* … */ } -}; -``` - -约 650 行接线降至约 250 行。可按 12 个类逐个 commit,每个独立可回滚。 - -**风险**:低。ArkTS 对象字面量要求有明确声明类型,`interface` 满足;改造过程中若某个 Hooks 含方法实现而非纯回调字段,保留为 class 但改为具名参数对象构造。 - ---- - -### S3 · 统一会话状态(3–5 天,**有行为风险**) - -**做什么** - -1. 抽出承载 §2.5 那 15 个共享字段的公共载体;`GeneralChatPageState` / `RemotePageState` 只保留各自特有字段; -2. 删除 `services/AppRootRouteState.ets`(88 行)——同时消掉硬违规 ① 的四分之一; -3. 收敛 `ConversationViewState.project` 的双源分支。 - -**前置 spike(0.5 天,必做)**:验证 ArkUI V2 的 `@Trace` 能否穿透 `@ObservedV2` 基类继承——本模块目前没有先例,不能假设。 - -- 若可以 → 用继承(`ConversationSessionState` 基类)。 -- 若不行 → **退化为组合**:两个 State 各持有一个 `ConversationCore` 字段,投影层只读 core。效果等价,只是访问路径多一层。 - -**Spike 结论(2026-08-06)**:采用组合方案。当前工程没有可证明 `@Trace` -跨 `@ObservedV2` 基类继承订阅关系的运行时先例,HAP 编译和 LocalTest 只能证明语法与 -状态行为,不能证明 UI 订阅穿透。`GeneralChatPageState` 与 `RemotePageState` 因此各自组合 -独立的 `ConversationCoreState`,组件和 `ConversationViewState` 直接读取 core。已通过窄屏 -真机 Local → Remote → Local 往返验证;宽屏真机仍需在折叠设备展开后复验。 - -**风险**:本方案中最高。但安全网充足——`ConversationStateUnit`(1057)+ `RemoteControllersUnit`(2177)直接覆盖这块。 - -**验证**:完整回路 + 真机走通四条路径:本地新建/继续会话、Remote 新建/继续会话、窄屏抽屉来源切换、宽屏来源切换。 - ---- - -### S4 · 拆解 God Facade(4–6 天,分批) - -**做什么**:按 S3 建立的特性边界,把 `AppRootRuntime` 切成 `ConversationController` / `RemoteConnectionController` / `SettingsController` / `FilePreviewController`,`AppRootRuntime` 退化为持有它们的组合根。 - -**实施结果(2026-08-07,已完成)**:已落地 `FilePreviewController`、 -`SettingsController`,并建立 `ConversationController` 的首批跨表面 composer/voice 状态边界; -对应旧方法已从 `AppRootRuntime` 删除,静态门禁禁止回流。现有连接实现也已从 -`RemoteConnectionViewModel` 更名为 `RemoteConnectionController`,根运行时的 21 个状态 getter -和 11 个连接状态转发已删除;路由、workspace/session 列表、polling/heartbeat 的 28 个 -owner 转发也已改为直接绑定。云账号凭据、持久化、云模型目录、权限设置与账号设备切换 -闭环也已迁入 `SettingsController`,包括原 91 行的 `selectCloudAccountDevice`。 -远程会话的发送、停止/重试、工具动作、时间线投影与 polling cursor 运行态已迁入 -`ConversationController`;Remote 新建会话的设备/workspace/模型选择、提交与路由流程也由其 -统一持有。本地会话的打开/新建/发送、草稿、归档与时间线投影同样已收口到该 owner。 -根运行时由 2608 行降至 372 行;纯依赖实例化和回调接线迁入 -`AppRootRuntimeComposition`,其抽象端口仍由根运行时实现,避免装配层反向拥有页面生命周期行为。 -HAP、完整 LocalTest 与窄屏真机 Local → Remote → Local 往返均通过。尚未完成 -宽屏复验,仍等待可用的展开设备。 - -顺序(每步独立 commit): - -1. 清理 45 个一行转发——调用点直接指向真正的 owner; -2. 拆 621 行字段初始化块(L140–761)为各 Controller 的构造; -3. 处理 `selectCloudAccountDevice`(91 行)等长方法; -4. 按官方 V2 形状收口:view 用 `@ComponentV2` + `@Local` 持有**所属特性的** ViewModel,而非同一个巨型对象。 - -**与 S5 的次序说明**:本阶段涉及的装配层(`AppRootPresentation` 及其拆出的 host)已经是 V2,`AppRoot.ets` 虽是 V1 但无任何状态装饰器,因此第 4 步不需要等 S5。S5 排在其后,是因为它的主体(`ConnectView`、`AppSidebar` 等叶子组件)与 Controller 拆分互不相干,放在结构稳定之后迁移,可以避免同一文件被两种性质的改动连续翻动。 - -目标:`AppRootRuntime` < 500 行。消除硬违规 ③。 - -**风险**:中。生命周期是重点——`aboutToAppear` / `onPageShow` / `onPageHide` / `aboutToDisappear` / `handleRootBack` 的调用顺序与轮询启停必须逐一保持。`LifecycleUnit`(748)+ `AppRootLifecycleUnit`(129)+ `AppRootRuntimeStartupUnit`(51)覆盖此处。 - ---- - -### S5 · V1 全量迁移到 V2(4–5 天,**逐文件有行为风险,已完成 2026-08-07**) - -**做什么**:把 §2.8 清单里的 15 个 V1 struct 全部迁到 `@ComponentV2`,之后 `pages/` 下不再存在 V1 装饰器。 - -**为什么值得单列一个阶段**(而不是像初版那样"顺手统一"): - -1. **官方推荐**。V2 是官方对新项目的推荐范式,官方 MVVM 示例也是 `@ComponentV2` + `@Local` 持有 ViewModel 实例的形式。范式统一后 §4 的目标结构与官方文档一一对应,不需要读代码的人在两套心智模型间切换。 -2. **消除一类难定位故障**。§2.8 已核查:目前**没有**任何 `@ObservedV2` 对象被 V1 装饰器持有。但只要 V1 struct 还在,后续任何一次改动都可能把状态对象传进 `@Prop`,得到"编译通过、界面不刷新"——与抽屉不刷新(§1.3.2)同型的故障,本模块已经为这类问题付出过一次排查成本。 -3. **观测边界更明确**。V2 的 `@Trace` 深度观测与 `@Monitor` 的新旧值回调,比 V1 的 `@Observed` / `@ObjectLink` 嵌套观测更容易推理,也更容易在 review 中判断对错。 - -**迁移映射表**(逐条替换,不是全局改名): - -| V1 | V2 | 语义差异——**必须逐字段确认,这是本阶段的主要风险**| -| --- | --- | --- | -| `@Component` | `@ComponentV2` | — | -| `@State`(53) | `@Local` | 基本等价,子组件自有状态 | -| `@Prop`(79) | `@Param` | **不等价**。V1 `@Prop` 是**深拷贝**,子组件可以本地改写;V2 `@Param` 是**按引用只读**,子组件不可赋值。凡是子组件确实在本地改写该字段的,需迁为 `@Param @Once`(仅初始同步、之后子组件自持)或 `@Local` + 显式初始化 | -| `@Link`(2) | `@Param` + `@Event` | **不等价**。V2 取消了双向绑定,须拆成"向下传值 + 向上回调"。仅 `CreateSessionSheet.ets` 的 `sessionTitle` / `instruction` 两处 | -| `@Watch`(4) | `@Monitor` | 回调签名不同,`@Monitor` 提供新旧值;`RemoteControlSettingsSheet` 1 处、`StreamingMarkdownContent` 3 处 | -| `@BuilderParam`(7) | 不变 | V2 同样支持,不属于迁移面 | - -**顺序**(每个文件独立 commit,从小到大以便先摸清坑): - -1. 先迁 5 个小文件(`DefaultAccountAvatar` 18、`ConversationSourceSwitcher` 40、`AppRoot` 48、`ChatStatusBar` 60、`ThinkingBlock` 67)——`AppRoot` 无任何状态装饰器,是纯粹的 `@Component` → `@ComponentV2` 改名,可作为第一个 commit 验证工具链; -2. 迁 `@Link` / `@Watch` 三个特殊文件(`CreateSessionSheet` 226、`StreamingMarkdownContent` 142、`RemoteControlSettingsSheet` 872)——语义变化集中在这里,单独处理便于 review; -3. 迁剩余中等文件(`FileReferenceCard` 85、`OpenBitFunAccountLoginPage` 146、`MarkdownContent` 199、`SettingsSheet` 297、`ModelServiceSettingsPanel` 662); -4. 最后迁 `AppSidebar`(908)与 `ConnectView`(1344)——这两个占 V1 总量 44%,且是 S6 的拆分目标,**先迁后拆**:若先拆再迁,会在拆分过程中制造 V1/V2 交界,把两类风险叠在同一个 commit 里。 - -**风险**:中。集中在 `@Prop` → `@Param` 的 79 处——**不能批量替换**,每一处都要确认子组件是否本地改写。`StreamingMarkdownContent` 尤其要小心:它的 3 个 `@Prop` 全部带 `@Watch`,流式 Markdown 的增量渲染依赖这套回调时序。 - -**验证**:完整回路,且**每个 commit 都要真机验证该组件所在界面**。重点回归:连接流程(`ConnectView`)、侧栏与会话列表(`AppSidebar`)、Remote 控制设置(`RemoteControlSettingsSheet`)、流式回复渲染(`StreamingMarkdownContent`)、新建会话(`CreateSessionSheet`)。 - -**完成标志**:`ArchitectureUnit` 的 V1 已知清单清空,范式断言由"等于清单"翻为"必须为空";此后新增 V1 组件在 CI 直接失败。 - -**实际结果**:15 个 V1 页面组件全部迁移。逐字段审计结论是:只读父输入迁为 -`@Param`;需要用户编辑的值由子组件 `@Local` draft 持有,并通过显式事件上送; -`CreateSessionSheet` 的两个 `@Link` 拆为 `@Param` + `@Event`; -`StreamingMarkdownContent` 与 `RemoteControlSettingsSheet` 的监听迁为 `@Monitor`。 -本轮没有字段符合“只接收一次父级初值、之后完全由子组件持有”的语义,因此没有使用 -`@Param @Once`。HAP 编译同时验证 `@Param` 未被子组件赋值,架构门禁中的 V1 清单 -已经为空。HAP、LocalTest、窄屏启动与 Local → Remote → Local 往返均通过。 - ---- - -### S6 · 纯化组件层(3–4 天,纯视觉风险) - -**做什么** - -1. 侧栏和工具列表的重复 glyph 已分别收口到 `SidebarGlyphs.ets`、`ToolGlyphs.ets`; -2. 按视觉关注点拆出 `ConnectAccountDevicePage`(账号设备选择)、 - `ChatMessageContent`(图片/Markdown/文件卡片)两个 V2 子组件, - `AppSidebar` 从 908 行降至 700 行,`ConnectView` 从 1344 行降至 1055 行。 - `ToolStatusList` 的业务分组和交互状态仍保留在原 owner,避免纯视觉迁移改变工具动作时序。 -3. S1 同时完成根展示面的纯视觉拆分:Remote、窄屏路由、宽屏会话和 overlay 已由 - 四组 V2 host/surface 组件持有,`AppRootPresentation` 当前为 406 行。 -4. 第二批拆分已落地:`ConnectManualPairingOverlay` 持有手工配对表单, - `ToolInteractionPanels` 持有工具 JSON 编辑/批准和问答草稿,`ChatMessageChrome` - 持有用户气泡、重试提示和流式三点动画。对应主文件当前分别为 - `ConnectView` 695 行、`ToolStatusList` 1106 行、`ChatMessageBubble` 972 行;预算已写入 - `pnpm run harmony:architecture`,禁止展示职责回流。 - -**目标已按 §3.4 修正**:不包含"切断 `components → state`"——该 import 合法。**也不再包含装饰器统一**——S5 已完成,本阶段拆出的新组件天然是 V2。 - -**风险**:纯视觉回归。**每一步必须真机截图,窄屏 + 宽屏 × 浅色 + 深色四组**;所有颜色走 `Theme.ets` 语义 token,`pnpm run theme:color-audit:all` 必须干净。 - -**实际进度(2026-08-07,进行中)**:已完成窄屏浅色启动、侧栏展开、 -Local → Remote → Local 往返截图;新接入 HUAWEI MatePad Pro `WEB-W00` -(2880 × 1920),已安装本轮 HAP,并完成 Pad 浅色/深色下 Local、Remote Home 和连接 -设备面板截图,应用进程持续存活。宽屏合同不等于 Pad 合同:现有 -`ConversationLayoutPolicy` 同时读取零/一/两道纵向折痕,两道折痕的三折叠继续使用 -“左屏 master + 中/右两屏同一个 detail”,正文与关键热区选择不跨第二道折痕的最宽 -内容带;零/一/两道折痕、非对称三屏和非法折痕均有 LocalTest 覆盖。 - -三折叠完整展开及双屏/三屏动态切换仍需要真实两折痕设备验证,Pad 不能替代该项; -文件预览打开/关闭矩阵也尚未闭合,因此 S6 仍不能标记为完成。 - ---- - -### S7 · 关闭护栏(0.5 天) - -原 3 处 `services/` → `pages/` 反向依赖已在 S1/S3 的文件归属迁移中清零;当前 -`pnpm run harmony:architecture` 的 `serviceToPages`、`componentToViewmodel`、 -`viewmodelToComponents` 均为空,V1 清单也为空。门禁已从基线清单切换为永久空集, -并补齐了 `AGENTS.md` 与 `ArchitectureUnit` 的归属说明。 - ---- - -## 6. 每阶段固定验证回路 - -```bash -source scripts/ohos-env.sh - -# 1. 构建 -"$HVIGORW" --mode module -p product=default -p module=entry@default assembleHap --no-daemon - -# 2. 本地单元测试(6612 行 hypium 用例) -"$HVIGORW" --mode module -p module=entry@default -p ohos.test.type=LocalTest test --no-daemon - -# 3. 颜色审计 -pnpm run theme:color-audit:all - -# 4. 真机验证(折叠设备 5ZU0226202001116) -hdc -t 5ZU0226202001116 shell snapshot_display -f /data/local/tmp/s.jpeg -hdc -t 5ZU0226202001116 file recv /data/local/tmp/s.jpeg ./s.jpeg -``` - -设备侧注意事项(已踩过的坑): - -- bundle 名以 `AppScope/app.json5` 为准,和手表端共用且作为升级兼容标识保持稳定;OpenBitFun 是产品展示名,不迁移 package identity、Preferences/HUKS/RDB/KV 的持久化标识。`distributedKVStore` 按 bundleName + storeId 隔离,任意改名都会让手机与手表落入互不相干的库,并让已安装用户丢失配对与登录恢复能力; -- `hdc` 必须带 `-t `,否则报 `[Fail]ExecuteCommand need connect-key`(列出了两个 target); -- 外屏分辨率 1080×2444;点击用 `hdc -t shell uinput -T -c X Y`。 - -**真机验证的最低集合**(每阶段都要过):窄屏抽屉 Local ↔ Remote 来源切换、宽屏三栏、文件预览打开/关闭、深浅色各一轮。 - ---- - -## 7. 明确不做的事 - -- **不引入三层架构(products / features / commons)**。理由见 §1.2:单 entry 模块,收益为零、构建复杂度为正。 -- **不引入新的状态管理库或跨端抽象层**。问题是组织方式,不是工具。 -- **不重构 `services/general-chat/`(21 文件 / 3296 行)内部结构**。它自身分层是干净的,只需在 S7 切断对 `pages/` 的反向依赖。 -- **不追求行数目标本身**。S1 + S2 净减约 800 行是副产品;真正的收益是"改一处不用改三处"和"违规能被 CI 挡住"。 - -> 初版方案曾把"V1 → V2 全量迁移"列在本节。该判断已推翻——理由见 §5 的 S5 阶段,迁移已提升为独立阶段。 - ---- - -## 8. 遗留事项 - -- **窄屏"刷新"与"助手选择"入口缺失**(baseline `6c35485bb` 引入)。删除 `RemoteHomeView.ets` 统一窄屏 Remote 界面时,这两个入口一并移除,宽屏本来就没有。待定:是否补进共享侧栏的 `...` 菜单。此项与本重构无依赖关系,可独立处理。 -- **S6 组件纯化尚未完成**。优先继续拆分 `ToolStatusList`、`ChatMessageBubble` 与 - `ConnectView`,每次拆分保持动作 owner 和时序不变。 -- **视觉验证矩阵尚未闭合**。仍需补窄屏深色、文件预览打开/关闭,以及宽屏三栏的 - 深浅色截图;后者等待可用的展开折叠屏或平板 target。 diff --git a/src/apps/mobile/harmonyos/docs/wide-conversation-navigation-design.md b/src/apps/mobile/harmonyos/docs/wide-conversation-navigation-design.md deleted file mode 100644 index e333588e0f..0000000000 --- a/src/apps/mobile/harmonyos/docs/wide-conversation-navigation-design.md +++ /dev/null @@ -1,545 +0,0 @@ -# HarmonyOS 双屏与三屏会话导航统一设计 - -Date: 2026-07-30 - -Scope: `src/apps/mobile/harmonyos`,主要涉及双屏/三屏布局、会话来源切换和响应式导航 - -## 实施状态 - -截至 2026-08-25: - -### 已实现 - -- 布局判定对齐官方 GridRow 横向断点:md `600vp` 起双栏,lg `840vp` 起 extra-wide;合盖与帐篷悬停(`HALF_FOLDED` / 双轴都半折,且不是仍横屏宽窗)强制不走 master-detail。三折单轴半折、另一轴展开时窗口仍是横屏宽窗,继续走 master-detail。不再用 `deviceType === tablet` 决定宽屏。 -- 展开折叠屏若 `getCurrentFoldCreaseRegion()` 为空,合成中线铰链(16vp)作为 master/detail 分界,避免内容压在铰链上。 -- 悬停态会话使用官方 `FolderStack`:上半为显示区(时间线),下半为操作区(Composer)。 -- 展开态只要存在可用纵向折痕(双折叠一道、三折叠两道),且当前视口放得下 master + detail,就进入 master-detail。 -- 宽屏本地与远程左栏在相同位置复用固定的“本地 / Remote”分段选择器,选中态由当前路由推导。 -- 来源选择器使用独立来源切换动作,不复用单屏 `enterCodeEntry()`;具体会话行只选择当前来源内的会话。 -- 宽屏来源切换使用 `clear(false)` 与 `pushPath(..., false)` 无转场替换路由,不播放页面进入或退出动画。 -- 宽屏本地和远程 master pane 均不提供全局侧边栏入口;远程宽屏标题栏已移除会叠加本地 drawer 的菜单按钮,单屏标题栏菜单保持不变。 -- 本地与远程来源切换使用路由合同计算目标,不累积跨来源返回路径。 -- 切回本地时停止手机侧远程轮询,但不清空远程活动会话或断开桌面。 -- 通过 `display.getCurrentFoldCreaseRegion()` 读取折痕;第一道有效纵向折痕用于 master/detail 分界。 -- 双折叠展开打开文件预览时,会话/预览分界对齐那一道折痕,而不是按视口对半切。三折一道或两道折痕对不齐三栏最小宽度时,仍对齐折痕做 focus split,不把整窗对半切。 -- 两道折痕或 lg 宽度被识别为 extra-wide,但会话仍使用同一个 master-detail,不创建第三会话栏。官方聊天分栏在 md/lg/xl 均为列表|会话;第三窗格只用于文件预览。 -- 第二道折痕不再把会话详情收成中间或右侧的单屏带。detail 从第一道折痕之后一直铺到窗口右缘,中间和右侧两屏共同承载同一会话;正文用最大宽度约束,避免无限制拉宽。不增加第三个业务 pane。 -- 监听 `foldStatusChange` 与 `foldDisplayModeChange`,折叠形态变化时重算几何。 -- 收起 master 后,会话 Header 铺满 detail;恢复按钮进入 leading slot,与 trailing 操作按钮 - 分别使用 detail 两侧的 16vp gutter。消息区和 Composer 继续独立限宽并按整窗居中,不再为 - 恢复按钮把整条内容带向右平移;该旧补偿在双屏没有可用余量时为 0,只有三屏会达到 72vp, - 导致同一交互在两种展开形态下位置不一致。 - -### 已验证 - -- 下列真机项仍以改前 HAP 为准,本轮官方断点/合成铰链/悬停改动需重新安装后复验。 -- `assembleHap` 在固定来源选择器和第二道折痕安全内容带实现后重新构建通过;主题颜色治理检查通过。 -- HarmonyOS 本地单元测试任务通过,覆盖折叠优先级、来源路由、连续来源切换不增长返回栈、零/一/两道折痕、非法折痕和非对称三屏几何。 -- `ConversationLayoutPolicy` 的新增行、函数和分支覆盖率均为 100%。 -- 在 HUAWEI Mate X7(`DEL-AL10`,展开分辨率 `2210 x 2416`)单折双屏真机展开态验证:本地与远程复用同一个“本地 / Remote”选择器,两种状态下控件边界均为 `[87,358][1004,464]`;选中态、下方列表来源和双向一步切换正确,不弹出单屏连接 Sheet,master/detail 分界与一道折痕一致。 -- 固定来源选择器改为 `clear(false)` / `pushPath(..., false)` 后重新安装 HAP,并在点击后连续抓取中间帧;本地与远程完整布局直接更新,未出现页面滑入、缩放或淡入转场。该无转场路径只由宽屏来源选择器调用。 -- 移除远程宽屏菜单入口后重新安装 HAP,在 Mate X7 展开态验证:远程 master 顶部只保留右侧设置按钮,控件树中该 header 仅有 `[897,177][1016,296]` 的右上点击区,没有左上全局侧边栏点击区;来源选择器仍可一步切回本地。 -- 设备切换进入 busy 或工作区变化时清空远程项目创建菜单;空工作区路径不渲染创建按钮,也不能与菜单关闭哨兵值匹配,避免选择设备后误弹 Code/Cowork 菜单。 -- 设备目录采用“设备列表 → 当前设备的工作区树”,不再把工作区和会话分别嵌套在每一台设备下。当前设备使用唯一卡片选中态;点击在线设备同时切换控制目标并进入该设备 Remote Home,点击离线设备只查看缓存目录。 -- 工作区标题旁的加号打开当前设备已有工作区选择器,语义为“添加工作区”,不伪装成协议尚不支持的远端建目录;每个工作区行自己的加号在该工作区新建会话。设备/工作区目录模式不再在其上方重复本地最近对话。 -- 未配对时远程设备身份保持为空,由界面显示“尚未连接桌面端”;只接受二维码 `dn` 参数或账号设备返回的真实名称,不再使用 `MacBook Pro` 伪默认值,清除配对时同步清空设备身份。 -- 移除伪设备名后重新安装 HAP,在 Mate X7 展开未连接态验证:右侧远程占位标题显示“尚未连接桌面端”,控件树中不存在 `MacBook` 文本。 -- 在同一设备的折叠单屏态(`1080 x 2444`)验证:页面保持原单屏头部和 Composer,可打开原侧边栏;点击 `Remote` 继续打开原“选择桌面设备”Sheet,系统返回可关闭 Sheet 并恢复本地 Home;本地历史会话的显示保持原样。 -- 折叠单屏连接已有在线桌面后验证:远程 Home 保留原头部、菜单和会话列表;进入已有远程会话后保留原会话头部与 Composer;系统返回从远程会话回到远程 Home;打开原侧边栏并选择本地会话可恢复本地内容。全程未发送消息、运行命令或启动远程任务。 -- 单屏根 `ChatHome` 的系统返回基线已核实:历史本地会话仍投影在根路由,侧边栏可见时也未接入根返回拦截,因此返回会退出 Ability。本次宽屏改动不改变该行为;是否优化应作为独立单屏导航问题处理。 -- 在 HUAWEI MatePad Pro(`WEB-W00`,`2880 x 1920`)安装最新 HAP,浅色与深色均验证本地/Remote 来源选择器、常驻 master、Remote 未连接占位和居中的连接设备面板;布局边界稳定,应用进程持续存活。Pad 验证只覆盖无折痕宽屏,不替代下述三折叠真机项。 - -### 待验证 - -- 本轮改动后的 Mate X7 展开态:折痕为空时应走中线铰链,而不是固定 344。 -- Mate X7 悬停态:`FolderStack` 将 Composer 放到下半操作区。 -- 两道折痕的三折叠真机完整展开态(Mate X7 不覆盖此项)。 -- 三屏与双屏之间的真实折叠切换连续性。 - -当前 Mate X7 的 DisplayManagerService 报告 `dms.hidumper.supportdebug false`,因此单屏验收使用设备真实折叠状态完成,没有用显示调试命令模拟合盖。 - -在上述真机项完成前,不应把三屏手工验收标记为完成。 - -## 背景 - -HarmonyOS 手机在展开双屏、完整展开三屏或其他宽屏形态下,本地会话和远程会话使用了两套不同的左栏: - -- 本地会话使用常驻的 `AppSidebar`。 -- 远程会话使用独立的 `RemoteMasterPane`。 -- 从远程会话返回本地会话时,需要先点击远程左栏左上角的菜单按钮,唤出全局侧边栏,再选择本地会话。 - -这使本地和远程两个平级的会话来源表现为不同层级的导航。问题不只是视觉不统一,也增加了双屏下的操作路径和认知成本。 - -本设计统一宽屏 master pane,并明确三屏继续沿用双屏的 master-detail 信息架构。现有折叠单屏和普通窄屏交互必须保持不变。 - -## 目标 - -1. 在宽屏左栏中统一本地和远程会话的导航框架。 -2. 用固定的“本地 / Remote”来源选择器表达一级上下文,让具体会话只承担二级内容选择。 -3. 本地与远程分别保留自己的会话数据、连接状态和特有操作。 -4. 切换来源时保留双方最后的活动会话及输入状态。 -5. 展开、折叠只改变布局,不改变当前路由或会话状态。 -6. 不改变现有单屏侧边栏、连接 Sheet、页面头部和系统返回行为。 -7. 三屏左侧第一屏继续承载 master pane,右侧两屏共同承载 detail pane。 - -## 非目标 - -- 不把本地会话和远程会话混合为一个无来源区分的列表。 -- 不重写单屏 `AppShell` 或抽屉动画。 -- 不改变远程连接、配对、鉴权或断线重连协议。 -- 不因为切换会话来源而停止桌面端正在执行的任务。 -- 第一阶段不调整 `RemoteCreate` 的页面结构。 -- 宽度阈值对齐官方 md/lg(600 / 840);合盖与悬停强制单屏(悬停走 FolderStack 上下分带)。展开后是否进入宽屏由宽度、纵向折痕和折叠状态决定,不使用 `deviceType`。 -- 不因为三屏增加一个独立的第三会话栏、第二套会话列表或新的业务路由模式。文件预览可以占用第三窗格。 -- 展开会话不改造成 `FoldSplitContainer` 外壳:该组件只有预设比例,无法对齐实测折痕像素。折叠屏展开继续用折痕几何;悬停用官方 `FolderStack`。 - -## 当前逻辑 - -### 响应式判定 - -`AppRootPresentation.isWideLayout()` 当前遵循以下逻辑: - -```text -设备处于折叠状态 -> 单屏 -设备处于帐篷悬停(HALF_FOLDED / 双轴都半折,且不是仍横屏宽窗) -> 单屏 + FolderStack(上显示 / 下操作) -设备单轴半折、另一轴展开,窗口仍是横屏宽窗 -> 宽屏 master-detail(左第一屏 master,右展开带 detail) -设备非折叠,宽视口(≥600vp 或 media query),有纵向折痕,且放得下两栏 -> 宽屏 -设备非折叠,宽视口,折叠屏展开且折痕缺失 -> 宽屏,合成中线铰链 -设备非折叠,宽视口,无折痕 -> 宽屏(断点驱动,含平板) -其他 -> 单屏 -``` - -折叠与悬停优先于宽度和折痕。双折叠展开的一道折痕与三折叠的两道折痕使用同一套 master-detail,不新增第三会话栏。 - -本应用自己用折痕几何做 master-detail,不能把会话交给系统 `Navigation` 分栏或平行视界。`module.json5` 的 `easyGo` 必须把 `wideWindowMode` 与 `squareWindowMode`(三折 M 态 / 双折展开)设为 `original`。根 `Navigation` 保持 `NavigationMode.Stack`,只承担单屏路由。宽屏可见内容必须画在 `Navigation` 外面,按 `activeRoute` 渲染 `WideConversationHost`;否则即使用 Stack,HarmonyOS 6.1 仍可能把 `Navigation` 切成 1:1,会话锁在左半屏,右侧露出 `startWindow`。 - -### 路由分流 - -当前 `AppRootPresentation.RouteContent()` 大致为: - -```text -ChatHome / GeneralChat + 宽屏 -> WideGeneralChatContent -RemoteHome + 宽屏 -> WideRemoteHomeContent -RemoteChat + 宽屏 -> WideRemoteChatContent -其他 -> RouteSurfaceContent -``` - -其中单屏路径最终使用: - -```text -RouteSurfaceContent(route, true, true) -``` - -该路径负责现有页面头部、侧边栏按钮和返回按钮,是本设计的不可变边界。 - -### 当前不一致 - -```text -宽屏本地:AppSidebar + 本地会话内容 -宽屏远程:RemoteMasterPane + 远程会话内容 -``` - -改造前,`RemoteMasterPane` 左上角菜单按钮调用 `openSidebar()`。因此远程到本地不是左栏内的平级切换,而是“打开另一层侧边栏,再选择本地内容”。改造后,该宽屏菜单入口被移除,本地和远程都只通过常驻来源选择器切换;单屏菜单入口不受影响。 - -### 当前三屏表现 - -当前代码只有单屏和宽屏两档,没有三屏专用分支。`WIDE_MASTER_PANE_WIDTH` 固定为 `344`,detail pane 使用 `layoutWeight(1)` 占据剩余宽度。 - -因此三屏完整展开时,现有结构会自然表现为: - -```text -固定 344 的 master pane + 横跨其余两屏的 detail pane -``` - -该方向与本设计目标一致,但仍需处理左栏边界与第一道折痕对齐、第二道折痕位于详情内部时的控件安全区,以及会话内容过度横向拉伸的问题。 - -## 设计原则 - -### 1. 路由是会话来源的唯一事实 - -宽屏左栏当前模式直接从路由推导,不新增独立的 `wideActiveSource` 状态: - -| 当前路由 | 宽屏会话来源 | -| --- | --- | -| `ChatHome` | 本地 | -| `GeneralChat` | 本地 | -| `RemoteHome` | 远程 | -| `RemoteChat` | 远程 | - -这样可以避免路由、左栏选中态和右侧内容之间发生状态漂移。 - -### 2. 统一外壳,不混合领域状态 - -统一的内容包括: - -- 左栏宽度、边界和背景。 -- 位置、尺寸、选中态和反馈一致的来源分段选择器。 -- 标题、搜索、列表行、选中态和底部操作的视觉节奏。 -- 连接失败、空列表和加载状态所在的布局区域。 - -继续分别持有的内容包括: - -- 本地置顶、最近、归档以及本地草稿。 -- 远程设备、工作区、连接状态和远程会话分页。 -- 本地与远程各自的活动会话和消息状态。 - -### 3. 来源切换是导航,不是生命周期销毁 - -切换来源时禁止调用以下行为: - -- 断开远程连接。 -- 清空本地或远程活动会话。 -- 清空任何一侧草稿或附件。 -- 停止桌面端正在运行的任务。 -- 重置设备、工作区或账号状态。 - -手机侧只允许按现有生命周期规则暂停或恢复当前不可见远程会话的轮询。 - -### 4. 三屏是双屏的超宽形态 - -三屏不引入新的信息层级: - -- 左侧第一屏继续显示双屏下的 master pane。 -- 中间屏和右侧屏共同组成一个 detail pane。 -- 本地/远程来源选择器、列表能力和路由语义与双屏完全一致。 -- 双屏与三屏之间切换只重新计算几何,不改变当前来源或会话。 - -## 目标布局 - -```text -RouteContent(route) -├── 非宽屏 -│ └── 原 RouteSurfaceContent,保持不变 -│ -├── 宽屏会话路由 -│ └── WideConversationShell -│ ├── WideConversationMasterPane -│ │ ├── 固定的“本地 / Remote”来源选择器 -│ │ ├── 本地模式:本地操作和会话列表 -│ │ └── 远程模式:远程状态、操作和会话列表 -│ └── DetailPane -│ ├── 本地会话内容 -│ ├── 远程会话内容 -│ └── 远程 Home 占位内容 -│ -└── 其他宽屏路由 - └── 维持现有 RouteSurfaceContent -``` - -建议将宽屏公共结构收敛为 `WideConversationShell` 或等价组件。单屏 `AppSidebar` 仍由 `AppShell` 管理,不应被新宽屏组件替代。 - -### 双屏几何 - -```text -┌────────────────────┬──────────────────────────────────┐ -│ Master pane │ Detail pane │ -│ 来源选择器 + 会话列表 │ 当前会话或 Home 占位 │ -└────────────────────┴──────────────────────────────────┘ -``` - -### 三屏几何 - -```text -┌────────────────────┬──────────────────┬──────────────────┐ -│ Master pane │ │ -│ 来源选择器 + 会话列表 │ Detail pane │ -│ │ 当前会话或 Home 占位 │ -└────────────────────┴──────────────────┴──────────────────┘ -``` - -三屏中间和右侧不是两个独立的 detail,也不分别承载不同功能。它们是同一个连续的 detail pane。 - -## 三屏几何与折痕 - -### 布局模式 - -业务布局仍然只需要两档: - -```text -Compact -> 现有单屏页面和抽屉 -MasterDetail -> 双屏和三屏共同使用的 master-detail -``` - -可以为 `MasterDetail` 额外携带 `isExtraWide`、可用宽度和折痕区域等 presentation 几何信息,但不应新增 `TriplePane` 业务模式。 - -### Master pane 边界 - -通过 `display.getCurrentFoldCreaseRegion()` 读取 `creaseRects`,可以同时表达双屏的一道折痕和三屏的两道折痕。该调用必须使用与现有 `safeFoldStatus()` 相同的异常回退原则。 - -当前 `344` 宽度可以作为无折痕信息时的兜底值。能够获得有效纵向折痕时: - -1. 双屏优先让 master/detail 分界与第一道折痕对齐。 -2. 三屏同样让 master pane 占据第一屏,并与第一道折痕对齐。 -3. 必须为折痕自身保留安全间距,避免列表行、来源选择器或点击热区跨越折痕。该占位使用页面底色,不把折痕宽度画成分隔条。 -4. 折痕坐标为像素,ArkUI 布局宽度使用布局单位;进入布局策略前必须转换到同一坐标系。 - -折痕信息不可用、坐标不在当前应用内容区域内或转换失败时,继续使用当前固定 master 宽度和弹性 detail,不得阻断页面渲染。 - -### Detail pane - -三屏 detail 的外层容器横跨中间和右侧两屏,但内部会话内容不应无约束拉伸: - -- 页面头部和背景可以占满整个 detail pane。 -- 消息阅读区、状态内容和 Composer 应设置合理最大宽度,并在 detail pane 内稳定对齐。 -- 存在第二道折痕时,会话详情仍占据第一道折痕之后的整段剩余宽度(中间+右侧),不得只留在最宽的那一屏。 -- 收起 master 后:双折和三折都把会话铺满整窗,Header 跨满 detail,恢复按钮与右侧操作按钮分别贴合两侧 16vp gutter;消息区和 Composer 保持居中限宽。展开态三折 detail 仍从第一道折痕铺到右缘;只有收起左栏时才占用第一屏。 -- 最大宽度不能按视口宽度缩放字体,只限制内容容器。 -- 第二道折痕位于 detail 内部时,不因此再切出第三会话栏;关键点击控件随内容带一起落在剩余两屏内。 -- 第一阶段不利用第二道折痕拆出文件、任务或其他辅助面板。 - -### 几何更新 - -在以下事件后重新计算几何: - -- `onAreaChange` 返回新的应用内容宽度。 -- `foldStatusChange` 返回新的折叠状态。 -- 折叠状态变化后重新读取当前折痕区域。 - -几何更新只能影响 presentation。不得由此压入或替换路由、连接远程设备、清空活动会话或重置草稿。 - -## 左栏交互 - -### 固定的来源选择器 - -宽屏左栏在本地和远程状态下都显示同一个“本地 / Remote”分段选择器: - -| 选中来源 | 选择器状态 | 下方内容 | -| --- | --- | --- | -| 本地 | `本地` 选中 | 本地操作和本地会话列表 | -| 远程 | `Remote` 选中 | 远程状态、操作和远程会话列表 | - -来源选择器是一级上下文控件;具体会话行是当前来源内的二级内容选择。两者不得使用相同的列表行视觉或选中语义。选择当前已激活分段不重复导航,选择另一分段才执行无转场来源切换,不能播放页面切换动画。 - -选择器在加载、空列表和远程断开状态下仍然可用。它不使用返回箭头、Home 图标或菜单按钮,因为来源切换既不是历史返回,也不是需要二次操作的菜单命令。 - -### 宽屏全局侧边栏规则 - -宽屏会话路由已经常驻一个 master pane,不应再从该 master pane 或 detail header 打开 `AppShell` 的全局 drawer。否则远程 master 会被本地 `AppSidebar` 再覆盖一层,形成两个左栏和两套导航层级;本地宽屏则没有对等且合理的行为,因为其 master 本身就是 `AppSidebar`。 - -因此断点规则固定为: - -- 折叠单屏和普通窄屏:本地 `GeneralChatHeader` 与远程 `RemoteHeader` 保留菜单按钮,继续打开全局侧边栏。 -- 展开宽屏:本地和远程 master pane 均不显示全局侧边栏按钮;来源切换只使用固定的“本地 / Remote”选择器。 -- 宽屏远程会话 detail 继续隐藏返回按钮,依靠常驻远程会话列表选择内容,不增加侧边栏入口。 -- 从宽屏折叠为单屏后,同一路由重新进入既有单屏组件,菜单按钮自然恢复;布局变化本身不自动打开 drawer。 - -### 本地模式 - -保持现有本地能力: - -- 使用显式宽屏 variant,将原 `Remote` 导航行替换为固定来源选择器。 -- 搜索。 -- 置顶会话。 -- 最近会话。 -- 归档展开与收起。 -- 新建会话。 -- 会话归档、导出和删除。 -- 账号与设置入口。 - -如果实现需要扩展 `AppSidebar`,应使用显式的宽屏 variant,默认值必须继续采用现有单屏 drawer 行为。禁止让宽屏条件散落在单屏侧边栏的事件处理中。 - -### 远程模式 - -保持现有远程能力: - -- 在远程标题区域与会话列表之间显示同一个来源选择器,并选中 `Remote`。 -- 先显示平铺设备列表和在线状态,当前设备只保留一个卡片选中态。 -- 下方只显示当前设备的工作区 → 会话树,不在每台设备行内复制目录。 -- 工作区标题加号添加桌面已有工作区,工作区行加号在其中新建远程会话。 -- 点击工作区切换工作区并展开会话;点击会话原位打开。 -- 连接、重连和远程设置。 - -未连接时,仅将远程内容区域替换为断开状态和连接操作。来源选择器必须继续显示。 - -## 来源切换状态机 - -### 本地切换到远程 - -宽屏来源切换使用单独的 presentation action,不复用单屏 `enterCodeEntry()`: - -```text -点击来源选择器的 `Remote` -├── 已存在可恢复的活动远程会话 -│ └── 进入 RemoteChat,恢复消息并恢复需要的轮询 -├── 已连接但没有活动远程会话 -│ └── 进入 RemoteHome -└── 未连接 - └── 进入 RemoteHome 的断开状态,由左栏提供连接操作 -``` - -宽屏下不应因为点击“远程”而自动打开单屏连接 Sheet。 - -### 远程切换到本地 - -```text -点击来源选择器的 `本地` -├── 暂停当前远程会话在手机侧的可见态轮询 -├── 保持远程连接和远程活动会话状态 -├── 清理来源切换产生的多余返回路径 -└── 进入 ChatHome,恢复本地活动会话 -``` - -切换回本地不应先打开全局侧边栏。 - -### 返回栈 - -来源切换不应不断向 `NavPathStack` 压入 `RemoteHome -> RemoteChat -> ChatHome` 等历史。应使用明确的来源切换导航语义,使切换后的系统返回行为仍符合当前 `AppRouteContract`。 - -普通的会话内导航继续使用现有规则: - -- `GeneralChat` 返回本地 Home。 -- `RemoteChat` 返回远程 Home。 -- `RemoteHome` 的单屏系统返回行为不变。 -- 根 `ChatHome` 的系统返回保持当前基线,不在本次宽屏改动中新增拦截;当前侧边栏打开时返回会退出 Ability。 - -## 折叠与展开 - -折叠和展开过程中不得修改当前路由。 - -### 单屏变宽屏 - -- `ChatHome` / `GeneralChat`:出现本地 master pane。 -- `RemoteHome` / `RemoteChat`:出现远程 master pane。 -- 当前会话、草稿、附件和滚动状态应尽可能保留。 - -### 宽屏变单屏 - -- 同一路由重新走现有 `RouteSurfaceContent`。 -- 单屏页面头部和侧边栏按钮重新出现。 -- 不自动打开侧边栏或 Sheet。 -- 不因布局变化连接或断开远程服务。 - -### 双屏变三屏 - -- master pane 继续位于左侧第一屏。 -- detail pane 从右侧一屏扩展到中间和右侧两屏。 -- 当前来源选中态、会话列表选中态和右侧会话保持不变。 -- 不出现新的第三栏,也不触发新的数据加载语义。 - -### 三屏变双屏 - -- detail pane 从两屏收回到右侧一屏。 -- 内部最大宽度和折痕安全区重新计算。 -- 当前路由、滚动状态、草稿、连接和活动会话保持不变。 - -## 单屏不可变边界 - -实现时必须保持以下路径的行为不变: - -1. `AppShell` 的侧边栏动画、遮罩、连接 Sheet 和设置 Sheet。 -2. `AppRootPresentation.SidebarContent()` 的现有调用链。 -3. `AppSidebar` 默认 drawer 模式的布局和事件。 -4. 单屏 `RemoteHomeView`、`RemoteChatHeader` 和 `GeneralChatHeader`。 -5. `enterCodeEntry()` 的单屏连接判断与 Sheet 行为。 -6. `AppRouteContract.backAction()` 的现有返回合同。 -7. 折叠状态优先于宽度的布局判定。 -8. 当前宽屏阈值及 media query 语义。 - -新增的宽屏 presentation action 只能由宽屏 master pane 调用,不应替换现有单屏 action。 - -## 建议实现边界 - -### Presentation - -主要改动应限制在: - -- `pages/components/AppRootPresentation.ets` -- 新增的宽屏 master pane 组件(如有) -- `AppSidebar.ets` 的显式宽屏 variant(仅在确有复用需要时) - -`RouteContent()` 应保留清晰的非宽屏早期分支,避免单屏意外进入统一宽屏组件。 - -### Runtime - -可以新增宽屏来源切换动作,但应复用既有的路由、草稿持久化和远程轮询能力。不要在 presentation 层直接操作连接器、轮询控制器或会话仓库。 - -### Contracts - -来源到路由的选择若包含条件判断,应放在可测试的纯函数或现有路由合同附近。不要让 UI 组件自行拼接返回栈。 - -## 验收矩阵 - -| 场景 | 预期结果 | -| --- | --- | -| 折叠单屏,本地 Home | 与改动前一致,可打开原侧边栏 | -| 折叠单屏,本地会话 | 原返回、草稿和会话操作不变 | -| 折叠单屏,远程未连接 | 原连接 Sheet 流程不变 | -| 折叠单屏,远程 Home | 原头部、菜单和返回行为不变 | -| 折叠单屏,远程会话 | 原会话头部、轮询和返回行为不变 | -| 展开宽屏,本地 Home | 来源选择器选中“本地”,左栏显示本地列表,可一步切 Remote | -| 展开宽屏,本地会话 | 来源选择器保持“本地”,会话选中态正确,右侧显示当前会话 | -| 展开宽屏,远程 Home | 来源选择器选中“Remote”,可一步切回本地,不显示全局侧边栏按钮 | -| 展开宽屏,远程会话 | 来源选择器保持“Remote”,会话选中态正确,右侧显示当前会话,不显示全局侧边栏按钮 | -| 宽屏点击远程会话 | 左侧立即选中新会话;右侧立即进入该会话,慢加载时显示时间线骨架,完成后原位替换为历史消息 | -| 三屏完整展开,本地会话 | 左屏显示本地 master,中间和右侧共同显示一个本地 detail | -| 三屏完整展开,远程会话 | 左屏显示远程 master,中间和右侧共同显示一个远程 detail | -| 三屏收起 master | detail 与 Header 铺满整窗,标题、消息区和 Composer 相对整窗居中;恢复按钮与右侧操作按钮分别使用两侧 16vp Header 边距 | -| 三屏远程断开 | 左屏仍显示来源选择器,右侧两屏显示一个连续断开状态 | -| 双屏切换到三屏 | detail 扩展到右侧两屏,路由和活动会话不变 | -| 三屏切换到双屏 | detail 收回右侧一屏,路由和活动会话不变 | -| 三屏 detail 内存在第二道折痕 | 关键点击控件不落在折痕安全区,正文不过度拉伸 | -| 远程断开后切本地 | 无需打开侧边栏,立即恢复本地会话 | -| 本地切远程再切回 | 两侧最后活动会话和草稿均保留 | -| 远程任务运行时切本地 | 桌面任务继续运行,不触发断开或停止命令 | -| 本地状态下折叠/展开 | 路由和活动本地会话不变 | -| 远程状态下折叠/展开 | 路由、连接和活动远程会话不变 | -| 连续切换来源 | 返回栈不持续增长,不出现跨来源错误返回 | -| 宽屏切换来源 | 左栏和 detail 直接更新,不播放页面进出场动画 | -| 设备选择完成 | 连接状态直接更新,不误弹项目的 Code/Cowork 创建菜单 | - -## 测试要求 - -### 自动化 - -- 为路由到宽屏来源的映射增加纯逻辑测试。 -- 为本地/远程目标路由选择增加测试,包括有无活动远程会话、连接和断开状态。 -- 为布局策略增加单屏、双屏、三屏宽度与零/一/两道折痕的纯逻辑测试。 -- 验证折痕信息缺失、异常或位于应用内容区域外时回退到当前固定 master 宽度。 -- 保留并运行现有 `AppRouteContract` 返回动作测试。 -- 确保 `AppSidebar` 的来源选择器开关默认关闭,单屏 action 仍使用 `enterCodeEntry()`,宽屏来源切换使用独立 action。 -- 确保宽屏远程 master 不调用 `openSidebar()`,同时保留单屏 `RemoteHeader.onOpenSidebar` 调用链。 - -### 构建 - -在配置好 DevEco Studio 环境后执行: - -```bash -source scripts/ohos-env.sh -"$OHPM" install -"$HVIGORW" --mode module -p module=entry assembleHap --no-daemon -``` - -### 真机手工验证 - -必须在支持折叠/展开的 HarmonyOS 真机上覆盖验收矩阵,重点录制: - -1. 在固定的“本地 / Remote”选择器中双向一步切换,并核对选中态与下方会话来源一致。 -2. 远程断开状态直接返回本地。 -3. 本地和远程会话中分别执行折叠、展开。 -4. 折叠单屏下原侧边栏、连接 Sheet 和系统返回流程。 -5. 双屏与三屏之间切换时 detail 的扩展、收回和状态连续性。 -6. 三屏第二道折痕附近的 Composer、菜单和会话操作热区。 - -本次 Mate X7 验收使用以下命令注入 HarmonyOS 系统返回键事件,并结合注入前后的控件树和截图判断实际导航结果: - -```bash -hdc -t 5ZU0226202001116 shell uitest uiInput keyEvent Back -``` - -该命令只用于触发系统 `Back` 事件,没有向应用代码加入临时返回拦截。折叠单屏远程会话收到事件后回到远程 Home;根 `ChatHome` 收到事件后的既有行为仍是退出 Ability。 - -## 完成标准 - -只有同时满足以下条件才视为完成: - -- 宽屏本地与远程使用统一的 master pane 框架。 -- 宽屏本地与远程在同一位置复用“本地 / Remote”来源选择器。 -- 宽屏远程可以通过来源选择器一步返回本地。 -- 宽屏本地与远程均不会在常驻 master pane 之上再打开全局侧边栏,折叠单屏仍保留原菜单入口。 -- 本地与远程会话状态可以往返恢复。 -- 远程断开时不会困住用户。 -- 折叠和展开不改变当前路由或连接状态。 -- 三屏保持双屏 master-detail 结构,右侧两屏只承载一个连续 detail pane。 -- 三屏会话正文宽度合理,关键点击控件避开折痕安全区。 -- 单屏验收矩阵全部与改动前一致。 -- 自动化测试、HarmonyOS 构建和真机手工验证均有记录。 diff --git a/src/apps/mobile/harmonyos/entry/.gitignore b/src/apps/mobile/harmonyos/entry/.gitignore deleted file mode 100644 index e2713a2779..0000000000 --- a/src/apps/mobile/harmonyos/entry/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -/node_modules -/oh_modules -/.preview -/build -/.cxx -/.test \ No newline at end of file diff --git a/src/apps/mobile/harmonyos/entry/build-profile.json5 b/src/apps/mobile/harmonyos/entry/build-profile.json5 deleted file mode 100644 index 0fc4bd6dbb..0000000000 --- a/src/apps/mobile/harmonyos/entry/build-profile.json5 +++ /dev/null @@ -1,52 +0,0 @@ -{ - "apiType": "stageMode", - "buildOption": { - "externalNativeOptions": { - "path": "./src/main/cpp/CMakeLists.txt" - }, - "resOptions": { - "copyCodeResource": { - "enable": false - } - } - }, - "buildOptionSet": [ - { - "name": "release", - "arkOptions": { - "obfuscation": { - "ruleOptions": { - "enable": false, - "files": [ - "./obfuscation-rules.txt" - ] - } - } - } - }, - ], - "targets": [ - { - "name": "default" - }, - { - "name": "ohosTest", - }, - { - // Emulator-only target. The x86_64 emulator cannot install the shipped - // arm64-only `default` artifact, so a separate target carries the ABI - // override. `default` stays arm64-only: nothing else may add x86_64 to it. - // Build with `-p module=entry@emulator`. - "name": "emulator", - "config": { - "buildOption": { - "externalNativeOptions": { - "abiFilters": [ - "x86_64" - ] - } - } - } - } - ] -} diff --git a/src/apps/mobile/harmonyos/entry/hvigorfile.ts b/src/apps/mobile/harmonyos/entry/hvigorfile.ts deleted file mode 100644 index 88474b5373..0000000000 --- a/src/apps/mobile/harmonyos/entry/hvigorfile.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { hapTasks } from '@ohos/hvigor-ohos-plugin'; - -// Include the current shared sources on every IDE and CLI build. -require('../miniapps/generate.cjs').generate(); -// Regenerate the HostTextRetranslator i18n rawfile catalog on every build. -require('../i18n/generate.cjs').generate(); - -export default { - system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ - plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ -} \ No newline at end of file diff --git a/src/apps/mobile/harmonyos/entry/obfuscation-rules.txt b/src/apps/mobile/harmonyos/entry/obfuscation-rules.txt deleted file mode 100644 index 1e7e54e150..0000000000 --- a/src/apps/mobile/harmonyos/entry/obfuscation-rules.txt +++ /dev/null @@ -1,23 +0,0 @@ -# Define project specific obfuscation rules here. -# You can include the obfuscation configuration files in the current module's build-profile.json5. -# -# For more details, see -# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/source-obfuscation - -# Obfuscation options: -# -disable-obfuscation: disable all obfuscations -# -enable-property-obfuscation: obfuscate the property names -# -enable-toplevel-obfuscation: obfuscate the names in the global scope -# -compact: remove unnecessary blank spaces and all line feeds -# -remove-log: remove all console.* statements -# -print-namecache: print the name cache that contains the mapping from the old names to new names -# -apply-namecache: reuse the given cache file - -# Keep options: -# -keep-property-name: specifies property names that you want to keep -# -keep-global-name: specifies names that you want to keep in the global scope - --enable-property-obfuscation --enable-toplevel-obfuscation --enable-filename-obfuscation --enable-export-obfuscation \ No newline at end of file diff --git a/src/apps/mobile/harmonyos/entry/oh-package-lock.json5 b/src/apps/mobile/harmonyos/entry/oh-package-lock.json5 deleted file mode 100644 index b1e8b8221f..0000000000 --- a/src/apps/mobile/harmonyos/entry/oh-package-lock.json5 +++ /dev/null @@ -1,19 +0,0 @@ -{ - "meta": { - "stableOrder": true, - "enableUnifiedLockfile": false - }, - "lockfileVersion": 3, - "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", - "specifiers": { - "libopenbitfun_crypto.so@src/main/cpp/types/libopenbitfun_crypto": "libopenbitfun_crypto.so@src/main/cpp/types/libopenbitfun_crypto" - }, - "packages": { - "libopenbitfun_crypto.so@src/main/cpp/types/libopenbitfun_crypto": { - "name": "libopenbitfun_crypto.so", - "version": "1.0.0", - "resolved": "src/main/cpp/types/libopenbitfun_crypto", - "registryType": "local" - } - } -} \ No newline at end of file diff --git a/src/apps/mobile/harmonyos/entry/oh-package.json5 b/src/apps/mobile/harmonyos/entry/oh-package.json5 deleted file mode 100644 index b5dcdfe340..0000000000 --- a/src/apps/mobile/harmonyos/entry/oh-package.json5 +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "entry", - "version": "1.0.0", - "description": "OpenBitFun HarmonyOS entry module.", - "main": "", - "author": "", - "license": "", - "dependencies": { - "libopenbitfun_crypto.so": "file:./src/main/cpp/types/libopenbitfun_crypto" - }, - "devDependencies": {}, - "dynamicDependencies": {} -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/cpp/CMakeLists.txt b/src/apps/mobile/harmonyos/entry/src/main/cpp/CMakeLists.txt deleted file mode 100644 index 1827ae28e6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/cpp/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -cmake_minimum_required(VERSION 3.16) -project(openbitfun_crypto) - -# Argon2 is a shared, platform-neutral source set. HarmonyOS and the KMP iOS -# actual both build this same implementation; keep the algorithm out of either -# platform directory so the two copies cannot drift. -set(OPENBITFUN_ARGON2_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../../shared/argon2) - -# Build the pinned upstream C codec for the device ABI. No runtime download. -include(FetchContent) -FetchContent_Declare(zstd_source - URL https://codeload.github.com/facebook/zstd/tar.gz/refs/tags/v1.5.7 - URL_HASH SHA256=37d7284556b20954e56e1ca85b80226768902e2edabd3b649e9e72c0c9012ee3) -FetchContent_GetProperties(zstd_source) -if(NOT zstd_source_POPULATED) - FetchContent_Populate(zstd_source) -endif() -set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE) -set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE) -set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE) -set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE) -add_subdirectory(${zstd_source_SOURCE_DIR}/build/cmake ${zstd_source_BINARY_DIR} EXCLUDE_FROM_ALL) - -add_library(openbitfun_crypto SHARED - relay_message_encoding.cpp - napi_argon2.cpp - ${OPENBITFUN_ARGON2_DIR}/argon2.c - ${OPENBITFUN_ARGON2_DIR}/core.c - ${OPENBITFUN_ARGON2_DIR}/encoding.c - ${OPENBITFUN_ARGON2_DIR}/ref.c - ${OPENBITFUN_ARGON2_DIR}/run.c - ${OPENBITFUN_ARGON2_DIR}/thread.c - ${OPENBITFUN_ARGON2_DIR}/blake2/blake2b.c -) - -target_include_directories(openbitfun_crypto PRIVATE ${OPENBITFUN_ARGON2_DIR}) -target_compile_definitions(openbitfun_crypto PRIVATE A2_VISCTL) -target_link_libraries(openbitfun_crypto PRIVATE libzstd_static libace_napi.z.so) diff --git a/src/apps/mobile/harmonyos/entry/src/main/cpp/napi_argon2.cpp b/src/apps/mobile/harmonyos/entry/src/main/cpp/napi_argon2.cpp deleted file mode 100644 index 0aae41df66..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/cpp/napi_argon2.cpp +++ /dev/null @@ -1,205 +0,0 @@ -#include -#include -#include -#include -#include - -#include "argon2.h" -#include "napi/native_api.h" - -void defineRelayMessageEncoding(napi_env env, napi_value exports); - -namespace { - -constexpr size_t ARGON2_OUTPUT_LENGTH = 32; - -struct Argon2Work { - napi_async_work asyncWork = nullptr; - napi_deferred deferred = nullptr; - std::vector password; - std::vector salt; - uint32_t memory = 0; - uint32_t time = 0; - uint32_t lanes = 0; - std::array output{}; - int result = ARGON2_OK; -}; - -void secureClear(uint8_t *data, size_t length) { - volatile uint8_t *cursor = data; - while (length > 0) { - *cursor = 0; - ++cursor; - --length; - } -} - -void clearWorkSecrets(Argon2Work *work) { - if (!work->password.empty()) { - secureClear(work->password.data(), work->password.size()); - } - secureClear(work->output.data(), work->output.size()); -} - -bool readBytes(napi_env env, napi_value value, const uint8_t **data, size_t *length) { - bool isTypedArray = false; - if (napi_is_typedarray(env, value, &isTypedArray) != napi_ok || !isTypedArray) { - return false; - } - napi_typedarray_type type; - size_t count = 0; - void *raw = nullptr; - napi_value arrayBuffer; - size_t offset = 0; - if (napi_get_typedarray_info(env, value, &type, &count, &raw, &arrayBuffer, &offset) != napi_ok || - type != napi_uint8_array || raw == nullptr) { - return false; - } - *data = static_cast(raw); - *length = count; - return true; -} - -napi_value throwTypeError(napi_env env, const char *message) { - napi_throw_type_error(env, nullptr, message); - return nullptr; -} - -napi_value throwError(napi_env env, const char *message) { - napi_throw_error(env, nullptr, message); - return nullptr; -} - -void executeArgon2(napi_env, void *data) { - auto *work = static_cast(data); - work->result = argon2id_hash_raw( - work->time, - work->memory, - work->lanes, - work->password.data(), - work->password.size(), - work->salt.data(), - work->salt.size(), - work->output.data(), - work->output.size()); - if (!work->password.empty()) { - secureClear(work->password.data(), work->password.size()); - } -} - -void completeArgon2(napi_env env, napi_status status, void *data) { - auto *work = static_cast(data); - if (status == napi_ok && work->result == ARGON2_OK) { - napi_value resultBuffer = nullptr; - void *resultData = nullptr; - napi_value resultArray = nullptr; - if (napi_create_arraybuffer(env, work->output.size(), &resultData, &resultBuffer) == napi_ok && - napi_create_typedarray(env, napi_uint8_array, work->output.size(), resultBuffer, 0, &resultArray) == napi_ok) { - std::memcpy(resultData, work->output.data(), work->output.size()); - napi_resolve_deferred(env, work->deferred, resultArray); - } else { - napi_value message = nullptr; - napi_value error = nullptr; - napi_create_string_utf8(env, "Unable to allocate Argon2id result.", NAPI_AUTO_LENGTH, &message); - napi_create_error(env, nullptr, message, &error); - napi_reject_deferred(env, work->deferred, error); - } - } else { - const char *reason = status == napi_cancelled ? "Argon2id operation was cancelled." : - (work->result == ARGON2_OK ? "Argon2id operation failed." : argon2_error_message(work->result)); - napi_value message = nullptr; - napi_value error = nullptr; - napi_create_string_utf8(env, reason, NAPI_AUTO_LENGTH, &message); - napi_create_error(env, nullptr, message, &error); - napi_reject_deferred(env, work->deferred, error); - } - - clearWorkSecrets(work); - napi_delete_async_work(env, work->asyncWork); - delete work; -} - -napi_value argon2idRaw(napi_env env, napi_callback_info info) { - size_t argc = 5; - napi_value argv[5] = {nullptr}; - if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok || argc != 5) { - return throwTypeError(env, "argon2idRaw requires five arguments."); - } - - const uint8_t *password = nullptr; - const uint8_t *salt = nullptr; - size_t passwordLength = 0; - size_t saltLength = 0; - if (!readBytes(env, argv[0], &password, &passwordLength) || - !readBytes(env, argv[1], &salt, &saltLength)) { - return throwTypeError(env, "Argon2id password and salt must be Uint8Array values."); - } - - uint32_t memory = 0; - uint32_t time = 0; - uint32_t lanes = 0; - if (napi_get_value_uint32(env, argv[2], &memory) != napi_ok || - napi_get_value_uint32(env, argv[3], &time) != napi_ok || - napi_get_value_uint32(env, argv[4], &lanes) != napi_ok) { - return throwTypeError(env, "Argon2id parameters must be unsigned integers."); - } - - auto *work = new (std::nothrow) Argon2Work(); - if (work == nullptr) { - return throwError(env, "Unable to allocate Argon2id work."); - } - work->password.assign(password, password + passwordLength); - work->salt.assign(salt, salt + saltLength); - work->memory = memory; - work->time = time; - work->lanes = lanes; - - napi_value promise = nullptr; - if (napi_create_promise(env, &work->deferred, &promise) != napi_ok) { - clearWorkSecrets(work); - delete work; - return throwError(env, "Unable to create Argon2id promise."); - } - - napi_value resourceName = nullptr; - if (napi_create_string_utf8(env, "OpenBitFunArgon2id", NAPI_AUTO_LENGTH, &resourceName) != napi_ok || - napi_create_async_work(env, nullptr, resourceName, executeArgon2, completeArgon2, work, - &work->asyncWork) != napi_ok) { - clearWorkSecrets(work); - delete work; - return throwError(env, "Unable to create Argon2id async work."); - } - if (napi_queue_async_work(env, work->asyncWork) != napi_ok) { - napi_delete_async_work(env, work->asyncWork); - clearWorkSecrets(work); - delete work; - return throwError(env, "Unable to queue Argon2id async work."); - } - return promise; -} - -napi_value init(napi_env env, napi_value exports) { - napi_property_descriptor descriptor = { - "argon2idRaw", nullptr, argon2idRaw, nullptr, nullptr, nullptr, napi_default, nullptr}; - napi_define_properties(env, exports, 1, &descriptor); - defineRelayMessageEncoding(env, exports); - return exports; -} - -} // namespace - -EXTERN_C_START -static napi_module module = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = init, - .nm_modname = "openbitfun_crypto", - .nm_priv = nullptr, - .reserved = {0}, -}; -EXTERN_C_END - -extern "C" __attribute__((constructor)) void RegisterOpenBitFunCrypto(void) { - napi_module_register(&module); -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/cpp/relay_message_encoding.cpp b/src/apps/mobile/harmonyos/entry/src/main/cpp/relay_message_encoding.cpp deleted file mode 100644 index a01d31d880..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/cpp/relay_message_encoding.cpp +++ /dev/null @@ -1,143 +0,0 @@ -#include -#include -#include -#include -#include -#include "napi/native_api.h" -#include "zstd.h" - -namespace { -constexpr uint8_t PREFIX[] = {0xff, 'O', 'Z', 1}; -constexpr size_t HEADER = 8; -constexpr size_t MAX_BYTES = 64 * 1024 * 1024; - -struct RelayCodecWork { - napi_async_work task = nullptr; - napi_deferred deferred = nullptr; - bool compress = false; - std::vector input; - std::vector output; - const char *error = nullptr; -}; - -napi_value fail(napi_env env, const char *message) { - napi_throw_error(env, nullptr, message); - return nullptr; -} - -void execute(napi_env, void *data) { - auto *work = static_cast(data); - const auto &input = work->input; - try { - if (work->compress) { - work->output.resize(ZSTD_compressBound(input.size()) + HEADER); - const size_t size = ZSTD_compress(work->output.data() + HEADER, - work->output.size() - HEADER, input.data(), input.size(), 1); - if (ZSTD_isError(size)) { - work->error = "Relay Zstd compression failed"; - return; - } - if (size + HEADER >= input.size()) { - work->output = std::move(work->input); - return; - } - std::memcpy(work->output.data(), PREFIX, sizeof(PREFIX)); - for (unsigned i = 0; i < 4; ++i) { - work->output[4 + i] = static_cast(input.size() >> (8 * i)); - } - work->output.resize(size + HEADER); - return; - } - if (input.size() <= HEADER || std::memcmp(input.data(), PREFIX, sizeof(PREFIX)) != 0) { - work->error = "Unknown Relay message encoding"; - return; - } - uint32_t expected = 0; - for (unsigned i = 0; i < 4; ++i) expected |= static_cast(input[4 + i]) << (8 * i); - if (!expected || expected > MAX_BYTES || - ZSTD_findFrameCompressedSize(input.data() + HEADER, input.size() - HEADER) != input.size() - HEADER) { - work->error = "Invalid Relay Zstd frame"; - return; - } - work->output.resize(expected); - if (ZSTD_decompress(work->output.data(), expected, input.data() + HEADER, input.size() - HEADER) != expected) { - work->error = "Relay decoded size mismatch"; - } - } catch (const std::bad_alloc &) { - work->error = "Unable to allocate Relay codec buffer"; - } -} - -void complete(napi_env env, napi_status status, void *data) { - std::unique_ptr work(static_cast(data)); - if (status != napi_ok) work->error = "Relay codec work failed"; - if (!work->error) { - void *bytes = nullptr; - napi_value storage, result; - if (napi_create_arraybuffer(env, work->output.size(), &bytes, &storage) == napi_ok && - napi_create_typedarray(env, napi_uint8_array, work->output.size(), storage, 0, &result) == napi_ok) { - std::memcpy(bytes, work->output.data(), work->output.size()); - napi_resolve_deferred(env, work->deferred, result); - } else { - work->error = "Unable to allocate Relay message"; - } - } - if (work->error) { - napi_value message, error; - napi_create_string_utf8(env, work->error, NAPI_AUTO_LENGTH, &message); - napi_create_error(env, nullptr, message, &error); - napi_reject_deferred(env, work->deferred, error); - } - napi_delete_async_work(env, work->task); -} - -napi_value transform(napi_env env, napi_callback_info info, bool compress) { - size_t argc = 1, length = 0, offset = 0; - napi_value arg, storage; - napi_typedarray_type type; - void *data = nullptr; - if (napi_get_cb_info(env, info, &argc, &arg, nullptr, nullptr) != napi_ok || argc != 1 || - napi_get_typedarray_info(env, arg, &type, &length, &data, &storage, &offset) != napi_ok || - type != napi_uint8_array) return fail(env, "Expected Relay message bytes"); - auto *src = static_cast(data); - const bool unchanged = compress ? length <= 256 || length > MAX_BYTES : length == 0 || src[0] != 0xff; - napi_value promise; - napi_deferred deferred; - if (napi_create_promise(env, &deferred, &promise) != napi_ok) return fail(env, "Unable to create Relay codec promise"); - if (unchanged) { - napi_resolve_deferred(env, deferred, arg); - return promise; - } - auto work = std::unique_ptr(new (std::nothrow) RelayCodecWork()); - if (!work) return fail(env, "Unable to allocate Relay codec work"); - work->compress = compress; - work->deferred = deferred; - try { - work->input.assign(src, src + length); - } catch (const std::bad_alloc &) { - return fail(env, "Unable to allocate Relay input"); - } - napi_value resource; - if (napi_create_string_utf8(env, "OpenBitFunRelayCodec", NAPI_AUTO_LENGTH, &resource) != napi_ok || - napi_create_async_work(env, nullptr, resource, execute, complete, work.get(), &work->task) != napi_ok) { - return fail(env, "Unable to create Relay codec work"); - } - if (napi_queue_async_work(env, work->task) != napi_ok) { - napi_delete_async_work(env, work->task); - return fail(env, "Unable to queue Relay codec work"); - } - work.release(); - return promise; -} - -napi_value encode(napi_env env, napi_callback_info info) { return transform(env, info, true); } -napi_value decode(napi_env env, napi_callback_info info) { return transform(env, info, false); } -} - -void defineRelayMessageEncoding(napi_env env, napi_value exports) { - napi_property_descriptor methods[] = { - {"encodeRelayMessage", nullptr, encode, nullptr, nullptr, nullptr, napi_default, nullptr}, - {"decodeRelayMessage", nullptr, decode, nullptr, nullptr, nullptr, napi_default, nullptr}, - }; - napi_define_properties(env, exports, 2, methods); -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/index.d.ts b/src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/index.d.ts deleted file mode 100644 index 667e0733ae..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -declare const openbitfunCrypto: { - encodeRelayMessage(plain: Uint8Array): Promise; - decodeRelayMessage(bytes: Uint8Array): Promise; - argon2idRaw( - password: Uint8Array, - salt: Uint8Array, - memory: number, - time: number, - lanes: number - ): Promise; -}; - -export default openbitfunCrypto; diff --git a/src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/oh-package.json5 b/src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/oh-package.json5 deleted file mode 100644 index 1c19fa8ed1..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/cpp/types/libopenbitfun_crypto/oh-package.json5 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "libopenbitfun_crypto.so", - "types": "./index.d.ts", - "version": "1.0.0", - "description": "OpenBitFun Argon2id NAPI bindings." -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/entryability/EntryAbility.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/entryability/EntryAbility.ets deleted file mode 100644 index e312b559f6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/entryability/EntryAbility.ets +++ /dev/null @@ -1,202 +0,0 @@ -import { AbilityConstant, Configuration, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; -import { hilog } from '@kit.PerformanceAnalysisKit'; -import { display, window } from '@kit.ArkUI'; -import { MobileDesignColors, MobileTextScale } from '../generated/MobileDesignTokens'; - -const DOMAIN = 0x0000; -const TAG = 'OpenBitFunRemote'; - -export default class EntryAbility extends UIAbility { - private mainWindow?: window.Window; - private initialPage: string = 'pages/AppRoot'; - private previewStorage?: LocalStorage; - - onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { - // `want.parameters` is untyped, so the scenario id is narrowed to a string - // once here; every branch below then compares or matches on text. - const previewId = want.parameters?.['openbitfunDesignPreview'] as string | undefined; - const scenarioId: string = previewId ?? ''; - // The device-model scenarios are one family: the prefix opens the design - // gallery and the `-dark` suffix locks the colour mode, so the list below - // does not have to grow by one id per state of that feature. - const deviceModelScenario: boolean = scenarioId.startsWith('device-model'); - if (scenarioId === 'history-scroll' || scenarioId === 'durable-timeline' || scenarioId === 'composer-submit' || scenarioId === 'catalog-refresh' || scenarioId === 'catalog-refresh-dark' || scenarioId === 'model-role-selector' || scenarioId === 'model-role-selector-dark' || scenarioId === 'model-role-selector-wide' || scenarioId === 'subagent-process' || scenarioId === 'subagent-process-dark' || scenarioId === 'subagent-swarm' || scenarioId === 'subagent-swarm-dark' || scenarioId === 'file-visibility' || scenarioId === 'file-visibility-dark' || scenarioId === 'immersive-bottom' || scenarioId === 'immersive-bottom-dark' || scenarioId === 'immersive-bottom-wide' || scenarioId === 'immersive-bottom-drawer' || scenarioId === 'immersive-bottom-drawer-dark' || scenarioId === 'immersive-bottom-settings' || scenarioId === 'immersive-bottom-settings-dark' || scenarioId === 'immersive-bottom-cover' || scenarioId === 'immersive-bottom-miniapps' || scenarioId === 'immersive-bottom-wide-shell' || scenarioId === 'immersive-bottom-tools' || scenarioId === 'immersive-bottom-tools-editor' || scenarioId === 'immersive-bottom-tools-file-action' || scenarioId === 'immersive-bottom-view-settings' || scenarioId === 'immersive-bottom-connect' || scenarioId === 'composer-overflow' || scenarioId === 'composer-overflow-empty' || scenarioId === 'composer-overflow-dark' || scenarioId === 'composer-overflow-wide' || scenarioId === 'composer-overflow-expanded' || scenarioId === 'composer-overflow-expanded-dark' || scenarioId === 'device-selector' || scenarioId === 'device-selector-dark' || scenarioId === 'welcome-home' || scenarioId === 'connected-conversation' || - scenarioId === 'streaming-dark' || - scenarioId === 'reconnecting-wide' || scenarioId === 'narrow-multiline' || - scenarioId === 'fold-context' || scenarioId === 'long-reading' || - scenarioId === 'cold-start-home' || scenarioId === 'cold-start-home-dark' || - scenarioId === 'copy-selection' || scenarioId === 'copy-selection-dark' || - scenarioId === 'copy-selection-nav' || scenarioId === 'copy-selection-wide' || - scenarioId === 'copy-rollback' || scenarioId === 'copy-rollback-dark' || - scenarioId === 'copy-rollback-send' || scenarioId === 'copy-rollback-send-dark' || - scenarioId === 'copy-rollback-send-fail' || scenarioId === 'copy-rollback-fail' || - scenarioId === 'copy-rollback-fail-dark' || scenarioId === 'copy-rollback-stale' || - scenarioId === 'copy-rollback-busy' || scenarioId === 'copy-rollback-unsupported' || - scenarioId === 'interaction-mailbox' || scenarioId === 'interaction-mailbox-dark' || - scenarioId.startsWith('command-palette') || - deviceModelScenario) { - this.initialPage = 'pages/preview/MobileDesignGallery'; - this.previewStorage = new LocalStorage(); - this.previewStorage.setOrCreate('scenarioId', scenarioId); - AppStorage.setOrCreate('scenarioId', scenarioId); - // A preview can ask for a variant of its scenario without a scenario id of - // its own, because the gallery routes by the id alone. Anything not asked - // for is the scenario's own default. - const option = want.parameters?.['openbitfunDesignOption'] as string | undefined; - AppStorage.setOrCreate('previewOption', option ?? ''); - } - try { - const colorMode = scenarioId === 'cold-start-home-dark' || scenarioId === 'catalog-refresh-dark' || scenarioId === 'model-role-selector-dark' || scenarioId === 'subagent-process-dark' || scenarioId === 'subagent-swarm-dark' || scenarioId === 'file-visibility-dark' || scenarioId === 'immersive-bottom-dark' || scenarioId === 'immersive-bottom-drawer-dark' || scenarioId === 'immersive-bottom-settings-dark' || scenarioId === 'composer-overflow-dark' || scenarioId === 'composer-overflow-expanded-dark' || scenarioId === 'device-selector-dark' || scenarioId === 'streaming-dark' || scenarioId === 'interaction-mailbox-dark' || scenarioId === 'copy-selection-dark' || scenarioId === 'copy-rollback-dark' || scenarioId === 'copy-rollback-send-dark' || scenarioId === 'copy-rollback-fail-dark' || (scenarioId.startsWith('command-palette') && scenarioId.endsWith('-dark')) || - (deviceModelScenario && scenarioId.endsWith('-dark')) - ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK - : scenarioId === 'cold-start-home' || scenarioId === 'catalog-refresh' || scenarioId === 'model-role-selector' || scenarioId === 'model-role-selector-wide' || scenarioId === 'subagent-process' || scenarioId === 'subagent-swarm' || scenarioId === 'file-visibility' || scenarioId === 'immersive-bottom' || scenarioId === 'immersive-bottom-wide' || scenarioId === 'immersive-bottom-drawer' || scenarioId === 'immersive-bottom-settings' || scenarioId === 'immersive-bottom-cover' || scenarioId === 'immersive-bottom-miniapps' || scenarioId === 'immersive-bottom-wide-shell' || scenarioId === 'immersive-bottom-tools' || scenarioId === 'immersive-bottom-tools-editor' || scenarioId === 'immersive-bottom-tools-file-action' || scenarioId === 'immersive-bottom-view-settings' || scenarioId === 'immersive-bottom-connect' || scenarioId === 'composer-overflow' || scenarioId === 'composer-overflow-empty' || scenarioId === 'composer-overflow-wide' || scenarioId === 'composer-overflow-expanded' || scenarioId === 'device-selector' || scenarioId === 'connected-conversation' || scenarioId === 'reconnecting-wide' || scenarioId === 'copy-selection' || scenarioId === 'copy-selection-nav' || scenarioId === 'copy-selection-wide' || scenarioId === 'copy-rollback' || scenarioId === 'copy-rollback-send' || scenarioId === 'copy-rollback-send-fail' || scenarioId === 'copy-rollback-fail' || scenarioId === 'copy-rollback-stale' || scenarioId === 'copy-rollback-busy' || scenarioId === 'copy-rollback-unsupported' || (scenarioId.startsWith('command-palette') && !scenarioId.endsWith('-dark')) || - (deviceModelScenario && !scenarioId.endsWith('-dark')) - ? ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT - : ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET; - this.context.getApplicationContext().setColorMode(colorMode); - } catch (err) { - hilog.error(DOMAIN, TAG, 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err)); - } - this.applyTextScale(); - hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onCreate'); - } - - // The type ramp is read through getters, so this has to land before the first - // page module loads; onCreate runs ahead of loadContent. A fold changing - // screens keeps the same pixel pitch on the devices we ship to, so one read at - // startup is enough. - private applyTextScale(): void { - try { - const metrics = display.getDefaultDisplaySync(); - const factor = MobileTextScale.apply(metrics.xDPI, metrics.densityPixels); - hilog.info(DOMAIN, TAG, 'Text scale %{public}s (xDPI %{public}s, density %{public}s)', - String(factor), String(metrics.xDPI), String(metrics.densityPixels)); - } catch (err) { - hilog.error(DOMAIN, TAG, 'Failed to read display metrics for text scale. Cause: %{public}s', JSON.stringify(err)); - } - } - - onDestroy(): void { - hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onDestroy'); - } - - onWindowStageCreate(windowStage: window.WindowStage): void { - // Main window is created, set main page for this ability - hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageCreate'); - try { - const mainWindow = windowStage.getMainWindowSync(); - this.mainWindow = mainWindow; - // The shell runs immersive: the chat page's transcript has to reach the - // bottom edge of the screen, and pages read the avoid areas themselves to - // keep their content clear of the system bars. - mainWindow.setWindowLayoutFullScreen(true); - this.logWindowInsets(mainWindow); - this.updateSystemBars(this.context.config?.colorMode); - } catch (err) { - hilog.error(DOMAIN, TAG, 'Failed to configure window bars. Cause: %{public}s', JSON.stringify(err)); - } - - const onContentLoaded = (err: BusinessError): void => { - if (err.code) { - hilog.error(DOMAIN, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); - return; - } - hilog.info(DOMAIN, TAG, 'Succeeded in loading the content.'); - }; - if (this.previewStorage) { - windowStage.loadContent(this.initialPage, this.previewStorage, onContentLoaded); - } else { - windowStage.loadContent(this.initialPage, onContentLoaded); - } - } - - onWindowStageDestroy(): void { - // Main window is destroyed, release UI related resources - hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageDestroy'); - } - - onForeground(): void { - // Ability has brought to foreground - hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onForeground'); - } - - onConfigurationUpdate(newConfig: Configuration): void { - this.updateSystemBars(newConfig.colorMode); - } - - onBackground(): void { - // Ability has back to background - hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onBackground'); - } - - /** - * The immersive shell is not verifiable from a screenshot alone: whether the - * window covers the status bar and how tall the bottom strip is are device - * facts, so state them once per launch. The camera cutout is stated in full — - * visibility and all four rectangles — because it is the one avoid area that - * moves to a different edge when the device rotates, and a device without a - * cutout reports zeroes here rather than staying silent about it. - */ - private logWindowInsets(mainWindow: window.Window): void { - try { - const system = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); - const navigation = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR); - hilog.info(DOMAIN, TAG, - 'Window insets statusBar=%{public}s navigation=%{public}s windowRect=%{public}s', - String(system.topRect.height), String(navigation.bottomRect.height), - JSON.stringify(mainWindow.getWindowProperties().windowRect)); - const cutout = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT); - hilog.info(DOMAIN, TAG, - 'Window cutout visible=%{public}s top=%{public}s bottom=%{public}s left=%{public}s right=%{public}s', - String(cutout.visible), String(cutout.topRect.height), String(cutout.bottomRect.height), - String(cutout.leftRect.width), String(cutout.rightRect.width)); - } catch (err) { - hilog.error(DOMAIN, TAG, 'Failed to read window insets. Cause: %{public}s', JSON.stringify(err)); - } - } - - /** - * The content colour of both system bars, for the whole window and the whole - * app. - * - * This is one value for one window, and it is derived from one thing only: the - * colour mode. There is no per-page override here, so any page whose top band - * is dark — a media viewer, an immersive title, a hero the design decides to - * paint dark — puts the light-mode ink on a dark band and the clock and the - * status icons stop being readable against it. Every top band the app ships - * today is a theme-following page colour (`PAGE_BG`, `SIDEBAR_BG`, - * `PAGE_BG_OVERLAY`, `WELCOME_PAGE_BG`, `CARD`), which is why the single value - * is correct as it stands; `immersive-bottom.test.cjs` guards that list as a - * tripwire. - * - * So: a new page that paints its own dark top band is not finished here. It has - * to come back to this method — either by declaring its band against the - * colour mode the way the others do, or by giving the app a per-page override - * (the platform's `HdsNavigation.systemBarStyle` is the page-level route, and - * the platform also warns against mixing it with the window-level calls used - * here). Either way the band and the content colour are one decision, not two. - */ - private updateSystemBars(colorMode?: ConfigurationConstant.ColorMode): void { - if (!this.mainWindow) { - return; - } - const dark = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK; - const content = dark ? MobileDesignColors.ink.dark : MobileDesignColors.ink.light; - try { - this.mainWindow.setWindowSystemBarProperties({ - // The window is laid out full-screen above (`setWindowLayoutFullScreen(true)`), - // so it already runs in the immersive layout, and the status bar and the - // navigation area are transparent by platform default: both strips carry - // the page's own background through. The page therefore owns what shows - // there — the drawer's fill and the chat page's blurred header band — and - // any background colour set here would repaint the page's edge instead. - // The content colours are the only thing left to state: they keep the - // clock and the icons legible against whatever the page puts behind them. - statusBarContentColor: content, - navigationBarContentColor: content - }); - } catch (err) { - hilog.error(DOMAIN, TAG, 'Failed to update system bars. Cause: %{public}s', JSON.stringify(err)); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets deleted file mode 100644 index 8b6a94488a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +++ /dev/null @@ -1,17 +0,0 @@ -import { hilog } from '@kit.PerformanceAnalysisKit'; -import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; - -const DOMAIN = 0x0000; -const TAG = 'OpenBitFunRemote'; - -export default class EntryBackupAbility extends BackupExtensionAbility { - async onBackup() { - hilog.info(DOMAIN, TAG, 'Backup completed.'); - await Promise.resolve(); - } - - async onRestore(bundleVersion: BundleVersion) { - hilog.info(DOMAIN, TAG, 'Restore completed. Bundle version: %{public}s', JSON.stringify(bundleVersion)); - await Promise.resolve(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobileDesignTokens.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobileDesignTokens.ets deleted file mode 100644 index 8626cd781e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobileDesignTokens.ets +++ /dev/null @@ -1,255 +0,0 @@ -// Generated by scripts/mobile-ui-design-system.mjs. Do not edit. - -export class MobileColorPair { - readonly light: string; - readonly dark: string; - - constructor(light: string, dark: string) { - this.light = light; - this.dark = dark; - } -} - -export class MobileDesignColors { - static readonly startWindowBackground: MobileColorPair = new MobileColorPair("#FFFFFF", "#000000"); - static readonly transparent: MobileColorPair = new MobileColorPair("#00000000", "#00000000"); - static readonly pageBg: MobileColorPair = new MobileColorPair("#FFFFFF", "#151514"); - static readonly welcomePageBg: MobileColorPair = new MobileColorPair("#FFFFFF", "#252522"); - static readonly pageBgFade: MobileColorPair = new MobileColorPair("#00FFFFFF", "#00151514"); - static readonly pageBgOverlay: MobileColorPair = new MobileColorPair("#B8FFFFFF", "#B8151514"); - static readonly ink: MobileColorPair = new MobileColorPair("#171717", "#F4F3EF"); - static readonly muted: MobileColorPair = new MobileColorPair("#706F6A", "#AAA8A0"); - static readonly subtle: MobileColorPair = new MobileColorPair("#A5A39B", "#77756E"); - static readonly line: MobileColorPair = new MobileColorPair("#E9E7E2", "#363531"); - static readonly card: MobileColorPair = new MobileColorPair("#FFFFFF", "#252522"); - static readonly cardOverlay: MobileColorPair = new MobileColorPair("#CCFFFFFF", "#CC252522"); - static readonly accent: MobileColorPair = new MobileColorPair("#111111", "#5B5954"); - static readonly fileLink: MobileColorPair = new MobileColorPair("#2563EB", "#60A5FA"); - static readonly primaryAction: MobileColorPair = new MobileColorPair("#111111", "#454540"); - static readonly contentOnAction: MobileColorPair = new MobileColorPair("#FFFFFF", "#FFFFFF"); - static readonly connectHeroBg: MobileColorPair = new MobileColorPair("#E6EDFF", "#2B2B29"); - static readonly connectHeroAccent: MobileColorPair = new MobileColorPair("#9DB4FF", "#4A4944"); - static readonly connectHeroSecondary: MobileColorPair = new MobileColorPair("#C9C5FF", "#3C3B38"); - static readonly connectHeroSurface: MobileColorPair = new MobileColorPair("#F8FAFF", "#252522"); - static readonly connectScanAccent: MobileColorPair = new MobileColorPair("#FFD021", "#FFD021"); - static readonly scrim: MobileColorPair = new MobileColorPair("#44000000", "#44000000"); - static readonly shellScrim: MobileColorPair = new MobileColorPair("#24000000", "#24000000"); - static readonly mediaBackground: MobileColorPair = new MobileColorPair("#FF000000", "#FF000000"); - static readonly mediaScrim: MobileColorPair = new MobileColorPair("#B8000000", "#B8000000"); - static readonly mediaControlBackground: MobileColorPair = new MobileColorPair("#8C000000", "#8C000000"); - static readonly toastBackground: MobileColorPair = new MobileColorPair("#D1171717", "#D1171717"); - static readonly shadowFaint: MobileColorPair = new MobileColorPair("#08000000", "#08000000"); - static readonly shadowSubtle: MobileColorPair = new MobileColorPair("#12000000", "#12000000"); - static readonly shadowMedium: MobileColorPair = new MobileColorPair("#18000000", "#18000000"); - static readonly shadowStrong: MobileColorPair = new MobileColorPair("#24000000", "#24000000"); - static readonly floatingBorder: MobileColorPair = new MobileColorPair("#18000000", "#18000000"); - static readonly soft: MobileColorPair = new MobileColorPair("#F4F3F0", "#2D2C28"); - static readonly floatingPanelBg: MobileColorPair = new MobileColorPair("#F7F7F5", "#1E1E1C"); - static readonly sidebarBg: MobileColorPair = new MobileColorPair("#F8F8F9", "#0E0E10"); - static readonly sidebarBgFade: MobileColorPair = new MobileColorPair("#00F8F8F9", "#000E0E10"); - static readonly sidebarRaised: MobileColorPair = new MobileColorPair("#FFFFFF", "#1C1C1F"); - static readonly sidebarLine: MobileColorPair = new MobileColorPair("#14101A27", "#1FFFFFFF"); - static readonly sidebarHover: MobileColorPair = new MobileColorPair("#F3F3F5", "#0FFFFFFF"); - static readonly sidebarSelection: MobileColorPair = new MobileColorPair("#14000000", "#1FFFFFFF"); - static readonly sidebarInk: MobileColorPair = new MobileColorPair("#CC000000", "#E8E8E8"); - static readonly sidebarMuted: MobileColorPair = new MobileColorPair("#99000000", "#B0B0B0"); - static readonly sidebarSubtle: MobileColorPair = new MobileColorPair("#66000000", "#858585"); - static readonly statusSuccess: MobileColorPair = new MobileColorPair("#27C46A", "#3BD47B"); - static readonly statusDanger: MobileColorPair = new MobileColorPair("#E04F4F", "#FF6B6B"); - static readonly codeLineNumber: MobileColorPair = new MobileColorPair("#AAA69D", "#77756E"); - static readonly codeKeyword: MobileColorPair = new MobileColorPair("#8F3F71", "#D99AC4"); - static readonly codeString: MobileColorPair = new MobileColorPair("#477A4A", "#9BCB9D"); - static readonly codeNumber: MobileColorPair = new MobileColorPair("#9A5B13", "#E3B36D"); - static readonly codeComment: MobileColorPair = new MobileColorPair("#7A8078", "#96958D"); - static readonly codeFunction: MobileColorPair = new MobileColorPair("#2C6693", "#8CBCE0"); - static readonly codeType: MobileColorPair = new MobileColorPair("#865A20", "#D5B27F"); - static readonly codeConstant: MobileColorPair = new MobileColorPair("#A04444", "#E79A9A"); - static readonly codeProperty: MobileColorPair = new MobileColorPair("#466D78", "#9CC8D0"); - static readonly codeTargetBg: MobileColorPair = new MobileColorPair("#FFF1BE", "#5A4E24"); - static readonly brandDot: MobileColorPair = new MobileColorPair("#16B9CE", "#16B9CE"); - static readonly welcomeDock: MobileColorPair = new MobileColorPair("#171917", "#000000"); - static readonly welcomeButton: MobileColorPair = new MobileColorPair("#FFFFFF", "#FFFFFF"); - static readonly welcomeButtonLabel: MobileColorPair = new MobileColorPair("#171917", "#171917"); - static readonly welcomeSecondary: MobileColorPair = new MobileColorPair("#B9BCB9", "#B9BCB9"); - static readonly statusWarning: MobileColorPair = new MobileColorPair("#FF8C00", "#FF8C00"); -} - -export class MobileTextScale { - static readonly referenceLogicalDpi: number = 153.3; - static readonly minFactor: number = 0.85; - static readonly maxFactor: number = 1; - private static current: number = 1; - - static get factor(): number { - return MobileTextScale.current; - } - - // xdpi is physical pixels per inch along the horizontal axis; densityPixels is - // physical pixels per logical unit. Their ratio is logical units per inch, - // compared against the reference the type ramp was tuned on. Displays that - // report an implausible xdpi against their nominal 160-per-unit density fall - // back to the unscaled ramp rather than trusting bad metrics. - static resolve(xdpi: number, densityPixels: number): number { - if (!(xdpi > 0) || !(densityPixels > 0)) { - return 1; - } - const nominalDpi = densityPixels * 160; - if (xdpi < nominalDpi * 0.5 || xdpi > nominalDpi * 2) { - return 1; - } - const factor = xdpi / densityPixels / MobileTextScale.referenceLogicalDpi; - const clamped = Math.min(MobileTextScale.maxFactor, Math.max(MobileTextScale.minFactor, factor)); - return Math.round(clamped * 1000) / 1000; - } - - static apply(xdpi: number, densityPixels: number): number { - MobileTextScale.current = MobileTextScale.resolve(xdpi, densityPixels); - return MobileTextScale.current; - } - - static reset(): void { - MobileTextScale.current = 1; - } - - static scaled(value: number): number { - return Math.round(value * MobileTextScale.current * 2) / 2; - } -} - -export class MobileTypographyToken { - readonly baseSize: number; - readonly baseLineHeight: number; - readonly weight: number; - - constructor(size: number, lineHeight: number, weight: number) { - this.baseSize = size; - this.baseLineHeight = lineHeight; - this.weight = weight; - } - - get size(): number { - return MobileTextScale.scaled(this.baseSize); - } - - get lineHeight(): number { - return MobileTextScale.scaled(this.baseLineHeight); - } -} - -export class MobileDesignTypography { - static readonly displayLarge: MobileTypographyToken = new MobileTypographyToken(24, 30, 700); - static readonly displayMedium: MobileTypographyToken = new MobileTypographyToken(22, 28, 700); - static readonly displaySmall: MobileTypographyToken = new MobileTypographyToken(20, 26, 700); - static readonly headlineLarge: MobileTypographyToken = new MobileTypographyToken(22, 28, 700); - static readonly headlineMedium: MobileTypographyToken = new MobileTypographyToken(20, 26, 700); - static readonly headlineSmall: MobileTypographyToken = new MobileTypographyToken(18, 24, 700); - static readonly titleLarge: MobileTypographyToken = new MobileTypographyToken(20, 26, 700); - static readonly conversationHeaderTitle: MobileTypographyToken = new MobileTypographyToken(17, 22, 600); - static readonly titleMedium: MobileTypographyToken = new MobileTypographyToken(17, 22, 500); - static readonly titleSmall: MobileTypographyToken = new MobileTypographyToken(15, 20, 500); - static readonly bodyLarge: MobileTypographyToken = new MobileTypographyToken(16, 24, 400); - static readonly bodyMedium: MobileTypographyToken = new MobileTypographyToken(14, 21, 400); - static readonly bodySmall: MobileTypographyToken = new MobileTypographyToken(13, 19, 400); - static readonly labelLarge: MobileTypographyToken = new MobileTypographyToken(15, 20, 500); - static readonly labelMedium: MobileTypographyToken = new MobileTypographyToken(14, 18, 500); - static readonly labelSmall: MobileTypographyToken = new MobileTypographyToken(12, 16, 400); - static readonly brandWordmark: MobileTypographyToken = new MobileTypographyToken(42, 56, 500); -} - -export class MobileDesignGeometry { - static readonly conversationHeaderHeight: number = 76; - static readonly conversationHeaderCompactHeight: number = 64; - static readonly controlTouchSize: number = 48; - static readonly contentGutter: number = 16; - static readonly connectionStripHeight: number = 48; - static readonly timelineTopPadding: number = 22; - static readonly conversationOverlaySideInset: number = 16; - static readonly conversationEdgeFadeHeight: number = 28; - static readonly messageSpacing: number = 18; - static readonly messageBubbleMaxWidth: number = 276; - static readonly messageBubbleHorizontalPadding: number = 14; - static readonly messageBubbleVerticalPadding: number = 11; - static readonly messageBubbleRadius: number = 17; - static readonly composerActionSize: number = 48; - static readonly composerInputHeight: number = 44; - static readonly composerExpandedInputHeight: number = 58; - static readonly composerCollapsedHeight: number = 56; - static readonly composerExpandedInputRowHeight: number = 60; - static readonly composerExpandedActionRowHeight: number = 48; - static readonly composerExpandedHeight: number = 120; - static readonly composerCollapsedRadius: number = 28; - static readonly composerExpandedRadius: number = 18; - static readonly composerModelSelectorWidth: number = 330; - static readonly composerModelSelectorRadius: number = 14; - static readonly composerModelSelectorRowHeight: number = 48; - static readonly composerModelSelectorRowRadius: number = 9; - static readonly composerModelSelectorRowGap: number = 6; - static readonly sheetTopRadius: number = 28; - static readonly loginSheetMaxWidth: number = 560; - static readonly loginSheetOuterMargin: number = 8; - static readonly loginSheetBodyMinHeight: number = 142; - static readonly sheetSideRadius: number = 28; - static readonly sheetHorizontalPadding: number = 20; - static readonly sheetHeaderHeight: number = 56; - static readonly sheetActionHeight: number = 48; - static readonly selectionTopRadius: number = 20; - static readonly selectionRowHeight: number = 64; - static readonly selectionCloseSize: number = 48; - static readonly popoverWidth: number = 292; - static readonly popoverRadius: number = 16; - static readonly popoverPadding: number = 12; - static readonly popoverVerticalPadding: number = 10; - static readonly popoverActionHeight: number = 48; - static readonly popoverShadowRadius: number = 18; - static readonly compactPopoverWidth: number = 150; - static readonly compactPopoverRadius: number = 14; - static readonly compactPopoverActionHeight: number = 42; - static readonly settingsCompactCardRadius: number = 12; - static readonly settingsCardRadius: number = 16; - static readonly settingsProminentCardRadius: number = 20; - static readonly modelCurrentRowHeight: number = 64; - static readonly modelSourceRowHeight: number = 62; - static readonly modelAccountRowHeight: number = 56; - static readonly modelAccountRowGap: number = 6; - static readonly modelSectionGap: number = 20; - static readonly modelOverviewTopPadding: number = 16; - static readonly modelOverviewBottomPadding: number = 24; - static readonly modelListTopPadding: number = 10; - static readonly modelListBottomPadding: number = 16; - static readonly modelEmptyAccountHeight: number = 80; - static readonly modelEditorHeight: number = 560; - static readonly welcomeMaxWidth: number = 520; - static readonly welcomeGutter: number = 25; - static readonly welcomeHeaderHeight: number = 58; - static readonly welcomeButtonHeight: number = 49; - static readonly welcomeButtonGap: number = 11; - static readonly welcomeDockRadius: number = 30; - static readonly welcomeDockBottom: number = 39; - static readonly welcomeMarkSize: number = 92; - static readonly welcomeWordSize: number = 34; - static readonly welcomeStageHeight: number = 220; - static readonly welcomeHeaderWordSize: number = 17; - static readonly recentHomeGutter: number = 24; - static readonly recentHomeMarkSize: number = 132; - static readonly recentHomeTitleSize: number = 25; - static readonly recentHomeMaxWidth: number = 560; - static readonly recentHomeRowPadding: number = 18; - static readonly approvalCardRadius: number = 12; - static readonly approvalCardPadding: number = 12; - static readonly approvalCardGap: number = 8; - static readonly approvalActionRadius: number = 8; - static readonly approvalActionHeight: number = 36; -} - -export class MobileDesignBreakpoints { - static readonly wide: number = 600; - static readonly extraWide: number = 840; - static readonly xl: number = 1440; -} - -export class MobileDesignMotion { - static readonly quick: number = 180; - static readonly structure: number = 220; - static readonly startupBrand: number = 6800; - static readonly coldStartHome: number = 2400; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobilePreviewScenarios.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobilePreviewScenarios.ets deleted file mode 100644 index bb70b2933e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/generated/MobilePreviewScenarios.ets +++ /dev/null @@ -1,155 +0,0 @@ -// Generated by scripts/mobile-ui-design-system.mjs. Do not edit. - -export class MobilePreviewMessage { - readonly role: string; - readonly text: string; - - constructor(role: string, text: string) { - this.role = role; - this.text = text; - } -} - -export class MobilePreviewScenario { - readonly id: string; - readonly title: string; - readonly description: string; - readonly appearance: string; - readonly viewportWidth: number; - readonly viewportHeight: number; - readonly headerTitle: string; - readonly headerSubtitle: string; - readonly messages: MobilePreviewMessage[]; - readonly composerDraft: string; - readonly composerPlaceholder: string; - readonly connectionPhase: string; - readonly streaming: boolean; - - constructor( - id: string, - title: string, - description: string, - appearance: string, - viewportWidth: number, - viewportHeight: number, - headerTitle: string, - headerSubtitle: string, - messages: MobilePreviewMessage[], - composerDraft: string, - composerPlaceholder: string, - connectionPhase: string, - streaming: boolean - ) { - this.id = id; - this.title = title; - this.description = description; - this.appearance = appearance; - this.viewportWidth = viewportWidth; - this.viewportHeight = viewportHeight; - this.headerTitle = headerTitle; - this.headerSubtitle = headerSubtitle; - this.messages = messages; - this.composerDraft = composerDraft; - this.composerPlaceholder = composerPlaceholder; - this.connectionPhase = connectionPhase; - this.streaming = streaming; - } -} - -export class MobilePreviewScenarios { - static readonly connectedConversation: MobilePreviewScenario = new MobilePreviewScenario( - "connected-conversation", - "Connected conversation", - "A remote desktop is answering and the composer is ready.", - "light", - 390, - 844, - "统一移动端设计系统", - "DESKTOP-KM3L4UI", - [new MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), new MobilePreviewMessage("assistant", "可以。共享视觉契约,三端继续使用原生渲染。")], - "", - "向 OpenBitFun 提问", - "connected", - false - ); - - static readonly streamingDark: MobilePreviewScenario = new MobilePreviewScenario( - "streaming-dark", - "Streaming in dark mode", - "An active turn exercises dark surfaces and the stop action.", - "dark", - 390, - 844, - "跨端视觉校验", - "正在由 MacBook Pro 运行", - [new MobilePreviewMessage("user", "比较三端的输入框、消息气泡和标题栏。"), new MobilePreviewMessage("assistant", "正在生成原生截图,并按相同基线并排展示。")], - "检查深色模式下的边框对比度", - "输入消息", - "connected", - true - ); - - static readonly reconnectingWide: MobilePreviewScenario = new MobilePreviewScenario( - "reconnecting-wide", - "Reconnecting on a wide viewport", - "A tablet-sized viewport keeps remote blocking states answerable.", - "light", - 1024, - 768, - "远程会话", - "正在恢复连接", - [new MobilePreviewMessage("assistant", "连接暂时中断。恢复后会从上次游标继续。")], - "", - "等待重新连接", - "reconnecting", - false - ); - - static readonly narrowMultiline: MobilePreviewScenario = new MobilePreviewScenario( - "narrow-multiline", - "Narrow phone with a multiline draft", - "Narrow phone with a multiline draft", - "light", - 360, - 800, - "检查移动端长标题、正文与控制目标的可读性", - "远程开发工作站 · OpenBitFun / feature/mobile-reading", - [new MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), new MobilePreviewMessage("assistant", "可以。共享视觉契约,三端继续使用原生渲染。")], - "请检查输入框是否能保留多行中文草稿。\n模型选择后内容应继续保留。\n附件与文本应各自成行。", - "向 OpenBitFun 提问", - "connected", - false - ); - - static readonly foldContext: MobilePreviewScenario = new MobilePreviewScenario( - "fold-context", - "Foldable with long remote context", - "Foldable with long remote context", - "light", - 700, - 840, - "检查移动端长标题、正文与控制目标的可读性", - "远程开发工作站 · OpenBitFun / feature/mobile-reading", - [new MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), new MobilePreviewMessage("assistant", "可以。共享视觉契约,三端继续使用原生渲染。")], - "请保留当前会话与控制目标。", - "向 OpenBitFun 提问", - "connected", - false - ); - - static readonly longReading: MobilePreviewScenario = new MobilePreviewScenario( - "long-reading", - "Long reading content", - "Long reading content", - "light", - 430, - 932, - "检查移动端长标题、正文与控制目标的可读性", - "远程开发工作站 · OpenBitFun / feature/mobile-reading", - [new MobilePreviewMessage("user", "三端的组件和样式可以保持一致吗?"), new MobilePreviewMessage("assistant", "移动端的阅读层级需要清晰,正文应该舒适地换行,辅助说明保留足够对比度。\n\n当内容变长时,消息区滚动,输入框仍然可以操作。请在系统大字体设置下检查这一场景。")], - "", - "向 OpenBitFun 提问", - "connected", - false - ); -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/AppLocale.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/AppLocale.ets deleted file mode 100644 index 1d5d851c39..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/AppLocale.ets +++ /dev/null @@ -1,110 +0,0 @@ -export const APP_LOCALE_ZH_CN: string = 'zh-CN'; -export const APP_LOCALE_EN_US: string = 'en-US'; - -export interface AppLocaleDescriptor { - readonly id: string; - readonly nativeNameKey: string; - readonly aliases: string[]; - readonly contentFallbacks: string[]; -} - -const LOCALES: AppLocaleDescriptor[] = [ - { - id: APP_LOCALE_ZH_CN, - nativeNameKey: 'settings.language.zhCN', - aliases: ['zh', 'zh-hans', 'zh-cn', 'zh_cn', 'zh-hans-cn'], - contentFallbacks: [APP_LOCALE_EN_US] - }, - { - id: APP_LOCALE_EN_US, - nativeNameKey: 'settings.language.enUS', - aliases: ['en', 'en-us', 'en_us', 'en-gb', 'en-au', 'en-ca'], - contentFallbacks: [APP_LOCALE_ZH_CN] - } -]; - -export class AppLocale { - static readonly DEFAULT: string = APP_LOCALE_ZH_CN; - - static supported(): string[] { - return LOCALES.map((locale: AppLocaleDescriptor): string => locale.id); - } - - static descriptors(): AppLocaleDescriptor[] { - return LOCALES.slice(); - } - - static isSupported(value: string | undefined | null): boolean { - return AppLocale.resolve(value).length > 0; - } - - static initial(stored: string | undefined | null, systemLanguage: string | undefined | null): string { - return AppLocale.resolve(stored) || AppLocale.resolve(systemLanguage) || AppLocale.DEFAULT; - } - - static resolve(value: string | undefined | null): string { - const normalized = (value || '').trim().toLowerCase().split('_').join('-'); - if (normalized.length === 0) { - return ''; - } - for (let index = 0; index < LOCALES.length; index += 1) { - const locale = LOCALES[index]; - if (locale.id.toLowerCase() === normalized || locale.aliases.indexOf(normalized) >= 0) { - return locale.id; - } - } - const language = normalized.split('-')[0]; - for (let index = 0; index < LOCALES.length; index += 1) { - const locale = LOCALES[index]; - if (locale.aliases.indexOf(language) >= 0) { - return locale.id; - } - } - return ''; - } - - static fallbackChain(language: string, includeSelf: boolean = true): string[] { - const resolved = AppLocale.resolve(language) || AppLocale.DEFAULT; - const locale = LOCALES.find((item: AppLocaleDescriptor): boolean => item.id === resolved); - const chain: string[] = []; - if (includeSelf) { - chain.push(resolved); - } - if (locale) { - for (let index = 0; index < locale.contentFallbacks.length; index += 1) { - const fallback = locale.contentFallbacks[index]; - if (chain.indexOf(fallback) < 0) { - chain.push(fallback); - } - } - } - if (chain.indexOf(AppLocale.DEFAULT) < 0) { - chain.push(AppLocale.DEFAULT); - } - return chain; - } - - static next(language: string): string { - const supported = AppLocale.supported(); - const currentIndex = supported.indexOf(AppLocale.resolve(language) || AppLocale.DEFAULT); - return supported[(currentIndex + 1) % supported.length]; - } - - static nativeNameKey(language: string): string { - const resolved = AppLocale.resolve(language) || AppLocale.DEFAULT; - const locale = LOCALES.find((item: AppLocaleDescriptor): boolean => item.id === resolved); - return locale ? locale.nativeNameKey : 'settings.language.zhCN'; - } - - static speechLanguage(language: string): string { - return AppLocale.resolve(language) || AppLocale.DEFAULT; - } - - static speechLocate(language: string): string { - return (AppLocale.resolve(language) || AppLocale.DEFAULT) === APP_LOCALE_EN_US ? 'US' : 'CN'; - } - - static systemLanguageTag(language: string): string { - return (AppLocale.resolve(language) || AppLocale.DEFAULT) === APP_LOCALE_EN_US ? 'en-US' : 'zh-Hans'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets deleted file mode 100644 index cb5dfaa7c2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets +++ /dev/null @@ -1,716 +0,0 @@ -export const EN_US_MESSAGES: [string, string][] = [ - ['queue.title', 'Queued messages · %1$s'], - ['queue.reorder', 'Drag to reorder'], - ['queue.moveUp', 'Move up'], - ['queue.moveDown', 'Move down'], - ['queue.refresh', 'Refresh'], - ['queue.refreshRequired', 'Queue status changed or could not be confirmed. Refresh before another action.'], - ['queue.attachments', '%1$s attachments'], - ['queue.waiting', 'Waiting for the execution host'], - ['queue.sendNow', 'Send now'], - ['queue.more', 'Message actions'], - ['queue.remove', 'Remove from queue'], - ['queue.unsupported', 'Update the execution host to reorder messages.'], - ['session.newTitle', 'New Session'], - ['workspaceTools.browse', 'Browse runtime folders'], - ['workspaceTools.selectFolder', 'Use this folder'], - ['workspaceTools.back', 'Back to files'], - ['workspaceTools.edit', 'Edit'], - ['workspaceTools.lineNumbers', 'Line numbers'], - ['workspaceTools.unsaved', 'Unsaved changes'], - ['workspaceTools.fileConflict', 'File changed on the computer. Your draft is preserved. Copy it before reopening the file to load the latest version.'], - ['workspaceTools.discard', 'Discard changes'], - ['workspaceTools.nameAsc', 'Name A–Z'], - ['workspaceTools.nameDesc', 'Name Z–A'], - ['workspaceTools.modifiedAsc', 'Oldest modified first'], - ['workspaceTools.modifiedDesc', 'Newest modified first'], - ['workspaceTools.upload', 'Upload file'], - ['workspaceTools.resumeUpload', 'Resume upload'], - ['workspaceTools.cancelUpload', 'Cancel upload'], - ['workspaceTools.selectLocation', 'Select a location'], - ['workspaceTools.runtimeLocal', 'This runtime'], - ['workspaceTools.download', 'Download'], - ['workspaceTools.title', 'Tools'], - ['workspaceTools.files', 'Files'], - ['sidebar.controlledDevice', 'Controlled device'], - ['sidebar.currentPath', 'Current path'], - ['sidebar.recentWorkspaces', 'Recent workspaces'], - ['sidebar.tapToSwitch', 'Tap to switch'], - ['workspaceTools.selectTerminal', 'Select an existing terminal'], - ['workspaceTools.terminal', 'Terminal'], - ['workspaceTools.up', 'Parent'], - ['workspaceTools.refresh', 'Refresh'], - ['workspaceTools.more', 'Load more'], - ['workspaceTools.fileName', 'File name'], - ['workspaceTools.path', 'Absolute path on controlled runtime'], - ['workspaceTools.newFile', 'New file'], - ['workspaceTools.mkdir', 'New folder'], - ['workspaceTools.rename', 'Rename'], - ['workspaceTools.save', 'Save'], - ['workspaceTools.delete', 'Delete file'], - ['workspaceTools.confirmDelete', 'Confirm delete'], - ['workspaceTools.rmdir', 'Remove empty folder'], - ['workspaceTools.createTerminal', 'New terminal'], - ['workspaceTools.command', 'Terminal input'], - ['workspaceTools.send', 'Send'], - ['workspaceTools.closeTerminal', 'Close terminal'], - ['workspaceTools.resize', 'Resize'], - ['home.recent_title', 'What would you like to do today?'], - ['home.recent_recent', 'Recent conversations'], - ['home.recent_browse', 'Browse workspaces'], - ['home.recent_all', 'All conversations'], - ['home.recent_empty', 'No conversations to continue yet'], - ['home.recent_connect', 'Connect a computer to continue your conversations.'], - ['account.errorNetwork', 'Unable to connect. Check your connection and try again.'], - ['account.errorTimeout', 'Connection timed out. Check your connection and try again.'], - ['account.errorSecureConnection', 'Unable to establish a secure connection. Check your network and try again.'], - ['account.errorRateLimited', 'Too many attempts. Try again later.'], - ['home.welcome_login', 'Sign in'], - ['home.welcome_work', 'Get things done'], - ['home.welcome_play', 'Try something fun'], - ['home.welcome_yours', 'Make it yours'], - ['home.connectComputer', 'Connect computer'], - ['home.connecting', 'Connecting…'], - ['home.exploreMiniApps', 'Explore MiniApps'], - ['home.miniAppsHint', 'Ready to use, even without a computer'], - ['miniapp.allApps', 'All apps'], - ['miniapp.availableOffline', 'Available offline'], - - ['miniapp.timeout', 'The local operation timed out. It may still finish; it was not retried.'], - ['miniapp.title', 'MiniApps'], - ['miniapp.refresh', 'Refresh'], - ['miniapp.empty', 'No built-in MiniApps are available.'], - ['miniapp.unsupported', 'This capability is unavailable in built-in mobile MiniApps.'], - ['miniapp.invalidPage', 'The MiniApp page is incomplete. Reopen it.'], - ['miniapp.closed', 'The MiniApp was closed or changed.'], - ['miniapp.previewHint', 'Built in · Works offline. Data stays on this phone.'], - ['notification.onboardingTitle', 'Task completion notifications'], - ['notification.onboardingBody', 'Allow OpenBitFun to notify you when tasks finish. You can change this later in system settings.'], - ['notification.onboardingLater', 'Later'], - ['notification.onboardingEnable', 'Enable notifications'], - ['app.title', 'OpenBitFun'], - - ['common.cancel', 'Cancel'], - ['common.back', 'Back'], - ['common.close', 'Close'], - ['common.copy', 'Copy'], - ['common.current', 'Current'], - ['common.done', 'Done'], - ['common.delete', 'Delete'], - ['common.failed', 'Failed'], - ['common.keep', 'Keep'], - ['common.loading', 'Loading...'], - ['common.open', 'Open'], - ['common.other', 'Other'], - ['common.ready', 'Ready'], - ['common.refresh', 'Refresh'], - ['common.retry', 'Retry'], - ['common.save', 'Save'], - ['common.search', 'Search'], - ['common.running', 'Running'], - ['common.waiting', 'Waiting'], - - ['notification.taskCompletedTitle', 'Task completed'], - ['notification.taskCompletedBody', 'Your OpenBitFun task is ready. Tap to open OpenBitFun and view the result.'], - - ['chatHome.prompt', 'What do you want to do today?'], - ['chat.promptSuggestionAccept', 'Use suggestion'], - ['chatHome.placeholder', 'Ask OpenBitFun'], - ['chatHome.localHint', 'This chat stays on the phone. Switch to Remote to read and write projects on your computer.'], - ['chatHome.research', 'Find sources'], - ['chatHome.researchPrompt', 'Help me find sources and summarize the key points:'], - ['chatHome.image', 'Analyze image'], - ['chatHome.imagePrompt', 'Please analyze this image.'], - ['chatHome.file', 'Work with a file'], - ['chatHome.filePrompt', 'Help me summarize the key points in this file.'], - ['chatHome.write', 'Help me write'], - ['chatHome.writePrompt', 'Please draft this for me:'], - ['chatHome.organize', 'Organize a problem'], - ['chatHome.organizePrompt', 'Help me organize the key points and approach for this problem:'], - ['chatHome.plan', 'Make an action plan'], - ['chatHome.planPrompt', 'Help me make a clear, actionable plan:'], - ['chatHome.codeHintTitle', 'This task may need Remote'], - ['chatHome.codeHintBody', 'Connect a desktop workspace before OpenBitFun can read project files, run commands, and change code.'], - ['chatHome.enterCode', 'Open Remote'], - - ['generalChat.ready', 'OpenBitFun is ready'], - ['generalChat.generating', 'OpenBitFun is answering'], - ['generalChat.sending', 'Sending message'], - ['generalChat.offline', 'Network unavailable. Drafts and history stay on this phone.'], - ['generalChat.stopped', 'Generation stopped.'], - ['generalChat.interrupted', 'The reply was interrupted. Received content was kept.'], - ['generalChat.replyInterrupted', 'Reply interrupted'], - ['generalChat.fileDownloadMock', 'General chat cannot download desktop files. Open Remote to work with local files.'], - ['generalChat.filePreviewUnavailable', 'General chat cannot preview desktop files. Open Remote to view them.'], - ['generalChat.localRestoreFailed', 'General chat history could not be restored. You can still start a new chat.'], - ['generalChat.modelNotConfigured', 'Configure a general chat model in Settings first.'], - ['generalChat.authenticationFailed', 'The API key is invalid or cannot access this model.'], - ['generalChat.rateLimited', 'The model service is rate-limited. Try again later.'], - ['generalChat.serviceUnavailable', 'The model service is temporarily unavailable. Try again later.'], - ['generalChat.invalidResponse', 'The model service returned an unrecognized response.'], - ['generalChat.emptyResponse', 'The model returned no text.'], - ['generalChat.requestFailed', 'Model request failed (HTTP {0}).'], - - ['settings.general.section', 'General'], - ['settings.account.section', 'Account'], - ['settings.account.currentIdentity', 'Current identity'], - ['settings.model.section', 'Model'], - ['settings.model.default', 'Default model'], - ['settings.devices.section', 'Devices'], - ['settings.title', 'Settings'], - ['settings.language.title', 'Language'], - ['settings.language.choose', 'Choose language'], - ['settings.language.zhCN', '简体中文'], - ['settings.language.enUS', 'English'], - ['settings.about.section', 'About'], - ['settings.about.openbitfun', 'About OpenBitFun'], - ['settings.about.product', 'Product'], - ['settings.about.version', 'Version'], - ['settings.modelService.title', 'Model'], - ['settings.modelService.manageTitle', 'General chat model'], - ['settings.modelService.localTitle', 'Custom local model'], - ['settings.modelService.currentModel', 'In use'], - ['settings.modelService.modelSources', 'Model sources'], - ['settings.modelService.chooseAccountModel', 'Choose account model'], - ['settings.modelService.accountModels', 'Account sync'], - ['settings.modelService.accountModelSummary', 'Cloud account models'], - ['settings.modelService.localModel', 'Custom local'], - ['settings.modelService.accountSource', 'Cloud account'], - ['settings.modelService.localSource', 'This device'], - ['settings.modelService.syncedCount', '{0} synced'], - ['settings.modelService.accountEmpty', 'No account models available'], - ['settings.modelService.configured', 'Configured'], - ['settings.modelService.notConfigured', 'Not configured'], - ['settings.modelService.apiUrl', 'API URL'], - ['settings.modelService.apiUrlPlaceholder', 'https://api.example.com'], - ['settings.modelService.apiKey', 'API Key'], - ['settings.modelService.apiKeyPlaceholder', 'Enter API Key'], - ['settings.modelService.apiKeyKeepPlaceholder', 'Leave blank to keep the saved key'], - ['settings.modelService.modelName', 'Model name'], - ['settings.modelService.modelPlaceholder', 'For example chat-model'], - ['settings.modelService.keySaved', 'Saved securely'], - ['settings.modelService.clearKey', 'Clear saved key'], - ['settings.modelService.keepKey', 'Keep saved key'], - ['settings.modelService.testConnection', 'Test connection'], - ['settings.modelService.testNeedsKey', 'Keep or enter an API key to test the connection.'], - ['settings.modelService.testSuccess', 'Connection test passed.'], - ['settings.modelService.invalidUrl', 'API URL must start with http:// or https://.'], - ['settings.modelService.modelRequired', 'Enter a model name.'], - ['settings.modelService.apiKeyRequired', 'Enter an API key.'], - ['settings.modelService.encryptFailed', 'Could not encrypt the API key.'], - ['settings.modelService.secureStoreFailed', 'System secure storage is unavailable. Try again later.'], - - ['sidebar.chat', 'Library'], - ['sidebar.projects', 'Projects'], - ['sidebar.tasks', 'Scheduled'], - ['sidebar.tools', 'Apps'], - ['sidebar.more', 'More'], - ['sidebar.newChat', 'Chat'], - ['sidebar.generalChat', 'General chat'], - ['sidebar.conversations', 'Recent chats'], - ['sidebar.devices', 'Devices'], - ['sidebar.legacyWorkspaceCatalog', 'Older device: showing recent workspaces'], - ['sidebar.workspaces', 'Workspaces'], - ['sidebar.deviceOnline', 'Online'], - ['sidebar.addWorkspace', 'Add workspace'], - ['sidebar.targetWorkspacePath', 'Path on controlled device'], - ['sidebar.openWorkspacePath', 'Open workspace'], - ['sidebar.remoteRootBrowseOnly', 'The remote root is for browsing. Choose a specific workspace folder.'], - ['sidebar.browseRemoteRoot', 'Browse remote root'], - ['sidebar.selectWorkspace', 'Select workspace'], - ['sidebar.workspacesOffline', 'Disconnected'], - ['sidebar.connectDesktop', 'Connect a computer'], - ['sidebar.addConnection', 'Add connection'], - ['sidebar.newInWorkspace', 'New in this workspace'], - ['sidebar.emptyWorkspaces', 'This computer has no workspaces yet'], - ['sidebar.moreSessions', '{0} more sessions'], - ['sidebar.moreWorkspaces', '{0} more workspaces'], - ['sidebar.deviceOffline', 'Offline'], - ['sidebar.deviceLoadFailed', 'This computer cannot be read right now'], - ['sidebar.moreDevices', '{0} more devices'], - ['sidebar.pinned', 'Pinned'], - ['sidebar.archived', 'Archived'], - ['sidebar.archive', 'Archive'], - ['sidebar.unarchive', 'Unarchive'], - ['sidebar.exportMarkdown', 'Copy Markdown'], - ['sidebar.untitled', 'Untitled session'], - ['sidebar.emptyRecentTitle', 'No recent sessions'], - ['sidebar.emptyRecentText', 'They will appear here after you start chatting.'], - ['sidebar.deleteConfirm', 'This session cannot be recovered after deletion.'], - ['sidebar.searchPlaceholder', 'Search chats'], - ['sidebar.noSearchResult', 'No matching sessions'], - ['sidebar.signedOutNewChat', 'New chat'], - ['sidebar.signInOpenBitFunAccount', 'Sign in with email or GitHub'], - ['sidebar.collapse', 'Collapse sidebar'], - ['sidebar.restore', 'Expand sidebar'], - - ['session.actions', 'Session actions'], - ['session.details', 'Session details'], - ['session.viewDetails', 'View details'], - ['session.agentType', 'Agent type'], - ['session.workspace', 'Workspace'], - ['session.workspacePath', 'Workspace path'], - ['session.createdAt', 'Created'], - ['session.updatedAt', 'Updated'], - ['session.messageCount', 'Messages'], - ['session.status', 'Status'], - - ['viewSettings.title', 'View settings'], - ['viewSettings.subtitle', 'Adjust session grouping and information density'], - ['viewSettings.grouping', 'Grouping'], - ['viewSettings.filters', 'Filters'], - ['viewSettings.metadata', 'Shown details'], - ['viewSettings.workspace', 'Workspace'], - ['viewSettings.agentType', 'Session type'], - ['viewSettings.allWorkspaces', 'All workspaces'], - ['viewSettings.allAgentTypes', 'All types'], - ['viewSettings.allStatuses', 'All statuses'], - ['viewSettings.updated', 'Updated time'], - ['viewSettings.status', 'Run status'], - - ['common.unknown', 'Unknown'], - - ['code.title', 'OpenBitFun Remote'], - ['code.heroTitle', 'Local development assistant'], - ['code.heroBody', 'After connecting the desktop, OpenBitFun can access your repositories, run commands, and edit files.'], - ['code.connectWorkspace', 'Connect a local workspace'], - ['code.noWorkspacePreview', 'Recently opened repositories appear here after you connect the desktop.'], - ['code.newTask', 'New remote task'], - ['code.switchWorkspace', 'Switch workspace'], - ['code.disconnect', 'Disconnect'], - ['code.recentSessions', 'Recent remote sessions'], - ['code.emptySessionTitle', 'No remote sessions'], - ['code.emptySessionText', 'After connecting a local workspace, create a remote task to work on the project.'], - - ['remote.actionUnsupported', 'This action is not supported by the connected device.'], - ['remote.title', 'Remote'], - ['remote.chats', 'Chats'], - ['remote.searchChats', 'Search chat history'], - ['remote.emptyTitle', 'No remote chats yet'], - ['remote.emptyText', 'Start a chat to continue desktop tasks from your phone.'], - ['remote.pickSession', 'Choose a session'], - ['remote.pickSessionText', 'Open a session from the sidebar, or create one.'], - ['remote.startSession', 'New session'], - ['remote.harness.title', 'Choose execution mode'], - ['remote.harness.minimal', 'Minimal'], - ['remote.harness.standard', 'Standard'], - ['remote.harness.ultimate', 'Ultimate'], - ['remote.connectTitle', 'Connect desktop'], - ['remote.actions', 'Remote settings'], - ['remote.device', 'Connected device'], - ['remote.newChat', 'Chat'], - ['remote.workspace', 'Workspace'], - ['remote.assistant', 'Assistant'], - ['remote.noAssistant', 'Default assistant'], - ['remote.loadMore', 'Load more chats'], - ['remote.menu.organize', 'Organize'], - ['remote.menu.byProject', 'By project'], - ['remote.menu.byTime', 'Newest first'], - ['remote.menu.chatFirst', 'Chats first'], - ['remote.menu.manage', 'Manage'], - ['remote.menu.cloudTasks', 'Cloud tasks'], - ['remote.menu.addConnection', 'Add connection'], - ['remote.menu.settings', 'Settings'], - ['remote.menu.refreshConnection', 'Refresh connection'], - ['remote.menu.comingSoon', 'Coming soon'], - ['remote.projects.showMore', 'Show {0} more projects'], - ['remote.sessions.showMore', 'Show {0} more sessions'], - ['remote.time.today', 'Today'], - ['remote.time.yesterday', 'Yesterday'], - ['remote.time.earlier', 'Earlier'], - ['remote.settings.relayReauthorizationRequired', 'Relay has been upgraded. Sign in again to reconnect; your saved account and data are retained.'], - ['remote.settings.currentControl', 'Current remote control'], - ['remote.settings.accountDevice', 'Account device'], - ['remote.settings.qrPairing', 'QR pairing'], - ['remote.settings.disconnect', 'Disconnect'], - ['remote.settings.disconnectTemporary', 'End temporary access'], - ['remote.settings.reconnect', 'Reconnect'], - ['remote.settings.noDesktop', 'No desktop connected yet'], - ['remote.settings.openbitfunUser', 'OpenBitFun user'], - ['remote.settings.accountSignedIn', 'Signed in'], - ['remote.settings.accountNotSignedIn', 'Signed out'], - ['remote.settings.accountTemporary', 'Temporary access'], - ['remote.settings.accountLoginTitle', 'Sign in with email or GitHub'], - ['remote.settings.accountLoginBody', 'Sign in with email or GitHub to connect to your computers.\nTasks and model settings stay on the controlled computer.'], - ['remote.settings.loginServer', 'Sign-in server'], - ['remote.settings.accountSignIn', 'Sign in with email or GitHub'], - ['remote.settings.accountSigningIn', 'Signing in…'], - ['remote.settings.accountLoginFailed', 'Unable to sign in right now. Try again later.'], - ['remote.settings.relayUrlPlaceholder', 'Relay URL, for example https://relay.example.com'], - ['remote.settings.accountLogout', 'Sign out'], - ['remote.settings.accountLoggingOut', 'Signing out…'], - ['remote.settings.deviceCurrent', 'This device'], - ['remote.settings.deviceRefresh', 'Refresh'], - ['remote.settings.deviceLoading', 'Loading devices…'], - ['remote.settings.deviceEmpty', 'No other registered devices on this account.'], - ['remote.settings.deviceLoginRequired', 'Sign in to the cloud account to see every device on it.'], - ['remote.settings.deviceOnline', 'Online'], - ['remote.settings.deviceOffline', 'Offline'], - ['remote.settings.deviceConnecting', 'Connecting'], - ['remote.settings.deviceControlling', 'Controlling'], - ['remote.settings.deviceSwitching', 'Switching to {0}…'], - ['remote.settings.deviceSwitchFailed', 'Could not switch the control device. Try again later.'], - ['remote.settings.deviceLoadFailed', 'Could not load devices. Try again later.'], - ['remote.settings.accountExpired', 'The cloud account expired. Sign in again.'], - ['remote.settings.deviceUnavailable', 'The target desktop is unavailable. Refresh the device list and retry.'], - ['remote.settings.deviceIncompatible', 'Incompatible client — this device cannot be controlled here'], - ['remote.settings.deviceName', 'Device'], - ['remote.settings.deviceManagementBody', 'This device stores account credentials encrypted with HUKS. Signing out clears them immediately.'], - ['remote.settings.githubId', 'Account ID: {0}'], - ['remote.settings.githubAccount', 'OpenBitFun account'], - ['remote.settings.connectedDesktop', 'Current desktop'], - ['remote.permissions.title', 'Permission mode'], - ['remote.permissions.scope', 'This setting syncs to the connected desktop and applies to every new tool call.'], - ['remote.permissions.ask', 'Ask'], - ['remote.permissions.askDescription', 'High-risk actions wait for your confirmation.'], - ['remote.permissions.auto', 'Auto approve'], - ['remote.permissions.autoDescription', 'Actions that would ask for confirmation are approved automatically.'], - ['remote.permissions.fullAccess', 'Full access'], - ['remote.permissions.fullAccessDescription', 'Every tool action is allowed without asking again.'], - ['remote.permissions.loading', 'Reading the desktop’s permission setting…'], - ['remote.permissions.loadFailed', 'Could not read the permission setting. Try again.'], - ['remote.permissions.saveFailed', 'Could not save the permission mode. Try again.'], - ['remote.permissions.connectionRequired', 'Connect a desktop to change the permission mode.'], - ['remote.permissions.fullAccessWarningTitle', 'Turn on full access?'], - ['remote.permissions.fullAccessWarningBody', 'Desktop tools will be able to run commands and change files directly.'], - ['remote.permissions.cancel', 'Cancel'], - ['remote.permissions.confirmFullAccess', 'Turn on full access'], - - ['connect.localTitle', 'Connect a local workspace'], - ['connect.chooseConnectionTitle', 'Connect a computer'], - ['connect.legacySignInRequired', 'Sign in with email or GitHub to reconnect this device. Previous connection records have been retained.'], - ['connect.subtitle', 'After connecting the desktop, OpenBitFun can access repositories, run commands, and handle local development tasks.'], - ['connect.accountDevicesTitle', 'Choose a desktop'], - ['connect.accountDevicesSubtitle', 'Remote'], - ['connect.accountDevicesBody', 'Choose an online desktop to continue.'], - ['connect.availableDevices', 'Account devices'], - ['connect.deviceLastUsed', 'Last connected'], - ['connect.deviceLinkInvalid', 'The saved connection link cannot be used. Sign in and choose a computer from your device list.'], - ['connect.deviceLinkUnavailable', 'This device is offline or does not belong to your OpenBitFun account.'], - ['connect.accountPairTitle', 'Account pairing'], - ['connect.accountPairIntro', 'The desktop is signed in to a OpenBitFun account. Verify the same account to continue.'], - ['connect.accountPairBody', 'The password is only used for this encrypted pairing and is not saved on the phone.'], - ['connect.enterAccountToPair', 'Sign in with email or GitHub to connect this device'], - ['connect.accountUsernamePlaceholder', 'OpenBitFun username'], - ['connect.accountPasswordPlaceholder', 'OpenBitFun password'], - ['connect.stepsTitle', 'How to connect'], - ['connect.or', 'or'], - ['connect.userId', 'Enter user ID'], - ['connect.userPlaceholder', 'For example: DESKTOP-KM3L4UI'], - ['connect.connect', 'Connect'], - ['connect.connecting', 'Connecting...'], - ['connect.remoteUrlShort', 'Remote connection link'], - ['connect.collapse', 'Collapse'], - ['connect.filled', 'Filled'], - ['connect.fill', 'Fill'], - ['connect.clear', 'Clear'], - ['connect.urlPlaceholder', 'openbitfun:// or https://...#/pair?room=...&pk=...&relay=...'], - ['connect.statusTitle', 'Connection status'], - ['connect.targetDesktop', 'Target desktop'], - ['connect.noDesktop', 'No desktop selected'], - ['connect.noDesktopDetail', 'Connection status appears here after you sign in and choose a computer.'], - ['connect.desktopId', 'Desktop ID: {0}'], - ['connect.desktopIdUnavailable', 'Desktop ID unavailable'], - ['connect.waitingDevice', 'Waiting to connect a desktop'], - ['connect.connected', 'Connected'], - ['connect.connectedTo', 'Connected to {0} · {1}'], - ['connect.waitingDesktop', 'Waiting for the desktop to confirm'], - ['connect.failed', 'Connection failed'], - ['connect.cannotConnectDesktop', 'Could not connect to the desktop'], - ['connect.disconnected', 'Disconnected'], - ['connect.desktopDisconnected', 'Disconnected from the desktop'], - ['connect.hintExpiredRoom', 'The legacy QR connection expired or the room does not exist. Sign in and choose a computer from your device list.'], - ['connect.hintNetwork', 'This phone cannot reach the relay. Check the network, proxy, or desktop relay URL, then retry.'], - ['connect.hintProtectedUser', 'This connection is bound to a user ID. Continue with the user ID confirmed on the desktop.'], - ['connect.hintInvalidLink', 'The saved connection link is incomplete. Sign in and choose a computer from your device list.'], - - ['connection.connected', 'Connected'], - ['connection.reconnecting', 'Reconnecting'], - ['connection.connecting', 'Connecting'], - ['connection.error', 'Connection error'], - ['connection.disconnected', 'Disconnected'], - ['connection.waiting', 'Waiting to connect'], - ['connection.user', 'User {0}'], - ['connection.reconnectingDesktop', 'Reconnecting to the desktop'], - ['connection.unavailableReconnect', 'Connection unavailable. Reconnect to continue.'], - ['connection.desktopDisconnected', 'Disconnected from the desktop'], - - ['home.reconnect', 'Reconnect'], - ['home.disconnect', 'Disconnect'], - ['home.clearPairing', 'Clear pairing'], - ['home.workbench', 'Workbench'], - ['home.currentAssistant', 'Current assistant'], - ['home.currentWorkspace', 'Current workspace'], - ['home.switchAssistant', 'Switch assistant'], - ['home.switch', 'Switch'], - ['home.recentWorkspaces', 'Recent workspaces'], - ['home.noRecentWorkspaces', 'No recent workspaces. Open one on the desktop first.'], - ['home.assistantWorkspaces', 'Assistant workspaces'], - ['home.noAssistants', 'No assistants available. Create or open one on the desktop first.'], - ['home.createSession', 'New session'], - ['home.assistantSession', 'Assistant session'], - ['home.assistantSessionDisabled', 'The desktop does not allow creating assistant sessions yet'], - ['home.codeDesc', 'Handle coding tasks'], - ['home.coworkDesc', 'Handle everyday work tasks'], - ['home.recent', 'Recent'], - ['home.viewAll', 'View all'], - ['home.sessionCount', '{0} sessions'], - ['home.searchPlaceholder', 'Search session titles'], - ['home.all', 'All'], - ['home.loadMore', 'Load more'], - ['home.deleteSession', 'Delete session'], - ['home.emptyLoadingTitle', 'Loading sessions'], - ['home.emptyLoadingText', 'Syncing the desktop session list.'], - ['home.emptySearchTitle', 'No matching sessions'], - ['home.emptySearchText', 'Try another keyword or filter.'], - ['home.emptyAssistantTitle', 'No assistant sessions'], - ['home.emptyAssistantText', 'You can start one here after the desktop allows creation.'], - ['home.emptyTitle', 'No sessions'], - ['home.emptyText', 'Use Remote for coding tasks, or general chat for everyday questions.'], - - ['sheet.createTitle', 'Create a {0} session'], - ['sheet.workspace', 'Workspace'], - ['sheet.sessionTitleOptional', 'Session title (optional)'], - ['sheet.firstInstructionOptional', 'First instruction (optional)'], - ['sheet.instructionPlaceholder', 'Tell OpenBitFun what to do...'], - ['sheet.advancedOptions', 'Advanced options'], - ['sheet.unavailable', 'Unavailable'], - ['sheet.creating', 'Creating...'], - ['sheet.start', 'Start'], - - ['chat.remoteSession', 'Remote session'], - ['chat.sessionTitle', 'Session title'], - ['chat.sessionSection', 'Session'], - ['chat.pin', 'Pin'], - ['chat.unpin', 'Unpin'], - ['chat.uploadedFiles', 'Uploaded files'], - ['chat.stop', 'Stop'], - ['chat.send', 'Send'], - ['chat.voiceInput', 'Voice input'], - ['chat.stopListening', 'Stop dictation'], - ['chat.addImage', 'Add image'], - ['chat.removeImage', 'Remove image'], - ['chat.selectModel', 'Select model'], - ['chat.modelPrimary', 'Primary Model'], - ['chat.modelFast', 'Fast Model'], - ['chat.modelFastNotConfigured', 'Not set, falls back to primary'], - ['chat.modelRolePrimary', 'Primary'], - ['chat.modelRoleFast', 'Fast'], - ['chat.loadOlder', 'Load older messages'], - ['chat.loadOlderFailed', 'Could not load earlier messages. Tap to retry.'], - ['chat.inputPlaceholder', 'Ask OpenBitFun'], - ['chat.voiceListeningPlaceholder', 'Listening, please speak...'], - ['chat.queuedAfterRunningTurn', 'Queued. It will run after the current task finishes.'], - ['chat.image', 'Image'], - ['chat.imageUnavailable', 'Image not synced to this device'], - ['chat.thinkingRunning', 'Running'], - ['chat.thinkingDone', 'Done'], - ['chat.thinkingInProgress', 'Thinking'], - ['chat.thinkingComplete', 'Thought'], - ['chat.toolCalls', 'Tool calls'], - ['chat.toolsRan', 'Ran {0} tools'], - ['chat.toolOpTodoWrite', 'Update task list'], - ['chat.toolOpTask', 'Start task'], - ['chat.toolOpRead', 'Read file'], - ['chat.toolOpWrite', 'Write file'], - ['chat.toolOpDelete', 'Delete file'], - ['chat.toolOpDiff', 'View changes'], - ['chat.toolOpEdit', 'Edit file'], - ['chat.toolOpCommand', 'Run command'], - ['chat.toolOpWebSearch', 'Web search'], - ['chat.toolOpWebFetch', 'Open web page'], - ['chat.toolOpSearch', 'Search code'], - ['chat.toolOpAskUser', 'Ask for confirmation'], - ['chat.toolTodoFallback', 'Task list'], - ['chat.toolTaskFallback', 'Subtask'], - ['chat.subagentOutput', 'Subtask output'], - ['chat.toolFailed', '{0} failed'], - ['chat.toolRunning', 'Running'], - ['chat.showMore', 'Show more'], - ['chat.showLess', 'Show less'], - ['chat.processing', 'Processing'], - ['chat.sendFailed', 'Send failed. Check the connection and retry.'], - ['chat.responseFailed', 'This response failed'], - ['chat.error', 'Error'], - ['chat.output', 'Output'], - ['chat.interactionLoadFailed', 'Unable to load pending interactions'], - ['chat.approvalFailed', 'Unable to submit response. Please retry.'], - ['chat.approvalRequired', 'Approval required'], - ['chat.editApprovalInput', 'Edit input'], - ['chat.hideApprovalInput', 'Hide input'], - ['chat.approve', 'Approve'], - ['chat.reject', 'Reject'], - ['chat.cancelTool', 'Cancel tool'], - ['chat.planView', 'View plan'], - ['chat.planBuild', 'Build Plan'], - ['chat.planBuildUnavailable', 'Update the desktop app to build plans from mobile.'], - ['chat.planBuildWaitForTurn', 'Wait for the current task to finish before building this plan.'], - ['chat.toolInput', 'Tool input'], - ['chat.reset', 'Reset'], - ['chat.editJsonInput', 'Edit JSON input'], - ['chat.answerPlaceholder', 'Enter your answer'], - ['chat.submitAnswer', 'Submit answer'], - ['chat.emptySyncing', 'Syncing'], - ['chat.emptyConnectionError', 'Connection error'], - ['chat.emptyReconnecting', 'Restoring connection'], - ['chat.emptyNoMessages', 'No messages yet'], - ['chat.emptyLoadingMessages', 'Loading desktop session messages.'], - ['chat.emptyReconnectFromHome', 'Return to the workbench and reconnect the desktop.'], - ['chat.emptyReconnectSync', 'Messages will keep syncing after the connection is restored.'], - ['chat.emptyFirstMessage', 'After you send the first instruction, the desktop response appears here.'], - ['chat.executing', 'OpenBitFun is working...'], - ['chat.model', 'Model'], - ['chat.openbitfunProcessing', 'OpenBitFun is processing...'], - ['chat.updatedSession', 'OpenBitFun updated the session'], - ['chat.desktopFile', 'Desktop file'], - ['chat.fileLink', 'File link'], - ['chat.reading', 'Reading'], - ['chat.download', 'Download'], - - ['filePreview.title', 'File preview'], - ['filePreview.loading', 'Reading file'], - ['filePreview.offline', 'Offline. Showing loaded content only.'], - ['filePreview.fitImage', 'Fit window'], - ['filePreview.actualImageSize', 'Actual size'], - ['filePreview.expand', 'Expand preview'], - ['filePreview.restoreSize', 'Restore preview'], - ['filePreview.imageDecodeFailed', 'The image could not be decoded. Retry or download the file.'], - ['filePreview.loadFailed', 'Could not open the file'], - ['filePreview.notFound', 'The file does not exist or was moved'], - ['filePreview.unavailable', 'The file does not exist or is outside the current workspace'], - ['filePreview.accessDenied', 'Cannot access files outside the workspace'], - ['filePreview.tooLarge', 'The file is too large to preview on mobile'], - ['filePreview.unsupported', 'This file type cannot be previewed yet'], - ['filePreview.truncated', 'Showing the first {0}. Download the file to see all of it.'], - - ['chat.pendingConfirmation', 'Pending confirmation'], - ['chat.cancelled', 'Cancelled'], - ['chat.jsonObjectRequired', 'Enter a JSON object'], - ['chat.jsonInvalid', 'Invalid JSON'], - ['chat.questionDefault', 'The desktop needs your answer.'], - ['chat.analyzeImageDefault', 'Please analyze this image.'], - - ['status.waitingConnection', 'Waiting to connect'], - ['status.notConnected', 'Not connected'], - ['status.restoringConnection', 'Restoring connection'], - ['status.parsingUrl', 'Parsing remote URL'], - ['status.pairing', 'Pairing'], - ['status.reconnecting', 'Reconnecting'], - ['status.pairingCleared', 'Pairing cleared'], - ['status.disconnected', 'Disconnected'], - ['status.remoteUnavailable', 'Connection unavailable. Reconnect first.'], - ['status.loadingRecentWorkspaces', 'Loading recent workspaces'], - ['status.chooseWorkspace', 'Choose a workspace'], - ['status.noRecentWorkspaces', 'No recent workspaces'], - ['status.switchingWorkspace', 'Switching workspace'], - ['status.workspaceSwitched', 'Workspace switched'], - ['status.loadingAssistants', 'Loading assistant workspaces'], - ['status.chooseAssistant', 'Choose an assistant'], - ['status.noAssistants', 'No assistants available'], - ['status.switchingAssistant', 'Switching assistant'], - ['status.assistantSwitched', 'Assistant switched'], - ['status.refreshSessions', 'Refresh session list'], - ['status.loadMoreSessions', 'Load more sessions'], - ['status.sessionsUpdated', 'Session list updated'], - ['status.createSession', 'Create remote session'], - ['status.sessionCreated', 'Session created'], - ['status.loadMessages', 'Load session messages'], - ['status.deletingSession', 'Deleting session'], - ['status.sessionDeleted', 'Session deleted'], - ['status.sessionArchived', 'Session archived'], - ['status.sessionUnarchived', 'Session unarchived'], - ['status.sessionExported', 'Copied as Markdown'], - ['status.messagesSynced', 'Messages synced'], - ['status.messagesRestored', 'Restored local session history'], - ['status.switchingModel', 'Switching model'], - ['status.modelSwitched', 'Model switched'], - ['status.loadOlderMessages', 'Load older messages'], - ['status.sendImage', 'Send image'], - ['status.sendCommand', 'Send instruction'], - ['status.sentWaiting', 'Sent. Waiting for the desktop.'], - ['status.pickImage', 'Choose image'], - ['status.noImageSelected', 'No image selected'], - ['status.imagesSelected', 'Selected {0} images'], - ['status.voiceStarting', 'Starting voice input'], - ['status.voiceListening', 'Listening'], - ['status.voiceRecognized', 'Filled recognized speech'], - ['status.voiceStopped', 'Voice input stopped'], - ['status.noRunningTask', 'No task is running'], - ['status.stoppingTask', 'Stopping task'], - ['status.stopRequested', 'Stop requested'], - ['status.updatingTitle', 'Updating session title'], - ['status.titleUpdated', 'Session title updated'], - ['status.messageCopied', 'Message copied'], - ['status.fileInfo', 'Read file info'], - ['status.prepareDownload', 'Preparing download {0}'], - ['status.downloadDone', 'Downloaded {0} · {1}'], - ['status.approvingTool', 'Approving tool call'], - ['status.toolApproved', 'Tool call approved'], - ['status.rejectingTool', 'Rejecting tool call'], - ['status.toolRejected', 'Tool call rejected'], - ['status.cancellingTool', 'Cancelling tool call'], - ['status.toolCancelRequested', 'Tool cancellation requested'], - ['status.submittingAnswer', 'Submitting answer'], - ['status.answerSubmitted', 'Answer submitted'], - ['status.desktopProcessing', 'Desktop is working'], - - ['errors.tooManyAttempts', 'Too many attempts. Try again in {0} seconds.'], - ['errors.userIdRequired', 'Enter a user ID.'], - ['errors.accountUsernameRequired', 'Enter a OpenBitFun username.'], - ['errors.accountPasswordRequired', 'Sign in with email or GitHub to continue.'], - ['errors.remoteDataInvalid', 'The relay returned data that could not be parsed. Confirm the desktop and mobile versions match.'], - ['errors.pairRejected', 'The relay rejected the legacy pairing. Sign in and choose a computer from your device list.'], - ['errors.roomNotFound', 'This remote room was not found. The legacy QR connection may have expired; sign in and choose a computer from your device list.'], - ['errors.relayTimeout', 'Timed out connecting to the relay. Check the network and retry.'], - ['errors.rateLimited', 'Too many requests. Try again later.'], - ['errors.relayUnavailable', 'The relay is temporarily unavailable (HTTP {0}). Try again later.'], - ['errors.relayHttp', 'The relay returned HTTP {0}. Pair again and retry.'], - ['errors.relayTimeoutDetail', 'Timed out connecting to the relay. Confirm the phone and desktop can reach the network.'], - ['errors.relayNetwork', 'Could not reach the relay. Check the remote link, network, or proxy settings.'], - ['errors.remoteConnectFailed', 'Remote connection failed. Check the network and retry.'], - ['errors.remoteUrlRequired', 'Enter the desktop remote connection URL.'], - ['errors.remoteUrlMissingParams', 'The remote URL is missing the room or pk parameter.'], - ['errors.remoteUrlInvalid', 'The remote connection link is invalid. Sign in and choose a computer from your device list.'], - ['errors.permissionDenied', 'Required permission was denied. Allow it in system settings and retry.'], - ['errors.operationFailed', 'The operation failed. Try again later.'], - ['errors.payloadTooLarge', 'This message’s attachments exceed the relay size limit. Send fewer images or smaller ones.'], - ['errors.workspaceIdUnsupported', 'The connected desktop does not support workspace ID references. Update the desktop app to open this workspace.'], - ['errors.hostStreamUnsupported', 'The connected desktop runs an older OpenBitFun version that does not support on-demand session streaming. Update OpenBitFun on that device to continue.'], - ['errors.imageTooLargeAfterCompression', 'The image is still larger than {0} MB after compression. Choose a smaller image.'], - ['errors.imageCompressionFailed', 'Image compression failed. Choose a smaller image.'], - ['errors.voicePermissionDenied', 'Microphone permission was denied, so voice input is unavailable.'], - ['errors.voiceInputUnavailable', 'Speech recognition is unavailable. Try again later.'], - ['errors.voiceInputFailed', 'Speech recognition failed ({0}). Try again later.'], - - ['watchProvision.title', 'Sign in with email or GitHub on this watch?'], - ['watchProvision.deviceId', 'Device {0}'], - ['watchProvision.body', 'If you allow this, the watch will sign in to your account and can connect to a desktop. Confirm the watch is in your hands.'], - ['watchProvision.approve', 'Allow'], - ['watchProvision.reject', 'Deny'], - ['watchProvision.gotIt', 'Got it'], - ['watchProvision.working', 'Setting up the watch account...'], - ['watchProvision.passwordBody', 'Confirm your account password once more to create a separate sign-in for this watch. The password is used only for this verification.'], - ['watchProvision.passwordPlaceholder', 'Account password'], - ['watchProvision.passwordConfirm', 'Confirm'], - ['watchProvision.doneBody', '{0} is signed in and ready to use OpenBitFun.'], - ['watchProvision.rejected', 'Denied on the phone.'], - ['watchProvision.busy', 'The phone is handling another device request. Try again later.'], - ['watchProvision.errors.noDesktop', 'Sign in with email or GitHub on the phone, or connect a desktop signed in to the same account.'], - ['watchProvision.errors.accountUnavailable', 'The account could not be verified. Check the phone network and try again.'], - ['watchProvision.errors.requestExpired', 'The watch sign-in request expired. Start sign-in again on the watch.'], - ['watchProvision.errors.alreadyRegistered', 'This watch is registered, but this phone has no recoverable credential. Revoke the old watch authorization and retry.'], - ['watchProvision.errors.desktopUnreachable', 'The desktop could not be reached. Make sure it is online and try again.'], - ['watchProvision.errors.desktopAuthorizationFailed', 'The desktop could not sign in the watch. Make sure it uses the same OpenBitFun account.'], - ['watchProvision.errors.passwordFailed', 'Account verification failed. Check the password or network and retry.'], - ['watchProvision.errors.handoffFailed', 'Authorization finished, but the credential could not be sent to the watch. Retry on the watch.'], - - ['ui.emptyMessage', '(empty message)'], - ['ui.desktopProcessing', 'Desktop is working...'], - ['ui.seedConnected', '{0} is connected. You can keep sending instructions; the desktop will run them in OpenBitFun.'], - - ['time.justNow', 'Just now'], - ['time.unknown', 'Unknown time'], - ['time.minutesAgo', '{0} minutes ago'], - ['time.hoursAgo', '{0} hours ago'], - ['time.daysAgo', '{0} days ago'], -]; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/HostTextRetranslator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/HostTextRetranslator.ets deleted file mode 100644 index 16a3e4eca1..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/HostTextRetranslator.ets +++ /dev/null @@ -1,292 +0,0 @@ -import { util } from '@kit.ArkTS'; -import { fillMessageTemplate } from './MessageTemplate'; - -interface TemplateEntry { - key: string; - template: string; -} - -interface StringEntry { - name: string; - value: string; -} - -interface StringCatalog { - string: StringEntry[]; -} - -interface EntryLanguage { - key: string; - language: string; -} - -// Retranslates catalog-backed host text across the app catalog languages. -// -// The rawfile catalog keeps every language in one document: a trailing -// 2-3 letter lowercase dot segment (for example "common.back.zh") tags the -// entry language, and untagged entries are the generator's English block. -// -// Reverse indexes recover the catalog key; rendering always uses the requested -// language. Already localized messages therefore remain stable across refreshes. -// -// Values that several keys share in one language cannot identify their key, -// so ambiguous values are refused rather than guessed, like the legacy -// retranslate policy. -export class HostTextRetranslator { - private currentLanguage: string = 'en'; - private languages: string[] = []; - private forwardByLanguage: Map> = new Map(); - private reverseByLanguage: Map> = new Map(); - private ambiguousByLanguage: Map> = new Map(); - private templatesByLanguage: Map = new Map(); - - constructor(locale: string) { - this.currentLanguage = this.languageTag(locale); - this.loadCatalog(); - } - - retranslate(message: string): string { - if (message.length === 0) { - return message; - } - - // 1. Exact match per language O(1) - for (let languageIndex = 0; languageIndex < this.languages.length; languageIndex += 1) { - const language = this.languages[languageIndex]; - const reverse = this.reverseByLanguage.get(language); - if (!reverse) { - continue; - } - const exactKey = reverse.get(message); - if (exactKey !== undefined) { - const translated = this.renderEntry(exactKey); - if (translated !== null) { - return translated; - } - } - } - - // Prefer the most specific template; an equal-specificity disagreement - // cannot identify a key safely and leaves the original message intact. - let best: string | null = null; - let bestSpecificity = -1; - let ambiguous = false; - // 2. Template match per language O(M) - for (let languageIndex = 0; languageIndex < this.languages.length; languageIndex += 1) { - const language = this.languages[languageIndex]; - const templates = this.templatesByLanguage.get(language); - if (!templates) { - continue; - } - for (let templateIndex = 0; templateIndex < templates.length; templateIndex += 1) { - const entry = templates[templateIndex]; - const matched = this.matchTemplate(entry.template, message); - if (matched !== null) { - const translated = this.renderTemplate(entry, matched); - if (translated !== null) { - const specificity = entry.template.replace(/%[12]\$s/g, '').length; - if (specificity > bestSpecificity) { - best = translated; - bestSpecificity = specificity; - ambiguous = false; - } else if (specificity === bestSpecificity && best !== translated) { - ambiguous = true; - } - } - } - } - } - - return best !== null && !ambiguous ? best : message; - } - - retranslateKnown(message: string, keys: string[]): string { - for (let index = 0; index < keys.length; index += 1) { - const key = keys[index].replace(/\./g, '_'); - for (let languageIndex = 0; languageIndex < this.languages.length; languageIndex += 1) { - const language = this.languages[languageIndex]; - const template = this.forwardByLanguage.get(language)?.get(key); - if (template === undefined) { - continue; - } - if (template === message) { - return this.renderEntry(key) ?? message; - } - const matched = this.matchTemplate(template, message); - if (matched !== null) { - return this.renderTemplate({ key, template }, matched) ?? message; - } - } - } - return message; - } - - private loadCatalog(): void { - try { - const resourceManager = getContext(this).resourceManager; - // Rawfile paths are relative to the resources/rawfile root, and the - // content arrives as UTF-8 bytes. Decode multi-byte catalog text with - // TextDecoder instead of per-byte fromCharCode, which mangles it. - const rawResource = resourceManager.getRawFileContentSync('string.json'); - const jsonString = util.TextDecoder.create('utf-8').decodeWithStream(rawResource); - const catalog = JSON.parse(jsonString) as StringCatalog; - const strings = catalog.string || []; - - for (let index = 0; index < strings.length; index += 1) { - const entry = strings[index]; - const tagged = this.splitEntryLanguage(entry.name); - this.ensureLanguage(tagged.language); - const forward = this.forwardByLanguage.get(tagged.language); - const reverse = this.reverseByLanguage.get(tagged.language); - const ambiguous = this.ambiguousByLanguage.get(tagged.language); - const templates = this.templatesByLanguage.get(tagged.language); - if (!forward || !reverse || !ambiguous || !templates) { - continue; - } - forward.set(tagged.key, entry.value); - const existingKey = reverse.get(entry.value); - if (existingKey !== undefined) { - if (existingKey !== tagged.key) { - // A second key shares this value within the language, so the - // value cannot identify its key: refuse it instead of letting - // the later entry win like a plain overwrite would. - ambiguous.add(entry.value); - reverse.delete(entry.value); - } - } else if (!ambiguous.has(entry.value)) { - reverse.set(entry.value, tagged.key); - } - if (entry.value.indexOf('%1$s') >= 0 || entry.value.indexOf('%2$s') >= 0) { - templates.push({ key: tagged.key, template: entry.value }); - } - } - this.pruneAmbiguousTemplates(); - } catch (error) { - // Fallback: catalog unavailable, retranslate returns original message - } - } - - // A template is trustworthy only when its key's value is unique in every - // catalog language: one shared value in any language leaves the template - // shape unable to identify its key. Refuse such templates in every - // language, matching the legacy hasUniqueTemplate gate. - private pruneAmbiguousTemplates(): void { - for (let languageIndex = 0; languageIndex < this.languages.length; languageIndex += 1) { - const language = this.languages[languageIndex]; - const templates = this.templatesByLanguage.get(language); - if (!templates) { - continue; - } - const kept: TemplateEntry[] = []; - for (let templateIndex = 0; templateIndex < templates.length; templateIndex += 1) { - const entry = templates[templateIndex]; - if (!this.hasAmbiguousTemplate(entry.key)) { - kept.push(entry); - } - } - this.templatesByLanguage.set(language, kept); - } - } - - private hasAmbiguousTemplate(key: string): boolean { - for (let languageIndex = 0; languageIndex < this.languages.length; languageIndex += 1) { - const language = this.languages[languageIndex]; - const forward = this.forwardByLanguage.get(language); - const ambiguous = this.ambiguousByLanguage.get(language); - if (!forward || !ambiguous) { - return true; - } - const value = forward.get(key); - if (value === undefined || ambiguous.has(value)) { - return true; - } - } - return false; - } - - private ensureLanguage(language: string): void { - if (this.forwardByLanguage.has(language)) { - return; - } - this.forwardByLanguage.set(language, new Map()); - this.reverseByLanguage.set(language, new Map()); - this.ambiguousByLanguage.set(language, new Set()); - this.templatesByLanguage.set(language, []); - this.languages.push(language); - } - - private languageTag(locale: string): string { - const primary = locale.split('-')[0].toLowerCase(); - return primary.length > 0 ? primary : 'en'; - } - - private splitEntryLanguage(name: string): EntryLanguage { - const lastDot = name.lastIndexOf('.'); - if (lastDot >= 0) { - const suffix = name.slice(lastDot + 1); - if (suffix.length >= 2 && suffix.length <= 3 && suffix.toLowerCase() === suffix) { - return { key: name.slice(0, lastDot), language: suffix }; - } - } - // Untagged entries are the generator's English block. - return { key: name, language: 'en' }; - } - - private renderEntry(baseKey: string): string | null { - const forward = this.forwardByLanguage.get(this.currentLanguage); - if (!forward) { - return null; - } - const value = forward.get(baseKey); - return value !== undefined ? value : null; - } - - private renderTemplate(entry: TemplateEntry, matched: string[]): string | null { - const forward = this.forwardByLanguage.get(this.currentLanguage); - if (!forward) { - return null; - } - const template = forward.get(entry.key); - if (template === undefined) { - return null; - } - return fillMessageTemplate(template, matched); - } - - private matchTemplate(template: string, message: string): string[] | null { - // Parse %1$s and %2$s placeholders - const firstSlot = template.indexOf('%1$s'); - if (firstSlot < 0) { - return null; - } - - const prefix = template.slice(0, firstSlot); - const afterFirst = template.slice(firstSlot + 4); - const secondSlot = afterFirst.indexOf('%2$s'); - - if (secondSlot < 0) { - // Single placeholder: %1$s - const suffix = afterFirst; - if (!message.startsWith(prefix) || !message.endsWith(suffix)) { - return null; - } - const value = message.slice(prefix.length, message.length - suffix.length); - return [value]; - } - - // Two placeholders: %1$s and %2$s - const middle = afterFirst.slice(0, secondSlot); - const suffix = afterFirst.slice(secondSlot + 4); - if (!message.startsWith(prefix) || !message.endsWith(suffix)) { - return null; - } - const body = message.slice(prefix.length, message.length - suffix.length); - const middleAt = body.indexOf(middle); - if (middleAt < 0) { - return null; - } - const first = body.slice(0, middleAt); - const second = body.slice(middleAt + middle.length); - return [first, second]; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/MessageTemplate.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/MessageTemplate.ets deleted file mode 100644 index 923c4fbce7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/MessageTemplate.ets +++ /dev/null @@ -1,8 +0,0 @@ -// Substitute only slots in the original template. Callback results are literal: -// dollar signs and placeholder-like text in user data must never be re-parsed. -export function fillMessageTemplate(template: string, values: string[]): string { - return template.replace(/%[12]\$s/g, (slot: string): string => { - const index = slot === '%1$s' ? 0 : 1; - return index < values.length ? values[index] : slot; - }); -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets deleted file mode 100644 index 845be95928..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/RemoteI18n.ets +++ /dev/null @@ -1,152 +0,0 @@ -import { AppLocale, APP_LOCALE_EN_US, APP_LOCALE_ZH_CN } from './AppLocale'; -import { HostTextRetranslator } from './HostTextRetranslator'; -import { fillMessageTemplate } from './MessageTemplate'; -import { intl } from '@kit.LocalizationKit'; - -@ObservedV2 -export class AppLocaleState { - @Trace language: string = AppLocale.DEFAULT; - @Trace revision: number = 0; -} - -export class RemoteI18n { - static readonly state: AppLocaleState = new AppLocaleState(); - private static retranslator: HostTextRetranslator | null = null; - private static retranslatorLocale: string = ''; - - static language(): string { - return RemoteI18n.state.language; - } - - static revision(): number { - return RemoteI18n.state.revision; - } - - static setLanguage(language: string): string { - const resolved = AppLocale.resolve(language) || AppLocale.DEFAULT; - if (RemoteI18n.state.language !== resolved) { - RemoteI18n.state.language = resolved; - RemoteI18n.state.revision += 1; - RemoteI18n.retranslator = null; - RemoteI18n.retranslatorLocale = ''; - } - return resolved; - } - - static t(key: string): string { - try { - const resourceManager = getContext(RemoteI18n).resourceManager; - // HarmonyOS resource names only allow [a-zA-Z0-9_]; map dotted code keys - // (e.g. "workspaceTools.browse") to underscore resource names. - const resourceName = key.replace(/\./g, '_'); - return resourceManager.getStringByNameSync(resourceName); - } catch (error) { - return key; - } - } - - static f(key: string, value: string): string { - return fillMessageTemplate(RemoteI18n.t(key), [value]); - } - - static f2(key: string, first: string, second: string): string { - return fillMessageTemplate(RemoteI18n.t(key), [first, second]); - } - - static translate(language: string, key: string): string { - return RemoteI18n.t(key); - } - - static textEquals(key: string, message: string): boolean { - const supported = AppLocale.supported(); - for (let index = 0; index < supported.length; index += 1) { - if (RemoteI18n.t(key) === message) { - return true; - } - } - return false; - } - - static textContains(key: string, message: string): boolean { - const supported = AppLocale.supported(); - for (let index = 0; index < supported.length; index += 1) { - const value = RemoteI18n.t(key); - if (value.length > 0 && message.indexOf(value) >= 0) { - return true; - } - } - return false; - } - - static textHasTemplatePrefix(key: string, message: string): boolean { - const supported = AppLocale.supported(); - for (let index = 0; index < supported.length; index += 1) { - const prefix = RemoteI18n.t(key).split('%1$s')[0]; - if (prefix.length > 0 && message.indexOf(prefix) >= 0) { - return true; - } - } - return false; - } - - static keys(language: string = AppLocale.DEFAULT): string[] { - // Return empty array - keys are now managed by the system resource manager - return []; - } - - static formatMessageTime(timestamp: number): string { - const locale = RemoteI18n.language() === APP_LOCALE_EN_US ? 'en-US' : 'zh-CN'; - return new intl.DateTimeFormat(locale, { - year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' - }).format(new Date(timestamp)); - } - - static formatAbsoluteDate(timestamp: number): string { - const locale = RemoteI18n.language() === APP_LOCALE_EN_US ? 'en-US' : 'zh-CN'; - const formatter = new intl.DateTimeFormat(locale, { - year: 'numeric', - month: '2-digit', - day: '2-digit' - }); - return formatter.format(new Date(timestamp)); - } - - static speechLanguage(): string { - return AppLocale.speechLanguage(RemoteI18n.language()); - } - - static speechLocate(): string { - return AppLocale.speechLocate(RemoteI18n.language()); - } - - static nativeName(language: string = RemoteI18n.language()): string { - return RemoteI18n.t(AppLocale.nativeNameKey(language)); - } - - static retranslateKnown(message: string, keys: string[]): string { - return RemoteI18n.hostTextRetranslator().retranslateKnown(message, keys); - } - - static retranslateWorkspaceName(name: string, path: string, workspaceId: string): string { - if (path.length > 0 || workspaceId.length > 0) { - return name; - } - return RemoteI18n.retranslateKnown(name, ['status.notConnected']); - } - - static retranslate(message: string): string { - if (message.length === 0) { - return message; - } - return RemoteI18n.hostTextRetranslator().retranslate(message); - } - - private static hostTextRetranslator(): HostTextRetranslator { - const locale = RemoteI18n.language(); - if (!RemoteI18n.retranslator || RemoteI18n.retranslatorLocale !== locale) { - RemoteI18n.retranslator = new HostTextRetranslator(locale); - RemoteI18n.retranslatorLocale = locale; - } - return RemoteI18n.retranslator!; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets deleted file mode 100644 index bcaa485eca..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets +++ /dev/null @@ -1,716 +0,0 @@ -export const ZH_CN_MESSAGES: [string, string][] = [ - ['queue.title', '待发送 · %1$s'], - ['queue.reorder', '拖动排序'], - ['queue.moveUp', '上移'], - ['queue.moveDown', '下移'], - ['queue.refresh', '刷新'], - ['queue.refreshRequired', '队列状态已变化或未能确认,请刷新后再操作。'], - ['queue.attachments', '%1$s 个附件'], - ['queue.waiting', '等待执行端处理'], - ['queue.sendNow', '立即发送'], - ['queue.more', '消息操作'], - ['queue.remove', '从队列移除'], - ['queue.unsupported', '升级执行端后可调整消息顺序。'], - ['session.newTitle', '新会话'], - ['workspaceTools.browse', '浏览受控设备文件夹'], - ['workspaceTools.selectFolder', '选择此文件夹'], - ['workspaceTools.back', '返回文件列表'], - ['workspaceTools.edit', '编辑'], - ['workspaceTools.lineNumbers', '行号'], - ['workspaceTools.unsaved', '有未保存的更改'], - ['workspaceTools.fileConflict', '电脑上的文件已被修改,当前草稿仍保留。请先复制草稿,再重新打开文件以读取最新内容。'], - ['workspaceTools.discard', '放弃更改'], - ['workspaceTools.nameAsc', '名称升序'], - ['workspaceTools.nameDesc', '名称降序'], - ['workspaceTools.modifiedAsc', '修改时间升序'], - ['workspaceTools.modifiedDesc', '修改时间降序'], - ['workspaceTools.upload', '上传文件'], - ['workspaceTools.resumeUpload', '继续上传'], - ['workspaceTools.cancelUpload', '取消上传'], - ['workspaceTools.selectLocation', '选择位置'], - ['workspaceTools.runtimeLocal', '受控设备本机'], - ['workspaceTools.download', '下载'], - ['workspaceTools.title', '工具'], - ['workspaceTools.files', '文件'], - ['sidebar.controlledDevice', '受控设备'], - ['sidebar.currentPath', '当前路径'], - ['sidebar.recentWorkspaces', '最近工作区'], - ['sidebar.tapToSwitch', '点击切换'], - ['workspaceTools.selectTerminal', '选择已有终端'], - ['workspaceTools.terminal', '终端'], - ['workspaceTools.up', '上级目录'], - ['workspaceTools.refresh', '刷新'], - ['workspaceTools.more', '加载更多'], - ['workspaceTools.fileName', '文件名'], - ['workspaceTools.path', '被控运行端绝对路径'], - ['workspaceTools.newFile', '新建文件'], - ['workspaceTools.mkdir', '新建文件夹'], - ['workspaceTools.rename', '重命名'], - ['workspaceTools.save', '保存'], - ['workspaceTools.delete', '删除文件'], - ['workspaceTools.confirmDelete', '确认删除'], - ['workspaceTools.rmdir', '删除空文件夹'], - ['workspaceTools.createTerminal', '新建终端'], - ['workspaceTools.command', '终端输入'], - ['workspaceTools.send', '发送'], - ['workspaceTools.closeTerminal', '关闭终端'], - ['workspaceTools.resize', '调整尺寸'], - ['home.recent_title', '今天,想做点什么?'], - ['home.recent_recent', '最近会话'], - ['home.recent_browse', '浏览工作区'], - ['home.recent_all', '全部会话'], - ['home.recent_empty', '还没有可继续的对话'], - ['home.recent_connect', '连接电脑后,继续你的对话。'], - ['account.errorNetwork', '暂时无法连接,请检查网络后重试。'], - ['account.errorTimeout', '连接超时,请检查网络后重试。'], - ['account.errorSecureConnection', '无法建立安全连接,请检查网络后重试。'], - ['account.errorRateLimited', '操作太频繁,请稍后重试。'], - ['home.welcome_login', '登录账号'], - ['home.welcome_work', '干点活儿'], - ['home.welcome_play', '玩点花样'], - ['home.welcome_yours', '随你发挥'], - ['home.connectComputer', '连接电脑'], - ['home.connecting', '正在连接…'], - ['home.exploreMiniApps', '探索小应用'], - ['home.miniAppsHint', '无需连接电脑,也能即刻使用'], - ['miniapp.allApps', '全部应用'], - ['miniapp.availableOffline', '离线可用'], - - ['miniapp.timeout', '本地操作超时,操作可能仍会完成,未自动重试。'], - ['miniapp.title', '小应用'], - ['miniapp.refresh', '刷新'], - ['miniapp.empty', '暂无内置小应用。'], - ['miniapp.unsupported', '手机内置小应用不支持此能力。'], - ['miniapp.invalidPage', '小应用页面数据不完整,请重新打开。'], - ['miniapp.closed', '小应用已关闭或切换。'], - ['miniapp.previewHint', '内置应用 · 离线可用,数据保存在本机。'], - ['notification.onboardingTitle', '开启任务完成提醒'], - ['notification.onboardingBody', '允许 OpenBitFun 在任务完成时发送通知。你可以稍后在系统设置中更改。'], - ['notification.onboardingLater', '稍后'], - ['notification.onboardingEnable', '开启通知'], - ['app.title', 'OpenBitFun'], - - ['common.cancel', '取消'], - ['common.back', '返回'], - ['common.close', '关闭'], - ['common.copy', '复制'], - ['common.current', '当前'], - ['common.done', '已完成'], - ['common.delete', '删除'], - ['common.failed', '失败'], - ['common.keep', '保留'], - ['common.loading', '加载中...'], - ['common.open', '打开'], - ['common.other', '其他'], - ['common.ready', '就绪'], - ['common.refresh', '刷新'], - ['common.retry', '重试'], - ['common.save', '保存'], - ['common.search', '搜索'], - ['common.running', '运行中'], - ['common.waiting', '等待中'], - - ['notification.taskCompletedTitle', '任务已完成'], - ['notification.taskCompletedBody', 'OpenBitFun 任务已经完成,点击打开 OpenBitFun 查看结果。'], - - ['chatHome.prompt', '今天想做什么?'], - ['chat.promptSuggestionAccept', '填入输入框'], - ['chatHome.placeholder', '问问 OpenBitFun'], - ['chatHome.localHint', '这是手机上的对话。要读写电脑上的项目,请切换到远程。'], - ['chatHome.research', '查找资料'], - ['chatHome.researchPrompt', '帮我查找资料并整理重点:'], - ['chatHome.image', '分析图片'], - ['chatHome.imagePrompt', '请分析这张图片。'], - ['chatHome.file', '处理文件'], - ['chatHome.filePrompt', '帮我总结这个文件的重点。'], - ['chatHome.write', '帮我写点内容'], - ['chatHome.writePrompt', '请帮我起草一段内容:'], - ['chatHome.organize', '梳理一个问题'], - ['chatHome.organizePrompt', '请帮我梳理这个问题的重点和思路:'], - ['chatHome.plan', '制定行动计划'], - ['chatHome.planPrompt', '请帮我制定一份清晰、可执行的行动计划:'], - ['chatHome.codeHintTitle', '这个任务可能需要远程能力'], - ['chatHome.codeHintBody', '连接桌面工作区后,OpenBitFun 才能读取项目文件、运行命令并修改代码。'], - ['chatHome.enterCode', '进入远程'], - - ['generalChat.ready', 'OpenBitFun 已就绪'], - ['generalChat.generating', 'OpenBitFun 正在回复'], - ['generalChat.sending', '正在发送消息'], - ['generalChat.offline', '网络不可用,草稿和历史仍保存在本机。'], - ['generalChat.stopped', '已停止生成。'], - ['generalChat.interrupted', '回复已中断,已保留收到的内容。'], - ['generalChat.replyInterrupted', '回复中断'], - ['generalChat.fileDownloadMock', '普通聊天暂不支持下载桌面端文件,请进入远程后处理本地文件。'], - ['generalChat.filePreviewUnavailable', '普通聊天暂不支持预览桌面端文件,请进入远程后打开。'], - ['generalChat.localRestoreFailed', '普通对话历史暂时无法恢复,你仍可新建对话。'], - ['generalChat.modelNotConfigured', '请先在设置中配置普通对话模型。'], - ['generalChat.authenticationFailed', 'API Key 无效或无权访问该模型。'], - ['generalChat.rateLimited', '模型服务请求过于频繁,请稍后重试。'], - ['generalChat.serviceUnavailable', '模型服务暂时不可用,请稍后重试。'], - ['generalChat.invalidResponse', '模型服务返回了无法识别的响应。'], - ['generalChat.emptyResponse', '模型没有返回文字内容。'], - ['generalChat.requestFailed', '模型请求失败(HTTP {0})。'], - - ['settings.general.section', '通用'], - ['settings.account.section', '账号'], - ['settings.account.currentIdentity', '当前身份'], - ['settings.model.section', '模型'], - ['settings.model.default', '默认模型'], - ['settings.devices.section', '设备'], - ['settings.title', '设置'], - ['settings.language.title', '语言'], - ['settings.language.choose', '选择语言'], - ['settings.language.zhCN', '简体中文'], - ['settings.language.enUS', 'English'], - ['settings.about.section', '关于'], - ['settings.about.openbitfun', '关于 OpenBitFun'], - ['settings.about.product', '产品'], - ['settings.about.version', '版本'], - ['settings.modelService.title', '模型'], - ['settings.modelService.manageTitle', '普通对话模型'], - ['settings.modelService.localTitle', '本机自定义模型'], - ['settings.modelService.currentModel', '当前使用'], - ['settings.modelService.modelSources', '模型来源'], - ['settings.modelService.chooseAccountModel', '选择账号模型'], - ['settings.modelService.accountModels', '账号同步'], - ['settings.modelService.accountModelSummary', '云端账号模型'], - ['settings.modelService.localModel', '本机自定义'], - ['settings.modelService.accountSource', '云端账号'], - ['settings.modelService.localSource', '本机'], - ['settings.modelService.syncedCount', '已同步 {0} 个'], - ['settings.modelService.accountEmpty', '暂无可用的账号模型'], - ['settings.modelService.configured', '已配置'], - ['settings.modelService.notConfigured', '未配置'], - ['settings.modelService.apiUrl', 'API URL'], - ['settings.modelService.apiUrlPlaceholder', 'https://api.example.com'], - ['settings.modelService.apiKey', 'API Key'], - ['settings.modelService.apiKeyPlaceholder', '输入 API Key'], - ['settings.modelService.apiKeyKeepPlaceholder', '留空则保留已保存的 Key'], - ['settings.modelService.modelName', '模型名称'], - ['settings.modelService.modelPlaceholder', '例如 chat-model'], - ['settings.modelService.keySaved', '已安全保存'], - ['settings.modelService.clearKey', '清除已保存的 Key'], - ['settings.modelService.keepKey', '保留已保存的 Key'], - ['settings.modelService.testConnection', '测试连接'], - ['settings.modelService.testNeedsKey', '保留或输入 API Key 后可测试连接。'], - ['settings.modelService.testSuccess', '连接测试通过。'], - ['settings.modelService.invalidUrl', 'API URL 必须以 http:// 或 https:// 开头。'], - ['settings.modelService.modelRequired', '请输入模型名称。'], - ['settings.modelService.apiKeyRequired', '请输入 API Key。'], - ['settings.modelService.encryptFailed', 'API Key 加密失败。'], - ['settings.modelService.secureStoreFailed', '无法访问系统安全存储,请稍后重试。'], - - ['sidebar.chat', '库'], - ['sidebar.projects', '项目'], - ['sidebar.tasks', '已计划'], - ['sidebar.tools', '应用'], - ['sidebar.more', '更多'], - ['sidebar.newChat', '聊天'], - ['sidebar.generalChat', '普通对话'], - ['sidebar.conversations', '最近对话'], - ['sidebar.devices', '设备'], - ['sidebar.legacyWorkspaceCatalog', '旧版设备:显示最近访问的工作区'], - ['sidebar.workspaces', '工作区'], - ['sidebar.deviceOnline', '在线'], - ['sidebar.addWorkspace', '添加工作区'], - ['sidebar.targetWorkspacePath', '受控设备上的路径'], - ['sidebar.openWorkspacePath', '打开工作区'], - ['sidebar.remoteRootBrowseOnly', '远程根目录仅用于浏览,请选择具体工作区目录'], - ['sidebar.browseRemoteRoot', '浏览远程根目录'], - ['sidebar.selectWorkspace', '选择工作区'], - ['sidebar.workspacesOffline', '未连接'], - ['sidebar.connectDesktop', '连接电脑'], - ['sidebar.addConnection', '添加连接'], - ['sidebar.newInWorkspace', '在此工作区新建'], - ['sidebar.emptyWorkspaces', '这台电脑还没有工作区'], - ['sidebar.moreSessions', '还有 {0} 个会话'], - ['sidebar.moreWorkspaces', '还有 {0} 个工作区'], - ['sidebar.deviceOffline', '离线'], - ['sidebar.deviceLoadFailed', '这台电脑暂时无法读取'], - ['sidebar.moreDevices', '还有 {0} 台设备'], - ['sidebar.pinned', '置顶'], - ['sidebar.archived', '已归档'], - ['sidebar.archive', '归档'], - ['sidebar.unarchive', '取消归档'], - ['sidebar.exportMarkdown', '复制 Markdown'], - ['sidebar.untitled', '未命名会话'], - ['sidebar.emptyRecentTitle', '暂无最近会话'], - ['sidebar.emptyRecentText', '开始聊天后会显示在这里。'], - ['sidebar.deleteConfirm', '删除后将无法恢复这条会话。'], - ['sidebar.searchPlaceholder', '搜索对话'], - ['sidebar.noSearchResult', '没有匹配的会话'], - ['sidebar.signedOutNewChat', '新聊天'], - ['sidebar.signInOpenBitFunAccount', '使用邮箱或 GitHub 登录'], - ['sidebar.collapse', '收起侧边栏'], - ['sidebar.restore', '展开侧边栏'], - - ['session.actions', '会话操作'], - ['session.details', '会话详情'], - ['session.viewDetails', '查看详情'], - ['session.agentType', '智能体类型'], - ['session.workspace', '工作区'], - ['session.workspacePath', '工作区路径'], - ['session.createdAt', '创建时间'], - ['session.updatedAt', '更新时间'], - ['session.messageCount', '消息数'], - ['session.status', '状态'], - - ['viewSettings.title', '视图设置'], - ['viewSettings.subtitle', '调整会话列表的分组和信息密度'], - ['viewSettings.grouping', '分组方式'], - ['viewSettings.filters', '筛选'], - ['viewSettings.metadata', '显示信息'], - ['viewSettings.workspace', '工作区'], - ['viewSettings.agentType', '会话类型'], - ['viewSettings.allWorkspaces', '全部工作区'], - ['viewSettings.allAgentTypes', '全部类型'], - ['viewSettings.allStatuses', '全部状态'], - ['viewSettings.updated', '更新时间'], - ['viewSettings.status', '运行状态'], - - ['common.unknown', '未知'], - - ['code.title', 'OpenBitFun 远程'], - ['code.heroTitle', '本地开发助手'], - ['code.heroBody', '连接桌面端后,OpenBitFun 可以访问你的代码仓库、运行命令和修改文件。'], - ['code.connectWorkspace', '连接本地工作区'], - ['code.noWorkspacePreview', '连接桌面端后会显示最近打开的代码仓库。'], - ['code.newTask', '新建远程任务'], - ['code.switchWorkspace', '切换工作区'], - ['code.disconnect', '断开连接'], - ['code.recentSessions', '最近远程会话'], - ['code.emptySessionTitle', '暂无远程会话'], - ['code.emptySessionText', '连接本地工作区后,可以新建远程任务处理项目问题。'], - - ['remote.actionUnsupported', '已连接的设备不支持此操作。'], - ['remote.title', '远程'], - ['remote.chats', '聊天'], - ['remote.searchChats', '搜索聊天记录'], - ['remote.emptyTitle', '还没有远程对话'], - ['remote.emptyText', '新建聊天后,可以从手机继续处理桌面端任务。'], - ['remote.pickSession', '选择一个会话'], - ['remote.pickSessionText', '从侧边栏打开会话,或新建一个。'], - ['remote.startSession', '新建会话'], - ['remote.harness.title', '选择执行模式'], - ['remote.harness.minimal', '极简'], - ['remote.harness.standard', '标准'], - ['remote.harness.ultimate', '极致'], - ['remote.connectTitle', '连接桌面端'], - ['remote.actions', '远程设置'], - ['remote.device', '连接的设备'], - ['remote.newChat', '聊天'], - ['remote.workspace', '工作区'], - ['remote.assistant', '助理'], - ['remote.noAssistant', '默认助理'], - ['remote.loadMore', '加载更多聊天'], - ['remote.menu.organize', '整理'], - ['remote.menu.byProject', '按项目'], - ['remote.menu.byTime', '按时间倒序排列'], - ['remote.menu.chatFirst', '聊天优先'], - ['remote.menu.manage', '管理'], - ['remote.menu.cloudTasks', '云端任务'], - ['remote.menu.addConnection', '添加连接'], - ['remote.menu.settings', '设置'], - ['remote.menu.refreshConnection', '刷新连接'], - ['remote.menu.comingSoon', '待上线'], - ['remote.projects.showMore', '再显示 {0} 个项目'], - ['remote.sessions.showMore', '再显示 {0} 条会话'], - ['remote.time.today', '今天'], - ['remote.time.yesterday', '昨天'], - ['remote.time.earlier', '更早'], - ['remote.settings.relayReauthorizationRequired', '中继服务已升级,请重新登录关联新服务;已保存的账户和数据会保留。'], - ['remote.settings.currentControl', '当前远程控制'], - ['remote.settings.accountDevice', '账号设备'], - ['remote.settings.qrPairing', '扫码配对'], - ['remote.settings.disconnect', '断开'], - ['remote.settings.disconnectTemporary', '断开临时连接'], - ['remote.settings.reconnect', '重新连接'], - ['remote.settings.noDesktop', '尚未连接桌面端'], - ['remote.settings.openbitfunUser', 'OpenBitFun 用户'], - ['remote.settings.accountSignedIn', '已登录'], - ['remote.settings.accountNotSignedIn', '未登录'], - ['remote.settings.accountTemporary', '临时登录'], - ['remote.settings.accountLoginTitle', '使用邮箱或 GitHub 登录'], - ['remote.settings.accountLoginBody', '使用邮箱或 GitHub 登录并连接自己的电脑。\n任务和模型配置保留在被控电脑上。'], - ['remote.settings.loginServer', '登录服务器'], - ['remote.settings.accountSignIn', '使用邮箱或 GitHub 登录'], - ['remote.settings.accountSigningIn', '正在登录…'], - ['remote.settings.accountLoginFailed', '暂时无法登录,请稍后重试。'], - ['remote.settings.relayUrlPlaceholder', 'Relay 地址,例如 https://relay.example.com'], - ['remote.settings.accountLogout', '退出登录'], - ['remote.settings.accountLoggingOut', '正在退出…'], - ['remote.settings.deviceCurrent', '当前设备'], - ['remote.settings.deviceRefresh', '刷新'], - ['remote.settings.deviceLoading', '正在加载设备…'], - ['remote.settings.deviceEmpty', '账号下还没有其他已注册设备。'], - ['remote.settings.deviceLoginRequired', '登录云账号后可查看该账号下的所有设备。'], - ['remote.settings.deviceOnline', '在线'], - ['remote.settings.deviceOffline', '离线'], - ['remote.settings.deviceConnecting', '正在连接'], - ['remote.settings.deviceControlling', '当前控制'], - ['remote.settings.deviceSwitching', '正在切换到 {0}…'], - ['remote.settings.deviceSwitchFailed', '切换控制设备失败,请稍后重试。'], - ['remote.settings.deviceLoadFailed', '设备列表加载失败,请稍后重试。'], - ['remote.settings.accountExpired', '云账号已失效,请重新登录。'], - ['remote.settings.deviceUnavailable', '目标桌面暂时不可用,请刷新设备列表后重试。'], - ['remote.settings.deviceIncompatible', '客户端版本不兼容,无法互控。'], - ['remote.settings.deviceName', '设备'], - ['remote.settings.deviceManagementBody', '此设备的账号凭据已使用 HUKS 加密保存。退出账号后会立即清理。'], - ['remote.settings.githubId', 'Account ID: {0}'], - ['remote.settings.githubAccount', 'OpenBitFun 账号'], - ['remote.settings.connectedDesktop', '当前桌面端'], - ['remote.permissions.title', '权限模式'], - ['remote.permissions.scope', '此设置会同步到当前桌面,并应用于所有新的工具调用。'], - ['remote.permissions.ask', '需要确认'], - ['remote.permissions.askDescription', '高风险操作会等待你确认。'], - ['remote.permissions.auto', '自动批准'], - ['remote.permissions.autoDescription', '原本需要确认的操作会自动通过。'], - ['remote.permissions.fullAccess', '完全访问'], - ['remote.permissions.fullAccessDescription', '允许所有工具操作,不再请求确认。'], - ['remote.permissions.loading', '正在读取桌面权限设置…'], - ['remote.permissions.loadFailed', '权限设置读取失败,请重试。'], - ['remote.permissions.saveFailed', '权限模式保存失败,请重试。'], - ['remote.permissions.connectionRequired', '连接桌面后可修改权限模式。'], - ['remote.permissions.fullAccessWarningTitle', '确认开启完全访问?'], - ['remote.permissions.fullAccessWarningBody', '开启后,桌面端工具可以直接执行命令和修改文件。'], - ['remote.permissions.cancel', '取消'], - ['remote.permissions.confirmFullAccess', '开启完全访问'], - - ['connect.localTitle', '连接本地工作区'], - ['connect.chooseConnectionTitle', '连接电脑'], - ['connect.legacySignInRequired', '请使用邮箱或 GitHub 登录后重新连接设备。原有连接记录已保留。'], - ['connect.subtitle', '连接桌面端后,OpenBitFun 可以访问代码仓库、运行命令和处理本地开发任务。'], - ['connect.accountDevicesTitle', '选择桌面设备'], - ['connect.accountDevicesSubtitle', '远程'], - ['connect.accountDevicesBody', '选择一台在线桌面继续工作。'], - ['connect.availableDevices', '账号设备'], - ['connect.deviceLastUsed', '上次连接'], - ['connect.deviceLinkInvalid', '已保存的连接链接无法使用,请登录账号后从设备列表选择电脑。'], - ['connect.deviceLinkUnavailable', '该设备已离线,或不属于当前 OpenBitFun 账户。'], - ['connect.accountPairTitle', '账号配对验证'], - ['connect.accountPairIntro', '桌面端已使用邮箱或 GitHub 登录,需要验证同一账号后继续连接。'], - ['connect.accountPairBody', '密码只用于本次加密配对,不会保存到手机。'], - ['connect.enterAccountToPair', '请使用邮箱或 GitHub 登录后连接设备'], - ['connect.accountUsernamePlaceholder', 'OpenBitFun 用户名'], - ['connect.accountPasswordPlaceholder', 'OpenBitFun 密码'], - ['connect.stepsTitle', '连接步骤'], - ['connect.or', '或'], - ['connect.userId', '输入用户 ID'], - ['connect.userPlaceholder', '例如:DESKTOP-KM3L4UI'], - ['connect.connect', '连接'], - ['connect.connecting', '连接中...'], - ['connect.remoteUrlShort', '远程连接链接'], - ['connect.collapse', '收起'], - ['connect.filled', '已填写'], - ['connect.fill', '填写'], - ['connect.clear', '清除'], - ['connect.urlPlaceholder', 'openbitfun:// 或 https://...#/pair?room=...&pk=...&relay=...'], - ['connect.statusTitle', '连接状态'], - ['connect.targetDesktop', '目标桌面端'], - ['connect.noDesktop', '尚未选择桌面端'], - ['connect.noDesktopDetail', '登录账号并选择一台电脑后,会在这里显示连接状态。'], - ['connect.desktopId', '桌面 ID:{0}'], - ['connect.desktopIdUnavailable', '桌面 ID 暂不可用'], - ['connect.waitingDevice', '等待连接桌面设备'], - ['connect.connected', '已连接'], - ['connect.connectedTo', '已连接到 {0} · {1}'], - ['connect.waitingDesktop', '等待桌面端确认'], - ['connect.failed', '连接失败'], - ['connect.cannotConnectDesktop', '无法连接到桌面设备'], - ['connect.disconnected', '已断开'], - ['connect.desktopDisconnected', '与桌面断开连接'], - ['connect.hintExpiredRoom', '旧的扫码连接已过期或房间不存在,请登录账号后从设备列表选择电脑。'], - ['connect.hintNetwork', '手机无法访问中继服务,请检查网络、代理或桌面端中继地址后重试。'], - ['connect.hintProtectedUser', '这个连接已绑定用户 ID,请继续使用桌面端确认过的用户 ID。'], - ['connect.hintInvalidLink', '已保存的连接链接不完整,请登录账号后从设备列表选择电脑。'], - - ['connection.connected', '已连接'], - ['connection.reconnecting', '正在重连'], - ['connection.connecting', '连接中'], - ['connection.error', '连接异常'], - ['connection.disconnected', '已断开'], - ['connection.waiting', '等待连接'], - ['connection.user', '用户 {0}'], - ['connection.reconnectingDesktop', '正在重新连接桌面端'], - ['connection.unavailableReconnect', '连接不可用,请重新连接'], - ['connection.desktopDisconnected', '与桌面端断开连接'], - - ['home.reconnect', '重连'], - ['home.disconnect', '断开'], - ['home.clearPairing', '清除配对'], - ['home.workbench', '工作台'], - ['home.currentAssistant', '当前助理'], - ['home.currentWorkspace', '当前工作区'], - ['home.switchAssistant', '切换助理'], - ['home.switch', '切换'], - ['home.recentWorkspaces', '最近工作区'], - ['home.noRecentWorkspaces', '没有最近工作区,请先在桌面端打开工作区。'], - ['home.assistantWorkspaces', '助理工作区'], - ['home.noAssistants', '没有可用助理,请先在桌面端创建或打开助理。'], - ['home.createSession', '新建会话'], - ['home.assistantSession', '助理会话'], - ['home.assistantSessionDisabled', '桌面端暂未开放创建助理会话'], - ['home.codeDesc', '处理编码任务'], - ['home.coworkDesc', '处理日常办公任务'], - ['home.recent', '最近'], - ['home.viewAll', '查看全部'], - ['home.sessionCount', '{0} 个会话'], - ['home.searchPlaceholder', '搜索会话标题'], - ['home.all', '全部'], - ['home.loadMore', '加载更多'], - ['home.deleteSession', '删除会话'], - ['home.emptyLoadingTitle', '加载会话中'], - ['home.emptyLoadingText', '正在同步桌面端会话列表。'], - ['home.emptySearchTitle', '没有匹配的会话'], - ['home.emptySearchText', '换一个关键词或筛选条件后再试。'], - ['home.emptyAssistantTitle', '暂无助理会话'], - ['home.emptyAssistantText', '桌面端开放创建后可在这里开始。'], - ['home.emptyTitle', '暂无会话'], - ['home.emptyText', '用远程处理编码任务,或用普通对话处理日常问题。'], - - ['sheet.createTitle', '创建 {0} 会话'], - ['sheet.workspace', '工作区'], - ['sheet.sessionTitleOptional', '会话标题(可选)'], - ['sheet.firstInstructionOptional', '首条指令(可选)'], - ['sheet.instructionPlaceholder', '告诉 OpenBitFun 要做什么...'], - ['sheet.advancedOptions', '高级选项'], - ['sheet.unavailable', '暂不可用'], - ['sheet.creating', '创建中...'], - ['sheet.start', '开始'], - - ['chat.remoteSession', '远程会话'], - ['chat.sessionTitle', '会话标题'], - ['chat.sessionSection', '会话'], - ['chat.pin', '置顶'], - ['chat.unpin', '取消置顶'], - ['chat.uploadedFiles', '已上传的文件'], - ['chat.stop', '停止'], - ['chat.send', '发送'], - ['chat.voiceInput', '语音输入'], - ['chat.stopListening', '停止听写'], - ['chat.addImage', '添加图片'], - ['chat.removeImage', '移除图片'], - ['chat.selectModel', '选择模型'], - ['chat.modelPrimary', '主力模型'], - ['chat.modelFast', '快速模型'], - ['chat.modelFastNotConfigured', '未配置时使用主力模型'], - ['chat.modelRolePrimary', '主力'], - ['chat.modelRoleFast', '快速'], - ['chat.loadOlder', '加载更早消息'], - ['chat.loadOlderFailed', '加载更早消息失败,点按重试。'], - ['chat.inputPlaceholder', '向 OpenBitFun 提问'], - ['chat.voiceListeningPlaceholder', '正在听,请说话...'], - ['chat.queuedAfterRunningTurn', '已排队,当前任务结束后执行'], - ['chat.image', '图片'], - ['chat.imageUnavailable', '图片未同步到此设备'], - ['chat.thinkingRunning', '运行中'], - ['chat.thinkingDone', '已完成'], - ['chat.thinkingInProgress', '正在思考'], - ['chat.thinkingComplete', '已思考'], - ['chat.toolCalls', '调用工具'], - ['chat.toolsRan', '已运行 {0} 个工具'], - ['chat.toolOpTodoWrite', '更新任务列表'], - ['chat.toolOpTask', '发起任务'], - ['chat.toolOpRead', '读取文件'], - ['chat.toolOpWrite', '写入文件'], - ['chat.toolOpDelete', '删除文件'], - ['chat.toolOpDiff', '查看变更'], - ['chat.toolOpEdit', '修改文件'], - ['chat.toolOpCommand', '运行命令'], - ['chat.toolOpWebSearch', '网页搜索'], - ['chat.toolOpWebFetch', '访问网页'], - ['chat.toolOpSearch', '搜索代码'], - ['chat.toolOpAskUser', '请求确认'], - ['chat.toolTodoFallback', '任务列表'], - ['chat.toolTaskFallback', '子任务'], - ['chat.subagentOutput', '子任务输出'], - ['chat.toolFailed', '{0}失败'], - ['chat.toolRunning', '正在运行'], - ['chat.showMore', '查看更多'], - ['chat.showLess', '收起'], - ['chat.processing', '正在处理'], - ['chat.sendFailed', '发送失败,请检查连接后重试'], - ['chat.responseFailed', '本次回复失败'], - ['chat.error', '错误'], - ['chat.output', '输出'], - ['chat.interactionLoadFailed', '待处理交互加载失败'], - ['chat.approvalFailed', '提交失败,请重试'], - ['chat.approvalRequired', '需要批准'], - ['chat.editApprovalInput', '编辑参数'], - ['chat.hideApprovalInput', '收起参数'], - ['chat.approve', '批准'], - ['chat.reject', '拒绝'], - ['chat.cancelTool', '取消工具'], - ['chat.planView', '查看计划'], - ['chat.planBuild', '构建 Plan'], - ['chat.planBuildUnavailable', '请更新桌面端后再从手机构建 Plan。'], - ['chat.planBuildWaitForTurn', '请等待当前任务结束后再构建这个 Plan。'], - ['chat.toolInput', '工具输入'], - ['chat.reset', '重置'], - ['chat.editJsonInput', '编辑 JSON 输入'], - ['chat.answerPlaceholder', '输入回答'], - ['chat.submitAnswer', '提交回答'], - ['chat.emptySyncing', '正在同步'], - ['chat.emptyConnectionError', '连接异常'], - ['chat.emptyReconnecting', '正在恢复连接'], - ['chat.emptyNoMessages', '暂无消息'], - ['chat.emptyLoadingMessages', '正在加载桌面端会话消息。'], - ['chat.emptyReconnectFromHome', '请返回工作台重新连接桌面端。'], - ['chat.emptyReconnectSync', '恢复后会继续同步桌面端消息。'], - ['chat.emptyFirstMessage', '发送第一条指令后,桌面端响应会显示在这里。'], - ['chat.executing', 'OpenBitFun 正在执行...'], - ['chat.model', '模型'], - ['chat.openbitfunProcessing', 'OpenBitFun 正在处理...'], - ['chat.updatedSession', 'OpenBitFun 已更新会话'], - ['chat.desktopFile', '桌面端文件'], - ['chat.fileLink', '文件链接'], - ['chat.reading', '读取中'], - ['chat.download', '下载'], - - ['filePreview.title', '文件预览'], - ['filePreview.loading', '正在读取文件'], - ['filePreview.offline', '离线,仅显示已加载内容'], - ['filePreview.fitImage', '适应窗口'], - ['filePreview.actualImageSize', '原始大小'], - ['filePreview.expand', '放大预览'], - ['filePreview.restoreSize', '还原预览'], - ['filePreview.imageDecodeFailed', '图片无法解码,请重试或下载文件。'], - ['filePreview.loadFailed', '无法打开文件'], - ['filePreview.notFound', '文件不存在或已被移动'], - ['filePreview.unavailable', '文件不存在或不在当前工作区'], - ['filePreview.accessDenied', '无法访问工作区外的文件'], - ['filePreview.tooLarge', '文件过大,无法在移动端预览'], - ['filePreview.unsupported', '此文件暂不支持预览'], - ['filePreview.truncated', '已显示前 {0},下载后可查看完整内容'], - - ['chat.pendingConfirmation', '待确认'], - ['chat.cancelled', '已取消'], - ['chat.jsonObjectRequired', '请输入 JSON 对象'], - ['chat.jsonInvalid', 'JSON 格式错误'], - ['chat.questionDefault', '桌面端需要你的回答。'], - ['chat.analyzeImageDefault', '请分析这张图片。'], - - ['status.waitingConnection', '等待连接'], - ['status.notConnected', '未连接'], - ['status.restoringConnection', '正在恢复连接'], - ['status.parsingUrl', '解析远程 URL'], - ['status.pairing', '正在配对'], - ['status.reconnecting', '正在重新连接'], - ['status.pairingCleared', '已清除配对信息'], - ['status.disconnected', '已断开连接'], - ['status.remoteUnavailable', '连接不可用,请先重新连接'], - ['status.loadingRecentWorkspaces', '加载最近工作区'], - ['status.chooseWorkspace', '请选择工作区'], - ['status.noRecentWorkspaces', '没有最近工作区'], - ['status.switchingWorkspace', '正在切换工作区'], - ['status.workspaceSwitched', '工作区已切换'], - ['status.loadingAssistants', '加载助理工作区'], - ['status.chooseAssistant', '请选择助理'], - ['status.noAssistants', '没有可用助理'], - ['status.switchingAssistant', '正在切换助理'], - ['status.assistantSwitched', '助理已切换'], - ['status.refreshSessions', '刷新会话列表'], - ['status.loadMoreSessions', '加载更多会话'], - ['status.sessionsUpdated', '会话列表已更新'], - ['status.createSession', '创建远程会话'], - ['status.sessionCreated', '会话已创建'], - ['status.loadMessages', '加载会话消息'], - ['status.deletingSession', '正在删除会话'], - ['status.sessionDeleted', '会话已删除'], - ['status.sessionArchived', '会话已归档'], - ['status.sessionUnarchived', '会话已取消归档'], - ['status.sessionExported', '已复制为 Markdown'], - ['status.messagesSynced', '消息已同步'], - ['status.messagesRestored', '已恢复本地会话记录'], - ['status.switchingModel', '正在切换模型'], - ['status.modelSwitched', '模型已切换'], - ['status.loadOlderMessages', '加载更早消息'], - ['status.sendImage', '发送图片'], - ['status.sendCommand', '发送指令'], - ['status.sentWaiting', '已发送,等待桌面端响应'], - ['status.pickImage', '选择图片'], - ['status.noImageSelected', '未选择图片'], - ['status.imagesSelected', '已选择 {0} 张图片'], - ['status.voiceStarting', '启动语音输入'], - ['status.voiceListening', '正在语音输入'], - ['status.voiceRecognized', '已填入语音识别文本'], - ['status.voiceStopped', '已停止语音输入'], - ['status.noRunningTask', '当前没有正在执行的任务'], - ['status.stoppingTask', '正在停止任务'], - ['status.stopRequested', '已请求停止'], - ['status.updatingTitle', '正在更新会话标题'], - ['status.titleUpdated', '会话标题已更新'], - ['status.messageCopied', '消息已复制'], - ['status.fileInfo', '读取文件信息'], - ['status.prepareDownload', '准备下载 {0}'], - ['status.downloadDone', '下载完成 {0} · {1}'], - ['status.approvingTool', '正在批准工具调用'], - ['status.toolApproved', '已批准工具调用'], - ['status.rejectingTool', '正在拒绝工具调用'], - ['status.toolRejected', '已拒绝工具调用'], - ['status.cancellingTool', '正在取消工具调用'], - ['status.toolCancelRequested', '已请求取消工具调用'], - ['status.submittingAnswer', '正在提交回答'], - ['status.answerSubmitted', '回答已提交'], - ['status.desktopProcessing', '桌面端正在处理'], - - ['errors.tooManyAttempts', '尝试次数过多,请 {0} 秒后再试。'], - ['errors.userIdRequired', '请输入用户 ID。'], - ['errors.accountUsernameRequired', '请输入 OpenBitFun 用户名。'], - ['errors.accountPasswordRequired', '请使用邮箱或 GitHub 登录以继续。'], - ['errors.remoteDataInvalid', '中继返回了无法解析的数据,请确认桌面端和移动端版本匹配。'], - ['errors.pairRejected', '中继拒绝了旧的配对连接,请登录账号后从设备列表选择电脑。'], - ['errors.roomNotFound', '没有找到这个远程房间,旧的扫码连接可能已过期,请登录账号后从设备列表选择电脑。'], - ['errors.relayTimeout', '连接中继超时,请检查网络后重试。'], - ['errors.rateLimited', '请求过于频繁,请稍后再试。'], - ['errors.relayUnavailable', '中继服务暂时不可用(HTTP {0}),请稍后重试。'], - ['errors.relayHttp', '中继返回 HTTP {0},请重新配对后再试。'], - ['errors.relayTimeoutDetail', '连接中继超时,请确认手机和桌面端网络可访问。'], - ['errors.relayNetwork', '无法连接到中继服务,请检查远程链接、网络或代理设置。'], - ['errors.remoteConnectFailed', '远程连接失败,请检查网络后重试。'], - ['errors.remoteUrlRequired', '请输入桌面端远程连接 URL。'], - ['errors.remoteUrlMissingParams', '远程 URL 缺少 room 或 pk 参数。'], - ['errors.remoteUrlInvalid', '远程连接链接格式不正确,请登录账号后从设备列表选择电脑。'], - ['errors.permissionDenied', '没有获得所需权限,请在系统设置中允许后重试。'], - ['errors.operationFailed', '操作失败,请稍后重试。'], - ['errors.payloadTooLarge', '这条消息带的附件超过了中继允许的大小,请减少图片数量或选择更小的图片。'], - ['errors.workspaceIdUnsupported', '已连接的桌面端不支持按工作区 ID 引用。请升级桌面端后再打开该工作区。'], - ['errors.hostStreamUnsupported', '已连接的桌面端 OpenBitFun 版本过旧,不支持按需会话流。请升级该设备上的 OpenBitFun 后继续。'], - ['errors.imageTooLargeAfterCompression', '图片压缩后仍超过 {0} MB,请选择较小图片。'], - ['errors.imageCompressionFailed', '图片压缩失败,请选择较小图片。'], - ['errors.voicePermissionDenied', '没有获得麦克风权限,无法语音输入。'], - ['errors.voiceInputUnavailable', '语音识别暂不可用,请稍后重试。'], - ['errors.voiceInputFailed', '语音识别失败({0}),请稍后重试。'], - - ['watchProvision.title', '在这块手表上使用邮箱或 GitHub 登录?'], - ['watchProvision.deviceId', '设备编号 {0}'], - ['watchProvision.body', '同意后,手表会登录你的账号并可以连接桌面端。请确认这块手表就在你手里。'], - ['watchProvision.approve', '允许'], - ['watchProvision.reject', '拒绝'], - ['watchProvision.gotIt', '知道了'], - ['watchProvision.working', '正在为手表开通账号...'], - ['watchProvision.passwordBody', '需要再确认一次账号密码,才能给这块手表创建独立的登录凭证。密码只会用于本次验证。'], - ['watchProvision.passwordPlaceholder', '账号密码'], - ['watchProvision.passwordConfirm', '确认'], - ['watchProvision.doneBody', '{0} 已登录,可以在手表上使用 OpenBitFun 了。'], - ['watchProvision.rejected', '已在手机上拒绝。'], - ['watchProvision.busy', '手机正在处理另一台设备的请求,请稍后再试。'], - ['watchProvision.errors.noDesktop', '请先在手机上使用邮箱或 GitHub 登录,或连接已登录同一账号的桌面端。'], - ['watchProvision.errors.accountUnavailable', '暂时无法验证账号,请检查手机网络后重试。'], - ['watchProvision.errors.requestExpired', '手表登录请求已过期,请在手表上重新发起登录。'], - ['watchProvision.errors.alreadyRegistered', '这块手表已注册,但本机没有可恢复的授权凭据。请撤销该手表的旧授权后重试。'], - ['watchProvision.errors.desktopUnreachable', '暂时无法连接桌面端,请确认桌面端在线后重试。'], - ['watchProvision.errors.desktopAuthorizationFailed', '桌面端没能完成手表登录,请确认桌面端已登录同一 OpenBitFun 账号。'], - ['watchProvision.errors.passwordFailed', '账号验证失败,请检查密码或网络后重试。'], - ['watchProvision.errors.handoffFailed', '授权已完成,但没能把凭证发给手表,请在手表上重试一次。'], - - ['ui.emptyMessage', '(空消息)'], - ['ui.desktopProcessing', '桌面端正在处理...'], - ['ui.seedConnected', '{0} 已连接。你可以继续发送指令,桌面端会在 OpenBitFun 中执行。'], - - ['time.justNow', '刚刚'], - ['time.unknown', '时间未知'], - ['time.minutesAgo', '{0} 分钟前'], - ['time.hoursAgo', '{0} 小时前'], - ['time.daysAgo', '{0} 天前'], -]; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/ChatTimelineModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/ChatTimelineModels.ets deleted file mode 100644 index c16a4e6766..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/ChatTimelineModels.ets +++ /dev/null @@ -1,167 +0,0 @@ -import { ChatMessage } from './RemoteModels'; - -export type ChatTimelineItemType = - | 'user_message' - | 'assistant_message' - | 'optimistic_user_message' - | 'assistant_live_turn' - | 'empty_state'; - -export interface ChatTimelineItem { - id: string; - type: ChatTimelineItemType; - message?: ChatMessage; - isStreaming: boolean; - isFinalizing: boolean; - showRetryAction?: boolean; -} - -/** - * Observable row retained for as long as a stable Repeat key remains visible. - * - * Repeat.virtualScroll() does not observe mutations inside plain object array - * entries. Keeping the projected DTO separate and reconciling it into this V2 - * row state lets streaming content update without putting mutable content in - * the row key or rebuilding the whole timeline. - */ -@ObservedV2 -export class ObservableChatTimelineItem implements ChatTimelineItem { - @Trace id: string = ''; - @Trace type: ChatTimelineItemType = 'empty_state'; - @Trace message: ChatMessage | undefined = undefined; - @Trace isStreaming: boolean = false; - @Trace isFinalizing: boolean = false; - @Trace showRetryAction: boolean = false; - - constructor(item: ChatTimelineItem) { - this.updateFrom(item); - } - - updateFrom(item: ChatTimelineItem): void { - this.id = item.id; - this.type = item.type; - this.message = item.message ? ObservableChatTimelineItem.copyMessage(item.message) : undefined; - this.isStreaming = item.isStreaming; - this.isFinalizing = item.isFinalizing; - this.showRetryAction = item.showRetryAction === true; - } - - private static copyMessage(message: ChatMessage): ChatMessage { - return { - id: message.id, - role: message.role, - text: message.text, - status: message.status, - renderVersion: message.renderVersion, - turnId: message.turnId, - detail: message.detail, - error: message.error, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools ? message.tools.slice() : undefined, - items: message.items ? message.items.slice() : undefined, - images: message.images ? message.images.slice() : undefined - }; - } -} - -/** Keyed bridge from pure timeline projections to ArkUI-observable rows. */ -export class ChatTimelineRowStore { - private rowsByKey: Map = new Map(); - private signaturesByKey: Map = new Map(); - - reconcile(items: ChatTimelineItem[]): ObservableChatTimelineItem[] { - // A lazy container requires unique keys. Keep the final projection for a - // key as a defensive boundary even if an upstream adapter temporarily - // exposes both a persisted assistant stub and its active turn snapshot. - const orderedKeys: string[] = []; - const itemsByKey: Map = new Map(); - items.forEach((item: ChatTimelineItem) => { - const key = ChatTimelineRevisionTracker.itemKey(item); - if (!itemsByKey.has(key)) { - orderedKeys.push(key); - } - itemsByKey.set(key, item); - }); - const nextRowsByKey: Map = - new Map(); - const nextSignaturesByKey: Map = new Map(); - const rows: ObservableChatTimelineItem[] = []; - orderedKeys.forEach((key: string) => { - const item = itemsByKey.get(key); - if (!item) { - return; - } - const signature = ChatTimelineRevisionTracker.itemSignature(item); - let row = this.rowsByKey.get(key); - if (row) { - if (this.signaturesByKey.get(key) !== signature) { - row.updateFrom(item); - } - } else { - row = new ObservableChatTimelineItem(item); - } - nextRowsByKey.set(key, row); - nextSignaturesByKey.set(key, signature); - rows.push(row); - }); - this.rowsByKey = nextRowsByKey; - this.signaturesByKey = nextSignaturesByKey; - return rows; - } - - clear(): void { - this.rowsByKey.clear(); - this.signaturesByKey.clear(); - } -} - -/** Shared render invalidation for both remote polling and general-chat streaming. */ -export class ChatTimelineRevisionTracker { - private signature: string = ''; - private revision: number = 0; - - /** Stable identity used by lazy UI containers. It must not include mutable content. */ - static itemKey(item: ChatTimelineItem): string { - if (item.message && item.message.role === 'assistant' && (item.message.turnId || '').length > 0) { - return `assistant_turn:${item.message.turnId}`; - } - return `${item.type}:${item.id}`; - } - - /** Everything about one item that can alter its rendered presentation. */ - static itemSignature(item: ChatTimelineItem): string { - const message = item.message; - return `${ChatTimelineRevisionTracker.itemKey(item)}:${item.isStreaming}:${item.isFinalizing}:` + - `${message ? message.status : ''}:${message ? message.renderVersion || 0 : 0}:` + - `${message ? ChatTimelineRevisionTracker.textSignature(message.text) : ''}:` + - `${message && message.error ? ChatTimelineRevisionTracker.textSignature(message.error) : ''}:` + - `${message && message.thinking ? ChatTimelineRevisionTracker.textSignature(message.thinking) : ''}:` + - `${message && message.items ? message.items.length : 0}:${message && message.tools ? message.tools.length : 0}`; - } - - update(items: ChatTimelineItem[]): number { - const nextSignature = items - .map((item: ChatTimelineItem) => ChatTimelineRevisionTracker.itemSignature(item)) - .join('|'); - if (nextSignature !== this.signature) { - this.signature = nextSignature; - this.revision += 1; - } - return this.revision; - } - - reset(): number { - this.signature = ''; - this.revision += 1; - return this.revision; - } - - private static textSignature(value: string): string { - let hash = 0; - for (let index = 0; index < value.length; index++) { - hash = ((hash << 5) - hash + value.charCodeAt(index)) | 0; - } - return `${value.length}:${Math.abs(hash).toString(36)}`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/ComposerSubmission.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/ComposerSubmission.ets deleted file mode 100644 index 1842637e47..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/ComposerSubmission.ets +++ /dev/null @@ -1,5 +0,0 @@ -/** In-memory draft handoff. No transport or persistence is owned by this handle. */ -export interface ComposerSubmission { - commit: () => void; - rollback: () => void; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/FilePreviewTarget.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/FilePreviewTarget.ets deleted file mode 100644 index 7bc0ffb89a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/FilePreviewTarget.ets +++ /dev/null @@ -1,62 +0,0 @@ -export class FilePreviewTarget { - readonly kind: string; - readonly rawReference: string; - readonly remotePath: string; - readonly displayName: string; - readonly sessionId: string; - readonly workspacePath: string; - readonly controlTargetEpoch: number; - readonly lineStart: number; - readonly lineEnd: number; - - constructor( - rawReference: string, - remotePath: string, - displayName: string, - sessionId: string, - workspacePath: string, - controlTargetEpoch: number, - lineStart: number = 0, - lineEnd: number = 0 - ) { - this.kind = 'remote_workspace_file'; - this.rawReference = rawReference; - this.remotePath = remotePath; - this.displayName = displayName; - this.sessionId = sessionId; - this.workspacePath = workspacePath; - this.controlTargetEpoch = controlTargetEpoch; - this.lineStart = lineStart; - this.lineEnd = lineEnd; - } - - static empty(): FilePreviewTarget { - return new FilePreviewTarget('', '', '', '', '', 0); - } - - isValid(): boolean { - return this.remotePath.length > 0 && this.sessionId.length > 0; - } -} - -export class FilePreviewTargetContext { - readonly sessionId: string; - readonly workspacePath: string; - readonly controlTargetEpoch: number; - - constructor(sessionId: string, workspacePath: string, controlTargetEpoch: number) { - this.sessionId = sessionId; - this.workspacePath = workspacePath; - this.controlTargetEpoch = controlTargetEpoch; - } -} - -export class FilePreviewRequest { - readonly reference: string; - readonly label: string; - - constructor(reference: string, label: string) { - this.reference = reference; - this.label = label; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/InteractionMailbox.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/InteractionMailbox.ets deleted file mode 100644 index c3dc5116b9..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/InteractionMailbox.ets +++ /dev/null @@ -1,51 +0,0 @@ -import { RemoteQuestionAnswerPayload } from './RemoteModels'; - -export interface PermissionSource { identity: string; } -export interface PendingPermission { - requestId: string; - sessionId: string; - toolCallId?: string; - action: string; - resources: string[]; - source?: PermissionSource; -} -export interface PendingQuestion { - toolId: string; - sessionId: string; - questions: Object; -} -export interface PermissionMailbox { requests: PendingPermission[]; revision: number; } -export interface QuestionMailbox { questions: PendingQuestion[]; revision: number; } -export interface SessionInteractionMailbox { - sessionId: string; - permissions: PermissionMailbox; - userQuestions: QuestionMailbox; -} - -/** Separate from persisted transcript and from the active turn's lifetime. */ -export class InteractionMailboxState { - sessionId: string = ''; - requests: PendingPermission[] = []; - questions: PendingQuestion[] = []; - ownedToolIds: string[] = []; - busy: boolean = false; - failure: string = ''; - - ownsToolInteraction(toolId: string): boolean { - return toolId.length > 0 && (this.ownedToolIds.includes(toolId) || - this.questions.some((item: PendingQuestion): boolean => item.toolId === toolId) || - this.requests.some((item: PendingPermission): boolean => item.toolCallId === toolId)); - } -} - -export enum InteractionMailboxActionType { - Refresh = 'refresh', Approve = 'approve', Reject = 'reject', - StartQuestion = 'start_question', Answer = 'answer' -} -export interface InteractionMailboxAction { - sessionId: string; - type: InteractionMailboxActionType; - id?: string; - updatedInput?: Object; - answers?: RemoteQuestionAnswerPayload; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets deleted file mode 100644 index cb04468ebb..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets +++ /dev/null @@ -1,19 +0,0 @@ - -export interface MessageQueueRequest { - sessionId: string; action: string; queueEpoch?: string; turnId?: string; - operationId?: string; expectedRevision?: number; beforeTurnId?: string; - expectedActiveTurnId?: string; -} -export interface MessageQueueItem { - turnId: string; displayContent: string; attachmentCount: number; status: string; reason?: string; -} -export interface MessageQueueSnapshot { - sessionId: string; queueEpoch: string; revision: number; items: MessageQueueItem[]; - supportsReorder?: boolean; activeTurnId?: string; -} -export interface MessageQueueResponse { resp?: string; message?: string; snapshot?: MessageQueueSnapshot; } -export class MessageQueueState { - sessionId: string = ''; items: MessageQueueItem[] = []; supportsReorder: boolean = false; - revisionKey: string = ''; busy: boolean = false; failure: string = ''; -} -export interface MessageQueueAction { sessionId: string; action: string; turnId?: string; beforeTurnId?: string; } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/MiniAppModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/MiniAppModels.ets deleted file mode 100644 index 558e8dd0fa..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/MiniAppModels.ets +++ /dev/null @@ -1,46 +0,0 @@ -export interface MiniAppSummary { - id: string; - name: string; - description: string; -} - -export interface MiniAppBridgeParams { - key?: string; - value?: Object | null; - text?: string; -} - -export interface MiniAppBridgeRequest { - id: string; - method: string; - params?: MiniAppBridgeParams; -} - -export interface MiniAppBridgeError { message: string; } -export interface MiniAppBridgeReply { - jsonrpc: string; - id: string; - result?: Object | null; - error?: MiniAppBridgeError; -} - -/** Local data source, deliberately independent of any connection/session. */ -export interface MiniAppHost { - list(locale: string): Promise; - document(appId: string): Promise; - call(appId: string, method: string, params: MiniAppBridgeParams): Promise; -} - -export interface MiniAppActions { - open: () => void; - close: () => void; - back: () => void; - refresh: () => void; - select: (id: string) => void; - request: (raw: string, revision: number) => Promise; -} - -export function emptyMiniAppActions(): MiniAppActions { - return { open: () => {}, close: () => {}, back: () => {}, refresh: () => {}, select: () => {}, - request: async (_raw: string, _revision: number): Promise => '' }; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets deleted file mode 100644 index 15eb301fe3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets +++ /dev/null @@ -1,870 +0,0 @@ -import { MessageQueueRequest } from './MessageQueue'; -export interface RuntimeFileLocation { path: string; remoteConnectionId?: string; } - - -export class EncryptedPayload { - encrypted_data: string = ''; - nonce: string = ''; - accept_encoding?: string; -} - -export interface WorkspaceInfo extends RemoteWorkspaceIdentity { - remoteConnectionId?: string; - remoteSshHost?: string; - path: string; - name: string; - hasWorkspace: boolean; - gitBranch: string; - workspaceKind: string; - assistantId?: string; -} - -export interface InitialSyncResult { - workspace: WorkspaceInfo; - sessions: RemoteSession[]; - hasMoreSessions: boolean; - authenticatedUserId: string; - capabilities?: string[]; -} - -export interface RecentWorkspaceEntry extends RemoteWorkspaceIdentity { - remoteConnectionId?: string; - remoteSshHost?: string; - path: string; - name: string; - lastOpened: string; - workspaceKind: string; -} - -/** - * A workspace reference. When `workspaceId` is present it is the whole - * identity; `path`, `remoteConnectionId` and `remoteSshHost` are then display - * strings and IO operands only. Only references from pre-ID hosts or old caches - * are identified by the legacy (connection, ssh host, path) triple. - */ -export interface RemoteWorkspaceIdentity { - workspaceId?: string; - path: string; - remoteConnectionId?: string; - remoteSshHost?: string; -} - -export interface RemoteSession { - id: string; - title: string; - agentType: string; - status: string; - updatedAt: string; - createdAt: string; - messageCount: number; - workspacePath?: string; - workspaceName?: string; - /** Optional for legacy caches; assigned from the actual scoped listing request. */ - workspaceIdentity?: RemoteWorkspaceIdentity; - pinned?: boolean; - titleGenerated?: boolean; - /** Set when the session hangs off another one (btw/review/miniapp/subagent). */ - parentSessionId?: string; - relationshipKind?: string; - /** Stamped by the phone after mapping; the wire payload has no device id. */ - deviceId?: string; -} - -export interface ChatMessage { - id: string; - role: string; - text: string; - status: string; - renderVersion?: number; - turnId?: string; - detail?: string; - error?: string; - timestamp?: string; - thinking?: string; - tools?: RemoteToolStatusResponse[]; - items?: ChatMessageItemResponse[]; - images?: ImageAttachment[]; -} - -export interface SessionSummary { - /** Owning workspace record ID; absent only for sessions from pre-ID hosts. */ - workspaceId?: string; - remoteSshHost?: string; - remoteConnectionId?: string; - sessionId: string; - title: string; - workspacePath: string; - agentType: string; - initialTurnId?: string; -} - -export interface CreateSessionOptions { - workspaceId?: string; - remoteSshHost?: string; - remoteConnectionId?: string; - agentType: string; - title: string; - instruction: string; - modelId?: string; - workspacePath?: string; -} - -export type RemotePermissionMode = 'ask' | 'auto' | 'full_access'; - -export interface PairRequest { - public_key: string; - device_id: string; - device_name: string; -} - -export interface ChallengeCommand { - challenge_echo: string; - device_id: string; - device_name: string; - mobile_install_id: string; - user_id: string; - password?: string; -} - -export interface SavedRuntimeConnection { id: string; name: string; host: string; } -export interface SavedRuntimeConnectionsResponse extends CommandStatusResponse { ok: boolean; value?: SavedRuntimeConnection[]; error?: string; } - -export interface RemoteCommand { - request?: MessageQueueRequest; - workspace_id?: string; - remote_ssh_host?: string; - command?: string; - args?: Object; - remote_connection_id?: string; - cmd: string; - _request_id?: string; - session_id?: string; - content?: string; - workspace_path?: string; - path?: string; - agent_type?: string; - session_name?: string; - title?: string; - limit?: number; - offset?: number; - query?: string; - before_message_id?: string; - since_version?: number; - known_msg_count?: number; - known_model_catalog_version?: number; - turn_id?: string; - display_content?: string; - plan_file_path?: string; - plan_name?: string; - tool_id?: string; - updated_input?: Object; - model_id?: string; - // set_model_defaults: the phone always sends all three managed slots. The host - // keeps a slot whose key is missing; an explicit null clears it (no model - // configured and, for `fast`, follow the primary). - primary?: string | null; - fast?: string | null; - image_understanding?: string | null; - reason?: string; - mode?: RemotePermissionMode; - answers?: Object; - // rollback_session_to_turn: the user turn being withdrawn and the storage - // index the caller last saw for it. Omitting the index only widens the race - // window; it never changes which turn the host addresses. - target_turn_id?: string; - expected_storage_turn_index?: number; - image_contexts?: RemoteImageContext[]; - images?: ImageAttachment[]; - // provision_peer_device. `request_id` is minted by the device being - // provisioned, unlike `_request_id`, which the phone stamps on every command - // for its own correlation logging. - device_id?: string; - device_name?: string; - request_id?: string; - // read_stream / unsubscribe_stream: host-owned stream pages read on demand - // from the online desktop (`remote_connect/host_stream.rs`). - stream_id?: string; - after?: number; - before?: number; - epoch?: number; - subscribe?: boolean; - subscription_id?: string; -} - -export interface PairChallengeResponse { - challenge: string; -} - -export interface CommandStatusResponse { - resp?: string; - message?: string; -} - -export interface PermissionModeResponse extends CommandStatusResponse { - mode?: RemotePermissionMode; -} - -export interface WorkspaceInfoResponse extends CommandStatusResponse { - workspace_id?: string; - remote_connection_id?: string; - remote_ssh_host?: string; - has_workspace?: boolean; - workspace_path?: string; - workspace_name?: string; - path?: string; - project_name?: string; - git_branch?: string; - workspace_kind?: string; - assistant_id?: string; - capabilities?: string[]; -} - -export interface RecentWorkspaceEntryResponse { - workspace_id?: string; - remote_connection_id?: string; - remote_ssh_host?: string; - path?: string; - name?: string; - last_opened?: string | number; - lastOpened?: string | number; - updated_at?: string | number; - updatedAt?: string | number; - workspace_kind?: string; -} - -export interface RecentWorkspaceListResponse extends CommandStatusResponse { - opened_workspaces?: RecentWorkspaceEntryResponse[] | null; - workspaces?: RecentWorkspaceEntryResponse[]; -} - -export interface SetWorkspaceResponse extends CommandStatusResponse { - workspace_id?: string; - success?: boolean; - path?: string; - project_name?: string; - remote_connection_id?: string; - remote_ssh_host?: string; - error?: string; -} - -export interface AssistantEntry { - workspace_id?: string; - path: string; - name: string; - assistant_id?: string; -} - -export interface AssistantListResponse extends CommandStatusResponse { - assistants?: AssistantEntry[]; -} - -export interface SetAssistantResponse extends CommandStatusResponse { - workspace_id?: string; - success?: boolean; - path?: string; - name?: string; - error?: string; -} - -export interface SessionItemResponse { - /** Owning workspace record ID; always set by ID-aware hosts. */ - workspace_id?: string; - id?: string; - session_id?: string; - title?: string; - name?: string; - agent_type?: string; - status?: string; - updated_at?: string | number; - updatedAt?: string | number; - updated?: string | number; - updated_time?: string | number; - update_time?: string | number; - modified_at?: string | number; - last_active_at?: string | number; - last_activity_at?: string | number; - last_message_at?: string | number; - last_interaction_at?: string | number; - lastUpdated?: string | number; - lastActivityAt?: string | number; - lastMessageAt?: string | number; - created_at?: string | number; - createdAt?: string | number; - created?: string | number; - created_time?: string | number; - create_time?: string | number; - inserted_at?: string | number; - started_at?: string | number; - start_time?: string | number; - timestamp?: string | number; - message_count?: number; - workspace_path?: string; - workspace_name?: string; - parent_session_id?: string; - relationship_kind?: string; -} - -export interface SessionListResponse extends CommandStatusResponse { - sessions?: SessionItemResponse[]; - has_more?: boolean; -} - -export interface InitialSyncResponse extends CommandStatusResponse { - workspace_id?: string; - has_workspace?: boolean; - path?: string; - project_name?: string; - git_branch?: string; - workspace_kind?: string; - assistant_id?: string; - remote_connection_id?: string; - remote_ssh_host?: string; - sessions?: SessionItemResponse[]; - has_more_sessions?: boolean; - authenticated_user_id?: string; - capabilities?: string[]; -} - -export interface DelegatedIdentityResponse extends CommandStatusResponse { - token?: string; - user_id?: string; - master_key?: string; - device_id?: string; -} - -/** - * Answer to `provision_peer_device`. Shaped like a delegated identity but - * carrying a 30-day *full* device credential, and `device_id` names the device - * that was just registered rather than the desktop that registered it. - */ -export interface PeerDeviceProvisionedResponse extends CommandStatusResponse { - token?: string; - user_id?: string; - master_key?: string; - device_id?: string; -} - -export interface SessionListResult { - sessions: RemoteSession[]; - hasMore: boolean; -} - -export interface CreateSessionResponse extends CommandStatusResponse { - /** Owning workspace record ID; absent only from pre-ID hosts. */ - workspace_id?: string; - remote_ssh_host?: string; - workspace_path?: string; - remote_connection_id?: string; - session_id?: string; - id?: string; - title?: string; -} - -export interface SendMessageResponse extends CommandStatusResponse { - turn_id?: string; -} - -export interface SteerTurnResponse extends CommandStatusResponse { - session_id?: string; - turn_id?: string; - steering_id?: string; -} - -export interface SteerTurnResult { - sessionId: string; - turnId: string; - steeringId: string; -} - -/** - * Answer to `rollback_session_to_turn`, sent as `resp: "session_rolled_back"`. - * - * `retired_turn_ids` includes the target turn itself. `composer_text` is the - * prompt the desktop would have put back into its composer, offered so the - * client can show the same edit-and-resend continuation; the host omits the key - * when it has no prompt to offer. The transcript itself is repaired by the next - * poll's authoritative snapshot, not by this answer. - */ -export interface SessionRolledBackResponse extends CommandStatusResponse { - session_id?: string; - retired_turn_ids?: string[]; - restored_files?: string[]; - composer_text?: string; - changed?: boolean; -} - -/** The decoded rollback answer, with absent host fields kept as absence. */ -export interface SessionRolledBackResult { - sessionId: string; - retiredTurnIds: string[]; - restoredFiles: string[]; - composerText?: string; - changed: boolean; -} - -export const REMOTE_CAPABILITY_DIALOG_STEER_V1: string = 'dialog_steer_v1'; -export const REMOTE_CAPABILITY_PLAN_BUILD_V1: string = 'plan_build_v1'; -export const REMOTE_CAPABILITY_HARNESS_PROFILES_V1: string = 'harness_profiles_v1'; -/** - * The host can retire a turn and every turn after it, then restore the files - * those turns touched (`rollback_session_to_turn`). A host without it answers - * the command with an error, so the client checks before offering the entry. - */ -export const REMOTE_CAPABILITY_SESSION_ROLLBACK_V1: string = 'session_rollback_v1'; -/** The host resolves `workspace_id` in commands and stamps it on its projections. */ -export const REMOTE_CAPABILITY_WORKSPACE_ID_REFERENCES_V1: string = 'workspace_id_references_v1'; -/** The host reads and writes the device-level model role defaults. */ -export const REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1: string = 'device_model_defaults_v1'; -/** - * The composer command palette has no capability of its own. - * - * Skills, compact, init and usage all reach the desktop through the existing - * `host_invoke` bridge, so the phone cannot ask for a capability that a host - * would have to be taught: it probes one of the verbs instead and degrades on - * the answer. Session goals are plain message text and need no host support at - * all. Only the skills picker's grouping is local, so these are display values. - */ -export const REMOTE_SKILL_SOURCE_BUILTIN: string = 'builtin'; -export const REMOTE_SKILL_SOURCE_USER: string = 'user'; -export const REMOTE_SKILL_SOURCE_PROJECT: string = 'project'; - -/** - * One palette entry, projected from the host's `get_mode_skill_configs` rows. - * - * The host payload is a `ModeSkillInfo`: a `SkillInfo` flattened beside the - * mode's availability flags. `id` is the skill key, because that is what the - * `[$key]` message token carries; the flags are kept on the entry so the picker - * can filter with host truth instead of guessing. - */ -export interface RemoteSkillCatalogEntry { - id: string; - name: string; - description: string; - /** Host group taxonomy; empty for user-authored skills. */ - group: string; - /** `builtin`, `project` or `user`; the picker's fallback grouping. */ - source: string; - /** Another skill of the same name wins in this mode. */ - shadowed: boolean; - selectedForRuntime: boolean; - effectiveEnabled: boolean; - globallyEnabled: boolean; - allowUserInvocation: boolean; -} - -export interface RemoteCommandCatalog { - skills: RemoteSkillCatalogEntry[]; -} - -/** - * Answer to `compact_session` / `run_init_agents_md`. - * - * Both handlers return `StartDialogTurnResponse`, so the accepted shape is the - * host's own success/message pair rather than a palette-specific envelope. - */ -export interface RemoteTurnAcceptedValue { - success?: boolean; - message?: string; -} - -/** - * The session usage report, mirrored from the desktop contract. - * - * Every field is optional on purpose: an older or a partially instrumented host - * reports the subset it can measure, and the sheet renders exactly the rows the - * payload carries instead of inventing zeroes for what is missing. Both the - * desktop camelCase spelling and the snake_case spelling are accepted, because - * this payload crosses a relay between two independently built versions. - */ -export interface RemoteUsageWorkspace { - kind?: string; - path_label?: string; - pathLabel?: string; - workspace_id?: string; - workspaceId?: string; -} - -export interface RemoteUsageScope { - kind?: string; - turn_count?: number; - turnCount?: number; - includes_subagents?: boolean; - includesSubagents?: boolean; -} - -export interface RemoteUsageCoverage { - level?: string; - available?: string[]; - missing?: string[]; - notes?: string[]; -} - -export interface RemoteUsageTime { - accounting?: string; - denominator?: string; - wall_time_ms?: number; - wallTimeMs?: number; - active_turn_ms?: number; - activeTurnMs?: number; - model_ms?: number; - modelMs?: number; - tool_ms?: number; - toolMs?: number; - idle_gap_ms?: number; - idleGapMs?: number; -} - -export interface RemoteUsageTokens { - source?: string; - input_tokens?: number; - inputTokens?: number; - output_tokens?: number; - outputTokens?: number; - total_tokens?: number; - totalTokens?: number; - cached_tokens?: number; - cachedTokens?: number; - cache_coverage?: string; - cacheCoverage?: string; -} - -export interface RemoteUsageModelRow { - model_id?: string; - modelId?: string; - call_count?: number; - callCount?: number; - total_tokens?: number; - totalTokens?: number; -} - -export interface RemoteUsageToolRow { - tool_name?: string; - toolName?: string; - category?: string; - call_count?: number; - callCount?: number; - error_count?: number; - errorCount?: number; -} - -export interface RemoteUsageFiles { - scope?: string; - changed_files?: number; - changedFiles?: number; - added_lines?: number; - addedLines?: number; - deleted_lines?: number; - deletedLines?: number; -} - -export interface RemoteUsageCompression { - compaction_count?: number; - compactionCount?: number; - manual_compaction_count?: number; - manualCompactionCount?: number; - automatic_compaction_count?: number; - automaticCompactionCount?: number; - saved_tokens?: number; - savedTokens?: number; -} - -export interface RemoteUsageErrors { - total_errors?: number; - totalErrors?: number; - tool_errors?: number; - toolErrors?: number; - model_errors?: number; - modelErrors?: number; -} - -export interface RemoteUsagePrivacy { - prompt_content_included?: boolean; - promptContentIncluded?: boolean; - tool_inputs_included?: boolean; - toolInputsIncluded?: boolean; - command_outputs_included?: boolean; - commandOutputsIncluded?: boolean; - file_contents_included?: boolean; - fileContentsIncluded?: boolean; -} - -/** - * The `get_session_usage_report` value, as the desktop contract serializes it. - * - * The command answers with the report itself rather than a wrapper, so this is - * the `value` of the `host_invoke` result and not a response envelope. - */ -export interface RemoteSessionUsageReport { - schema_version?: number; - schemaVersion?: number; - report_id?: string; - reportId?: string; - session_id?: string; - sessionId?: string; - generated_at?: number; - generatedAt?: number; - workspace?: RemoteUsageWorkspace; - scope?: RemoteUsageScope; - coverage?: RemoteUsageCoverage; - time?: RemoteUsageTime; - tokens?: RemoteUsageTokens; - models?: RemoteUsageModelRow[]; - tools?: RemoteUsageToolRow[]; - files?: RemoteUsageFiles; - compression?: RemoteUsageCompression; - errors?: RemoteUsageErrors; - privacy?: RemoteUsagePrivacy; -} - -export interface RemoteModelConfig { - id: string; - name: string; - provider: string; - base_url: string; - model_name: string; - context_window?: number; - enabled: boolean; - capabilities: string[]; - reasoning?: RemoteReasoningCatalogProjection; -} - -export interface RemoteReasoningPresetDescriptor { - id: string; - label: string; - order: number; - actions: RemoteReasoningPresetAction[]; - source: string; -} - -export interface RemoteReasoningPresetAction { - type: string; - value?: string | number; - enabled?: boolean; - body?: Record; -} - -export interface RemoteReasoningCatalogProjection { - status: string; - default_preset?: string; - presets?: RemoteReasoningPresetDescriptor[]; -} - -/** - * Device-level model role defaults, exactly as the host persists them. - * - * All six slots are always projected; only `primary`, `fast` and - * `image_understanding` are writable from the phone. `null` is a real value and - * means "no model configured" (`fast` then follows `primary`), so every reader - * must treat it as such rather than as an absent field. - */ -export interface RemoteDefaultModels { - primary?: string | null; - fast?: string | null; - search?: string | null; - image_understanding?: string | null; - image_generation?: string | null; - speech_recognition?: string | null; -} - -export interface RemoteModelCatalog { - version: number; - models: RemoteModelConfig[]; - default_models: RemoteDefaultModels; - session_model_id?: string; -} - -export interface ModelCatalogResponse extends CommandStatusResponse { - catalog?: RemoteModelCatalog; -} - -export interface SetSessionModelResponse extends CommandStatusResponse { - session_id?: string; - model_id?: string; -} - -/** - * `set_model_defaults` acknowledgement. - * - * `default_models` is the reconcile result the host read back, all six slots - * included. A host that only acknowledges the command without the payload - * leaves it undefined, which the client answers with its own authoritative - * re-read instead of guessing. - */ -export interface ModelDefaultsUpdatedResponse extends CommandStatusResponse { - default_models?: RemoteDefaultModels; -} - -export interface RemoteToolStatusResponse { - permission_request_id?: string; - id?: string; - name?: string; - status?: string; - duration_ms?: number; - start_ms?: number; - input_preview?: string; - tool_input?: Object; - stdout?: string; - stderr?: string; - tool_output?: Object; - result_preview?: string; - error_preview?: string; - exit_code?: number; - plan?: RemotePlanToolResponse; - /** - * Child Session a launching tool started, when this record is a delegation. - * - * The durable record names it (`subagent_session_id` on the item data), and - * this projection keeps the name instead of dropping it: a transcript restored - * from the phone's cache is the only thing a cold or offline session view has, - * and the link is what maps a stored child back to the branch that owns it. - */ - subagent_session_id?: string; -} - -export interface RemotePlanToolResponse { - file_path: string; - name: string; - overview?: string; -} - -export interface RemoteQuestionAnswerPayload { - answer?: string; - '0'?: string | string[]; - '1'?: string | string[]; - '2'?: string | string[]; - '3'?: string | string[]; -} - -export interface ChatMessageItemResponse { - type?: string; - steering_id?: string; - round_index?: number; - content?: string; - tool?: RemoteToolStatusResponse; - is_subagent?: boolean; - subItems?: ChatMessageItemResponse[]; - images?: ImageAttachment[]; -} - -export interface ImageAttachment { - name: string; - data_url: string; - mime_type?: string; -} - -export interface SelectedImageAttachment extends ImageAttachment { - id: string; - uri: string; - mime_type: string; - size: number; - original_size: number; - compressed: boolean; -} - -export interface RemoteImageContext { - id: string; - image_path?: string; - data_url?: string; - mime_type: string; - metadata?: Object; -} - -export interface ChatMessageResponse { - id?: string; - message_id?: string; - turn_id?: string; - role: string; - content: string; - status?: string; - error?: string; - timestamp?: string; - metadata?: Object; - thinking?: string; - items?: ChatMessageItemResponse[]; - tools?: RemoteToolStatusResponse[]; - images?: ImageAttachment[]; -} - -export interface ActiveTurnSnapshotResponse { - turn_id: string; - status: string; - error?: string; - text?: string; - thinking?: string; - tools?: RemoteToolStatusResponse[]; - round_index?: number; - items?: ChatMessageItemResponse[]; -} - -export interface SessionMessagesResponse extends CommandStatusResponse { - messages?: ChatMessageResponse[]; - has_more?: boolean; -} - -export interface SessionMessagesResult { - messages: ChatMessage[]; - hasMore: boolean; -} - -export interface PollSessionResponse extends CommandStatusResponse { - version: number; - changed: boolean; - session_state?: string; - title?: string; - new_messages?: ChatMessageResponse[]; - total_msg_count?: number; - message_snapshot?: ChatMessageResponse[]; - active_turn?: ActiveTurnSnapshotResponse; - model_catalog?: RemoteModelCatalog; -} - -export interface PollSessionResult { - version: number; - changed: boolean; - sessionState: string; - title: string; - newMessages: ChatMessage[]; - totalMessageCount: number; - messageSnapshot?: ChatMessage[]; - activeTurn?: ChatMessage; - modelCatalog?: RemoteModelCatalog; -} - -export interface FileInfoResponse extends CommandStatusResponse { - name?: string; - size?: number; - mime_type?: string; -} - -export interface FileInfo { - name: string; - size: number; - mimeType: string; -} - -export interface ReadFileChunkResponse extends CommandStatusResponse { - revision?: string; - name?: string; - chunk_base64?: string; - offset?: number; - chunk_size?: number; - total_size?: number; - mime_type?: string; -} - -export interface ReadFileResult { - name: string; - contentBase64: string; - mimeType: string; - size: number; -} - -export interface ReadFileChunkResult { - revision?: string; - name: string; - contentBase64: string; - offset: number; - chunkSize: number; - totalSize: number; - mimeType: string; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets deleted file mode 100644 index 27c1fa9861..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets +++ /dev/null @@ -1,108 +0,0 @@ -import { StartupRevealPreference } from '../services/StartupRevealPreference'; -import { StartupBrandReveal } from './components/StartupBrandReveal'; -import { ColdStartPresentationState } from './state/ColdStartPresentationState'; -import { ColdStartHomeTransition } from './components/ColdStartHomeTransition'; -import { AppRootPresentation } from './components/AppRootPresentation'; -import { WatchProvisionCard } from './components/WatchProvisionCard'; -import { ArkUiAppRootHostAdapter } from './host/AppRootHostAdapter'; -import { AppRootRuntime } from './runtime/AppRootRuntime'; - -@Entry -@ComponentV2 -struct AppRoot { - @Local showStartupBrand: boolean = false; - @Local showColdStart: boolean = false; - private readonly hostAdapter: ArkUiAppRootHostAdapter = new ArkUiAppRootHostAdapter(); - private readonly runtime: AppRootRuntime = new AppRootRuntime(this.hostAdapter); - @Provider() coldStartGeometry: ColdStartPresentationState = new ColdStartPresentationState(); - private coldStartConsumed: boolean = false; - - async aboutToAppear(): Promise { - const hostContext = this.getUIContext().getHostContext(); - if (!hostContext) { - throw new Error('App root host context is unavailable.'); - } - this.showStartupBrand = StartupRevealPreference.claim(hostContext); - this.hostAdapter.attach(hostContext, this.getUIContext()); - const firstLaunch = this.showStartupBrand; - const coldStartCandidate = ColdStartPresentationState.claimProcess() && !firstLaunch; - await this.runtime.aboutToAppear((signedIn: boolean): void => { - if (!this.coldStartConsumed) { - this.coldStartConsumed = true; - this.showColdStart = coldStartCandidate && signedIn; - } - }); - } - - onPageShow(): void { - this.runtime.onPageShow(); - } - - onPageHide(): void { - this.showStartupBrand = false; - this.showColdStart = false; - this.coldStartConsumed = true; - this.runtime.onPageHide(); - } - - aboutToDisappear(): void { - this.coldStartConsumed = true; - this.showColdStart = false; - this.runtime.aboutToDisappear(); - } - - onBackPress(): boolean { - if (this.runtime.miniAppViewModel.state.visible) { - if (this.runtime.miniAppViewModel.state.appId) this.runtime.miniAppViewModel.actions.back(); - else this.runtime.miniAppViewModel.close(); - return true; - } - return this.runtime.handleRootBack(); - } - - build() { - Stack() { - AppRootPresentation({ - shellState: this.runtime.appShellState, - miniAppState: this.runtime.miniAppViewModel.state, - miniAppActions: this.runtime.miniAppViewModel.actions, - navigationStack: this.runtime.navigationStack, - remotePageState: this.runtime.remotePageState, - deviceDirectoryState: this.runtime.deviceDirectoryState, - generalPageState: this.runtime.generalChatPageState, - filePreviewState: this.runtime.filePreviewState, - deviceId: this.runtime.remoteConnectionController.getDeviceId(), - actions: this.runtime.presentationActions - }) - .accessibilityLevel(this.showStartupBrand || this.showColdStart ? 'no-hide-descendants' : 'auto') - - if (this.showStartupBrand) { - StartupBrandReveal({ onFinished: () => { this.showStartupBrand = false; } }) - } - if (this.showColdStart) { - ColdStartHomeTransition({ geometry: this.coldStartGeometry, onFinished: () => { this.showColdStart = false; } }) - } - - // Sits above every route on purpose: a watch waiting for approval must - // not be hidden behind whatever screen the phone happens to be on. - WatchProvisionCard({ - state: this.runtime.watchProvisionState, - onApprove: (password: string) => { - void this.runtime.watchProvisionController.approve(password); - }, - onReject: () => { - void this.runtime.watchProvisionController.reject(); - }, - onDismiss: () => { - this.runtime.watchProvisionController.dismiss(); - } - }) - } - .width('100%') - .height('100%') - .onAreaChange((_old: Area, area: Area) => { - this.coldStartGeometry.originX = Number(area.globalPosition.x); - this.coldStartGeometry.originY = Number(area.globalPosition.y); - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/AppRootPresentationActions.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/AppRootPresentationActions.ets deleted file mode 100644 index 4ce6ec83d3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/AppRootPresentationActions.ets +++ /dev/null @@ -1,170 +0,0 @@ -import { WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; -import { RemoteDefaultModels, RemoteModelCatalog, RemotePermissionMode, RemoteSession } from '../../model/RemoteModels'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; -import { ConversationIntent } from './ConversationIntent'; -import { AppRoute } from '../navigation/AppRouteContract'; - -export interface AppRootPresentationActions { - readonly onWorkspaceTools: (intent: WorkspaceToolsIntent) => void; - readonly onNavigationBack: (route: AppRoute) => boolean; - readonly onConversationIntent: (route: AppRoute, intent: ConversationIntent) => void; - readonly onCloseSidebar: () => void; - readonly onCompactLayoutEntered: () => void; - readonly onLayoutModeChanged: (wideLayout: boolean) => void; - readonly onRemoteHome: RemoteHomePresentationActions; - readonly onSidebar: SidebarPresentationActions; - readonly onSettings: SettingsPresentationActions; - readonly onConnect: ConnectPresentationActions; - readonly onFilePreview: FilePreviewPresentationActions; - readonly generalStatus: () => string; -} - -export interface FilePreviewPresentationActions { - readonly close: () => void; - readonly refresh: () => void; - readonly download: (path: string) => void; - readonly openLink: (reference: string, label: string) => void; -} - -export interface RemoteHomePresentationActions { - readonly openMiniApps: () => void; - readonly openSidebar: () => void; - readonly connectWorkspace: () => void; - readonly addConnection: () => void; - readonly refresh: () => void; - readonly showWorkspaces: () => void; - readonly showAssistants: () => void; - readonly selectWorkspace: (path: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void; - readonly selectAssistant: (path: string, workspaceId?: string) => void; - readonly cancelWorkspace: () => void; - readonly cancelAssistant: () => void; - readonly queryChanged: (query: string) => void; - readonly search: () => void; - readonly loadMore: () => void; - readonly reconnect: () => void; - readonly disconnect: () => void; - readonly clearPairing: () => void; - readonly create: (agentType: string) => void; - readonly createInPlace: (agentType: string) => void; - readonly createInWorkspace: (path: string, agentType: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void; - readonly createInWorkspaceInPlace: (path: string, agentType: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void; - readonly selectDirectoryDevice: (deviceId: string) => void; - readonly addDirectoryWorkspace: (deviceId: string) => void; - readonly retryDirectoryDevice: (deviceId: string) => void; - readonly loadWorkspaceSessions: (deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string) => Promise; - readonly openSession: (session: RemoteSession) => void; - readonly openSessionInPlace: (session: RemoteSession) => void; - readonly deleteSession: (session: RemoteSession) => void; -} - -export interface SidebarPresentationActions { - readonly close: () => void; - readonly newChat: (agentType?: string) => void; - readonly enterCode: () => void; - /** Opens account settings, where the account device directory selects a desktop. */ - readonly openAccountDevices: () => void; - /** Refreshes device presence and the disclosed workspace session lists. */ - readonly refreshDevices: () => Promise; - readonly refreshSessions: () => Promise; - readonly settings: () => void; - readonly openAccount: () => void; - readonly openSession: (session: RemoteSession) => void; - readonly deleteSession: (session: RemoteSession) => void; -} - -export interface SettingsPresentationActions { - readonly close: () => void; - /** Account login finished or signed out inside settings; return to the single settings page. */ - readonly accountSettled: () => void; - readonly disconnect: () => void; - readonly clearPairing: () => void; - readonly reconnect: () => void; - readonly openAccount: () => void; - readonly cloudCancelLogin: () => void; - readonly cloudLogin: () => Promise; - readonly cloudLogout: () => Promise; - readonly cloudListDevices: () => Promise; - readonly cloudSelectDevice: (device: CloudAccountDevice) => Promise; - readonly getPermissionMode: () => Promise; - readonly setPermissionMode: (mode: RemotePermissionMode) => Promise; - /** - * Device-level model catalog of the connected desktop: read without a session - * id, so the projection carries the defaults that belong to the desktop. - */ - readonly getDeviceModelCatalog: () => Promise; - /** - * Writes the three phone-managed slots as one object. `null` is a value: - * the fast model then follows the primary one and the others are left - * unconfigured. The answer is the desktop's reconciled projection. - */ - readonly setDeviceModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ) => Promise; - readonly setLanguage: (language: string) => Promise; -} - -export interface ConnectPresentationActions { - readonly back: () => void; - readonly openAccount: () => void; - readonly connect: (password?: string) => void; - readonly clearPairing: () => void; - readonly cloudListDevices: () => Promise; - readonly cloudSelectDevice: (device: CloudAccountDevice) => Promise; -} - -export function emptyAppRootPresentationActions(): AppRootPresentationActions { - return { - onWorkspaceTools: () => {}, - onNavigationBack: () => false, - onConversationIntent: () => {}, - onCloseSidebar: () => {}, - onCompactLayoutEntered: () => {}, - onLayoutModeChanged: () => {}, - onRemoteHome: { - openMiniApps: () => {}, - openSidebar: () => {}, connectWorkspace: () => {}, addConnection: () => {}, - refresh: () => {}, showWorkspaces: () => {}, showAssistants: () => {}, selectWorkspace: () => {}, - selectAssistant: () => {}, cancelWorkspace: () => {}, cancelAssistant: () => {}, queryChanged: () => {}, - search: () => {}, loadMore: () => {}, reconnect: () => {}, disconnect: () => {}, clearPairing: () => {}, - create: () => {}, createInPlace: () => {}, createInWorkspace: () => {}, - createInWorkspaceInPlace: () => {}, selectDirectoryDevice: () => {}, addDirectoryWorkspace: () => {}, - retryDirectoryDevice: () => {}, loadWorkspaceSessions: async () => {}, - openSession: () => {}, openSessionInPlace: () => {}, deleteSession: () => {} - }, - onSidebar: { - close: () => {}, newChat: () => {}, enterCode: () => {}, openAccountDevices: () => {}, - refreshDevices: async () => {}, refreshSessions: async () => {}, settings: () => {}, openAccount: () => {}, - openSession: () => {}, deleteSession: () => {} - }, - onSettings: { - close: () => {}, accountSettled: () => {}, disconnect: () => {}, clearPairing: () => {}, - reconnect: () => {}, openAccount: () => {}, - cloudCancelLogin: () => {}, - cloudLogin: async () => '', cloudLogout: async () => {}, - cloudListDevices: async () => [], cloudSelectDevice: async () => {}, - getPermissionMode: async () => 'ask', - setPermissionMode: async (mode: RemotePermissionMode) => mode, - getDeviceModelCatalog: async () => ({ version: 0, models: [], default_models: {} }), - setDeviceModelDefaults: async ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ) => { - return { - primary, - fast, - image_understanding: imageUnderstanding - }; - }, - setLanguage: async () => {} - }, - onConnect: { - back: () => {}, openAccount: () => {}, connect: () => {}, clearPairing: () => {}, - cloudListDevices: async () => [], cloudSelectDevice: async () => {} - }, - onFilePreview: { close: () => {}, refresh: () => {}, download: () => {}, openLink: () => {} }, - generalStatus: () => '' - }; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets deleted file mode 100644 index 32b9696a87..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets +++ /dev/null @@ -1,293 +0,0 @@ -import { MessageQueueAction } from '../../model/MessageQueue'; -import { InteractionMailboxAction } from '../../model/InteractionMailbox'; -import { ConversationUiQuestionAnswer } from '../state/ConversationUiModels'; -import { FilePreviewRequest } from '../../model/FilePreviewTarget'; - -export enum ConversationIntentType { - MessageQueue = 'message_queue', - Mailbox = 'mailbox', - OpenSidebar = 'open_sidebar', - Back = 'back', - NewSession = 'new_session', - TogglePin = 'toggle_pin', - Archive = 'archive', - Delete = 'delete', - ShowUploadedFiles = 'show_uploaded_files', - Stop = 'stop', - LoadOlder = 'load_older', - ApproveTool = 'approve_tool', - RejectTool = 'reject_tool', - CancelTool = 'cancel_tool', - AnswerQuestion = 'answer_question', - RenameSession = 'rename_session', - CopyMessage = 'copy_message', - RetryMessage = 'retry_message', - SelectModel = 'select_model', - PickImages = 'pick_images', - RemoveImage = 'remove_image', - OpenFilePreview = 'open_file_preview', - DownloadFile = 'download_file', - BuildPlan = 'build_plan', - BranchExpanded = 'branch_expanded', - CommandPalette = 'command_palette', - RollbackSession = 'rollback_session', - RollbackResync = 'rollback_resync', - RollbackNotice = 'rollback_notice', - Send = 'send', - VoiceInput = 'voice_input', - ChatInputChanged = 'chat_input_changed' -} - -/** - * What one tap in the composer command row asks for. - * - * The row is a single funnel by construction: the two verbs keep their wire ids, - * and everything else is a local decision about the draft or a sheet. None of - * these carry a session — the active conversation is resolved once, where the - * command is sent. - */ -export enum CommandPaletteAction { - Compact = 'compact', - InitAgentsMd = 'init_agents_md', - ToggleGoal = 'toggle_goal', - OpenUsage = 'open_usage', - RetryUsage = 'retry_usage', - OpenSkills = 'open_skills', - RefreshCatalog = 'refresh_catalog', - SelectSkill = 'select_skill', - ClearSkill = 'clear_skill', - RetryCommand = 'retry_command' -} - -export class CommandPaletteRequest { - readonly action: CommandPaletteAction; - /** The picked skill's key, for `SelectSkill`; empty otherwise. */ - readonly skillId: string; - /** The verb a `RetryCommand` repeats, empty otherwise. */ - readonly wireAction: string; - /** - * The picked skill's name, for `SelectSkill`; empty otherwise. - * - * It travels beside the key because the two are not the same string and the - * user sees only this one: the message carries `[$]` while the row's - * identity, and every comparison the picker makes, stays the key. - */ - readonly skillLabel: string; - - constructor( - action: CommandPaletteAction, - skillId: string = '', - wireAction: string = '', - skillLabel: string = '' - ) { - this.action = action; - this.skillId = skillId; - this.wireAction = wireAction; - this.skillLabel = skillLabel; - } -} - -export class PlanBuildRequest { - readonly path: string; - readonly name: string; - - constructor(path: string, name: string) { - this.path = path; - this.name = name; - } -} - -/** - * One staged rollback the view asks the host for. - * - * `sendText` is what makes the two exits one command: an empty value is the plain - * confirm, which leaves the composer alone, while a non-empty value is the - * send-while-staging exit, where the rollback has to complete before that text is - * sent from the withdrawn point. Both travel together because the order between - * them is the whole contract and splitting them into two intents would let a - * caller reverse it. - */ -export class SessionRollbackRequest { - readonly targetTurnId: string; - readonly sendText: string; - - constructor(targetTurnId: string, sendText: string = '') { - this.targetTurnId = targetTurnId; - this.sendText = sendText; - } -} - -/** - * What a `CopyMessage` intent asks the clipboard owner to write. - * - * `Plain` is the default so every caller that existed before the assistant copy - * menu — the code-block copy button and the user message's "full text" copy — - * keeps its single-flavor plain write. Only `Rich` changes the payload shape. - */ -export enum MessageCopyScope { - /** Markdown source as the plain flavor plus its rendered html. */ - Rich = 'rich', - /** The Markdown source alone, one plain flavor. */ - Markdown = 'markdown', - /** A plain-text rendering of the message, one plain flavor. */ - Plain = 'plain' -} - -export class ConversationIntent { - readonly type: ConversationIntentType; - readonly value: string; - readonly toolId: string; - readonly updatedInput?: Object; - readonly answers?: ConversationUiQuestionAnswer; - readonly filePreviewRequest?: FilePreviewRequest; - readonly planBuildRequest?: PlanBuildRequest; - // Assigned by the factory rather than through the constructor, the same way - // `mailboxAction` is: the class's positional constructor is already long, and a - // payload only one intent type reads does not belong in every other one's call. - rollbackRequest?: SessionRollbackRequest; - readonly copyScope: MessageCopyScope; - readonly commandPaletteRequest?: CommandPaletteRequest; - queueAction?: MessageQueueAction; - mailboxAction?: InteractionMailboxAction; - - constructor( - type: ConversationIntentType, - value: string = '', - toolId: string = '', - updatedInput?: Object, - answers?: ConversationUiQuestionAnswer, - filePreviewRequest?: FilePreviewRequest, - planBuildRequest?: PlanBuildRequest, - copyScope: MessageCopyScope = MessageCopyScope.Plain, - commandPaletteRequest?: CommandPaletteRequest - ) { - this.type = type; - this.value = value; - this.toolId = toolId; - this.updatedInput = updatedInput; - this.answers = answers; - this.filePreviewRequest = filePreviewRequest; - this.planBuildRequest = planBuildRequest; - this.copyScope = copyScope; - this.commandPaletteRequest = commandPaletteRequest; - } -} - -export class ConversationIntents { - static queue(action: MessageQueueAction): ConversationIntent { - const intent = new ConversationIntent(ConversationIntentType.MessageQueue); intent.queueAction = action; return intent; - } - static mailbox(action: InteractionMailboxAction): ConversationIntent { - const intent = new ConversationIntent(ConversationIntentType.Mailbox); - intent.mailboxAction = action; - return intent; - } - static simple(type: ConversationIntentType): ConversationIntent { - return new ConversationIntent(type); - } - - static value(type: ConversationIntentType, value: string): ConversationIntent { - return new ConversationIntent(type, value); - } - - /** - * The scoped copy intent. The value is already the text for that scope: the - * Markdown source for `rich`/`markdown`, the plain rendering for `plain`. - */ - static copyMessage(text: string, scope: MessageCopyScope): ConversationIntent { - return new ConversationIntent( - ConversationIntentType.CopyMessage, - text, - '', - undefined, - undefined, - undefined, - undefined, - scope - ); - } - - static approveTool(toolId: string, updatedInput?: Object): ConversationIntent { - return new ConversationIntent(ConversationIntentType.ApproveTool, '', toolId, updatedInput); - } - - static tool(type: ConversationIntentType, toolId: string): ConversationIntent { - return new ConversationIntent(type, '', toolId); - } - - static answerQuestion(toolId: string, answers: ConversationUiQuestionAnswer): ConversationIntent { - return new ConversationIntent(ConversationIntentType.AnswerQuestion, '', toolId, undefined, answers); - } - - static openFilePreview(reference: string, label: string): ConversationIntent { - return new ConversationIntent( - ConversationIntentType.OpenFilePreview, - '', - '', - undefined, - undefined, - new FilePreviewRequest(reference, label) - ); - } - - static buildPlan(path: string, name: string): ConversationIntent { - return new ConversationIntent( - ConversationIntentType.BuildPlan, - '', - '', - undefined, - undefined, - undefined, - new PlanBuildRequest(path, name) - ); - } - - /** One tap in the composer command row, as a typed request rather than a parameter list. */ - static commandPalette(request: CommandPaletteRequest): ConversationIntent { - return new ConversationIntent( - ConversationIntentType.CommandPalette, - '', - '', - undefined, - undefined, - undefined, - undefined, - MessageCopyScope.Plain, - request - ); - } - - /** - * The reader opened a delegation card. The branch id is the tool call that - * launched the worker, which is what its records are found by. - */ - static branchExpanded(branchId: string): ConversationIntent { - return new ConversationIntent(ConversationIntentType.BranchExpanded, '', branchId); - } - - /** - * The one rollback intent, for both staged exits. - * - * `sendText` is empty for a confirm and non-empty for send-while-staging; the - * host command itself is identical, and the viewmodel decides whether a message - * follows it. - */ - static rollback(targetTurnId: string, sendText: string = ''): ConversationIntent { - const intent = new ConversationIntent(ConversationIntentType.RollbackSession); - intent.rollbackRequest = new SessionRollbackRequest(targetTurnId, sendText); - return intent; - } - - /** Refetch the authoritative transcript after a host outcome this client refused. */ - static rollbackResync(): ConversationIntent { - return new ConversationIntent(ConversationIntentType.RollbackResync); - } - - /** - * Say one refusal out loud. The value is a dotted i18n key, not a sentence: the - * policy owns which key a given denial resolves to and this app owns no copy. - */ - static rollbackNotice(key: string): ConversationIntent { - return new ConversationIntent(ConversationIntentType.RollbackNotice, key); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets deleted file mode 100644 index 7db924d5cc..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets +++ /dev/null @@ -1,107 +0,0 @@ -import { MessageQueueAction } from '../../model/MessageQueue'; -import { InteractionMailboxAction } from '../../model/InteractionMailbox'; -import { RemoteQuestionAnswerPayload, RemoteSession } from '../../model/RemoteModels'; -import { AppRoute, AppRouteContract } from '../navigation/AppRouteContract'; -import { ConversationIntent, ConversationIntentType, CommandPaletteRequest, MessageCopyScope, SessionRollbackRequest } from './ConversationIntent'; -import { toRemoteQuestionAnswer } from '../state/ConversationUiModels'; -import { FilePreviewRequest } from '../../model/FilePreviewTarget'; - -export interface ConversationIntentDispatcherHooks { - readonly queue?: (action: MessageQueueAction) => Promise; - readonly mailbox: (action: InteractionMailboxAction) => Promise; - readonly openSidebar: () => void; - readonly back: () => void; - readonly newRemoteSession: () => void; - readonly unsupported: () => void; - readonly stop: () => Promise; - readonly loadOlder: () => Promise; - readonly approve: (toolId: string, input?: Object) => Promise; - readonly reject: (toolId: string) => Promise; - readonly cancel: (toolId: string) => Promise; - readonly answer: (toolId: string, answers: RemoteQuestionAnswerPayload) => Promise; - readonly rename: (title: string) => Promise; - readonly copy: (text: string, scope: MessageCopyScope) => Promise; - readonly retry: (text: string) => Promise; - readonly selectModel: (modelId: string) => Promise; - readonly pickImages: () => Promise; - readonly removeImage: (id: string) => void; - readonly openFilePreview: (route: AppRoute, request: FilePreviewRequest) => void; - readonly downloadFile: (path: string) => void; - readonly buildPlan: (path: string, name: string) => Promise; - readonly branchExpanded: (branchId: string) => void; - readonly commandPalette: (request: CommandPaletteRequest) => Promise; - /** - * Run one staged rollback against the host. - * - * It resolves only when the host has answered, because a send-while-staging - * exit has to append its message after the turn the rollback retired. - */ - readonly rollback: (request: SessionRollbackRequest) => Promise; - /** Refetch the transcript when a host outcome left this client unsure. */ - readonly rollbackResync: () => Promise; - /** Show one rollback refusal, keyed by i18n key. */ - readonly rollbackNotice: (key: string) => void; - readonly send: () => Promise; - readonly voiceInput: () => Promise; - readonly inputChanged: (route: AppRoute, value: string) => void; -} - -export class ConversationIntentDispatcher { - private readonly hooks: ConversationIntentDispatcherHooks; - - constructor(hooks: ConversationIntentDispatcherHooks) { - this.hooks = hooks; - } - - dispatch(route: AppRoute, intent: ConversationIntent): void { - switch (intent.type) { - case ConversationIntentType.MessageQueue: if (route === AppRoute.RemoteChat && intent.queueAction) void this.hooks.queue?.(intent.queueAction); return; - case ConversationIntentType.Mailbox: if (intent.mailboxAction) void this.hooks.mailbox(intent.mailboxAction); return; - case ConversationIntentType.OpenSidebar: this.hooks.openSidebar(); return; - case ConversationIntentType.Back: this.hooks.back(); return; - case ConversationIntentType.NewSession: this.hooks.newRemoteSession(); return; - case ConversationIntentType.TogglePin: - case ConversationIntentType.Archive: - case ConversationIntentType.Delete: - case ConversationIntentType.ShowUploadedFiles: - this.hooks.unsupported(); return; - case ConversationIntentType.Stop: void this.hooks.stop(); return; - case ConversationIntentType.LoadOlder: void this.hooks.loadOlder(); return; - case ConversationIntentType.ApproveTool: void this.hooks.approve(intent.toolId, intent.updatedInput); return; - case ConversationIntentType.RejectTool: void this.hooks.reject(intent.toolId); return; - case ConversationIntentType.CancelTool: void this.hooks.cancel(intent.toolId); return; - case ConversationIntentType.AnswerQuestion: - if (intent.answers) void this.hooks.answer(intent.toolId, toRemoteQuestionAnswer(intent.answers)); return; - case ConversationIntentType.RenameSession: void this.hooks.rename(intent.value); return; - case ConversationIntentType.CopyMessage: void this.hooks.copy(intent.value, intent.copyScope); return; - case ConversationIntentType.RetryMessage: void this.hooks.retry(intent.value); return; - case ConversationIntentType.SelectModel: void this.hooks.selectModel(intent.value); return; - case ConversationIntentType.PickImages: void this.hooks.pickImages(); return; - case ConversationIntentType.RemoveImage: this.hooks.removeImage(intent.value); return; - case ConversationIntentType.OpenFilePreview: - if (intent.filePreviewRequest) this.hooks.openFilePreview(route, intent.filePreviewRequest); return; - case ConversationIntentType.DownloadFile: this.hooks.downloadFile(intent.value); return; - case ConversationIntentType.BuildPlan: - if (route === AppRoute.RemoteChat && intent.planBuildRequest) { - void this.hooks.buildPlan(intent.planBuildRequest.path, intent.planBuildRequest.name); - } - return; - case ConversationIntentType.BranchExpanded: this.hooks.branchExpanded(intent.toolId); return; - case ConversationIntentType.RollbackSession: - if (intent.rollbackRequest) void this.hooks.rollback(intent.rollbackRequest); return; - case ConversationIntentType.RollbackResync: void this.hooks.rollbackResync(); return; - case ConversationIntentType.RollbackNotice: this.hooks.rollbackNotice(intent.value); return; - case ConversationIntentType.Send: void this.hooks.send(); return; - case ConversationIntentType.VoiceInput: void this.hooks.voiceInput(); return; - case ConversationIntentType.ChatInputChanged: this.hooks.inputChanged(route, intent.value); return; - case ConversationIntentType.CommandPalette: - // Command palette verbs ride the same remote conversation as everything - // else, so a general-chat route must not reach the remote host with one. - if (route === AppRoute.RemoteChat && intent.commandPaletteRequest) { - void this.hooks.commandPalette(intent.commandPaletteRequest); - } - return; - } - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountLoginSheet.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountLoginSheet.ets deleted file mode 100644 index fc57f3b9f6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountLoginSheet.ets +++ /dev/null @@ -1,31 +0,0 @@ -import { PAGE_BG } from './Theme'; -import { OpenBitFunAccountLoginPage } from './OpenBitFunAccountLoginPage'; -import { SHEET_TOP_RADIUS } from './SheetLayout'; - -/** - * Signed-out account request (settings mode 'account'). Settings itself is a - * single page; this sheet only hosts the separate login step and hands back to - * that page once the account settles. - */ -@ComponentV2 -export struct AccountLoginSheet { - @Event onClose: () => void = () => {}; - /** Account login finished: return to the single settings page. */ - @Event onAccountSettled: () => void = () => {}; - @Event cloudCancelLogin: () => void = () => {}; - @Event cloudLogin: () => Promise = async (): Promise => ''; - - build() { - Stack() { - OpenBitFunAccountLoginPage({ - cloudLogin: this.cloudLogin, - cloudCancelLogin: this.cloudCancelLogin, - onClose: this.onClose, - onLoginSuccess: this.onAccountSettled - }) - } - .width('100%') - .backgroundColor(PAGE_BG) - .borderRadius({ topLeft: SHEET_TOP_RADIUS, topRight: SHEET_TOP_RADIUS }) - } -} 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 deleted file mode 100644 index 7f8b4b7b1c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountProfilePanel.ets +++ /dev/null @@ -1,506 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -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, - INK, - LINE, - MUTED, - PAGE_BG, - PRIMARY_ACTION, - SOFT, - STATUS_DANGER, - STATUS_SUCCESS -} from './Theme'; -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 = ''; - @Param fallbackUserId: string = ''; - @Param deviceId: string = ''; - @Param controlTargetType: string = 'none'; - @Param controlTargetDeviceId: string = ''; - @Param connectionState: string = 'idle'; - /** The connected desktop advertises `device_model_defaults_v1`. */ - @Param supportsDeviceModelDefaults: boolean = false; - @BuilderParam preferences: () => void = this.EmptyBuilder; - @BuilderParam connection: () => void = this.EmptyBuilder; - @BuilderParam about: () => void = this.EmptyBuilder; - @Event onLoggedOut: () => void = () => {}; - @Event onOpenAccount: () => void = () => {}; - @Event onReconnect: () => void = () => {}; - @Event onOpenDeviceModelSettings: () => void = () => {}; - @Event cloudLogout: () => Promise = async (): Promise => {}; - @Event cloudListDevices: () => Promise = - async (): Promise => []; - @Event cloudSelectDevice: (device: CloudAccountDevice) => Promise = - async (_device: CloudAccountDevice): Promise => {}; - @Local accountDevicesBusy: boolean = false; - @Local accountDevicesError: string = ''; - @Local switchingDeviceId: string = ''; - @Local logoutBusy: boolean = false; - /** - * Why the device model settings entry could not open, shown once under the - * row that was tapped. A missing capability is a state, not a failure, so it - * is explained in place instead of by opening a page that cannot answer. - */ - @Local deviceModelSettingsReason: string = ''; - /** The row the reason belongs to; empty when no row was tapped. */ - @Local deviceModelSettingsReasonDeviceId: string = ''; - - aboutToAppear(): void { - if (this.isAccountAuthenticated()) { - this.refreshAccountDevices(); - } - } - - build() { - Column({ space: 0 }) { - this.CompactIdentityCard() - this.connection() - this.preferences() - this.DeviceManagementSection() - this.about() - if (this.isAccountAuthenticated()) { - this.LogoutAction() - } - } - .width('100%') - } - - @Builder - private CompactIdentityCard() { - this.EmbeddedSectionTitle(RemoteI18n.t('settings.account.section')) - Row({ space: 14 }) { - DefaultAccountAvatar({ avatarSize: 46, avatarUrl: this.accountAvatarUrl }) - Column({ space: 4 }) { - Text(this.isAccountAuthenticated() ? this.profileName() : - RemoteI18n.t('settings.account.currentIdentity')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .width('100%') - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.isAccountAuthenticated() ? RemoteI18n.f('remote.settings.githubId', this.accountUserId) : - this.shortProfileIdentifier()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .width('100%') - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - Row({ space: 6 }) { - Text(this.compactAccountStatus()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(this.isAccountAuthenticated() ? STATUS_SUCCESS : MUTED) - if (!this.isAccountAuthenticated()) { - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(13) - .fontColor([MUTED]) - } - } - } - .width('100%') - .constraintSize({ minHeight: 72 }) - .padding({ left: 18, right: 18, top: 12, bottom: 12 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .margin({ bottom: 24 }) - .onClick(() => { - if (!this.isAccountAuthenticated()) { - this.onOpenAccount(); - } - }) - } - - @Builder - private EmbeddedSectionTitle(title: string) { - Text(title) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .width('100%') - .margin({ left: 8, bottom: 10 }) - } - - @Builder - private DeviceManagementSection() { - Column({ space: 8 }) { - Row() { - Text(RemoteI18n.t('settings.devices.section')) - .fontSize(MobileDesignTypography.titleSmall.size) - .lineHeight(MobileDesignTypography.titleSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Blank() - Button() { - SymbolGlyph($r('sys.symbol.arrow_clockwise')) - .fontSize(18) - .fontColor([this.accountDevicesBusy ? MUTED : INK]) - } - .width(MobileDesignGeometry.controlTouchSize) - .height(MobileDesignGeometry.controlTouchSize) - .padding(0) - .type(ButtonType.Circle) - .backgroundColor(PAGE_BG) - .opacity(this.accountDevicesBusy ? 0.55 : 1) - .enabled(!this.accountDevicesBusy) - .accessibilityText(RemoteI18n.t('common.refresh')) - .onClick(async () => { - await this.refreshAccountDevices(); - }) - } - .width('100%') - .constraintSize({ minHeight: 48 }) - .padding({ left: 8, right: 4 }) - - Column({ space: 4 }) { - 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.directoryState.devices.length === 0) { - Text(RemoteI18n.t('remote.settings.deviceLoading')) - .fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).width('100%') - } else if (this.desktopDevices().length === 0) { - Text(this.accountDevicesError || RemoteI18n.t('remote.settings.deviceEmpty')) - .fontSize(MobileDesignTypography.bodySmall.size).lineHeight(MobileDesignTypography.bodySmall.lineHeight).fontColor(MUTED).width('100%') - } else { - ForEach(this.desktopDevices(), (device: CloudAccountDevice) => { - Column({ space: 0 }) { - this.AccountDeviceRow(device) - if (this.deviceModelSettingsReasonDeviceId === device.deviceId && - this.deviceModelSettingsReason.length > 0) { - this.DeviceModelSettingsReasonBand() - } - } - .width('100%') - }, (device: CloudAccountDevice): string => - `${device.deviceId}:${device.online ? 'online' : 'offline'}:${device.lastSeenAt || 0}:${accountDeviceDisplayName(device)}` + - `:${this.isCurrentControlDevice(device) ? 'driven' : 'idle'}` + - `:${this.supportsDeviceModelDefaults ? 'model-defaults' : 'no-model-defaults'}`) - } - if (this.accountDevicesError.length > 0 && this.desktopDevices().length > 0) { - Text(this.accountDevicesError) - .fontSize(MobileDesignTypography.bodySmall.size).lineHeight(MobileDesignTypography.bodySmall.lineHeight).fontColor(STATUS_DANGER).width('100%') - } - } - .width('100%') - .padding({ left: 8, right: 8, top: 8, bottom: 8 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - } - .width('100%') - .margin({ bottom: 24 }) - } - - @Builder - private AccountDeviceRow(device: CloudAccountDevice) { - Row({ space: 12 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.desktop')) - .fontSize(20) - .fontColor([this.isCurrentControlDevice(device) ? INK : MUTED]) - .opacity(this.isCurrentControlDevice(device) ? 0.9 : 0.66) - } - .width(28) - .height(28) - Column({ space: 2 }) { - Text(accountDeviceDisplayName(device)) - .fontSize(MobileDesignTypography.titleSmall.size).fontWeight(FontWeight.Medium).fontColor(INK) - .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.deviceStatus(device)) - .fontSize(MobileDesignTypography.bodySmall.size).fontColor(device.online ? STATUS_SUCCESS : MUTED) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - if (this.showsDeviceModelSettingsEntry(device)) { - this.DeviceModelSettingsEntry(device) - } else if (this.shouldShowDeviceConnectAction(device)) { - Text(this.switchingDeviceId === device.deviceId ? - RemoteI18n.t('remote.settings.deviceConnecting') : RemoteI18n.t('connect.connect')) - .fontSize(MobileDesignTypography.bodyMedium.size).fontColor(INK) - .padding({ left: 10, right: 10, top: 6, bottom: 6 }) - .backgroundColor(SOFT).borderRadius(14) - } - } - .width('100%') - .constraintSize({ minHeight: 62 }) - .padding({ left: 10, right: 10, top: 10, bottom: 10 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.isCurrentControlDevice(device) ? SOFT : CARD) - .borderRadius(MobileDesignGeometry.settingsCompactCardRadius) - .opacity(device.online ? 1 : 0.48) - .onClick(() => { - void this.connectAccountDevice(device); - }) - } - - /** - * The model settings entry on the row of the desktop this phone is driving. - * - * Same pill as the row's connect action, because it is the same slot: the - * connected target offers its own settings instead of re-connecting. An older - * desktop keeps the pill, greyed, with an upgrade corner badge, and tapping it - * explains itself instead of opening a page that cannot answer. - */ - @Builder - private DeviceModelSettingsEntry(device: CloudAccountDevice) { - // The Stack wraps the pill, so the badge can be lifted above the pill's top - // corner without taking part in the row's layout: an inline badge would push - // the device name out of the row's width. - Stack({ alignContent: Alignment.TopEnd }) { - Row({ space: 4 }) { - SymbolGlyph($r('sys.symbol.gearshape')) - .fontSize(14) - .fontColor([MUTED]) - Text(RemoteI18n.t('settings.model.settingsTitle')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .padding({ left: 10, right: 10, top: 6, bottom: 6 }) - .backgroundColor(SOFT) - .borderRadius(14) - .opacity(this.deviceModelSettingsEnabled() ? 1 : 0.38) - // The two states of this pill are its whole contract, so the state is part - // of its identity: an enabled entry that still looked greyed would be the - // same bug as a greyed one that opened the page. - .id(`device-model-entry-${this.deviceModelSettingsEnabled() ? 'enabled' : 'degraded'}`) - .onClick(() => { - this.openDeviceModelSettings(device); - }) - - if (!this.deviceModelSettingsEnabled()) { - Text(RemoteI18n.t('settings.model.upgradeBadge')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Bold) - .fontColor(CONTENT_ON_ACTION) - .height(15) - .padding({ left: 4, right: 4 }) - .backgroundColor(PRIMARY_ACTION) - .borderRadius(4) - .offset({ x: 0, y: -14 }) - } - } - } - - @Builder - private DeviceModelSettingsReasonBand() { - Text(this.deviceModelSettingsReason) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .padding({ left: 12, right: 12, top: 10, bottom: 10 }) - .backgroundColor(SOFT) - .borderRadius(MobileDesignGeometry.settingsCompactCardRadius) - .margin({ left: 4, right: 4, bottom: 4 }) - } - - @Builder - private LogoutAction() { - Divider() - .strokeWidth(1) - .color(LINE) - .margin({ left: 8, right: 8, top: 24 }) - Row({ space: 14 }) { - SymbolGlyph($r('sys.symbol.arrow_right_and_square')) - .fontSize(22).fontColor([STATUS_DANGER]).width(24).height(24) - Text(this.logoutBusy ? RemoteI18n.t('remote.settings.accountLoggingOut') : - RemoteI18n.t('remote.settings.accountLogout')) - .fontSize(MobileDesignTypography.titleMedium.size).fontWeight(FontWeight.Medium).fontColor(STATUS_DANGER) - } - .width('100%') - .constraintSize({ minHeight: 62 }) - .padding({ left: 20, right: 20, top: 12, bottom: 12 }) - .backgroundColor(PAGE_BG) - .margin({ top: 4, bottom: 8 }) - .opacity(this.logoutBusy ? 0.55 : 1) - .enabled(!this.logoutBusy) - .onClick(async () => { - this.logoutBusy = true; - try { - await this.cloudLogout(); - this.onLoggedOut(); - } finally { - this.logoutBusy = false; - } - }) - } - - private async refreshAccountDevices(): Promise { - if (!this.isAccountAuthenticated() || this.accountDevicesBusy) return; - this.accountDevicesBusy = true; - this.accountDevicesError = ''; - try { - await this.cloudListDevices(); - } catch (err) { - this.accountDevicesError = err instanceof Error ? err.message : - RemoteI18n.t('remote.settings.deviceLoadFailed'); - } finally { - this.accountDevicesBusy = false; - } - } - - private desktopDevices(): DeviceDirectoryEntry[] { - return this.directoryState.devices.filter((device: DeviceDirectoryEntry): boolean => - device.deviceId !== this.deviceId && device.deviceName !== 'HarmonyOS Phone'); - } - - private canActivateAccountDevice(device: CloudAccountDevice): boolean { - return AccountDeviceSelectionPolicy.canActivate( - device.online, - device.deviceId, - this.deviceId, - this.controlTargetDeviceId, - this.connectionState, - this.switchingDeviceId - ); - } - - private shouldShowDeviceConnectAction(device: CloudAccountDevice): boolean { - return AccountDeviceSelectionPolicy.shouldShowConnectAction( - device.online, - device.deviceId, - this.deviceId, - this.controlTargetDeviceId, - this.connectionState - ); - } - - /** The entry belongs to the desktop this phone is connected to and driving. */ - private showsDeviceModelSettingsEntry(device: CloudAccountDevice): boolean { - return DeviceModelSettingsEntryPolicy.showsEntry( - device.online, - device.deviceId, - this.deviceId, - this.controlTargetDeviceId, - this.connectionState - ); - } - - private deviceModelSettingsEnabled(): boolean { - return DeviceModelSettingsEntryPolicy.entryEnabled(this.supportsDeviceModelDefaults); - } - - private openDeviceModelSettings(device: CloudAccountDevice): void { - const reasonKey = DeviceModelSettingsEntryPolicy.degradeReasonKey( - this.showsDeviceModelSettingsEntry(device), - this.supportsDeviceModelDefaults - ); - if (reasonKey.length > 0) { - this.deviceModelSettingsReasonDeviceId = device.deviceId; - this.deviceModelSettingsReason = RemoteI18n.t(reasonKey); - return; - } - this.deviceModelSettingsReasonDeviceId = ''; - this.deviceModelSettingsReason = ''; - this.onOpenDeviceModelSettings(); - } - - private async connectAccountDevice(device: CloudAccountDevice): Promise { - if (!this.canActivateAccountDevice(device)) return; - this.switchingDeviceId = device.deviceId; - this.accountDevicesError = ''; - try { - if (AccountDeviceSelectionPolicy.canSelectOnline( - device.online, device.deviceId, this.deviceId, '' - )) { - await this.cloudSelectDevice(device); - } else { - this.onReconnect(); - } - } catch (err) { - this.accountDevicesError = err instanceof Error ? err.message : - RemoteI18n.t('remote.settings.deviceSwitchFailed'); - } finally { - this.switchingDeviceId = ''; - } - } - - private deviceStatus(device: CloudAccountDevice): string { - if (device.deviceId === this.deviceId) return RemoteI18n.t('remote.settings.deviceCurrent'); - const presence = device.online ? RemoteI18n.t('remote.settings.deviceOnline') : - RemoteI18n.t('remote.settings.deviceOffline'); - if (device.deviceId === this.controlTargetDeviceId && this.connectionState === 'connected') { - return `${RemoteI18n.t('remote.settings.deviceControlling')} · ${presence}`; - } - if (device.deviceId === this.controlTargetDeviceId) { - return `${RemoteI18n.t('connect.deviceLastUsed')} · ${presence}`; - } - return presence; - } - - private isCurrentControlDevice(device: CloudAccountDevice): boolean { - return device.deviceId === this.controlTargetDeviceId && this.connectionState === 'connected'; - } - - private profileName(): string { - return this.accountUsername && this.accountUsername !== this.accountUserId ? `@${this.accountUsername}` : - RemoteI18n.t('remote.settings.githubAccount'); - } - - private profileIdentifier(): string { - return this.accountUserId || this.fallbackUserId || this.deviceId || '-'; - } - - private shortProfileIdentifier(): string { - const identifier = this.profileIdentifier(); - if (identifier.length <= 22) return identifier; - return `${identifier.slice(0, 18)}…`; - } - - private compactAccountStatus(): string { - if (this.isAccountAuthenticated()) { - return RemoteI18n.t('remote.settings.accountSignedIn'); - } - if (this.controlTargetType === 'room') { - return RemoteI18n.t('remote.settings.accountTemporary'); - } - return RemoteI18n.t('remote.settings.accountNotSignedIn'); - } - - private isAccountAuthenticated(): boolean { - return this.accountUserId.trim().length > 0; - } - - @Builder - private EmptyBuilder() { - Column() { - } - } - - @Monitor('accountUserId') - private handleAccountUserChanged(): void { - if (this.isAccountAuthenticated() && this.directoryState.devices.length === 0) { - this.refreshAccountDevices(); - } - } - - /** - * A link or capability change makes the explanation stale: it described the - * host as it was when the entry was tapped. - */ - @Monitor('connectionState', 'supportsDeviceModelDefaults') - private clearDeviceModelSettingsReason(): void { - this.deviceModelSettingsReasonDeviceId = ''; - this.deviceModelSettingsReason = ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AdaptiveSheetOptions.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AdaptiveSheetOptions.ets deleted file mode 100644 index f7eb4d3d22..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AdaptiveSheetOptions.ets +++ /dev/null @@ -1,66 +0,0 @@ -import { - SettingsPlacement, - SettingsPlacementMode -} from '../policy/SettingsPlacementPolicy'; -import { SCRIM, TRANSPARENT } from './Theme'; - -/** - * Shared SheetOptions for the four overlay sheets. Policy stays ArkUI-free; - * this is the only place preferType is chosen. - */ -export class AdaptiveSheetOptions { - static fromPlacement(placement: SettingsPlacement, dragBar: boolean = false): SheetOptions { - if (placement.mode === SettingsPlacementMode.FoldOperate) { - return { - height: placement.height, - keyboardAvoidMode: SheetKeyboardAvoidMode.RESIZE_ONLY, - backgroundColor: TRANSPARENT, - maskColor: SCRIM, - showClose: false, - dragBar - }; - } - if (placement.mode === SettingsPlacementMode.Side) { - return { - height: placement.height, - width: placement.width, - keyboardAvoidMode: SheetKeyboardAvoidMode.RESIZE_ONLY, - preferType: SheetType.SIDE, - backgroundColor: TRANSPARENT, - maskColor: SCRIM, - showClose: false, - dragBar: false - }; - } - if (placement.mode === SettingsPlacementMode.Center) { - return { - height: placement.height, - width: placement.width, - keyboardAvoidMode: SheetKeyboardAvoidMode.RESIZE_ONLY, - preferType: SheetType.CENTER, - backgroundColor: TRANSPARENT, - maskColor: SCRIM, - showClose: false, - dragBar: false - }; - } - if (placement.height > 0) { - return { - height: placement.height, - keyboardAvoidMode: SheetKeyboardAvoidMode.RESIZE_ONLY, - backgroundColor: TRANSPARENT, - maskColor: SCRIM, - showClose: false, - dragBar - }; - } - return { - height: SheetSize.LARGE, - keyboardAvoidMode: SheetKeyboardAvoidMode.RESIZE_ONLY, - backgroundColor: TRANSPARENT, - maskColor: SCRIM, - showClose: false, - dragBar - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppActionButton.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppActionButton.ets deleted file mode 100644 index a15067c309..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppActionButton.ets +++ /dev/null @@ -1,68 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { - CARD, - CONTENT_ON_ACTION, - INK, - LINE, - PRIMARY_ACTION, - SHADOW_FAINT, - SHADOW_SUBTLE, - SOFT, - STATUS_DANGER -} from './Theme'; - -/** Visual intent for a product action. Layout may still choose its own width and height. */ -export enum AppActionStyle { - Primary = 'primary', - Secondary = 'secondary', - Quiet = 'quiet', - Destructive = 'destructive' -} - -/** Shared action appearance without forcing every workflow into one fixed geometry. */ -@ComponentV2 -export struct AppActionButton { - @Param label: string = ''; - @Param style: AppActionStyle = AppActionStyle.Secondary; - @Param actionHeight: number = MobileDesignGeometry.sheetActionHeight; - @Param isEnabled: boolean = true; - @Param elevated: boolean = true; - @Event onAction: () => void = () => {}; - - build() { - Button(this.label) - .width('100%') - .height(this.actionHeight) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(this.isFilled() ? CONTENT_ON_ACTION : INK) - .backgroundColor(this.actionBackgroundColor()) - .border({ width: this.style === AppActionStyle.Secondary ? 1 : 0, color: LINE }) - .borderRadius(this.actionHeight / 2) - .shadow({ - radius: this.elevated && this.hasElevation() ? 14 : 0, - color: this.isFilled() ? SHADOW_SUBTLE : SHADOW_FAINT, - offsetY: this.elevated && this.hasElevation() ? 5 : 0 - }) - .opacity(this.isEnabled ? 1 : 0.32) - .enabled(this.isEnabled) - .onClick(() => { - this.onAction(); - }) - } - - private isFilled(): boolean { - return this.style === AppActionStyle.Primary || this.style === AppActionStyle.Destructive; - } - - private hasElevation(): boolean { - return this.isEnabled && this.style !== AppActionStyle.Quiet; - } - - private actionBackgroundColor(): ResourceColor { - if (this.style === AppActionStyle.Primary) return PRIMARY_ACTION; - if (this.style === AppActionStyle.Destructive) return STATUS_DANGER; - if (this.style === AppActionStyle.Quiet) return SOFT; - return CARD; - } -} 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 deleted file mode 100644 index 93898c02ce..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootOverlaySurfaces.ets +++ /dev/null @@ -1,212 +0,0 @@ -import { - AppRootPresentationActions, - emptyAppRootPresentationActions -} from '../actions/AppRootPresentationActions'; -import { AppRouteContract } from '../navigation/AppRouteContract'; -import { AppShellState } from '../state/AppShellState'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { SettingsPagePolicy } from '../policy/SettingsPagePolicy'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { DeviceDirectoryState } from '../state/DeviceDirectoryState'; -import { RemotePageState } from '../state/RemotePageState'; -import { REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1, REMOTE_CAPABILITY_HARNESS_PROFILES_V1 } from '../../model/RemoteModels'; -import { AppSidebar } from './AppSidebar'; -import { ConnectView } from './ConnectView'; -import { AccountLoginSheet } from './AccountLoginSheet'; -import { RemoteSurfaceState } from './remote/RemoteSurfaceHost'; -import { SettingsSheet } from './SettingsSheet'; -import { SidebarWorkspaceSection } from './SidebarWorkspaceSection'; - -@ComponentV2 -export struct AppSidebarSurface { - @Param shellState: AppShellState = new AppShellState(); - @Param sessionDetailsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SessionDetails); - @Param remotePageState: RemotePageState = new RemotePageState(); - @Param deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param generalPageState: GeneralChatPageState = new GeneralChatPageState(); - @Param remoteSurfaceState: RemoteSurfaceState = new RemoteSurfaceState(); - @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - @Event onOpenRemoteViewSettings: () => void = () => {}; - - build() { - AppSidebar({ - toolLocations: this.remotePageState.savedConnectionsTargetId === this.remotePageState.controlTargetDeviceId ? this.remotePageState.savedConnections : [], - onWorkspaceTools: this.actions.onWorkspaceTools, - connectionState: this.remotePageState.connectionState, - isBusy: this.remotePageState.isBusy, - workspaceKind: this.remotePageState.workspaceKind, - workspacePath: this.remotePageState.workspacePath, - controlTargetDeviceId: this.remotePageState.controlTargetDeviceId, - supportsHarnessProfiles: this.remotePageState.supportsHostCapability(REMOTE_CAPABILITY_HARNESS_PROFILES_V1), - accountUserId: this.remotePageState.accountUserId, - controlTargetType: this.remotePageState.controlTargetType, - showViewSettingsButton: false, - showWorkspaceSection: true, - contentSlot: () => { - this.WorkspaceContent() - }, - onClose: this.actions.onSidebar.close, - onNewChat: this.actions.onSidebar.newChat, - onEnterCode: this.actions.onSidebar.enterCode, - onOpenMiniApps: this.actions.onRemoteHome.openMiniApps, - onOpenViewSettings: this.onOpenRemoteViewSettings, - onSearchQueryChange: (query: string) => { - this.actions.onRemoteHome.queryChanged(query); - }, - onOpenSettings: this.actions.onSidebar.settings, - onOpenAccount: this.actions.onSidebar.openAccount, - }) - } - - @Builder - private WorkspaceContent() { - SidebarWorkspaceSection({ - workspaceTools: this.remotePageState.workspaceTools, - onWorkspaceTools: this.actions.onWorkspaceTools, - directoryState: this.deviceDirectoryState, - sessions: this.remotePageState.visibleSessions(), - recentWorkspaces: this.remotePageState.recentWorkspaces, - savedConnections: this.remotePageState.savedConnections, - savedConnectionsTargetId: this.remotePageState.savedConnectionsTargetId, - workspaceName: this.remotePageState.workspaceName, - workspacePath: this.remotePageState.workspacePath, - workspaceConnectionId: this.remotePageState.workspaceConnectionId, - workspaceSshHost: this.remotePageState.workspaceSshHost, - workspaceId: this.remotePageState.workspaceId, - workspaceKind: this.remotePageState.workspaceKind, - connectionState: this.remotePageState.connectionState, - controlTargetType: this.remotePageState.controlTargetType, - controlTargetDeviceId: this.remotePageState.controlTargetDeviceId, - controlTargetDeviceName: this.remotePageState.controlTargetDeviceName || - this.remotePageState.desktopName, - selectedSessionId: this.remoteSelectedSessionId(), - runningSessionId: this.remoteRunningSessionId(), - supportsHarnessProfiles: this.remotePageState.supportsHostCapability( - REMOTE_CAPABILITY_HARNESS_PROFILES_V1), - workspacePickerPlacement: this.sessionDetailsPlacement, - onOpenSession: this.actions.onSidebar.openSession, - onCreateInWorkspace: (deviceId: string, path: string, agentType: string, connectionId?: string, sshHost?: string, - workspaceId?: string) => { - this.actions.onSidebar.close(); - this.actions.onRemoteHome.createInWorkspace(path, agentType, deviceId, connectionId, sshHost, workspaceId); - }, - onOpenWorkspace: (deviceId: string, path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => { - this.actions.onRemoteHome.selectWorkspace(path, deviceId, connectionId, sshHost, workspaceId); - }, - onExpandWorkspace: async (deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, - workspaceId?: string): Promise => { - await this.actions.onRemoteHome.loadWorkspaceSessions(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId); - }, - onSelectDevice: this.actions.onRemoteHome.selectDirectoryDevice, - onRetryDevice: this.actions.onRemoteHome.retryDirectoryDevice, - onReconnect: this.actions.onRemoteHome.reconnect, - onAddWorkspace: this.actions.onRemoteHome.addDirectoryWorkspace, - onRefreshDevices: this.actions.onSidebar.refreshDevices, - onAddDevice: this.actions.onSidebar.openAccountDevices - }) - } - - private remoteSelectedSessionId(): string { - if (AppRouteContract.isGeneralComposerRoute(this.shellState.activeRoute)) { - return ''; - } - if (this.remotePageState.pendingSessionId.length > 0) { - return this.remotePageState.pendingSessionId; - } - return this.remotePageState.activeSession.sessionId; - } - - private remoteRunningSessionId(): string { - return this.remotePageState.hasRunningActiveTurn() ? this.remotePageState.activeSession.sessionId : ''; - } -} - -@ComponentV2 -export struct AppSettingsSurface { - @Param deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param shellState: AppShellState = new AppShellState(); - @Param remotePageState: RemotePageState = new RemotePageState(); - @Param generalPageState: GeneralChatPageState = new GeneralChatPageState(); - @Param deviceId: string = ''; - @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - - build() { - if (SettingsPagePolicy.resolve(this.shellState.settingsMode === 'account', - this.remotePageState.accountUserId.trim().length > 0) === 'login') { - AccountLoginSheet({ - onClose: this.actions.onSettings.close, - onAccountSettled: this.actions.onSettings.accountSettled, - cloudLogin: this.actions.onSettings.cloudLogin, - cloudCancelLogin: this.actions.onSettings.cloudCancelLogin - }) - } else { - SettingsSheet({ - directoryState: this.deviceDirectoryState, - sheetState: this.shellState.settingsSheet, - accountUsername: this.remotePageState.accountUsername, - accountAvatarUrl: this.remotePageState.accountAvatarUrl, - authenticatedUserId: this.remotePageState.accountUserId, - fallbackUserId: this.remotePageState.userId, - desktopName: this.remotePageState.desktopName, - desktopId: this.remotePageState.desktopId, - deviceId: this.deviceId, - controlTargetType: this.remotePageState.controlTargetType, - controlTargetDeviceId: this.remotePageState.controlTargetDeviceId, - connectionState: this.remotePageState.connectionState, - supportsDeviceModelDefaults: this.remotePageState.supportsHostCapability( - REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1), - statusText: this.remotePageState.conversation.statusText, - onOpenAccount: this.actions.onSettings.openAccount, - onDisconnect: this.actions.onSettings.disconnect, - onClearPairing: this.actions.onSettings.clearPairing, - onReconnect: this.actions.onSettings.reconnect, - cloudLogout: this.actions.onSettings.cloudLogout, - cloudListDevices: this.actions.onSettings.cloudListDevices, - cloudSelectDevice: this.actions.onSettings.cloudSelectDevice, - getPermissionMode: this.actions.onSettings.getPermissionMode, - setPermissionMode: this.actions.onSettings.setPermissionMode, - getDeviceModelCatalog: this.actions.onSettings.getDeviceModelCatalog, - setDeviceModelDefaults: this.actions.onSettings.setDeviceModelDefaults, - onSetLanguage: this.actions.onSettings.setLanguage, - onClose: this.actions.onSettings.close - }) - } - } -} - -@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, - connectionState: this.remotePageState.connectionState, - connectionFailureKind: this.remotePageState.connectionFailureKind, - isBusy: this.remotePageState.conversation.isBusy, - isConnected: this.remotePageState.connectionState === 'connected', - desktopName: this.remotePageState.desktopName, - deviceId: this.deviceId, - accountUserId: this.remotePageState.accountUserId, - controlTargetDeviceId: this.remotePageState.controlTargetDeviceId, - onBack: this.actions.onConnect.back, - onOpenAccount: this.actions.onConnect.openAccount, - onConnect: this.actions.onConnect.connect, - cloudListDevices: this.actions.onConnect.cloudListDevices, - cloudSelectDevice: this.actions.onConnect.cloudSelectDevice - }) - .width('100%') - .height('100%') - } -} 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 deleted file mode 100644 index ae50ff0452..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootPresentation.ets +++ /dev/null @@ -1,655 +0,0 @@ -import { RemoteCompactHomePolicy } from '../policy/RemoteCompactHomePolicy'; -import { MiniAppActions, emptyMiniAppActions } from '../../model/MiniAppModels'; -import { MiniAppState } from '../state/MiniAppState'; -import { MiniAppSurface } from './MiniAppSurface'; -import display from '@ohos.display'; -import mediaQuery from '@ohos.mediaquery'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { AppShell } from './AppShell'; -import { FilePreviewSurface } from './FilePreviewSurface'; -import { PAGE_BG } from './Theme'; -import { AppRoute } from '../navigation/AppRouteContract'; -import { - AppRootPresentationActions, - emptyAppRootPresentationActions -} from '../actions/AppRootPresentationActions'; -import { AppShellState } from '../state/AppShellState'; -import { - ConversationLayoutCrease, - ConversationLayoutHorizontalCrease, - ConversationLayoutPolicy, - ConversationLayoutRect -} from '../policy/ConversationLayoutPolicy'; -import { AdaptiveLayoutInput } from '../policy/AdaptiveLayoutInput'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { AdaptiveSheetOptions } from './AdaptiveSheetOptions'; -import { i18n } from '@kit.LocalizationKit'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { DeviceDirectoryState } from '../state/DeviceDirectoryState'; -import { RemotePageState } from '../state/RemotePageState'; -import { FilePreviewState } from '../state/FilePreviewState'; -import { - FilePreviewLayout, - FilePreviewPlacement, - FilePreviewPlacementPolicy -} from '../policy/FilePreviewPlacementPolicy'; -import { WideLayoutGeometry } from '../layout/WideLayoutGeometry'; -import { ConversationRouteSurface } from './ConversationRouteSurface'; -import { WideConversationHost } from './WideConversationHost'; -import { - AppConnectSurface, - AppSettingsSurface, - AppSidebarSurface -} from './AppRootOverlaySurfaces'; -import { - RemoteSurfaceHost, - RemoteSurfaceMode, - RemoteSurfaceState -} from './remote/RemoteSurfaceHost'; - -function safeFoldStatus(): display.FoldStatus { - try { return display.getFoldStatus(); } catch (_err) { return display.FoldStatus.FOLD_STATUS_UNKNOWN; } -} - -enum WideWorkspacePresentationMode { - Default = 'default', - SidebarCollapsed = 'sidebar_collapsed', - PreviewExpanded = 'preview_expanded' -} - -@ComponentV2 -export struct AppRootPresentation { - @Param miniAppState: MiniAppState = new MiniAppState(); - @Param miniAppActions: MiniAppActions = emptyMiniAppActions(); - @Param shellState: AppShellState = new AppShellState(); - @Param navigationStack: NavPathStack = new NavPathStack(); - @Param remotePageState: RemotePageState = new RemotePageState(); - @Param deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param generalPageState: GeneralChatPageState = new GeneralChatPageState(); - @Param filePreviewState: FilePreviewState = new FilePreviewState(); - @Param deviceId: string = ''; - @Local viewportWidth: number = 0; - @Local viewportHeight: number = 0; - @Local wideLayoutMatched: boolean = false; - @Local foldStatus: display.FoldStatus = safeFoldStatus(); - @Local largeScreenLayout: boolean = false; - @Local wideMasterPaneWidth: number = ConversationLayoutPolicy.FALLBACK_MASTER_PANE_WIDTH; - @Local wideMasterDetailGap: number = 0; - @Local wideDetailContentOffset: number = 0; - @Local wideDetailContentWidth: number = 0; - @Local wideCollapsedDetailContentOffset: number = 0; - @Local wideCollapsedDetailContentWidth: number = 0; - // Every launch starts with the wide sidebar collapsed; the toggle only lasts for this run. - @Local wideWorkspacePresentationMode: WideWorkspacePresentationMode = - WideWorkspacePresentationMode.SidebarCollapsed; - @Local wideMasterPaneMotionActive: boolean = false; - @Local showRemoteViewSettings: boolean = false; - @Local remoteSurfaceState: RemoteSurfaceState = new RemoteSurfaceState(); - @Local settingsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.Settings); - @Local connectPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.Connect); - @Local sessionDetailsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SessionDetails); - @Local remoteViewSettingsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.RemoteViewSettings); - @Local fullTextPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - @Local skillPickerPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SkillPicker); - @Local usageReportPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UsageReport); - private verticalCreases: ConversationLayoutCrease[] = []; - private horizontalCreases: ConversationLayoutHorizontalCrease[] = []; - private wideQueryListener?: mediaQuery.MediaQueryListener; - private foldStatusChanged: (status: display.FoldStatus) => void = - (status: display.FoldStatus): void => { - this.foldStatus = status; - this.refreshWideGeometry(); - }; - private foldDisplayModeChanged: (mode: display.FoldDisplayMode) => void = - (_mode: display.FoldDisplayMode): void => { - this.refreshWideGeometry(); - }; - private wideQueryChanged: (result: mediaQuery.MediaQueryResult) => void = - (result: mediaQuery.MediaQueryResult): void => { - this.wideLayoutMatched = result.matches; - this.refreshWideGeometry(); - }; - @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - - aboutToAppear(): void { - this.bindResponsiveQueries(); - this.bindFoldStatus(); - } - - aboutToDisappear(): void { - this.unbindFoldStatus(); - this.unbindResponsiveQueries(); - } - - @Monitor('filePreviewState.visible') - onFilePreviewVisibilityChanged(): void { - if (!this.filePreviewState.visible && this.isFilePreviewExpanded()) { - this.wideWorkspacePresentationMode = WideWorkspacePresentationMode.Default; - } - } - - build() { - Stack() { - AppShell({ - shellState: this.shellState, - useWideLayout: this.isWideLayout(), - allowSidebar: !this.showWelcomeHome(), - settingsPlacement: this.settingsPlacement, - compactAccountLogin: this.shellState.settingsMode === 'account' && - this.remotePageState.accountUserId.trim().length === 0, - connectPlacement: this.connectPlacement, - content: () => { this.NavigationContent(); }, - sidebar: () => { this.SidebarContent(); }, - settings: () => { this.SettingsContent(); }, - connect: () => { this.ConnectContent(); }, - onCloseSidebar: this.actions.onCloseSidebar - }) - if (this.filePreviewPlacement() === FilePreviewPlacement.CompactFullPage) { - this.FilePreviewPane() - } - } - .width('100%') - .height('100%') - .id(`app-root-locale-${this.shellState.localeRevision}`) - .bindSheet($$this.showRemoteViewSettings, this.RemoteViewSettingsSheet(), this.remoteViewSettingsSheetOptions()) - .onAreaChange((_oldArea: Area, newArea: Area) => { - const areaWidth = this.areaWidth(newArea.width); - const areaHeight = this.areaWidth(newArea.height); - const displaySize = this.currentDisplaySize(); - this.viewportWidth = ConversationLayoutPolicy.resolveLayoutViewportWidth( - areaWidth, - areaHeight, - displaySize[0], - displaySize[1], - displaySize[2] - ); - this.viewportHeight = areaHeight > 0 ? areaHeight : displaySize[1]; - if (this.viewportWidth === Math.max(displaySize[0], displaySize[1]) && - areaWidth !== this.viewportWidth) { - this.viewportHeight = Math.min(displaySize[0], displaySize[1]); - } - this.refreshWideGeometry(); - }) - } - - @Builder - NavigationContent() { - Stack() { - Navigation(this.navigationStack) { this.RouteContent(AppRoute.RemoteHome) } - .id('openbitfunHomeNavigation') - .width('100%').height('100%').hideTitleBar(true) - .mode(NavigationMode.Stack) - .navBarWidth('100%') - .minContentWidth(0) - .navDestination(this.NavigationDestination) - .visibility(this.isWideLayout() ? Visibility.Hidden : Visibility.Visible) - - if (this.isWideLayout()) { - Column() { this.WideRouteContent() } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - - // Sidebar destinations belong to the moving content pane. A root-level - // overlay would cover the drawer before its closing animation can run. - if (this.miniAppState.visible) { - MiniAppSurface({ state: this.miniAppState, actions: this.miniAppActions }) - } - } - .width('100%') - .height('100%') - } - - @Builder - NavigationDestination(name: string) { - NavDestination() { this.RouteContent(name as AppRoute) }.hideTitleBar(true).backgroundColor(PAGE_BG) - .onBackPressed(() => this.actions.onNavigationBack(name as AppRoute)) - } - - /** - * The wide column, and the only place the wide surface is built. The route is - * read here rather than taken as a @Builder parameter: a parameterised - * builder re-evaluates its arguments only when its own body re-runs, so the - * column used to keep whatever route it was first built with and a workspace - * session opened behind a pane that never followed. - */ - @Builder - WideRouteContent() { - if (this.showWelcomeHome()) { - RemoteSurfaceHost({ - mode: RemoteSurfaceMode.Placeholder, - remotePageState: this.remotePageState, - presentationState: this.remoteSurfaceState, - actions: this.actions - }) - } else { - WideConversationHost({ - route: this.shellState.activeRoute, - shellState: this.shellState, - remotePageState: this.remotePageState, - deviceDirectoryState: this.deviceDirectoryState, - generalPageState: this.generalPageState, - filePreviewState: this.filePreviewState, - remoteSurfaceState: this.remoteSurfaceState, - actions: this.actions, - filePreviewLayout: this.filePreviewLayout(), - sessionDetailsPlacement: this.sessionDetailsPlacement, - fullTextSheetPlacement: this.fullTextPlacement, - skillPickerSheetPlacement: this.skillPickerPlacement, - usageReportSheetPlacement: this.usageReportPlacement, - wideMasterPaneWidth: this.wideMasterPaneWidth, - wideMasterDetailGap: this.wideMasterDetailGap, - wideDetailContentOffset: this.wideDetailContentOffset, - wideDetailContentWidth: this.wideDetailContentWidth, - wideCollapsedDetailContentOffset: this.wideCollapsedDetailContentOffset, - wideCollapsedDetailContentWidth: this.wideCollapsedDetailContentWidth, - wideMasterPaneCollapsed: this.wideWorkspacePresentationMode === - WideWorkspacePresentationMode.SidebarCollapsed, - wideMasterPaneMotionActive: this.wideMasterPaneMotionActive, - filePreviewExpanded: this.wideWorkspacePresentationMode === - WideWorkspacePresentationMode.PreviewExpanded, - canToggleFilePreviewExpanded: this.canToggleFilePreviewExpanded(), - onCollapseMasterPane: () => this.collapseWideMasterPane(), - onRestoreMasterPane: () => this.restoreWideMasterPane(), - onToggleFilePreviewExpanded: () => this.toggleFilePreviewExpanded(), - onOpenRemoteViewSettings: () => { this.showRemoteViewSettings = true; } - }) - } - } - - /** - * Navigation content, which is the compact surface only. Wide layout keeps - * the stack for its paths and its back handling but draws the surface in - * WideRouteContent, so building it here too would put an invisible second - * copy behind the visible one — per nav bar, and per pushed destination. - */ - @Builder - RouteContent(route: AppRoute) { - if (!this.isWideLayout()) { - ConversationRouteSurface({ - route, - remotePageState: this.remotePageState, - generalPageState: this.generalPageState, - filePreviewState: this.filePreviewState, - remoteSurfaceState: this.remoteSurfaceState, - actions: this.actions, - showSidebarButton: true, - // Compact conversations own the drawer, not a back control: Local and - // Remote both open the sidebar over the chat instead of leaving it. - showBackButton: false, - hoverOperateMode: this.isHoverLayout(), - fullTextSheetPlacement: this.fullTextPlacement, - skillPickerSheetPlacement: this.skillPickerPlacement, - usageReportSheetPlacement: this.usageReportPlacement, - onRestoreSidebar: () => this.restoreWideMasterPane() - }) - } - } - - @Builder - RemoteViewSettingsSheet() { - RemoteSurfaceHost({ - mode: RemoteSurfaceMode.Settings, - remotePageState: this.remotePageState, - presentationState: this.remoteSurfaceState, - actions: this.actions, - onCloseSettings: () => { this.showRemoteViewSettings = false; } - }) - } - - @Builder - FilePreviewPane(paneWidth: number = 0) { - Column() { - FilePreviewSurface({ - state: this.filePreviewState, - remoteAvailable: RemoteUiState.canUseRemote(this.remotePageState.connectionState), - downloadPath: this.remotePageState.downloadingFilePath, - downloadedPath: this.remotePageState.downloadedFilePath, - downloadStatus: this.remotePageState.fileDownloadStatus, - onClose: this.actions.onFilePreview.close, - onRefresh: this.actions.onFilePreview.refresh, - onDownload: this.actions.onFilePreview.download, - onOpenLink: this.actions.onFilePreview.openLink - }) - } - .layoutWeight(paneWidth > 0 ? 0 : 1) - .width(paneWidth > 0 ? paneWidth : '100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - private showWelcomeHome(): boolean { - return RemoteCompactHomePolicy.shouldShowWelcomeHome(this.remotePageState.controlTargetType, - this.remotePageState.connectionState, this.remotePageState.accountUserId.trim().length > 0); - } - - private isWideLayout(): boolean { - return this.largeScreenLayout; - } - - private collapseWideMasterPane(): void { - if (!this.isWideLayout()) { - return; - } - // Expanded preview borrows the conversation panels while keeping workspace - // navigation visible. Collapsing navigation exits that focus mode first, - // then leaves the regular right-panel preview beside the wider chat. - this.enableWideMasterPaneMotion(); - this.getUIContext().animateTo({ duration: 220, curve: Curve.EaseInOut }, () => { - this.wideWorkspacePresentationMode = WideWorkspacePresentationMode.SidebarCollapsed; - }); - } - - private restoreWideMasterPane(): void { - void this.actions.onSidebar.refreshSessions(); - const previewLayout = this.filePreviewLayout(); - if (WideLayoutGeometry.restoreMasterClosesPreview(previewLayout)) { - // Focus split temporarily borrows the master pane's space. Restoring the - // master therefore dismisses the preview instead of leaving a restore - // control that cannot change the visible layout. - this.actions.onFilePreview.close(); - } - this.enableWideMasterPaneMotion(); - this.getUIContext().animateTo({ duration: 220, curve: Curve.EaseInOut }, () => { - this.wideWorkspacePresentationMode = WideWorkspacePresentationMode.Default; - }); - } - - private enableWideMasterPaneMotion(): void { - this.wideMasterPaneMotionActive = true; - setTimeout(() => { - this.wideMasterPaneMotionActive = false; - }, 240); - } - - private toggleFilePreviewExpanded(): void { - if (!this.canToggleFilePreviewExpanded()) { - return; - } - this.wideWorkspacePresentationMode = this.isFilePreviewExpanded() ? - WideWorkspacePresentationMode.Default : WideWorkspacePresentationMode.PreviewExpanded; - } - - private canToggleFilePreviewExpanded(): boolean { - if (!this.filePreviewState.visible || !this.isWideLayout()) { - return false; - } - const defaultLayout = FilePreviewPlacementPolicy.resolveLayout( - true, - true, - this.viewportWidth, - this.verticalCreases, - this.wideMasterPaneWidth, - false - ); - const expandedLayout = FilePreviewPlacementPolicy.resolveLayout( - true, - true, - this.viewportWidth, - this.verticalCreases, - this.wideMasterPaneWidth, - true - ); - return defaultLayout.placement === FilePreviewPlacement.WideTriplePane && - expandedLayout.placement === FilePreviewPlacement.WideMasterPreviewFocus; - } - - private filePreviewPlacement(): FilePreviewPlacement { - return this.filePreviewLayout().placement; - } - - private filePreviewLayout(): FilePreviewLayout { - return FilePreviewPlacementPolicy.resolveLayout( - this.filePreviewState.visible, - this.isWideLayout(), - this.viewportWidth, - this.verticalCreases, - this.wideMasterPaneWidth, - this.isFilePreviewExpanded() - ); - } - - private isWideMasterPaneCollapsed(): boolean { - return this.wideWorkspacePresentationMode === WideWorkspacePresentationMode.SidebarCollapsed; - } - - private isFilePreviewExpanded(): boolean { - return this.wideWorkspacePresentationMode === WideWorkspacePresentationMode.PreviewExpanded; - } - - private bindResponsiveQueries(): void { - this.unbindResponsiveQueries(); - try { - const appMediaQuery = this.getUIContext().getMediaQuery(); - this.wideQueryListener = appMediaQuery.matchMediaSync( - `screen and (${ConversationLayoutPolicy.MD_MIN_WIDTH} < width)` - ); - this.wideLayoutMatched = this.wideQueryListener.matches; - this.wideQueryListener.on('change', this.wideQueryChanged); - } catch (_err) { - this.wideLayoutMatched = this.viewportWidth >= ConversationLayoutPolicy.WIDE_LAYOUT_MIN_WIDTH; - this.unbindResponsiveQueries(); - } - } - - private bindFoldStatus(): void { - this.unbindFoldStatus(); - try { - this.foldStatus = display.getFoldStatus(); - this.refreshWideGeometry(); - display.on('foldStatusChange', this.foldStatusChanged); - display.on('foldDisplayModeChange', this.foldDisplayModeChanged); - } catch (_err) { - this.foldStatus = display.FoldStatus.FOLD_STATUS_UNKNOWN; - this.unbindFoldStatus(); - } - } - - private unbindFoldStatus(): void { - try { - display.off('foldStatusChange', this.foldStatusChanged); - display.off('foldDisplayModeChange', this.foldDisplayModeChanged); - } catch (_err) { - } - } - - private unbindResponsiveQueries(): void { - if (this.wideQueryListener) { - this.wideQueryListener.off('change', this.wideQueryChanged); - this.wideQueryListener = undefined; - } - } - - private areaWidth(width: Object): number { - return WideLayoutGeometry.areaLength(width); - } - - private refreshWideGeometry(): void { - const wasWideLayout = this.largeScreenLayout; - const creaseRects = this.reportedCreaseRects(); - const reportedVertical = ConversationLayoutPolicy.verticalCreasesFromRects( - this.viewportWidth, - this.viewportHeight, - creaseRects - ); - this.horizontalCreases = ConversationLayoutPolicy.horizontalCreasesFromRects( - this.viewportWidth, - this.viewportHeight, - creaseRects - ); - const verticalCreases = this.currentVerticalCreases(reportedVertical); - this.verticalCreases = verticalCreases; - this.largeScreenLayout = ConversationLayoutPolicy.useMasterDetail( - this.viewportWidth, - this.wideLayoutMatched, - ConversationLayoutPolicy.isFoldedStatus(this.foldStatus), - verticalCreases, - this.isExpandedFoldable(), - this.isHoverLayout() - ); - const geometry = ConversationLayoutPolicy.resolveWideGeometry( - this.viewportWidth, - verticalCreases - ); - this.wideMasterPaneWidth = geometry.masterPaneWidth; - this.wideMasterDetailGap = geometry.masterDetailGap; - this.wideDetailContentOffset = geometry.detailContentOffset; - this.wideDetailContentWidth = geometry.detailContentWidth; - this.wideCollapsedDetailContentOffset = geometry.collapsedDetailContentOffset; - this.wideCollapsedDetailContentWidth = geometry.collapsedDetailContentWidth; - this.refreshSheetPlacements(reportedVertical); - this.actions.onLayoutModeChanged(this.largeScreenLayout); - if (wasWideLayout && !this.largeScreenLayout) { - this.actions.onCompactLayoutEntered(); - } - } - - private refreshSheetPlacements(reportedVertical: ConversationLayoutCrease[]): void { - const input = new AdaptiveLayoutInput( - this.viewportWidth, - this.viewportHeight, - this.foldStatus, - ConversationLayoutPolicy.isFoldedStatus(this.foldStatus), - this.isExpandedFoldable(), - this.isHoverLayout(), - this.wideLayoutMatched, - reportedVertical, - this.horizontalCreases, - this.isRtlLayout() - ); - this.settingsPlacement = SettingsPlacementPolicy.resolve(input, SettingsSheetKind.Settings); - this.connectPlacement = SettingsPlacementPolicy.resolve(input, SettingsSheetKind.Connect); - this.sessionDetailsPlacement = SettingsPlacementPolicy.resolve(input, SettingsSheetKind.SessionDetails); - this.remoteViewSettingsPlacement = SettingsPlacementPolicy.resolve( - input, - SettingsSheetKind.RemoteViewSettings - ); - this.fullTextPlacement = SettingsPlacementPolicy.resolve( - input, - SettingsSheetKind.UserMessageFullText - ); - this.skillPickerPlacement = SettingsPlacementPolicy.resolve(input, SettingsSheetKind.SkillPicker); - this.usageReportPlacement = SettingsPlacementPolicy.resolve(input, SettingsSheetKind.UsageReport); - } - - private isRtlLayout(): boolean { - try { - return i18n.isRTL(RemoteI18n.language()); - } catch (_err) { - return false; - } - } - - private isHoverLayout(): boolean { - return ConversationLayoutPolicy.useHoverOperate( - this.foldStatus, - this.viewportWidth, - this.viewportHeight - ); - } - - private isExpandedFoldable(): boolean { - return ConversationLayoutPolicy.isExpandedFoldableStatus(this.foldStatus) && this.isFoldableDevice(); - } - - private currentDisplaySize(): [number, number, number] { - try { - const metrics = display.getDefaultDisplaySync(); - return [ - this.getUIContext().px2vp(metrics.width), - this.getUIContext().px2vp(metrics.height), - metrics.rotation - ]; - } catch (_err) { - return [0, 0, 0]; - } - } - - private isFoldableDevice(): boolean { - try { - return display.isFoldable(); - } catch (_err) { - return ConversationLayoutPolicy.isExpandedFoldableStatus(this.foldStatus) || - ConversationLayoutPolicy.isFoldedStatus(this.foldStatus); - } - } - - private currentVerticalCreases(reportedVertical: ConversationLayoutCrease[]): ConversationLayoutCrease[] { - if (ConversationLayoutPolicy.isFoldedStatus(this.foldStatus) || this.isHoverLayout()) { - return []; - } - return ConversationLayoutPolicy.effectiveVerticalCreases( - this.viewportWidth, - reportedVertical, - this.isExpandedFoldable() - ); - } - - private reportedCreaseRects(): ConversationLayoutRect[] { - try { - const region = display.getCurrentFoldCreaseRegion(); - const creaseRects = region.creaseRects; - if (!creaseRects) { - return []; - } - return creaseRects.map((rect: display.Rect): ConversationLayoutRect => { - return new ConversationLayoutRect( - this.getUIContext().px2vp(rect.left), - this.getUIContext().px2vp(rect.top), - this.getUIContext().px2vp(rect.width), - this.getUIContext().px2vp(rect.height) - ); - }); - } catch (_err) { - return []; - } - } - - private remoteViewSettingsSheetOptions(): SheetOptions { - return AdaptiveSheetOptions.fromPlacement(this.remoteViewSettingsPlacement, true); - } - - @Builder SidebarContent() { - AppSidebarSurface({ - shellState: this.shellState, - sessionDetailsPlacement: this.sessionDetailsPlacement, - remotePageState: this.remotePageState, - deviceDirectoryState: this.deviceDirectoryState, - generalPageState: this.generalPageState, - remoteSurfaceState: this.remoteSurfaceState, - actions: this.actions, - onOpenRemoteViewSettings: () => { this.showRemoteViewSettings = true; } - }) - } - - @Builder SettingsContent() { - AppSettingsSurface({ - deviceDirectoryState: this.deviceDirectoryState, - shellState: this.shellState, - remotePageState: this.remotePageState, - generalPageState: this.generalPageState, - deviceId: this.deviceId, - actions: this.actions - }) - } - - @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/AppShell.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppShell.ets deleted file mode 100644 index 40e16ac111..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppShell.ets +++ /dev/null @@ -1,258 +0,0 @@ -import { MobileDesignGeometry } from '../../generated/MobileDesignTokens'; -import { AppShellState } from '../state/AppShellState'; -import { ConversationLayoutPolicy } from '../policy/ConversationLayoutPolicy'; -import { - SettingsPlacement, - SettingsPlacementMode, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { AdaptiveSheetOptions } from './AdaptiveSheetOptions'; -import { - PAGE_BG, - SCRIM, - SHELL_SCRIM, - SIDEBAR_BG, - TRANSPARENT, -} from './Theme'; - -const WIDE_SHEET_RADIUS: number = 30; - -@ComponentV2 -export struct AppShell { - @Param shellState: AppShellState = new AppShellState(); - @Param useWideLayout: boolean = false; - @Param allowSidebar: boolean = true; - @Param compactAccountLogin: boolean = false; - @Param settingsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.Settings); - @Param connectPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.Connect); - @BuilderParam content: () => void = this.EmptyBuilder; - @BuilderParam sidebar: () => void = this.EmptyBuilder; - @BuilderParam settings: () => void = this.EmptyBuilder; - @BuilderParam connect: () => void = this.EmptyBuilder; - @Event onCloseSidebar: () => void = () => {}; - @Local shellWidth: number = 440; - - build() { - Stack({ alignContent: Alignment.Start }) { - Column().width(0).height(0) - .bindContentCover(this.shellState.showSettings && this.compactAccountLogin, - this.CompactLoginCover(), { - backgroundColor: TRANSPARENT, - modalTransition: ModalTransition.NONE, - enableSafeArea: true, - onWillDismiss: (action: DismissContentCoverAction): void => { - this.shellState.showSettings = false; - action.dismiss(); - } - }) - - // The open drawer's fill is a floor under the whole shell, not a panel - // the width of the sidebar. The content card's rounded corners have to - // curve onto something: when the fill stopped at the card's left edge - // they curved onto the page white instead, so a square-cornered grey - // block sat against a rounded card with a white wedge between them. - Column() - .width('100%') - .height('100%') - .backgroundColor(SIDEBAR_BG) - // The cutout is an avoid area of its own, so the floor claims it too: a - // notch the framework would otherwise leave bare has to end up under the - // same fill the rest of the window is. The floor is the window itself — - // full width and full height — so it names all four edges. - // `expandSafeArea` is per edge and takes effect only where this - // component's boundary meets that edge's safe-area boundary, so claiming - // the top strip with `TOP` says nothing about the side strip a rotated - // cutout lands on: without `START`/`END` the fill stops at the inset and - // the page colour shows beside it. - .expandSafeArea([SafeAreaType.SYSTEM, SafeAreaType.CUTOUT], - [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM, SafeAreaEdge.START, SafeAreaEdge.END]) - .hitTestBehavior(HitTestMode.None) - .opacity((this.allowSidebar && this.shellState.showSidebar) ? 1 : 0) - // Matched to the content card rather than to the sidebar panel: the - // card must never finish moving before the floor it curves onto has - // finished fading, in either direction. - .animation({ - duration: (this.allowSidebar && this.shellState.showSidebar) ? 320 : 250, - curve: Curve.EaseOut - }) - - Column() { - // The drawer is a compact affordance. Wide layouts put the same session - // list in the master pane instead, and this copy stayed mounted behind - // an opacity of 0 — invisible, but rebuilt on every selection change, - // which on a tablet doubled the cost of switching sessions. Compact - // keeps it mounted so opening and closing still cross-fades. - if (!this.useWideLayout || (this.allowSidebar && this.shellState.showSidebar)) { - this.sidebar() - } - } - .width(this.sidebarWidth()) - .height('100%') - .alignItems(HorizontalAlign.Start) - .opacity((this.allowSidebar && this.shellState.showSidebar) ? 1 : 0) - .translate({ x: (this.allowSidebar && this.shellState.showSidebar) ? '0%' : '-10%' }) - .animation({ - duration: (this.allowSidebar && this.shellState.showSidebar) ? 300 : 220, - curve: Curve.EaseOut - }) - - Stack({ alignContent: Alignment.Start }) { - Column() { - this.content() - } - .width('100%') - .height('100%') - .bindSheet($$this.shellState.showConnectSheet, this.ConnectSheetContent(), this.connectSheetOptions()) - - if ((this.allowSidebar && this.shellState.showSidebar)) { - Column() { - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .opacity(0.62) - .transition(TransitionEffect.opacity(0) - .animation({ duration: 210, curve: Curve.EaseOut })) - .onClick(() => { - this.onCloseSidebar(); - }) - } - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .borderRadius((this.allowSidebar && this.shellState.showSidebar) ? 28 : 0) - .clip(true) - .shadow({ - radius: (this.allowSidebar && this.shellState.showSidebar) ? 34 : 0, - color: (this.allowSidebar && this.shellState.showSidebar) ? SHELL_SCRIM : TRANSPARENT, - offsetX: (this.allowSidebar && this.shellState.showSidebar) ? -10 : 0 - }) - .blur((this.allowSidebar && this.shellState.showSidebar) ? 1.1 : 0) - .scale({ - x: (this.allowSidebar && this.shellState.showSidebar) ? 0.985 : 1, - y: (this.allowSidebar && this.shellState.showSidebar) ? 0.992 : 1, - centerX: '0%', - centerY: MobileDesignGeometry.conversationHeaderHeight / 2 - }) - .translate({ x: (this.allowSidebar && this.shellState.showSidebar) ? this.sidebarWidth() : 0 }) - .animation({ - duration: (this.allowSidebar && this.shellState.showSidebar) ? 320 : 250, - curve: Curve.EaseOut - }) - } - .width('100%') - .height('100%') - .onAreaChange((_oldArea: Area, newArea: Area) => { - this.shellWidth = this.areaLength(newArea.width); - }) - .bindSheet(this.shellState.showSettings && !this.compactAccountLogin, - this.SettingsSheetContent(), this.settingsSheetOptions()) - - } - - @Builder - private CompactLoginCover() { - Stack({ alignContent: Alignment.Bottom }) { - Column().width('100%').height('100%').backgroundColor(SCRIM) - // The scrim is the cover's own background over the whole shell, so a bare - // notch would read as a hole in the dimming: it claims the cutout too. - // Like the floor it is the whole shell, so it names the same four edges: - // a rotated cutout sits on a side edge, and the scrim has to reach it or - // the dimming has a hole in it. - .expandSafeArea([SafeAreaType.SYSTEM, SafeAreaType.CUTOUT], - [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM, SafeAreaEdge.START, SafeAreaEdge.END]) - .onClick(() => { this.shellState.showSettings = false; }) - Scroll() { - Column() { this.settings() } - .width('100%') - } - .width(Math.min(MobileDesignGeometry.loginSheetMaxWidth, - this.shellWidth - 2 * MobileDesignGeometry.loginSheetOuterMargin)) - .scrollBar(BarState.Off) - .backgroundColor(PAGE_BG) - .borderRadius(MobileDesignGeometry.sheetTopRadius) - .clip(true) - // The cover is bound with `enableSafeArea: true`, so the framework already - // ends its page above the navigation bar and this stays the design's own - // float above that edge. - .margin({ bottom: MobileDesignGeometry.loginSheetOuterMargin }) - } - .width('100%') - .height('100%') - } - - @Builder - private SettingsSheetContent() { - Column() { - this.settings() - } - .width('100%') - .height(this.compactAccountLogin ? undefined : '100%') - .borderRadius(this.usesWideSheetChrome(this.settingsPlacement) ? WIDE_SHEET_RADIUS : 0) - .clip(this.usesWideSheetChrome(this.settingsPlacement)) - .shadow({ - radius: this.usesWideSheetChrome(this.settingsPlacement) ? 30 : 0, - color: this.usesWideSheetChrome(this.settingsPlacement) ? SHELL_SCRIM : TRANSPARENT, - offsetY: this.usesWideSheetChrome(this.settingsPlacement) ? 12 : 0 - }) - } - - @Builder - private ConnectSheetContent() { - Column() { - this.connect() - } - .width('100%') - .height('100%') - .borderRadius(this.usesWideSheetChrome(this.connectPlacement) ? WIDE_SHEET_RADIUS : 0) - .clip(this.usesWideSheetChrome(this.connectPlacement)) - .shadow({ - radius: this.usesWideSheetChrome(this.connectPlacement) ? 30 : 0, - color: this.usesWideSheetChrome(this.connectPlacement) ? SHELL_SCRIM : TRANSPARENT, - offsetY: this.usesWideSheetChrome(this.connectPlacement) ? 12 : 0 - }) - } - - private sidebarWidth(): number { - if (this.shellWidth <= 0) { - return 280; - } - if (this.shellWidth < ConversationLayoutPolicy.MD_MIN_WIDTH) { - return Math.min(280, Math.max(220, Math.round(this.shellWidth * 0.68))); - } - return Math.min(420, Math.max(280, Math.round(this.shellWidth * 0.35))); - } - - private settingsSheetOptions(): SheetOptions { - const options = AdaptiveSheetOptions.fromPlacement(this.settingsPlacement); - options.onWillDismiss = (action: DismissSheetAction): void => { - this.shellState.showSettings = false; - action.dismiss(); - }; - return options; - } - - private connectSheetOptions(): SheetOptions { - return AdaptiveSheetOptions.fromPlacement(this.connectPlacement); - } - - private usesWideSheetChrome(placement: SettingsPlacement): boolean { - return placement.mode === SettingsPlacementMode.Side || - placement.mode === SettingsPlacementMode.Center; - } - - private areaLength(value: Object): number { - const parsed = Number.parseFloat(`${value}`); - return Number.isNaN(parsed) ? 0 : parsed; - } - - @Builder - EmptyBuilder() { - Column() { - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppSidebar.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppSidebar.ets deleted file mode 100644 index cf87d8971d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppSidebar.ets +++ /dev/null @@ -1,364 +0,0 @@ -import { SidebarToolsFooter } from './SidebarToolsFooter'; -import { SavedRuntimeConnection } from '../../model/RemoteModels'; -import { WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - CARD, - INK, - SHADOW_FAINT, - SIDEBAR_BG, - SIDEBAR_BG_FADE, - SIDEBAR_HOVER, - SIDEBAR_INK, - SIDEBAR_LINE, - SIDEBAR_RAISED, - SIDEBAR_SUBTLE, - TRANSPARENT, -} from './Theme'; -import { SidebarToggleButton } from './SidebarToggleButton'; -import { SidebarGlyph } from './SidebarGlyphs'; -import { SidebarConnectionActionPolicy } from '../policy/SidebarConnectionActionPolicy'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; - -/** Device and workspace navigation shared by compact and wide controllers. */ -@ComponentV2 -export struct AppSidebar { - @Param connectionState: string = 'idle'; - @Param isBusy: boolean = false; - @Param workspaceKind: string = 'normal'; - @Param workspacePath: string = ''; - @Param controlTargetDeviceId: string = ''; - @Param supportsHarnessProfiles: boolean = false; - @Param toolLocations: SavedRuntimeConnection[] = []; - @Event onWorkspaceTools: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - @Param accountUserId: string = ''; - @Param controlTargetType: string = 'none'; - @Param showCollapseButton: boolean = false; - @Param showViewSettingsButton: boolean = false; - @Param showWorkspaceSection: boolean = false; - @Event onClose: () => void = () => {}; - @Event onOpenMiniApps: () => void = () => {}; - @Event onNewChat: (agentType: string) => void = (_agentType: string) => {}; - @Event onEnterCode: () => void = () => {}; - @Event onCollapse: () => void = () => {}; - @Event onOpenViewSettings: () => void = () => {}; - @Event onSearchQueryChange: (query: string) => void = (_query: string) => {}; - @Event onOpenSettings: () => void = () => {}; - @Event onOpenAccount: () => void = () => {}; - @Local showSearch: boolean = false; - @Local sessionSearchQuery: string = ''; - /** - * The window's own insets, in vp. The panel's fill runs to its bottom edge — - * the screen edge for the compact drawer — and the session rows scroll under - * the navigation indicator, so the strip is the list's own business now. The - * floating footer keeps its distance from that edge itself, which is what - * keeps the buttons above the bar while the rows run under it. The panel's top - * edge is the screen edge too, so the status bar strip is the panel's own - * padding rather than a band the framework reserved for it. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - /** - * The authenticated device/workspace section. - * - * It is a slot rather than a component this file constructs because the - * sidebar has no business knowing about remote state; the host wires it. - */ - @BuilderParam contentSlot: () => void = this.EmptySlot; - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - this.SidebarContent() - } - - @Builder - private SidebarContent() { - Column() { - if (this.shouldShowPrimaryNavigation()) { - this.PrimaryNavigationHeader() - } else { - this.SignedOutHeader() - } - - Stack({ alignContent: Alignment.Bottom }) { - // Device sections own their remote workspace and session rows. - Scroll() { - Column() { - Button({ type: ButtonType.Normal }) { - Row({ space: 14 }) { - Stack({ alignContent: Alignment.Center }) { - SidebarGlyph({ kind: 'apps' }) - }.width(24).height(24) - Text(RemoteI18n.t('miniapp.title')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(SIDEBAR_INK) - Blank() - }.width('100%').alignItems(VerticalAlign.Center) - } - .width('100%').height(48).padding({ left: 4, right: 8 }) - .backgroundColor(TRANSPARENT).borderRadius(12) - .margin({ top: 4, bottom: 8 }).stateEffect(true) - .accessibilityText(RemoteI18n.t('miniapp.title')) - .onClick(() => this.onOpenMiniApps()) - if (this.showWorkspaceSection) { - this.contentSlot() - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - .padding({ bottom: this.scrollTailPadding() }) - } - .width('100%') - .height('100%') - .align(Alignment.TopStart) - .scrollable(ScrollDirection.Vertical) - .scrollBar(BarState.Off) - - // Pre-connection actions form a conventional footer and retain a fade. - // Once either account or QR access unlocks the workspace, navigation - // uses two floating controls and the scroll stays visible behind them. - // The fade stops above the navigation bar with the controls it serves, - // so the rows it does not cover stay readable in the strip below it. - if (!this.shouldShowPrimaryNavigation()) { - Column() - .width('100%') - .height(this.usesCompactFooter() ? 92 : 120) - .hitTestBehavior(HitTestMode.None) - .linearGradient({ - angle: 180, - colors: [[SIDEBAR_BG_FADE, 0.0], [SIDEBAR_BG, 0.62]] - }) - .margin({ bottom: this.footerBottomPadding() }) - } - - if (this.shouldShowPrimaryNavigation()) { - this.PrimaryNavigationFooter() - } else { - this.SignedOutFooter() - } - } - .width('100%') - .layoutWeight(1) - } - .width('100%') - .height('100%') - // The panel's fill runs to its own bottom edge — the screen edge for the - // compact drawer, the wide master pane's card edge in the wide host — and - // the session rows are content that scrolls under the navigation indicator. - // The footer, its fade and the list's tail are what keep the strip clear, - // each against the edge this panel actually has. - // - // The panel's top edge is the screen edge in both hosts, so its own first - // row is what has to keep clear of the status bar: the fill still reaches - // the top of the window, and the title, the search field and the session - // rows start below the strip. - // - // Its side edges are the screen's too, and a rotated device moves the camera - // cutout onto one of them: the wider of the design's gutter and the cutout - // is what the panel reserves, so the 20 the design asks for survives on a - // device that claims no side strip at all. - .padding({ left: this.insets.leftPadding(20), right: this.insets.rightPadding(20), top: this.insets.top }) - .backgroundColor(SIDEBAR_BG) - } - - @Builder - private EmptySlot() { - } - - @Builder - private PrimaryNavigationHeader() { - Row() { - Text(RemoteI18n.t('app.title')) - .fontSize(MobileDesignTypography.headlineMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(SIDEBAR_INK) - Blank() - // Right-aligned so the search and collapse controls keep the same - // position whether or not the source-specific view-settings entry shows. - Row({ space: 6 }) { - if (this.showViewSettingsButton) { - Button() { - SidebarGlyph({ kind: 'session_more' }) - } - .width(MobileDesignGeometry.controlTouchSize) - .height(MobileDesignGeometry.controlTouchSize) - .padding(0) - .backgroundColor(TRANSPARENT) - .borderRadius(12) - .stateEffect(true) - .accessibilityText(RemoteI18n.t('remote.actions')) - .onClick(() => { - this.onOpenViewSettings(); - }) - } - - Button() { - SidebarGlyph({ kind: 'search' }) - } - .width(44) - .height(44) - .padding(0) - .backgroundColor(SIDEBAR_RAISED) - .border({ width: 0.5, color: SIDEBAR_LINE }) - .borderRadius(22) - .shadow({ radius: 18, color: SHADOW_FAINT, offsetY: 5 }) - .stateEffect(true) - .accessibilityText(RemoteI18n.t('common.search')) - .onClick(() => { - this.showSearch = !this.showSearch; - if (!this.showSearch) { - this.updateSearchQuery(''); - } - }) - - if (this.showCollapseButton) { - SidebarToggleButton({ - controlSize: MobileDesignGeometry.controlTouchSize, - onToggle: this.onCollapse - }) - } - } - } - .width('100%') - .height(MobileDesignGeometry.conversationHeaderHeight) - .alignItems(VerticalAlign.Center) - - if (this.showSearch) { - TextInput({ placeholder: RemoteI18n.t('sidebar.searchPlaceholder'), text: this.sessionSearchQuery }) - .width('100%') - .height(42) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(SIDEBAR_INK) - .placeholderColor(SIDEBAR_SUBTLE) - .padding(0) - .backgroundColor(SIDEBAR_HOVER) - .borderRadius(8) - .margin({ top: 12 }) - .onChange((value: string) => { - this.updateSearchQuery(value); - }) - } - } - - private updateSearchQuery(value: string): void { - this.sessionSearchQuery = value; - this.onSearchQueryChange(value); - } - - @Builder - private SignedOutHeader() { - Row() { - Row({ space: 14 }) { - SymbolGlyph($r('sys.symbol.desktop')) - .fontSize(23) - .fontColor([SIDEBAR_INK]) - .width(24) - .height(24) - Text(RemoteI18n.t('sidebar.devices')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(SIDEBAR_INK) - } - .layoutWeight(1) - .height(50) - .alignItems(VerticalAlign.Center) - .onClick(() => { - this.onEnterCode(); - }) - - if (this.showCollapseButton) { - SidebarToggleButton({ - controlSize: MobileDesignGeometry.controlTouchSize, - onToggle: this.onCollapse - }) - } - } - .width('100%') - .height(50) - .alignItems(VerticalAlign.Center) - } - - @Builder - private PrimaryNavigationFooter() { - SidebarToolsFooter({ - toolsEnabled: this.connectionState === 'connected', - onOpenTools: () => this.requestDeviceTools(), - onOpenSettings: () => this.onOpenSettings() - }) - .margin({ bottom: this.footerBottomPadding() }) - } - - @Builder - private SignedOutFooter() { - Column({ space: 8 }) { - Button() { - Text(RemoteI18n.t('sidebar.signInOpenBitFunAccount')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Bold) - .fontColor(CARD) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Clip }) - } - .width('100%') - .height(48) - .padding(0) - .backgroundColor(INK) - .borderRadius(16) - .onClick(() => { - this.onOpenAccount(); - }) - } - .width('100%') - .margin({ bottom: this.footerBottomPadding() }) - .zIndex(2) - } - - private requestDeviceTools(): void { - if (this.connectionState !== 'connected') return; - this.onWorkspaceTools({ type: 'open-device', deviceId: this.controlTargetDeviceId, connectionId: '', tab: 0 }); - } - - private shouldShowPrimaryNavigation(): boolean { - return SidebarConnectionActionPolicy.shouldShowPrimaryNavigation( - this.accountUserId, - this.controlTargetType, - this.connectionState - ); - } - - private usesCompactFooter(): boolean { - return this.shouldShowPrimaryNavigation() || this.connectionState === 'connected'; - } - - /** - * The distance the floating footer and its fade keep from the panel's own - * bottom edge: the design's spacing where the strip is already clear of it, - * the strip itself where it is not. In the compact drawer that edge is the - * screen edge, so the buttons sit directly above the navigation bar; in the - * wide master pane the edge is the floating card's, and the same number - * keeps the buttons clear of the bar there too. - */ - private footerBottomPadding(): number { - return this.insets.bottomPadding(16); - } - - /** - * The session list's tail spacer: the floating footer's clearance plus the - * strip. The rows roll under the footer and the navigation indicator while - * they are moving, and the last row still rests above the bar. - */ - private scrollTailPadding(): number { - return (this.usesCompactFooter() ? 84 : 120) + this.insets.bottom; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/BrandMark.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/BrandMark.ets deleted file mode 100644 index 794b512be3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/BrandMark.ets +++ /dev/null @@ -1,12 +0,0 @@ -import { TemplateIcon } from './TemplateIcon'; - -/** The same contour mark used by the desktop splash, tinted for both themes. */ -@ComponentV2 -export struct BrandMark { - @Param markSize: number = 96; - - build() { - TemplateIcon({ src: $r('app.media.openbitfun_brand_mark'), iconWidth: this.markSize, iconHeight: this.markSize }) - .accessibilityLevel('no') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets deleted file mode 100644 index 0f48a6db0d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageBubble.ets +++ /dev/null @@ -1,840 +0,0 @@ -import { InteractionMailboxState } from '../../model/InteractionMailbox'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { ConversationUiImage, ConversationUiMessage, ConversationUiMessageItem, ConversationUiQuestionAnswer, ConversationUiToolStatus } from '../state/ConversationUiModels'; -import { MessageCopyScope } from '../actions/ConversationIntent'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ActivityGroupPolicy, ActivityThinkingPart } from '../policy/ActivityGroupPolicy'; -import { ChatMessageStructurePolicy, StructuredRenderGroup } from '../policy/ChatMessageStructurePolicy'; -import { AssistantProcessLayoutPolicy } from '../policy/AssistantProcessLayoutPolicy'; -import { ConversationMessageRenderPolicy } from '../policy/ConversationMessageRenderPolicy'; -import { ThinkingPresentationPolicy } from '../policy/ThinkingPresentationPolicy'; -import { SubagentBranchExpansionState } from '../state/SubagentBranchExpansionState'; -import { ACCENT, INK, LINE, STATUS_DANGER } from './Theme'; -import { MessageBodyMarkdown, MessageFileCards, MessageImageGallery, MessageMarkdown } from './ChatMessageContent'; -import { - AssistantMessageCopyAction, - ChatMessageRetryAction, - ChatMessageTimestamp, - ChatTypingDots, - ChatUserMessageBubble -} from './ChatMessageChrome'; -import { SubagentTaskCard } from './SubagentTaskCard'; -import { ThinkingBlock } from './ThinkingBlock'; -import { ToolStatusList } from './ToolStatusList'; -import { MessageFileReference, MessageFileReferenceProjectionCache } from '../policy/MessageFileReferenceProjector'; - -class MessageTextBuilderParams { - text: string = ''; - active: boolean = false; - streamKey: string = ''; - renderRevision: number = 0; -} - -@ReusableV2 -@ComponentV2 -export struct ChatUserMessageRow { - @Param item: ConversationUiMessage = { - id: '', - role: 'user', - text: '', - status: '', - detail: '' - }; - @Param showRetryAction: boolean = false; - /** Whether the staged rollback's preview covers this row. See ChatTimeline. */ - @Param ghost: boolean = false; - @Event onCopyMessage: (text: string) => void = (_text: string) => {}; - @Event onOpenFullText: (text: string, turnId: string) => void = - (_text: string, _turnId: string) => {}; - @Event onRetryMessage: (text: string) => void = (_text: string) => {}; - @Event onRollbackMessage: (turnId: string, text: string) => void = - (_turnId: string, _text: string) => {}; - - build() { - ChatUserMessageBubble({ - item: this.item, - showRetryAction: this.showRetryAction, - ghost: this.ghost, - onCopyMessage: this.onCopyMessage, - onOpenFullText: this.onOpenFullText, - onRetryMessage: this.onRetryMessage, - onRollbackMessage: this.onRollbackMessage - }) - } -} - -@ReusableV2 -@ComponentV2 -export struct ChatMessageBubble { - @Param interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - @Param item: ConversationUiMessage = { - id: '', - role: 'assistant', - text: '', - status: '', - detail: '' - }; - @Param renderRevision: number = 0; - @Param isStreaming: boolean = false; - @Param isFinalizing: boolean = false; - @Param showRetryAction: boolean = false; - @Param isBusy: boolean = false; - @Param downloadingFilePath: string = ''; - @Param downloadedFilePath: string = ''; - @Param fileDownloadStatus: string = ''; - @Param activeFilePreviewPath: string = ''; - @Param activeFilePreviewLoading: boolean = false; - @Event onApproveTool: (toolId: string, updatedInput?: Object) => void = - (_toolId: string, _updatedInput?: Object) => {}; - @Event onRejectTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onCancelTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => void = - (_toolId: string, _answers: ConversationUiQuestionAnswer) => {}; - @Event onCopyMessage: (text: string) => void = (_text: string) => {}; - @Event onCopyMessageScoped: (text: string, scope: MessageCopyScope) => void = - (_text: string, _scope: MessageCopyScope) => {}; - @Event onOpenFullText: (text: string, turnId: string) => void = - (_text: string, _turnId: string) => {}; - /** - * The rollback entry, forwarded for the user-authored bubbles this row draws. - * - * A steering message is drawn with the user bubble, so it carries the entry - * too. It has no turn of its own, which is why the entry is wired rather than - * hidden: the tap reaches the pane and is answered out loud, instead of a menu - * item that silently does nothing. - */ - @Event onRollbackMessage: (turnId: string, text: string) => void = - (_turnId: string, _text: string) => {}; - @Event onRetryMessage: (text: string) => void = (_text: string) => {}; - @Event onOpenFilePreview: (path: string, label: string) => void = (_path: string, _label: string) => {}; - @Event onBuildPlan: (path: string, name: string) => void = (_path: string, _name: string) => {}; - @Event onDownloadFile: (path: string) => void = (_path: string) => {}; - /** - * Disclosure of the delegation cards in this message, owned by the - * conversation: the row and the structured subtree under it are rebuilt - * whenever the turn is republished, and disclosure has to outlive that. - */ - @Param subagentBranches: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - /** Raised when the reader opens a delegation card, so its worker is followed. */ - @Event onBranchExpanded: (branchId: string) => void = (_branchId: string) => {}; - private readonly fileReferenceCache: MessageFileReferenceProjectionCache = - new MessageFileReferenceProjectionCache(); - - build() { - this.AssistantBubble() - } - - /** - * The Task branch as the transcript currently holds it. - * - * The structured ForEach that draws the card is keyed by the branch view key, - * which deliberately does not change while the subagent publishes steps, so its - * item builder keeps the entry it captured — the empty one a Task has before - * its subagent starts. Param expressions are re-evaluated on every render, so - * the branch is re-read from the observed message here, and a step that arrives - * later reaches the card without recreating it or closing it. - * - * Known limits. A branch nested inside another branch's child items resolves - * only through its captured entry: the lookup scans the top-level transcript, - * and today's wire publishes subagent records flat, so that shape is not - * reachable yet. The lookup also runs once per card param — title, status and - * items — which is bounded by the few branches a turn can draw. - */ - private currentSubagentBranch(entry: ConversationUiMessageItem, path: string): ConversationUiMessageItem { - return ChatMessageStructurePolicy.subagentBranchAt( - this.structuredProcessItems(this.item.items || []), - ChatMessageStructurePolicy.subagentOrdinal(path), - entry.tool?.id || '' - ) || entry; - } - - @Builder - AssistantBubble() { - Row() { - Column({ space: 10 }) { - if (this.shouldRenderFinalOnly(this.item)) { - this.FinalContent() - } else { - this.ProcessContent() - } - if (this.item.images && this.item.images.length > 0) { - this.MessageImages(this.item.images) - } - if (this.isFailedAssistant(this.item) && (this.item.error || '').trim().length > 0) { - this.AssistantFailure( - this.item.error || '', - this.showRetryAction ? (this.item.detail || '') : '' - ) - } - ChatMessageTimestamp({ timestamp: this.item.timestamp || '' }) - this.ActionRow() - } - .layoutWeight(1) - .padding({ right: 2 }) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .alignItems(VerticalAlign.Top) - .padding({ top: 2, bottom: 2 }) - } - - /** - * The assistant message's bottom action row: retry and copy side by side, in - * the frozen design's order. - * - * Both occupants are optional and the row disappears when neither applies. - * Retry keeps the exact condition the previous `else if` used — including its - * exclusion by the errored branch above, which draws its own retry action — - * so moving it into this row changes no failed-state behavior. Copy is drawn - * only after the assistant turn has settled; streamed text is not an export - * target while it is still changing. - */ - @Builder - ActionRow() { - if (this.showsRetryAction() || this.canCopyAssistantText()) { - Row({ space: 10 }) { - if (this.showsRetryAction()) { - ChatMessageRetryAction({ - assistant: true, - retryText: this.item.detail || '', - onRetry: this.onRetryMessage - }) - } - if (this.canCopyAssistantText()) { - AssistantMessageCopyAction({ - source: this.copySourceText(), - onCopyScoped: this.onCopyMessageScoped - }) - } - } - .alignItems(VerticalAlign.Center) - } - } - - private showsRetryAction(): boolean { - if (this.isFailedAssistant(this.item) && (this.item.error || '').trim().length > 0) { - return false; - } - return this.item.status === 'failed' && this.showRetryAction && - (this.item.detail || '').trim().length > 0; - } - - @Builder - AssistantFailure(errorText: string, retryText: string) { - Column({ space: 6 }) { - Text(RemoteI18n.t('chat.responseFailed')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(STATUS_DANGER) - Text(errorText.trim()) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(INK) - if (retryText.trim().length > 0) { - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(ACCENT) - .height(28) - .padding({ right: 10 }) - .onClick(() => this.onRetryMessage(retryText)) - } - } - .width('100%') - .padding({ left: 12, top: 2, bottom: 2 }) - .border({ width: { left: 2 }, color: STATUS_DANGER }) - .alignItems(HorizontalAlign.Start) - } - - @Builder - FinalContent() { - this.MessageText({ - text: this.finalMessageText(this.item), - active: false, - streamKey: `${this.item.id}-final`, - renderRevision: this.renderRevision - }) - if (this.fileReferences(this.finalMessageText(this.item)).length > 0) { - this.FileCards(this.finalMessageText(this.item)) - } - } - - @Builder - ProcessContent() { - if (this.leadingThinkingText(this.item).length > 0) { - this.Thinking( - this.leadingThinkingText(this.item), - this.leadingThinkingStatus(this.item), - `${this.item.id}-thinking`, - ThinkingPresentationPolicy.isRunning(this.leadingThinkingStatus(this.item)) - ) - } - if (this.shouldRenderStructuredItems(this.item)) { - // Read the observed message here. Passing its plain items array through - // an @Builder parameter freezes the first tool-only snapshot on current - // ArkUI builds, even though the retained message row itself keeps - // receiving revisions. - ForEach([ - this.structuredRenderKey(this.structuredProcessItems(this.item.items || [])) - ], (_frameKey: string) => { - Column({ space: 10 }) { - ForEach( - this.structuredGroups(this.structuredProcessItems(this.item.items || []), 'item'), - (group: StructuredRenderGroup) => { - this.StructuredGroup(group, this.shouldOmitStructuredThinking(this.item)) - }, - (group: StructuredRenderGroup) => group.key - ) - } - .width('100%') - }, (frameKey: string) => frameKey) - if (this.uncoveredTools(this.item).length > 0) { - this.Tools(this.uncoveredTools(this.item)) - } - if (this.trailingStructuredText(this.item).length > 0) { - // Keep the growing answer outside the keyed structured ForEach. The - // latter intentionally rebuilds entries whose content hash changes, - // which turns a streamed answer into a sequence of static snapshots. - MessageBodyMarkdown({ - text: this.trailingStructuredText(this.item), - renderRevision: this.renderRevision, - active: this.isStreamingAssistant(), - streamKey: `${this.item.id}-trailing-body`, - onCopyText: this.onCopyMessage, - onOpenLink: this.onOpenFilePreview - }) - if (this.fileReferences(this.trailingStructuredText(this.item)).length > 0) { - this.FileCards(this.trailingStructuredText(this.item)) - } - } - } else { - if (this.item.tools && this.item.tools.length > 0) { - this.Tools(this.item.tools) - } - if (this.shouldShowTypingDots(this.item)) { - ChatTypingDots() - } - if (this.item.role !== 'user' && this.visibleMessageText(this.item).length > 0 && - this.visibleMessageText(this.item) !== this.item.thinking) { - MessageBodyMarkdown({ - text: this.item.text, - renderRevision: this.renderRevision, - active: this.isStreamingAssistant(), - streamKey: `${this.item.id}-body`, - onCopyText: this.onCopyMessage, - onOpenLink: this.onOpenFilePreview - }) - if (this.fileReferences(this.visibleMessageText(this.item)).length > 0) { - this.FileCards(this.visibleMessageText(this.item)) - } - } - } - if (this.pinnedThinkingText(this.item).length > 0) { - this.Thinking( - this.pinnedThinkingText(this.item), - this.item.status, - `${this.item.id}-pinned-thinking`, - this.isStreamingAssistant() - ) - } - } - - @Builder - StructuredGroup(group: StructuredRenderGroup, omitActiveThinking: boolean = false) { - if (group.type === 'activity_group') { - this.ActivityGroup(group, omitActiveThinking) - } else if (group.type === 'tool_group') { - this.Tools(group.tools) - if (group.items.length > 0) { - ForEach(group.items, (entry: ConversationUiMessageItem, index: number) => { - this.StructuredItem( - entry, - `${group.path}-adjacent-${index}`, - group.itemStatuses[index] || '', - group.itemStreaming[index] || false, - group.itemChildActiveScopes[index] || false - ) - }, (entry: ConversationUiMessageItem, index: number) => { - return ChatMessageStructurePolicy.structuredItemKey(entry, `${group.path}-adjacent-${index}`); - }) - } - } else if (group.items.length > 0) { - if (!omitActiveThinking || !this.isThinkingEntry(group.items[0])) { - this.StructuredItem( - group.items[0], - group.path, - group.itemStatuses[0] || '', - group.itemStreaming[0] || false, - group.itemChildActiveScopes[0] || false - ) - } - } - } - - @Builder - ActivityGroup(group: StructuredRenderGroup, omitActiveThinking: boolean = false) { - Column({ space: 6 }) { - if (this.activityGroupTools(group).length > 0) { - // Reasoning and the tools it drove are one stretch of work, so they fold - // behind a single summary row instead of stacking two cards. - this.Tools( - this.activityGroupTools(group), - omitActiveThinking ? [] : this.activityThinkingParts(group) - ) - } else if (!omitActiveThinking && - ActivityGroupPolicy.thinkingHeaderCount(this.activityThinkingCount(group)) > 0 && - (this.activityThinkingText(group).length > 0 || this.activityThinkingStreaming(group))) { - this.Thinking( - this.activityThinkingText(group), - this.activityThinkingStatus(group), - `${this.item.id}-${group.path}-activity-thinking`, - this.activityThinkingStreaming(group) - ) - } - } - .width('100%') - } - - @Builder - StructuredItem( - entry: ConversationUiMessageItem, - path: string, - statusOverride: string = '', - streaming: boolean = false, - childActiveScope: boolean = false - ) { - if (this.isSubagentEntry(entry)) { - this.SubagentGroup(entry, path, childActiveScope) - } else { - if (this.isUserSteeringEntry(entry)) { - ChatUserMessageBubble({ - item: this.steeringMessage(entry, path), - showRetryAction: false, - onCopyMessage: this.onCopyMessage, - onOpenFullText: this.onOpenFullText, - onRollbackMessage: this.onRollbackMessage - }) - } else if (this.isThinkingEntry(entry)) { - this.Thinking( - entry.content || '', - statusOverride || this.item.status, - `${this.item.id}-${path}-thinking`, - streaming - ) - } else if (this.isTextEntry(entry)) { - this.MessageText({ - text: entry.content || '', - active: streaming, - streamKey: `${this.item.id}-${path}-text`, - renderRevision: this.renderRevision - }) - if (this.fileReferences(entry.content || '').length > 0) { - this.FileCards(entry.content || '') - } - } else if (entry.tool) { - this.Tools([entry.tool]) - } - if (entry.subItems && entry.subItems.length > 0) { - this.ChildItems(entry.subItems, path, childActiveScope) - } - } - } - - @Builder - SubagentGroup(entry: ConversationUiMessageItem, path: string, activeScope: boolean = false) { - SubagentTaskCard({ - interactionMailbox: this.interactionMailbox, - title: this.subagentTitle(this.currentSubagentBranch(entry, path)), - path: path, - branchId: entry.tool?.id || '', - status: this.currentSubagentBranch(entry, path).tool?.status || - (activeScope ? 'running' : 'completed'), - items: this.currentSubagentBranch(entry, path).subItems || [], - expansion: this.subagentBranches, - renderRevision: this.renderRevision, - onBranchExpanded: this.onBranchExpanded, - onApproveTool: this.onApproveTool, - onRejectTool: this.onRejectTool, - onCancelTool: this.onCancelTool, - onAnswerQuestion: this.onAnswerQuestion, - onOpenFilePreview: this.onOpenFilePreview, - onBuildPlan: this.onBuildPlan - }) - } - - @Builder - ChildItems(items: ConversationUiMessageItem[], parentPath: string, activeScope: boolean = false) { - Column({ space: 8 }) { - ForEach(this.structuredGroups(items, parentPath, activeScope), (group: StructuredRenderGroup) => { - this.StructuredGroup(group) - }, (group: StructuredRenderGroup) => group.key) - } - .width('100%') - .padding({ left: 12 }) - .border({ width: { left: 1 }, color: LINE }) - } - - @Builder - Thinking(text: string, status: string, streamKey: string = '', streaming: boolean = false) { - ThinkingBlock({ - text, - status, - keepExpandedWhenDone: false, - streaming, - streamKey - }) - } - - @Builder - Tools(tools: ConversationUiToolStatus[], thinkingParts: ActivityThinkingPart[] = []) { - ToolStatusList({ - interactionMailbox: this.interactionMailbox, - tools, - thinkingParts, - renderRevision: this.renderRevision, - isBusy: this.isBusy, - onApproveTool: (toolId: string, updatedInput?: Object) => { - this.onApproveTool(toolId, updatedInput); - }, - onRejectTool: (toolId: string) => { - this.onRejectTool(toolId); - }, - onCancelTool: (toolId: string) => { - this.onCancelTool(toolId); - }, - onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => { - this.onAnswerQuestion(toolId, answers); - }, - onOpenFilePreview: (path: string, label: string) => { - this.onOpenFilePreview(path, label); - }, - onBuildPlan: (path: string, name: string) => { - this.onBuildPlan(path, name); - } - }) - } - - @Builder - MessageImages(images: ConversationUiImage[]) { - MessageImageGallery({ images }) - } - - @Builder - MessageText($$: MessageTextBuilderParams) { - MessageMarkdown({ - text: $$.text, - renderRevision: $$.renderRevision, - active: $$.active, - streamKey: $$.streamKey, - onCopyText: this.onCopyMessage, - onOpenLink: this.onOpenFilePreview - }) - } - - @Builder - FileCards(text: string) { - MessageFileCards({ - text, - downloadingFilePath: this.downloadingFilePath, - downloadedFilePath: this.downloadedFilePath, - fileDownloadStatus: this.fileDownloadStatus, - activeFilePreviewPath: this.activeFilePreviewPath, - activeFilePreviewLoading: this.activeFilePreviewLoading, - onPreview: this.onOpenFilePreview, - onDownload: this.onDownloadFile - }) - } - - private fileReferences(text: string): MessageFileReference[] { - return this.fileReferenceCache.referencesFor(text); - } - - private visibleMessageText(item: ConversationUiMessage): string { - return ConversationMessageRenderPolicy.visibleText(item.text); - } - - private shouldShowTypingDots(item: ConversationUiMessage): boolean { - if (item.role === 'user' || (item.status || '').toLowerCase() !== 'active') { - return false; - } - return this.visibleMessageText(item).length === 0 && - (!item.thinking || item.thinking.trim().length === 0) && - (!item.tools || item.tools.length === 0); - } - - private isStreamingAssistant(): boolean { - return this.item.role !== 'user' && - (this.isStreaming || (this.item.status || '').toLowerCase() === 'active'); - } - - private shouldRenderStructuredItems(item: ConversationUiMessage): boolean { - if (item.role === 'user' || !item.items || item.items.length === 0) { - return false; - } - return ChatMessageStructurePolicy.requiresStructuredRendering(item.items); - } - - private uncoveredTools(item: ConversationUiMessage): ConversationUiToolStatus[] { - return this.toolsNotCoveredByItems(item.tools || [], item.items || []); - } - - private structuredProcessItems(items: ConversationUiMessageItem[]): ConversationUiMessageItem[] { - return ChatMessageStructurePolicy.withoutTrailingTopLevelText(items); - } - - private trailingStructuredText(item: ConversationUiMessage): string { - return ChatMessageStructurePolicy.trailingTopLevelText(item.items || []); - } - - private shouldPinThinkingToBottom(item: ConversationUiMessage): boolean { - return AssistantProcessLayoutPolicy.pinsThinkingAfterTools() && - this.isStreamingAssistant() && - this.currentThinkingText(item).length > 0; - } - - private pinnedThinkingText(item: ConversationUiMessage): string { - if (!this.shouldPinThinkingToBottom(item)) { - return ''; - } - return this.currentThinkingText(item); - } - - private leadingThinkingText(item: ConversationUiMessage): string { - if (this.shouldPinThinkingToBottom(item)) { - return ''; - } - if (this.lastThinkingText(item.items || []).length > 0) { - return ''; - } - return (item.thinking || '').trim(); - } - - private leadingThinkingStatus(item: ConversationUiMessage): string { - return ThinkingPresentationPolicy.liveThinkingStatus( - item.status, - this.hasLaterProcessOutput(item) - ); - } - - private hasLaterProcessOutput(item: ConversationUiMessage): boolean { - if (item.tools && item.tools.length > 0) { - return true; - } - const visible = this.visibleMessageText(item); - if (visible.length > 0 && visible !== (item.thinking || '').trim()) { - return true; - } - return this.hasToolOrTextItems(item.items || []); - } - - private hasToolOrTextItems(items: ConversationUiMessageItem[]): boolean { - return items.some((entry: ConversationUiMessageItem) => { - if (entry.tool || this.isTextEntry(entry)) { - return true; - } - return !!entry.subItems && this.hasToolOrTextItems(entry.subItems); - }); - } - - private shouldOmitStructuredThinking(_item: ConversationUiMessage): boolean { - return AssistantProcessLayoutPolicy.omitsInFlowThinkingWhileStreaming(); - } - - private currentThinkingText(item: ConversationUiMessage): string { - const structured = this.lastThinkingText(item.items || []); - if (structured.length > 0) { - return structured; - } - return (item.thinking || '').trim(); - } - - private lastThinkingText(items: ConversationUiMessageItem[]): string { - for (let index = items.length - 1; index >= 0; index--) { - const entry = items[index]; - if (this.isThinkingEntry(entry)) { - return (entry.content || '').trim(); - } - if (!this.isSubagentEntry(entry) && entry.subItems) { - const childText = this.lastThinkingText(entry.subItems); - if (childText.length > 0) { - return childText; - } - } - } - return ''; - } - - private shouldRenderFinalOnly(item: ConversationUiMessage): boolean { - if (item.role === 'user') { - return false; - } - if (this.shouldRenderStructuredItems(item)) { - return false; - } - if (!this.isFinishedAssistant(item)) { - return false; - } - return this.finalMessageText(item).length > 0; - } - - private isFinishedAssistant(item: ConversationUiMessage): boolean { - const status = (item.status || '').toLowerCase(); - return status === 'done' || - status === 'completed' || - status === 'success' || - status === 'sent' || - status.length === 0; - } - - private isFailedAssistant(item: ConversationUiMessage): boolean { - return item.role !== 'user' && (item.status || '').toLowerCase() === 'failed'; - } - - /** - * The message body the copy entries act on. - * - * Deliberately the same gathering the bubble already draws from, rather than - * a second reading of `items`: a structured turn's raw Markdown lives in its - * trailing top-level text entry, and a copy path that re-derived it would - * drift from what the user is looking at. - */ - private copySourceText(): string { - return this.finalMessageText(this.item); - } - - private canCopyAssistantText(): boolean { - return ConversationMessageRenderPolicy.canCopyAssistant( - this.item, - this.isStreamingAssistant(), - this.isFinalizing, - this.copySourceText().length - ); - } - - private finalMessageText(item: ConversationUiMessage): string { - const structuredText = this.lastTopLevelText(item.items || []); - if (structuredText.length > 0) { - return structuredText; - } - const visible = this.visibleMessageText(item); - if (visible.length > 0 && visible !== (item.thinking || '').trim()) { - return visible; - } - return ''; - } - - private lastTopLevelText(items: ConversationUiMessageItem[]): string { - for (let index = items.length - 1; index >= 0; index--) { - if (this.isMainTextEntry(items[index])) { - const text = (items[index].content || '').trim(); - if (text.length > 0) { - return text; - } - } - } - return ''; - } - - private hasVisibleProcessAttention(item: ConversationUiMessage): boolean { - return ChatMessageStructurePolicy.hasAttentionTools(item.tools || []) || - ChatMessageStructurePolicy.hasAttentionItems(item.items || []); - } - - private structuredGroups( - items: ConversationUiMessageItem[], - prefix: string, - activeScope: boolean = this.isStreamingAssistant() - ): StructuredRenderGroup[] { - return ChatMessageStructurePolicy.structuredGroups( - items, - prefix, - activeScope, - this.item.status || 'active' - ); - } - - private structuredRenderKey(items: ConversationUiMessageItem[]): string { - return ChatMessageStructurePolicy.structuredRenderKey( - items, - 'item', - this.isStreamingAssistant(), - this.item.status || 'active' - ); - } - - private activityGroupTools(group: StructuredRenderGroup): ConversationUiToolStatus[] { - return ChatMessageStructurePolicy.activityGroupTools(group); - } - - private activityThinkingParts(group: StructuredRenderGroup): ActivityThinkingPart[] { - return ChatMessageStructurePolicy.activityThinkingParts(group, this.item.id); - } - - private activityThinkingCount(group: StructuredRenderGroup): number { - return ChatMessageStructurePolicy.activityThinkingCount(group); - } - - private activityThinkingText(group: StructuredRenderGroup): string { - return ChatMessageStructurePolicy.activityThinkingText(group); - } - - private activityThinkingStatus(group: StructuredRenderGroup): string { - return ChatMessageStructurePolicy.activityThinkingStatus(group); - } - - private activityThinkingStreaming(group: StructuredRenderGroup): boolean { - return ChatMessageStructurePolicy.activityThinkingStreaming(group); - } - - private toolsNotCoveredByItems( - tools: ConversationUiToolStatus[], - items: ConversationUiMessageItem[] - ): ConversationUiToolStatus[] { - return ChatMessageStructurePolicy.toolsNotCoveredByItems(tools, items); - } - - private isRenderableStructuredEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isRenderableStructuredEntry(entry); - } - - private isThinkingEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isThinkingEntry(entry); - } - - private isUserSteeringEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isUserSteeringEntry(entry); - } - - private steeringMessage(entry: ConversationUiMessageItem, path: string): ConversationUiMessage { - return { - id: entry.steering_id || `${this.item.id}-${path}-steering`, - role: 'user', - text: entry.content || '', - status: 'sent', - detail: '', - images: entry.images - }; - } - - private isTextEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isTextEntry(entry); - } - - private isMainTextEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isTextEntry(entry); - } - - private isSubagentEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isSubagentEntry(entry); - } - - private subagentTitle(entry: ConversationUiMessageItem): string { - const title = ChatMessageStructurePolicy.subagentTitle(entry); - return title.length > 0 ? title : RemoteI18n.t('chat.toolTaskFallback'); - } - - private isRunningTool(tool: ConversationUiToolStatus): boolean { - return (tool.status || '').toLowerCase() === 'running' || (tool.status || '').toLowerCase() === 'active'; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets deleted file mode 100644 index bb50087fc8..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageChrome.ets +++ /dev/null @@ -1,367 +0,0 @@ -import { TimeFormat } from '../../services/TimeFormat'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MessageCopyScope } from '../actions/ConversationIntent'; -import { MarkdownParser } from '../../services/MarkdownParser'; -import { - AssistantMessageCopyMenuItem, - AssistantMessageCopyMenuPolicy -} from '../policy/AssistantMessageCopyMenuPolicy'; -import { - UserMessageMenuAction, - UserMessageMenuItem, - UserMessageMenuPolicy -} from '../policy/UserMessageMenuPolicy'; -import { UserMessageTruncationPolicy } from '../policy/UserMessageTruncationPolicy'; -import { ConversationUiMessage } from '../state/ConversationUiModels'; -import { MessageImageGallery } from './ChatMessageContent'; -import { RollbackSelectionMenu } from './RollbackSelectionMenu'; -import { - ACCENT, - CARD, - INK, - LINE, - MUTED, - CONTENT_ON_ACTION, - SHADOW_SUBTLE, - SOFT, - STATUS_DANGER, - TRANSPARENT, - FILE_LINK -} from './Theme'; - -@ComponentV2 -export struct ChatTypingDots { - @Local phase: number = 0; - private timerId: number = 0; - - aboutToAppear(): void { - this.timerId = setInterval(() => { - this.phase = (this.phase + 1) % 3; - }, 360); - } - - aboutToDisappear(): void { - if (this.timerId !== 0) { - clearInterval(this.timerId); - this.timerId = 0; - } - } - - build() { - Row({ space: 5 }) { - ForEach([0, 1, 2], (index: number) => { - Text('•') - .width(6) - .height(18) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(MUTED) - .opacity(this.phase === index ? 1.0 : 0.34) - .animation({ duration: 180, curve: Curve.EaseInOut }) - }) - } - .height(24) - .padding({ left: 2 }) - } -} - -@ComponentV2 -export struct ChatMessageRetryAction { - @Param assistant: boolean = false; - @Param retryText: string = ''; - @Event onRetry: (text: string) => void = (_text: string) => {}; - - build() { - Row({ space: 8 }) { - Text(this.assistant ? RemoteI18n.t('generalChat.replyInterrupted') : RemoteI18n.t('chat.sendFailed')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(STATUS_DANGER) - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(CONTENT_ON_ACTION) - .height(28) - .padding({ left: 10, right: 10 }) - .backgroundColor(ACCENT) - .borderRadius(14) - .onClick(() => this.onRetry(this.retryText)) - } - } -} - -@ComponentV2 -export struct ChatUserMessageBubble { - @Param item: ConversationUiMessage = { - id: '', - role: 'user', - text: '', - status: '', - detail: '' - }; - @Param showRetryAction: boolean = false; - /** - * Whether this message is part of the staged rollback's local preview. - * - * The bubble only weakens what it draws — the muted fill and the muted body the - * approved artboard specifies for a ghost row. It is told, not asked: which rows - * ghost is the timeline's decision, expressed in turn order. - */ - @Param ghost: boolean = false; - @Event onCopyMessage: (text: string) => void = (_text: string) => {}; - /** - * The reader asked to read this message in full. The turn id travels with the - * text because the panel that opens is also a rollback entry, and a rollback - * addresses the turn rather than what the message displays. - */ - @Event onOpenFullText: (text: string, turnId: string) => void = - (_text: string, _turnId: string) => {}; - @Event onRetryMessage: (text: string) => void = (_text: string) => {}; - /** - * The staged rollback was asked for from this message. The turn id travels with - * the text because staging addresses the host by turn, not by what it displays. - */ - @Event onRollbackMessage: (turnId: string, text: string) => void = - (_turnId: string, _text: string) => {}; - /** - * The bubble's own text controller, so the rollback item can dismiss the system - * selection menu it was tapped in (see `RollbackSelectionMenu`). - */ - private readonly selectionController: TextController = new TextController(); - - build() { - Row() { - Blank() - Column({ space: 6 }) { - if (this.visibleText().length > 0 || (this.item.images && this.item.images.length > 0)) { - Column({ space: 8 }) { - if (this.item.images && this.item.images.length > 0) { - MessageImageGallery({ images: this.item.images, userStyle: true }) - } - if (this.visibleText().length > 0) { - if (UserMessageTruncationPolicy.shouldTruncate(this.visibleText())) { - this.TruncatedText() - } else { - // A short message is the ordinary selectable Text: a long press - // raises the system selection menu and its handles. - this.PlainText() - } - } - } - .padding({ - left: MobileDesignGeometry.messageBubbleHorizontalPadding, - right: MobileDesignGeometry.messageBubbleHorizontalPadding, - top: MobileDesignGeometry.messageBubbleVerticalPadding, - bottom: MobileDesignGeometry.messageBubbleVerticalPadding - }) - .backgroundColor(this.ghost ? LINE : SOFT) - .borderRadius(MobileDesignGeometry.messageBubbleRadius) - .alignItems(HorizontalAlign.Start) - } - ChatMessageTimestamp({ timestamp: this.item.timestamp || '' }) - if (this.item.status === 'failed' && this.showRetryAction) { - ChatMessageRetryAction({ retryText: this.item.text, onRetry: this.onRetryMessage }) - } - } - .constraintSize({ maxWidth: MobileDesignGeometry.messageBubbleMaxWidth }) - .alignItems(HorizontalAlign.End) - } - .width('100%') - .padding({ top: 2, bottom: 2 }) - } - - /** - * The short message's own Text. - * - * The rollback entry rides the system selection menu through - * `editMenuOptions` — the menu the long press already opens for selection — so - * the entry costs the bubble no new affordance and no new layout. The item is - * always offered: whether the rollback can run is a fact about the connected - * host and the session, which the tap answers with a notice rather than the row - * answering with a guess. - */ - @Builder - private PlainText() { - Text(this.visibleText(), { controller: this.selectionController }) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(this.ghost ? MUTED : INK) - .copyOption(CopyOptions.LocalDevice) - .editMenuOptions(RollbackSelectionMenu.options(this.selectionController, () => { - this.requestRollback(); - })) - } - - /** - * The truncated bubble. The cut is made by the policy rather than by - * `maxLines` ellipsis: the full-text affordance has to sit inline after the - * ellipsis, and an ellipsized Text cannot host an appended clickable span. - * - * This Text carries no `copyOption`: the frozen design keeps selection - * handles off a bubble whose text continues past what is drawn, and answers a - * long press with the menu below instead. Handles belong to the panel. - * - * It also carries no `width`: a percentage width resolves against the row the - * bubble sits in rather than the bubble's own content box, so the Text was - * measured wider than the fill behind it. Measured on device, the bubble's - * fill ended at 1215 of a 1256-wide screen while the Text's own box ran to - * 1256, and the appended affix — the only content on the last line that - * reaches past the fill — was drawn outside the bubble and clipped there. At - * the content's own width the line breaks inside the bubble, and the - * affordance wraps onto the next line when it does not fit, which is the shape - * the frozen design specifies. - */ - @Builder - private TruncatedText() { - Text() { - Span(UserMessageTruncationPolicy.truncatedPreview(this.visibleText())) - .fontColor(this.ghost ? MUTED : INK) - Span(` ${RemoteI18n.t('chat.fullText')}`) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(FILE_LINK) - .decoration({ type: TextDecorationType.Underline, color: FILE_LINK }) - .onClick(() => { - this.onOpenFullText(this.visibleText(), this.item.turnId || ''); - }) - } - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .bindContextMenu(this.TruncatedMenu(), ResponseType.LongPress) - } - - @Builder - private TruncatedMenu() { - Menu() { - ForEach(UserMessageMenuPolicy.items(), (entry: UserMessageMenuItem) => { - MenuItem({ content: RemoteI18n.t(entry.labelKey) }) - .onClick(() => { - this.runMenuAction(entry.action); - }) - }, (entry: UserMessageMenuItem) => entry.action) - } - } - - private runMenuAction(action: UserMessageMenuAction): void { - if (action === UserMessageMenuAction.CopyFullText) { - this.onCopyMessage(this.visibleText()); - return; - } - if (action === UserMessageMenuAction.RollbackToMessage) { - this.requestRollback(); - } - } - - private requestRollback(): void { - this.onRollbackMessage(this.item.turnId || '', this.visibleText()); - } - - private visibleText(): string { - const text = this.item.text.trim(); - return text === '(空消息)' || text === '(empty message)' ? '' : text; - } -} - -/** - * The assistant message's copy affordance: the SOFT-weakened capsule of the - * bottom action row, beside the retry pill's ACCENT one. - * - * It opens an anchored popover rather than a bottom sheet, because the frozen - * design keeps a lightweight action list at its trigger on compact and wide - * layouts alike. The popup is bound to the control it was opened from, so it - * points at that control, dismisses on an outside tap, and carries the same - * short transition as the conversation header's menu. A row thawed from the - * reusable pool closes its menu first: the pool hands a kept `@Local` back to a - * different message. - * - * The bubble passes the message's Markdown source as the transcript holds it. - * Only the plain entry renders it down, through the parser's existing - * Markdown-to-text pass; the other two copy the source itself. - */ -@ComponentV2 -export struct AssistantMessageCopyAction { - @Param source: string = ''; - @Event onCopyScoped: (text: string, scope: MessageCopyScope) => void = - (_text: string, _scope: MessageCopyScope) => {}; - @Local showMenu: boolean = false; - - aboutToReuse(): void { - this.showMenu = false; - } - - build() { - Text(RemoteI18n.t('common.copy')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .height(28) - .padding({ left: 10, right: 10 }) - .backgroundColor(SOFT) - .borderRadius(14) - .accessibilityText(RemoteI18n.t('common.copy')) - .onClick(() => { - this.showMenu = !this.showMenu; - }) - .bindPopup(this.showMenu, { - builder: () => { - this.CopyMenu(); - }, - placement: Placement.BottomLeft, - popupColor: TRANSPARENT, - enableArrow: false, - autoCancel: true, - mask: false, - targetSpace: 8, - onStateChange: (event: PopupStateChangeParam) => { - this.showMenu = event.isVisible; - } - }) - } - - // Keep the three copy scopes compact while preserving 44vp touch targets. - @Builder - private CopyMenu() { - Column() { - ForEach(AssistantMessageCopyMenuPolicy.items(), (entry: AssistantMessageCopyMenuItem) => { - Text(RemoteI18n.t(entry.labelKey)) - .width('100%') - .height(44) - .padding({ left: 8, right: 8 }) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(INK) - .textAlign(TextAlign.Start) - .borderRadius(10) - .onClick(() => { - this.runMenuAction(entry); - }) - }, (entry: AssistantMessageCopyMenuItem) => entry.action) - } - .width(196) - .padding({ left: 8, right: 8, top: 4, bottom: 4 }) - .backgroundColor(CARD) - .border({ width: 0.5, color: LINE }) - .borderRadius(16) - .shadow({ radius: 18, color: SHADOW_SUBTLE, offsetY: 7 }) - .transition(TransitionEffect.opacity(0).animation({ duration: 150, curve: Curve.EaseOut })) - } - - private runMenuAction(entry: AssistantMessageCopyMenuItem): void { - this.showMenu = false; - this.onCopyScoped(this.payloadFor(entry.scope), entry.scope); - } - - private payloadFor(scope: MessageCopyScope): string { - return scope === MessageCopyScope.Plain ? MarkdownParser.formatInlineText(this.source) : this.source; - } -} - -@ComponentV2 -export struct ChatMessageTimestamp { - @Param timestamp: string = ''; - - build() { - if (TimeFormat.message(this.timestamp).length > 0) { - Text(TimeFormat.message(this.timestamp)) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .id('chat-message-timestamp') - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageContent.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageContent.ets deleted file mode 100644 index a20b886d2c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatMessageContent.ets +++ /dev/null @@ -1,171 +0,0 @@ -import { ConversationUiImage } from '../state/ConversationUiModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConversationMessageRenderPolicy } from '../policy/ConversationMessageRenderPolicy'; -import { FileTargetResolver } from '../policy/FileTargetResolver'; -import { - MessageFileReference, - MessageFileReferenceProjectionCache -} from '../policy/MessageFileReferenceProjector'; -import { FileReferenceCard } from './FileReferenceCard'; -import { MarkdownContent } from './MarkdownContent'; -import { StreamingMarkdownContent } from './StreamingMarkdownContent'; -import { LINE, MEDIA_BACKGROUND, MUTED } from './Theme'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; - -@ComponentV2 -export struct MessageImageGallery { - @Param images: ConversationUiImage[] = []; - @Param userStyle: boolean = false; - - build() { - Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap }) { - ForEach(this.images, (image: ConversationUiImage, index: number) => { - Stack() { - if (ConversationMessageRenderPolicy.hasRenderableImagePixels(image)) { - Image(image.data_url) - .width('100%') - .height('100%') - .objectFit(ImageFit.Cover) - } else { - // Without pixels an Image() draws an unexplained blank box, so name - // the attachment instead and say why it is not here. - Column() { - Text(image.name || RemoteI18n.t('chat.image')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .textAlign(TextAlign.Center) - Text(RemoteI18n.t('chat.imageUnavailable')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .textAlign(TextAlign.Center) - .margin({ top: 4 }) - } - .width('100%') - .padding(8) - .justifyContent(FlexAlign.Center) - } - } - .width(this.userStyle ? 112 : 92) - .height(this.userStyle ? 112 : 92) - .backgroundColor(MEDIA_BACKGROUND) - .borderRadius(this.userStyle ? 12 : 14) - .border({ width: 1, color: LINE }) - .clip(true) - .margin({ - right: this.userStyle ? (index % 2 === 0 && this.images.length > 1 ? 8 : 0) : 8, - bottom: this.userStyle ? (index < this.images.length - 2 ? 8 : 0) : 8 - }) - }, (image: ConversationUiImage, index: number) => `${image.name}-${index}`) - } - .width(this.userStyle ? (this.images.length > 1 ? 232 : 112) : '100%') - } -} - -@ComponentV2 -export struct MessageMarkdown { - @Param text: string = ''; - @Param renderRevision: number = 0; - @Param active: boolean = false; - @Param streamKey: string = ''; - @Event onCopyText: (text: string) => void = (_text: string) => {}; - @Event onOpenLink: (reference: string, label: string) => void = - (_reference: string, _label: string) => {}; - - build() { - if (this.active) { - StreamingMarkdownContent({ - text: this.text, - active: this.active, - streamKey: this.streamKey, - renderRevision: this.renderRevision, - onCopyText: this.onCopyText, - onOpenLink: this.onOpenLink - }) - } else { - MarkdownContent({ - text: this.text, - renderRevision: this.renderRevision, - onCopyText: this.onCopyText, - onOpenLink: this.onOpenLink - }) - } - } -} - -/** - * Keeps a retained message object as the reactive source. Deriving text inside - * this component avoids snapshotting a computed string through an @Builder. - */ -@ComponentV2 -export struct MessageBodyMarkdown { - @Param text: string = ''; - @Param renderRevision: number = 0; - @Param active: boolean = false; - @Param streamKey: string = ''; - @Event onCopyText: (text: string) => void = (_text: string) => {}; - @Event onOpenLink: (reference: string, label: string) => void = - (_reference: string, _label: string) => {}; - - build() { - MessageMarkdown({ - text: ConversationMessageRenderPolicy.visibleText(this.text), - renderRevision: this.renderRevision, - active: this.active, - streamKey: this.streamKey, - onCopyText: this.onCopyText, - onOpenLink: this.onOpenLink - }) - } -} - -@ComponentV2 -export struct MessageFileCards { - @Param text: string = ''; - @Param downloadingFilePath: string = ''; - @Param downloadedFilePath: string = ''; - @Param fileDownloadStatus: string = ''; - @Param activeFilePreviewPath: string = ''; - @Param activeFilePreviewLoading: boolean = false; - @Event onPreview: (path: string, label: string) => void = (_path: string, _label: string) => {}; - @Event onDownload: (path: string) => void = (_path: string) => {}; - private readonly cache: MessageFileReferenceProjectionCache = new MessageFileReferenceProjectionCache(); - - build() { - Column({ space: 8 }) { - ForEach(this.cache.referencesFor(this.text), (file: MessageFileReference) => { - FileReferenceCard({ - path: file.path, - label: file.label, - status: this.fileStatus(file.path), - previewLabel: RemoteI18n.t('common.open'), - buttonLabel: this.fileButtonLabel(file.path), - disabled: this.downloadingFilePath === file.path, - selected: FileTargetResolver.matchesRemotePath(file.path, this.activeFilePreviewPath), - previewLoading: this.activeFilePreviewLoading && - FileTargetResolver.matchesRemotePath(file.path, this.activeFilePreviewPath), - onPreview: this.onPreview, - onDownload: this.onDownload - }) - }, (file: MessageFileReference) => file.id) - } - .width('100%') - } - - private fileStatus(path: string): string { - if ((this.downloadingFilePath === path || this.downloadedFilePath === path) && - this.fileDownloadStatus.length > 0) return this.fileDownloadStatus; - if (path.indexOf('computer://') === 0) return RemoteI18n.t('chat.desktopFile'); - if (path.indexOf('file://') === 0) return RemoteI18n.t('chat.fileLink'); - return path; - } - - private fileButtonLabel(path: string): string { - if (this.downloadingFilePath === path) return RemoteI18n.t('chat.reading'); - if (this.downloadedFilePath === path) return RemoteI18n.t('common.done'); - return RemoteI18n.t('chat.download'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatStatusBar.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatStatusBar.ets deleted file mode 100644 index b77e6088b7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatStatusBar.ets +++ /dev/null @@ -1,62 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { INK, LINE, MUTED, PAGE_BG, SOFT } from './Theme'; - -@ComponentV2 -export struct ChatStatusBar { - @Param title: string = ''; - @Param detail: string = ''; - @Param color: ResourceColor = MUTED; - @Param canStop: boolean = false; - @Event onStop: () => void = () => {}; - - build() { - Row({ space: 10 }) { - if (this.canStop) { - Blank() - .width(68) - } - Row({ space: 7 }) { - Text('') - .width(8) - .height(8) - .backgroundColor(this.color) - .borderRadius(4) - Text(this.statusLabel()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.canStop ? MUTED : this.color) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .justifyContent(this.canStop ? FlexAlign.Center : FlexAlign.Start) - if (this.canStop) { - Text(RemoteI18n.t('chat.stop')) - .width(68) - .height(34) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .textAlign(TextAlign.Center) - .backgroundColor(SOFT) - .borderRadius(17) - .accessibilityText(RemoteI18n.t('chat.stop')) - .onClick(() => { - this.onStop(); - }) - } - } - .width('100%') - .height(48) - .padding({ left: 24, right: 24 }) - .backgroundColor(PAGE_BG) - .border({ width: { top: 1, bottom: 1 }, color: LINE }) - } - - private statusLabel(): string { - if (this.detail.length > 0) { - return `${this.title} · ${this.detail}`; - } - return this.title; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets deleted file mode 100644 index e77453317c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ChatTimeline.ets +++ /dev/null @@ -1,853 +0,0 @@ -import { InteractionMailboxState } from '../../model/InteractionMailbox'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { - ConversationUiMessage, - ConversationUiMessageItem, - ConversationUiQuestionAnswer, - ObservableConversationUiMessage, - toConversationUiMessage -} from '../state/ConversationUiModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - ChatTimelineItem, - ChatTimelineRevisionTracker, - ObservableChatTimelineItem -} from '../../model/ChatTimelineModels'; -import { ChatSurface } from '../state/ChatSurface'; -import { SubagentBranchExpansionState } from '../state/SubagentBranchExpansionState'; -import { MessageCopyScope } from '../actions/ConversationIntent'; -import { - CARD, - INK, - LINE, - MUTED, - SHADOW_SUBTLE, - STATUS_DANGER, -} from './Theme'; -import { ChatMessageBubble, ChatUserMessageRow } from './ChatMessageBubble'; -import { HistoryPageArrivalTracker } from '../policy/HistoryPageArrivalTracker'; -import { RemoteLogger } from '../../services/RemoteLogger'; - -/** - * How far a row inside the staged rollback's local preview is weakened. - * - * Frozen in the approved artboard (H): the withdrawn rows stay exactly where they - * are, at 58% opacity, so the preview reads as a state of the same transcript - * rather than as a second list. The user bubble additionally swaps its fill and - * its body ink, which is the artboard's own pairing for ghost rows. - */ -const GHOST_ROW_OPACITY: number = 0.58; - -/** - * Repeat retains this adapter by row identity while the observed row mutates. - * Keep one observable presentation message for the whole reusable lifetime: - * aboutToAppear covers a new instance, aboutToReuse covers an instance thawed - * from Repeat's pool, and the monitor covers an already-visible row update. - */ -@ReusableV2 -@ComponentV2 -struct ChatAssistantTimelineRow { - @Param interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - @Param row: ObservableChatTimelineItem = new ObservableChatTimelineItem({ - id: '', - type: 'empty_state', - isStreaming: false, - isFinalizing: false - }); - @Param renderRevision: number = 0; - @Param isBusy: boolean = false; - @Param downloadingFilePath: string = ''; - @Param downloadedFilePath: string = ''; - @Param fileDownloadStatus: string = ''; - @Param activeFilePreviewPath: string = ''; - @Param activeFilePreviewLoading: boolean = false; - @Local uiMessage: ObservableConversationUiMessage = new ObservableConversationUiMessage(); - @Event onApproveTool: (toolId: string, updatedInput?: Object) => void = - (_toolId: string, _updatedInput?: Object) => {}; - @Event onRejectTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onCancelTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => void = - (_toolId: string, _answers: ConversationUiQuestionAnswer) => {}; - @Event onCopyMessage: (text: string) => void = (_text: string) => {}; - @Event onCopyMessageScoped: (text: string, scope: MessageCopyScope) => void = - (_text: string, _scope: MessageCopyScope) => {}; - @Event onOpenFullText: (text: string, turnId: string) => void = - (_text: string, _turnId: string) => {}; - @Event onRollbackMessage: (turnId: string, text: string) => void = - (_turnId: string, _text: string) => {}; - @Event onRetryMessage: (text: string) => void = (_text: string) => {}; - @Event onOpenFilePreview: (path: string, label: string) => void = (_path: string, _label: string) => {}; - @Event onBuildPlan: (path: string, name: string) => void = (_path: string, _name: string) => {}; - @Event onDownloadFile: (path: string) => void = (_path: string) => {}; - /** Disclosure of this row's delegation cards, owned above the row. */ - @Param subagentBranches: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - /** Raised when the reader opens a delegation card, so its worker is followed. */ - @Event onBranchExpanded: (branchId: string) => void = (_branchId: string) => {}; - - aboutToAppear(): void { - this.synchronizeMessage(); - } - - aboutToReuse(): void { - this.synchronizeMessage(); - } - - @Monitor('row.id', 'row.message', 'renderRevision') - private onMessageChanged(): void { - this.synchronizeMessage(); - } - - build() { - // The parent only creates this row for a renderable message. Do not put a - // second structural condition around the reusable subtree: a V2 component - // can be thawed before its retained @Local state has been synchronized, - // and omitting the child at that point leaves a permanently hollow row. - ChatMessageBubble({ - interactionMailbox: this.interactionMailbox, - item: this.uiMessage, - renderRevision: this.renderRevision, - isStreaming: this.row.isStreaming, - isFinalizing: this.row.isFinalizing, - showRetryAction: this.row.showRetryAction, - isBusy: this.isBusy, - downloadingFilePath: this.downloadingFilePath, - downloadedFilePath: this.downloadedFilePath, - fileDownloadStatus: this.fileDownloadStatus, - activeFilePreviewPath: this.activeFilePreviewPath, - activeFilePreviewLoading: this.activeFilePreviewLoading, - subagentBranches: this.subagentBranches, - onApproveTool: this.onApproveTool, - onRejectTool: this.onRejectTool, - onCancelTool: this.onCancelTool, - onAnswerQuestion: this.onAnswerQuestion, - onCopyMessage: this.onCopyMessage, - onCopyMessageScoped: this.onCopyMessageScoped, - onOpenFullText: this.onOpenFullText, - onRollbackMessage: this.onRollbackMessage, - onRetryMessage: this.onRetryMessage, - onOpenFilePreview: this.onOpenFilePreview, - onBuildPlan: this.onBuildPlan, - onDownloadFile: this.onDownloadFile, - onBranchExpanded: this.onBranchExpanded - }) - } - - private synchronizeMessage(): void { - if (this.row.message) { - this.uiMessage.updateFrom(toConversationUiMessage(this.row.message)); - } - } -} - -@ComponentV2 -export struct ChatTimeline { - @Param interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - private readonly listScroller: Scroller = new Scroller(); - private readonly historyArrival: HistoryPageArrivalTracker = new HistoryPageArrivalTracker(); - private followTimerId: number = 0; - private followedActiveTurnKey: string = ''; - private userScrollActive: boolean = false; - private historyTouchActive: boolean = false; - private firstVisibleIndex: number = 0; - private historyRestoreKey: string = ''; - private historyRestoreTop: number = 0; - private lastVisibleIndex: number = 0; - private historyRestoreTimer: number = 0; - private historyRestoreAttempts: number = 0; - private historyStableFrames: number = 0; - // Whether new content should pull the viewport down with it. True until the - // user scrolls up to read back through the transcript: at that point taking - // the viewport away from them would be worse than letting the reply grow off - // screen, and the chevron button below gives them the way back. - @Local stickToBottom: boolean = true; - @Param surface: ChatSurface = ChatSurface.Remote; - @Param timelineItems: ObservableChatTimelineItem[] = []; - @Param timelineRevision: number = 0; - @Param hasMoreMessages: boolean = false; - @Param historyLoading: boolean = false; - @Param historyFailed: boolean = false; - @Param isBusy: boolean = false; - @Param connectionState: string = 'connected'; - @Param statusText: string = ''; - @Param downloadingFilePath: string = ''; - @Param downloadedFilePath: string = ''; - @Param fileDownloadStatus: string = ''; - @Param activeFilePreviewPath: string = ''; - @Param activeFilePreviewLoading: boolean = false; - @Param maxContentWidth: number = 0; - /** - * Disclosure of the delegation cards in this transcript. - * - * A conversation projection passes the instance its state owns, so a card the - * reader opened stays open while the rows around it are rebuilt. A host that - * passes nothing — the previews — gets one per timeline, which is still wider - * than the row and the card it outlives. - */ - @Param subagentBranches: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - /** - * How much of the pane the floating header and composer cover. The list runs - * the full height behind them, so without these the first and last messages - * would sit under a capsule and never come out from under it. - */ - @Param topInset: number = 0; - @Param bottomInset: number = 0; - /** - * Row keys the staged rollback previews as withdrawn. - * - * Keyed rather than indexed because the rows themselves are virtualized: which - * rows are withdrawn is a statement about the turns the pane is showing, and the - * pane derives it from row order (see `RollbackPresentationPolicy`). A row whose - * key is in here is drawn weakened; nothing about the model changes. - */ - @Param ghostRowKeys: string[] = []; - /** - * The system hint row a successful rollback leaves behind, drawn as the - * transcript's own last line. Empty while no rollback has succeeded. - */ - @Param rollbackNotice: string = ''; - @Event onLoadOlder: () => void = () => {}; - @Event onApproveTool: (toolId: string, updatedInput?: Object) => void = - (_toolId: string, _updatedInput?: Object) => {}; - @Event onRejectTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onCancelTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => void = - (_toolId: string, _answers: ConversationUiQuestionAnswer) => {}; - @Event onCopyMessage: (text: string) => void = (_text: string) => {}; - @Event onCopyMessageScoped: (text: string, scope: MessageCopyScope) => void = - (_text: string, _scope: MessageCopyScope) => {}; - @Event onOpenFullText: (text: string, turnId: string) => void = - (_text: string, _turnId: string) => {}; - @Event onRollbackMessage: (turnId: string, text: string) => void = - (_turnId: string, _text: string) => {}; - @Event onRetryMessage: (text: string) => void = (_text: string) => {}; - @Event onOpenFilePreview: (path: string, label: string) => void = (_path: string, _label: string) => {}; - @Event onBuildPlan: (path: string, name: string) => void = (_path: string, _name: string) => {}; - @Event onDownloadFile: (path: string) => void = (_path: string) => {}; - /** Raised when the reader opens a delegation card, so its worker is followed. */ - @Event onBranchExpanded: (branchId: string) => void = (_branchId: string) => {}; - - // Says whether an open reuses this subtree or rebuilds it. A rebuild means - // every bubble is constructed from nothing, and the cost of that is the - // difference between the two readings. - aboutToAppear(): void { - RemoteLogger.info(`chat timeline mounted surface=${this.surface} items=${this.timelineItems.length}`); - this.logTimelineProjection('mount'); - } - - aboutToDisappear(): void { - RemoteLogger.info(`chat timeline disposed items=${this.timelineItems.length}`); - this.clearFollowTimer(); - this.cancelHistoryAnchor(); - } - - // A new turn means the user has just sent a message and expects to follow its - // answer even if opening the keyboard changed the List viewport. Subsequent - // revisions keep following only until the user deliberately scrolls away. - @Monitor('timelineRevision', 'historyLoading') - onTimelineChanged(): void { - this.restoreHistoryAnchorIfNeeded(); - this.logTimelineProjection('revision'); - const activeTurnKey = this.activeTurnKey(); - if (activeTurnKey.length > 0 && activeTurnKey !== this.followedActiveTurnKey) { - this.followedActiveTurnKey = activeTurnKey; - this.userScrollActive = false; - this.stickToBottom = true; - RemoteLogger.info( - `chat timeline follow start revision=${this.timelineRevision} turn=${activeTurnKey}` - ); - } - this.requestFollowToBottom('revision'); - } - - build() { - Stack({ alignContent: Alignment.Bottom }) { - List({ space: MobileDesignGeometry.messageSpacing, scroller: this.listScroller }) { - if (this.hasMoreMessages) { - ListItem() { - Text(this.historyLoading ? RemoteI18n.t('common.loading') : RemoteI18n.t(this.historyFailed ? 'chat.loadOlderFailed' : 'chat.loadOlder')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .width('100%') - .padding({ top: 10, bottom: 10 }) - .onClick(() => { - if (!this.historyLoading) { - this.historyArrival.cancelArrival(); - this.stickToBottom = false; - this.captureHistoryAnchor(); - this.onLoadOlder(); - } - }) - } - } - Repeat(this.historyTimelineItems()) - .virtualScroll() - .each((repeatItem: RepeatItem) => { - // Repeat must own the reusable row directly. Routing its item - // through an @Builder snapshots the nested component subtree on - // current ArkUI builds, so streaming message params never update. - if (repeatItem.item.type === 'empty_state') { - ListItem() { - this.EmptyChatState() - } - .onAppear(() => { - this.logRenderedItem(repeatItem.item); - }) - } else if (repeatItem.item.message) { - ListItem() { - if (repeatItem.item.message!.role === 'user') { - ChatUserMessageRow({ - item: toConversationUiMessage(repeatItem.item.message!), - showRetryAction: repeatItem.item.showRetryAction === true, - ghost: this.isGhostRow(repeatItem.item), - onCopyMessage: (text: string) => { - this.onCopyMessage(text); - }, - onOpenFullText: (text: string, turnId: string) => { - this.onOpenFullText(text, turnId); - }, - onRetryMessage: (text: string) => { - this.onRetryMessage(text); - }, - onRollbackMessage: (turnId: string, text: string) => { - this.onRollbackMessage(turnId, text); - } - }) - .reuse({ reuseId: () => 'chat_user' }) - } else { - ChatAssistantTimelineRow({ - interactionMailbox: this.interactionMailbox, - row: repeatItem.item, - renderRevision: this.timelineRevision, - isBusy: this.isBusy, - downloadingFilePath: this.downloadingFilePath, - downloadedFilePath: this.downloadedFilePath, - fileDownloadStatus: this.fileDownloadStatus, - activeFilePreviewPath: this.activeFilePreviewPath, - activeFilePreviewLoading: this.activeFilePreviewLoading, - subagentBranches: this.subagentBranches, - onApproveTool: (toolId: string, updatedInput?: Object) => { - this.onApproveTool(toolId, updatedInput); - }, - onRejectTool: (toolId: string) => { - this.onRejectTool(toolId); - }, - onCancelTool: (toolId: string) => { - this.onCancelTool(toolId); - }, - onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => { - this.onAnswerQuestion(toolId, answers); - }, - onCopyMessage: (text: string) => { - this.onCopyMessage(text); - }, - onCopyMessageScoped: (text: string, scope: MessageCopyScope) => { - this.onCopyMessageScoped(text, scope); - }, - onOpenFullText: (text: string, turnId: string) => { - this.onOpenFullText(text, turnId); - }, - onRollbackMessage: (turnId: string, text: string) => { - this.onRollbackMessage(turnId, text); - }, - onRetryMessage: (text: string) => { - this.onRetryMessage(text); - }, - onOpenFilePreview: (path: string, label: string) => { - this.onOpenFilePreview(path, label); - }, - onBuildPlan: (path: string, name: string) => { - this.onBuildPlan(path, name); - }, - onDownloadFile: (path: string) => { - this.onDownloadFile(path); - }, - onBranchExpanded: (branchId: string) => { - this.onBranchExpanded(branchId); - } - }) - .reuse({ reuseId: () => 'chat_assistant' }) - } - } - .onAppear(() => { - this.logRenderedItem(repeatItem.item); - }) - .opacity(this.rowOpacity(repeatItem.item)) - } - }) - .key((item: ObservableChatTimelineItem, _index: number) => ChatTimelineRevisionTracker.itemKey(item)) - - // Keep the single volatile row outside Repeat.virtualScroll(). Feed it - // through the same observed adapter as history rows: passing a mapped - // temporary object through an @Builder freezes the first empty active - // snapshot on current ArkUI builds. - ForEach(this.activeTimelineItems(), (item: ObservableChatTimelineItem) => { - if (item.message) { - ListItem() { - ChatAssistantTimelineRow({ - interactionMailbox: this.interactionMailbox, - row: item, - renderRevision: this.timelineRevision, - isBusy: this.isBusy, - downloadingFilePath: this.downloadingFilePath, - downloadedFilePath: this.downloadedFilePath, - fileDownloadStatus: this.fileDownloadStatus, - activeFilePreviewPath: this.activeFilePreviewPath, - activeFilePreviewLoading: this.activeFilePreviewLoading, - subagentBranches: this.subagentBranches, - onApproveTool: this.onApproveTool, - onRejectTool: this.onRejectTool, - onCancelTool: this.onCancelTool, - onAnswerQuestion: this.onAnswerQuestion, - onCopyMessage: this.onCopyMessage, - onCopyMessageScoped: this.onCopyMessageScoped, - onOpenFullText: this.onOpenFullText, - onRollbackMessage: this.onRollbackMessage, - onRetryMessage: this.onRetryMessage, - onOpenFilePreview: this.onOpenFilePreview, - onBuildPlan: this.onBuildPlan, - onDownloadFile: this.onDownloadFile, - onBranchExpanded: this.onBranchExpanded - }) - } - .onAppear(() => { - this.logRenderedItem(item); - }) - .onAreaChange((oldArea: Area, newArea: Area) => { - if (Math.abs(this.areaLength(newArea.height) - this.areaLength(oldArea.height)) > 0.5) { - this.requestFollowToBottom('active-height'); - } - }) - .opacity(this.rowOpacity(item)) - } - }, (item: ObservableChatTimelineItem) => ChatTimelineRevisionTracker.itemKey(item)) - - // The one line a successful rollback leaves where the withdrawn rows were. - // It is a transcript row rather than a toast because the answer has to - // outlive the moment: the authoritative transcript arrives a poll later, - // and what it repaired is what this line accounts for. - if (this.rollbackNotice.length > 0) { - ListItem() { - this.RollbackNoticeRow() - } - .id('chat-timeline-rollback-notice') - } - - } - .width('100%') - .height('100%') - .padding({ - left: MobileDesignGeometry.contentGutter, - right: MobileDesignGeometry.contentGutter, - bottom: this.bottomInset > 0 ? 0 : 12 - }) - // Content offsets, not padding: padding shrinks the viewport, so the - // transcript would stop at the floating header and composer instead of - // running underneath them. These reserve the space at rest and still let - // the content scroll through — ArkUI's equivalent of Compose's - // contentPadding and SwiftUI's safeAreaInset. - .contentStartOffset(this.topInset) - .contentEndOffset(this.bottomInset) - // Keep short transcripts at the content start. Active turns and explicit - // follow-to-bottom calls still place streaming content at the tail. - .stackFromEnd(false) - .id('chat-timeline-list') - // Keeps the read position when older messages are prepended above. - .maintainVisibleContentPosition(false) - .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true }) - .scrollBar(BarState.Off) - .cachedCount(4) - .onTouch((event: TouchEvent) => { - if (event.type === TouchType.Down) { - if (!this.historyLoading) this.cancelHistoryAnchor(); - this.historyTouchActive = true; - this.historyArrival.beginGesture(); - RemoteLogger.info(`history gesture begin loading=${this.historyLoading} offset=${this.listScroller.currentOffset().yOffset}`); - } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) { - this.historyTouchActive = false; - } - }) - .onWillScroll((_scrollOffset: number, _scrollState: ScrollState, scrollSource: ScrollSource) => { - if (this.isUserScrollSource(scrollSource)) { - this.userScrollActive = true; - } - }) - .onScrollIndex((start: number, end: number, _center: number) => { - this.firstVisibleIndex = start; - this.lastVisibleIndex = end; - }) - .onDidScroll((_scrollOffset: number, scrollState: ScrollState) => { - if (this.listScroller.isAtEnd()) { - this.stickToBottom = true; - } else if (this.userScrollActive) { - this.stickToBottom = false; - } - this.evaluateHistoryStart(); - if (scrollState === ScrollState.Idle) { - this.userScrollActive = false; - } - }) - - if (this.surface === ChatSurface.Remote && !this.stickToBottom) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.chevron_down')) - .fontSize(18) - .fontColor([INK]) - } - .id('chat-timeline-jump') - .width(42) - .height(42) - .backgroundColor(CARD) - .borderRadius(21) - .shadow({ radius: 14, color: SHADOW_SUBTLE, offsetY: 5 }) - // Rides above the floating composer rather than hiding behind it. - .margin({ bottom: this.bottomInset + 4 }) - .onClick(() => { - this.stickToBottom = true; - this.userScrollActive = false; - this.requestFollowToBottom('jump-button'); - }) - } - } - .layoutWeight(1) - .width('100%') - .constraintSize({ maxWidth: this.maxContentWidth > 0 ? this.maxContentWidth : 10000 }) - .alignSelf(ItemAlign.Center) - } - - @Builder - EmptyChatState() { - Row({ space: 12 }) { - Text(this.emptyChatIcon()) - .width(38) - .height(38) - .fontSize(MobileDesignTypography.headlineSmall.size) - .fontColor(this.connectionState === 'failed' ? STATUS_DANGER : MUTED) - .textAlign(TextAlign.Center) - .backgroundColor(CARD) - .borderRadius(14) - .border({ width: 1, color: LINE }) - Column({ space: 5 }) { - Text(this.emptyChatTitle()) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(this.emptyChatText()) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .padding(14) - .backgroundColor(CARD) - .borderRadius(18) - .border({ width: 1, color: LINE }) - } - - private historyTimelineItems(): ObservableChatTimelineItem[] { - return this.timelineItems.filter((item: ObservableChatTimelineItem) => !this.isVolatileItem(item)); - } - - /** - * The centre-tracked line a successful rollback leaves in place of the rows it - * withdrew: what was rolled back, and what came back with it. - */ - @Builder - RollbackNoticeRow() { - Row({ space: 10 }) { - Divider().color(LINE).layoutWeight(1) - Text(this.rollbackNotice) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Divider().color(LINE).layoutWeight(1) - } - .width('100%') - .alignItems(VerticalAlign.Center) - .padding({ top: 4, bottom: 4 }) - } - - /** - * Whether a row is withdrawn by the staged rollback preview. - * - * Answered by key lookup against the pane's own derivation, so the preview can - * never disagree with the rows the timeline is actually showing. - */ - private isGhostRow(item: ObservableChatTimelineItem): boolean { - return this.ghostRowKeys.indexOf(ChatTimelineRevisionTracker.itemKey(item)) >= 0; - } - - private rowOpacity(item: ObservableChatTimelineItem): number { - return this.isGhostRow(item) ? GHOST_ROW_OPACITY : 1; - } - - private activeTimelineItems(): ObservableChatTimelineItem[] { - return this.timelineItems.filter((item: ObservableChatTimelineItem) => this.isVolatileItem(item)); - } - - private isVolatileItem(item: ChatTimelineItem): boolean { - return item.type === 'assistant_live_turn' && (item.isStreaming || item.isFinalizing); - } - - private activeTurnKey(): string { - const activeItems = this.activeTimelineItems(); - if (activeItems.length === 0) { - return ''; - } - return ChatTimelineRevisionTracker.itemKey(activeItems[activeItems.length - 1]); - } - - /** - * Asks for the next history page when the reader arrives at the start. - * - * What counts is the reader's position, not the content's: the list keeps the - * visible content in place while a page is prepended above it, so the arrival - * it answered is spent by it and reaching the start again is a deliberate - * scroll back. A timeline still following the tail is excluded — a first page - * that does not fill the viewport sits at the start without the reader having - * gone there — except while the reader is dragging, where the arrival is - * theirs even if the drag never leaves the end. - */ - private evaluateHistoryStart(): void { - const atStart: boolean = this.listScroller.currentOffset().yOffset <= 0; - const readerOwnsPosition: boolean = this.historyTouchActive && this.userScrollActive; - if (atStart && this.historyTouchActive) { - RemoteLogger.info(`history start check owns=${readerOwnsPosition} loading=${this.historyLoading} hasMore=${this.hasMoreMessages} failed=${this.historyFailed}`); - } - if (!this.historyArrival.arrived(atStart && readerOwnsPosition)) { - return; - } - if (this.hasMoreMessages && !this.historyLoading && !this.historyFailed) { - this.stickToBottom = false; - this.captureHistoryAnchor(); - this.onLoadOlder(); - return; - } - // A drag made while busy is consumed, not queued for after completion. - } - - private cancelHistoryAnchor(): void { - if (this.historyRestoreTimer !== 0) clearTimeout(this.historyRestoreTimer); - this.historyRestoreTimer = 0; - this.historyRestoreKey = ''; - this.historyRestoreAttempts = 0; - this.historyStableFrames = 0; - } - - private captureHistoryAnchor(): void { - const history = this.historyTimelineItems(); - const header = this.hasMoreMessages ? 1 : 0; - // A page can extend the first assistant row upwards without adding rows. - // Preserve the lower visible row's trailing edge, not that row's changing head. - const index = Math.min(history.length - 1, Math.max(0, this.lastVisibleIndex - header)); - const item = history[index]; - if (!item) return; - try { - const rect = this.listScroller.getItemRect(index + header); - if (rect.height <= 0) return; - this.historyRestoreKey = ChatTimelineRevisionTracker.itemKey(item); - this.historyRestoreTop = rect.y + rect.height; - this.historyRestoreAttempts = 0; - this.historyStableFrames = 0; - this.clearFollowTimer(); - this.stickToBottom = false; - RemoteLogger.info( - `history viewport capture key=${this.historyRestoreKey} index=${index} bottom=${this.historyRestoreTop} rows=${history.length}` - ); - } catch (_) { - RemoteLogger.warn('History viewport capture unavailable'); - } - } - - private restoreHistoryAnchorIfNeeded(): void { - if (!this.historyRestoreKey || this.historyLoading || this.historyRestoreTimer !== 0) return; - this.historyRestoreTimer = setTimeout(() => { - this.historyRestoreTimer = 0; - const key = this.historyRestoreKey; - const history = this.historyTimelineItems(); - const index = history.findIndex((item: ObservableChatTimelineItem) => - ChatTimelineRevisionTracker.itemKey(item) === key); - if (index < 0 || this.historyFailed) { - this.cancelHistoryAnchor(); - return; - } - this.historyRestoreAttempts++; - try { - const listIndex = index + (this.hasMoreMessages ? 1 : 0); - const rect = this.listScroller.getItemRect(listIndex); - if (rect.height <= 0) { - // Mount the identity's new virtual position before measuring it. - this.listScroller.scrollToIndex(listIndex, false, ScrollAlign.END); - this.historyStableFrames = 0; - } else { - const actual = rect.y + rect.height; - const delta = actual - this.historyRestoreTop; - RemoteLogger.info( - `history viewport measure key=${key} rows=${history.length} actual=${actual} expected=${this.historyRestoreTop} delta=${delta} attempt=${this.historyRestoreAttempts}` - ); - if (Math.abs(delta) > 0.5) { - this.historyStableFrames = 0; - this.listScroller.scrollBy(0, delta); - } else { - this.historyStableFrames++; - } - } - } catch (_) { - this.listScroller.scrollToIndex(index + (this.hasMoreMessages ? 1 : 0), false, ScrollAlign.END); - } - if (this.historyStableFrames >= 3 || this.historyRestoreAttempts >= 30) { - RemoteLogger.info(`history viewport settle stable=${this.historyStableFrames} attempts=${this.historyRestoreAttempts}`); - this.cancelHistoryAnchor(); - } else { - this.restoreHistoryAnchorIfNeeded(); - } - }, 16); - } - - private requestFollowToBottom(reason: string): void { - // Explicit navigation supersedes a pending history-position restoration. - // Jump now even if the host response is still pending; ordinary revisions - // resume tail following when historyLoading clears, including on failure. - if (reason === 'jump-button') { - this.cancelHistoryAnchor(); - } - if (this.historyRestoreKey || (this.historyLoading && reason !== 'jump-button') || - !this.stickToBottom || this.followTimerId !== 0) { - return; - } - this.followTimerId = setTimeout(() => { - this.followTimerId = 0; - if (!this.stickToBottom) { - return; - } - const wasAtEnd = this.listScroller.isAtEnd(); - this.listScroller.scrollEdge(Edge.Bottom); - if (!wasAtEnd || reason === 'jump-button') { - RemoteLogger.info( - `chat timeline follow apply reason=${reason} revision=${this.timelineRevision} ` + - `wasAtEnd=${wasAtEnd ? 1 : 0}` - ); - } - }, 0); - } - - private clearFollowTimer(): void { - if (this.followTimerId !== 0) { - clearTimeout(this.followTimerId); - this.followTimerId = 0; - } - } - - private isUserScrollSource(source: ScrollSource): boolean { - return source === ScrollSource.DRAG || source === ScrollSource.FLING || - source === ScrollSource.EDGE_EFFECT || source === ScrollSource.OTHER_USER_INPUT; - } - - private areaPosition(position: Object): number { - const value = (position as Record)?.y; - return this.areaLength(value === undefined ? 0 : value); - } - - private areaLength(value: Object): number { - const parsed = Number.parseFloat(`${value}`); - return Number.isNaN(parsed) ? 0 : parsed; - } - - private logRenderedItem(item: ChatTimelineItem): void { - const message = item.message; - const uiMessage = message ? toConversationUiMessage(message) : undefined; - const thinkingLength = uiMessage && uiMessage.thinking ? uiMessage.thinking.length : 0; - const toolCount = uiMessage && uiMessage.tools ? uiMessage.tools.length : 0; - const itemCount = uiMessage && uiMessage.items ? uiMessage.items.length : 0; - RemoteLogger.info( - `chat timeline item appear revision=${this.timelineRevision} type=${item.type} id=${item.id} ` + - `status=${uiMessage ? uiMessage.status : ''} textLength=${uiMessage ? uiMessage.text.length : 0} ` + - `thinkingLength=${thinkingLength} toolCount=${toolCount} itemCount=${itemCount} ` + - `itemTypes=${this.itemTypeSummary(uiMessage && uiMessage.items ? uiMessage.items : [])}` - ); - } - - private itemTypeSummary(items: ConversationUiMessageItem[]): string { - if (items.length === 0) { - return ''; - } - const parts: string[] = []; - items.forEach((entry: ConversationUiMessageItem) => { - if (entry.tool && entry.tool.name) { - parts.push(entry.tool.name); - } else if ((entry.type || '').length > 0) { - parts.push(entry.type || ''); - } else { - parts.push('item'); - } - }); - const summary = parts.join(','); - if (summary.length > 80) { - return summary.substring(0, 80); - } - return summary; - } - - private logTimelineProjection(reason: string): void { - const parts: string[] = []; - this.timelineItems.forEach((item: ChatTimelineItem) => { - const message = item.message; - parts.push( - `${item.type}:${item.id}:role=${message ? message.role : 'none'}:` + - `text=${message && message.text ? message.text.length : -1}:` + - `thinking=${message && message.thinking ? message.thinking.length : 0}:` + - `tools=${message && message.tools ? message.tools.length : 0}:` + - `items=${message && message.items ? message.items.length : 0}` - ); - }); - const summary = parts.join(' | '); - RemoteLogger.info( - `chat timeline project reason=${reason} revision=${this.timelineRevision} ` + - `count=${this.timelineItems.length} ${summary.length > 600 ? summary.substring(0, 600) : summary}` - ); - } - - private emptyChatIcon(): string { - if (this.isBusy) { - return '◌'; - } - if (this.connectionState === 'failed') { - return '!'; - } - if (this.connectionState === 'reconnecting') { - return '◌'; - } - return '∅'; - } - - private emptyChatTitle(): string { - if (this.isBusy) { - return RemoteI18n.t('chat.emptySyncing'); - } - if (this.connectionState === 'failed') { - return RemoteI18n.t('chat.emptyConnectionError'); - } - if (this.connectionState === 'reconnecting') { - return RemoteI18n.t('chat.emptyReconnecting'); - } - return RemoteI18n.t('chat.emptyNoMessages'); - } - - private emptyChatText(): string { - if (this.isBusy) { - return this.statusText || RemoteI18n.t('chat.emptyLoadingMessages'); - } - if (this.connectionState === 'failed') { - return this.statusText || RemoteI18n.t('chat.emptyReconnectFromHome'); - } - if (this.connectionState === 'reconnecting') { - return RemoteI18n.t('chat.emptyReconnectSync'); - } - return RemoteI18n.t('chat.emptyFirstMessage'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ColdStartHomeTransition.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ColdStartHomeTransition.ets deleted file mode 100644 index 2037a01bdd..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ColdStartHomeTransition.ets +++ /dev/null @@ -1,60 +0,0 @@ -import { ColdStartPresentationState } from '../state/ColdStartPresentationState'; -import { MotionPreference } from '../../services/MotionPreference'; -import { MobileDesignMotion } from '../../generated/MobileDesignTokens'; -import { WelcomeBrandFlow } from './WelcomeBrandFlow'; -import { PAGE_BG } from './Theme'; - -/** Authenticated cold-start cover. The home page stays mounted underneath. */ -@ComponentV2 -export struct ColdStartHomeTransition { - @Param geometry: ColdStartPresentationState = new ColdStartPresentationState(); - @Local viewportWidth: number = 0; - @Local viewportHeight: number = 0; - @Event onFinished: () => void = () => {}; - @Local progress: number = 0; - private timer: number = -1; - private started: number = 0; - - aboutToAppear(): void { - if (MotionPreference.reduceMotion()) { this.onFinished(); return; } - this.started = Date.now(); - this.timer = setInterval(() => { - if (MotionPreference.reduceMotion()) { clearInterval(this.timer); this.onFinished(); return; } - this.progress = Math.min(1, (Date.now() - this.started) / MobileDesignMotion.coldStartHome); - if (this.progress >= 1) { clearInterval(this.timer); this.onFinished(); } - }, 16); - } - aboutToDisappear(): void { clearInterval(this.timer); } - private clamp(value: number): number { return Math.max(0, Math.min(1, value)); } - private smooth(value: number): number { - const p = this.clamp(value); - return p * p * (3 - 2 * p); - } - private travel(): number { return this.smooth((this.progress - 0.16) / 0.52); } - private markSize(): number { return 56 + ((this.geometry.targetSize > 0 ? this.geometry.targetSize : 56) - 56) * this.travel(); } - private markX(): number { - const center = this.viewportWidth / 2; - if (this.geometry.targetSize <= 0) return center - this.markSize() / 2; - return center + (this.geometry.targetX - this.geometry.originX - center) * this.travel() - this.markSize() / 2; - } - private markY(): number { - const center = this.viewportHeight * 0.53; - if (this.geometry.targetSize <= 0) return center - this.markSize() / 2; - return center + (this.geometry.targetY - this.geometry.originY - center) * this.travel() - - Math.sin(this.travel() * Math.PI) * 9 - this.markSize() / 2; - } - build() { - Stack({ alignContent: Alignment.TopStart }) { - WelcomeBrandFlow({ markSize: this.markSize(), sweep: true }) - .position({ x: this.markX(), y: this.markY() }) - .opacity(this.clamp(this.progress / 0.13)) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - .onSizeChange((_old: SizeOptions, size: SizeOptions) => { - this.viewportWidth = Number(size.width); - this.viewportHeight = Number(size.height); - }) - .opacity(1 - this.smooth((this.progress - 0.68) / 0.32)) - .hitTestBehavior(HitTestMode.Block).accessibilityLevel('no-hide-descendants') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CommandChipRow.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CommandChipRow.ets deleted file mode 100644 index 97aeb9f0b6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CommandChipRow.ets +++ /dev/null @@ -1,318 +0,0 @@ -import { MobileDesignGeometry, MobileDesignMotion, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CommandPaletteChip, CommandPaletteChipKind, CommandPaletteChipState } from '../../services/CommandPalettePolicy'; -import { CommandPaletteNotice, CommandPalettePresentation } from '../state/CommandPaletteState'; -import { CommandPaletteAction, CommandPaletteRequest } from '../actions/ConversationIntent'; -import { ComposerPresentation } from './ComposerBar'; -import { - CONTENT_ON_INK, - INK, - LINE, - MUTED, - PAGE_BG, - SOFT, - STATUS_DANGER, - TRANSPARENT -} from './Theme'; - -// The row's own geometry. It is new to this component and is not part of the -// cross-platform token contract yet, so it lives here rather than being pushed -// into another platform's generated tokens. -const CHIP_HEIGHT: number = 32; -const CHIP_RADIUS: number = 16; -const CHIP_HORIZONTAL_PADDING: number = 9; -const CHIP_GAP: number = 4; -const CHIP_TOP_PADDING: number = 6; -const CHIP_END_GUTTER: number = 32; -const CHIP_ICON_SIZE: number = 13; -const CHIP_CHEVRON_SIZE: number = 9; -const CHIP_ROW_FADE_WIDTH: number = 18; -const CHIP_DISABLED_OPACITY: number = 0.38; -const CHIP_IN_FLIGHT_OPACITY: number = 0.52; -const CHIP_BADGE_HEIGHT: number = 15; -const HINT_ICON_SIZE: number = 14; -const CHIP_ROW_HEIGHT: number = CHIP_HEIGHT + CHIP_TOP_PADDING + 2; - -/** - * The composer's command chips: one horizontally scrollable row directly above - * the input, plus the single line the row owes the user underneath it. - * - * Commands execute on the tap; the skills chip opens the picker instead, which - * is what its up-chevron says. A chip that cannot run is drawn grey and stays - * tappable, because "nothing happened" is not an answer — the row explains - * itself in the hint line below. - */ -@ComponentV2 -export struct CommandChipRow { - @Param palette: CommandPalettePresentation = CommandPalettePresentation.hidden(); - @Param presentation: ComposerPresentation = ComposerPresentation.Compact; - @Event onRequest: (request: CommandPaletteRequest) => void = (_request: CommandPaletteRequest) => {}; - @Local showReason: boolean = false; - - build() { - Column({ space: 4 }) { - Stack({ alignContent: Alignment.End }) { - Scroll() { - Row({ space: CHIP_GAP }) { - ForEach(this.palette.chips, (chip: CommandPaletteChip) => { - this.Chip(chip) - }, (chip: CommandPaletteChip) => chip.kind) - } - .alignItems(VerticalAlign.Center) - .padding({ - left: this.horizontalInset(), - right: CHIP_END_GUTTER, - top: CHIP_TOP_PADDING, - bottom: 2 - }) - } - .scrollable(ScrollDirection.Horizontal) - .scrollBar(BarState.Off) - // Scroll centres content narrower than the viewport, which would park the - // first chip in the middle of the row instead of at the composer's edge. - .align(Alignment.Start) - .width('100%') - .height(CHIP_ROW_HEIGHT) - - this.RowEndFade() - } - .width('100%') - .height(CHIP_ROW_HEIGHT) - - if (this.hintKey().length > 0) { - this.HintLine() - } - } - .width('100%') - .constraintSize({ maxWidth: this.presentation === ComposerPresentation.Floating ? 760 : 10000 }) - .alignSelf(ItemAlign.Center) - } - - @Builder - Chip(chip: CommandPaletteChip) { - Stack({ alignContent: Alignment.TopEnd }) { - Row({ space: 4 }) { - if (chip.state === CommandPaletteChipState.InFlight) { - LoadingProgress() - .width(CHIP_ICON_SIZE) - .height(CHIP_ICON_SIZE) - .color(MUTED) - } else { - SymbolGlyph(this.chipGlyph(chip.kind)) - .fontSize(CHIP_ICON_SIZE) - .fontColor([this.chipGlyphColor(chip)]) - .opacity(chip.state === CommandPaletteChipState.Dimmed ? 1 : 0.82) - } - Text(RemoteI18n.t(chip.labelKey)) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(this.chipLabelColor(chip)) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (chip.showsChevron) { - SymbolGlyph($r('sys.symbol.chevron_up')) - .fontSize(CHIP_CHEVRON_SIZE) - .fontColor([this.chipChevronColor(chip)]) - .opacity(chip.state === CommandPaletteChipState.Dimmed ? 1 : 0.56) - } - } - .height(CHIP_HEIGHT) - .padding({ left: CHIP_HORIZONTAL_PADDING, right: CHIP_HORIZONTAL_PADDING }) - .backgroundColor(this.chipBackgroundColor(chip)) - .borderRadius(CHIP_RADIUS) - - // Absolutely offset rather than laid out inline: a badge that eats width - // pushes the row's last chip off the screen edge. - if (chip.badgeKey.length > 0) { - this.ChipBadge(chip.badgeKey) - } - } - .height(CHIP_HEIGHT) - .opacity(this.chipOpacity(chip)) - .accessibilityText(chip.badgeKey.length > 0 ? - `${RemoteI18n.t(chip.labelKey)} · ${RemoteI18n.t(chip.badgeKey)}` : - RemoteI18n.t(chip.labelKey)) - .animation({ duration: MobileDesignMotion.quick, curve: Curve.EaseOut }) - .onClick(() => { - this.tapChip(chip); - }) - } - - /** The corner badge an unsupported host's chips carry. */ - @Builder - ChipBadge(badgeKey: string) { - Text(RemoteI18n.t(badgeKey)) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(CHIP_BADGE_HEIGHT) - .fontColor(MUTED) - .padding({ left: 4, right: 4 }) - .backgroundColor(LINE) - .borderRadius(4) - .offset({ x: 2, y: -CHIP_TOP_PADDING }) - } - - @Builder - RowEndFade() { - Column() - .width(CHIP_ROW_FADE_WIDTH) - .height(CHIP_HEIGHT) - .margin({ top: CHIP_TOP_PADDING }) - .hitTestBehavior(HitTestMode.None) - .linearGradient({ - angle: 90, - colors: [[TRANSPARENT, 0.0], [PAGE_BG, 1.0]] - }) - } - - /** - * The row's explanation line. - * - * Three things can be said here and only one at a time: an unsupported host, a - * verb that just failed (with its retry), or the goal chip waiting for its - * argument. The goal prefill outranks the rest while it is lit, because that is - * the state the user has to act on before anything can be sent. - */ - @Builder - HintLine() { - Row({ space: 6 }) { - SymbolGlyph(this.hintGlyph()) - .fontSize(HINT_ICON_SIZE) - .fontColor([this.hintColor()]) - Text(RemoteI18n.t(this.hintKey())) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(this.hintColor()) - .layoutWeight(1) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.retryable()) { - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .padding({ left: 6, right: 6, top: 2, bottom: 2 }) - .backgroundColor(SOFT) - .borderRadius(8) - .accessibilityText(RemoteI18n.t('common.retry')) - .onClick(() => { - this.onRequest(new CommandPaletteRequest( - CommandPaletteAction.RetryCommand, '', this.palette.notice.retryCommand)); - }) - } - } - .width('100%') - .padding({ left: this.horizontalInset(), right: MobileDesignGeometry.conversationOverlaySideInset }) - .alignItems(VerticalAlign.Top) - } - - private horizontalInset(): number { - return this.presentation === ComposerPresentation.Floating ? - 24 : MobileDesignGeometry.conversationOverlaySideInset; - } - - private tapChip(chip: CommandPaletteChip): void { - if (!chip.runsAction) { - // Degraded is a state to explain, not a dead control: the reason appears - // under the row instead of being swallowed by the tap. - this.showReason = chip.reasonKey.length > 0; - return; - } - this.showReason = false; - this.onRequest(this.requestFor(chip.kind)); - } - - private requestFor(kind: CommandPaletteChipKind): CommandPaletteRequest { - if (kind === CommandPaletteChipKind.Compact) { - return new CommandPaletteRequest(CommandPaletteAction.Compact); - } - if (kind === CommandPaletteChipKind.Init) { - return new CommandPaletteRequest(CommandPaletteAction.InitAgentsMd); - } - if (kind === CommandPaletteChipKind.Goal) { - return new CommandPaletteRequest(CommandPaletteAction.ToggleGoal); - } - if (kind === CommandPaletteChipKind.Usage) { - return new CommandPaletteRequest(CommandPaletteAction.OpenUsage); - } - return new CommandPaletteRequest(CommandPaletteAction.OpenSkills); - } - - private chipGlyph(kind: CommandPaletteChipKind): Resource { - if (kind === CommandPaletteChipKind.Compact) return $r('sys.symbol.arrow_up_left_and_arrow_down_right'); - if (kind === CommandPaletteChipKind.Init) return $r('sys.symbol.doc_text_badge_arrow_up'); - if (kind === CommandPaletteChipKind.Goal) return $r('sys.symbol.list_checkmark'); - if (kind === CommandPaletteChipKind.Usage) return $r('sys.symbol.square_grid_2x2'); - return $r('sys.symbol.wrench_and_screwdriver'); - } - - private chipBackgroundColor(chip: CommandPaletteChip): ResourceColor { - return chip.state === CommandPaletteChipState.Pending ? INK : SOFT; - } - - private chipLabelColor(chip: CommandPaletteChip): ResourceColor { - if (chip.state === CommandPaletteChipState.Pending) return CONTENT_ON_INK; - return chip.state === CommandPaletteChipState.Dimmed ? MUTED : INK; - } - - private chipGlyphColor(chip: CommandPaletteChip): ResourceColor { - if (chip.state === CommandPaletteChipState.Pending) return CONTENT_ON_INK; - return chip.state === CommandPaletteChipState.Dimmed ? MUTED : INK; - } - - private chipChevronColor(chip: CommandPaletteChip): ResourceColor { - return chip.state === CommandPaletteChipState.Dimmed ? MUTED : INK; - } - - private chipOpacity(chip: CommandPaletteChip): number { - if (chip.state === CommandPaletteChipState.InFlight) return CHIP_IN_FLIGHT_OPACITY; - return chip.state === CommandPaletteChipState.Dimmed ? CHIP_DISABLED_OPACITY : 1; - } - - private notice(): CommandPaletteNotice { - return this.palette.notice; - } - - private retryable(): boolean { - return this.palette.rowReasonKey.length === 0 && this.notice().retryable; - } - - private hintKey(): string { - if (this.palette.rowReasonKey.length > 0) { - return this.palette.rowReasonKey; - } - if (this.notice().visible) { - return this.notice().labelKey; - } - const goal = this.palette.chips.find((chip: CommandPaletteChip): boolean => - chip.kind === CommandPaletteChipKind.Goal); - if (goal && goal.state === CommandPaletteChipState.Pending) { - return 'commands.goalHint'; - } - if (this.showReason) { - const dimmed = this.palette.chips.find((chip: CommandPaletteChip): boolean => - chip.reasonKey.length > 0); - if (dimmed) { - return dimmed.reasonKey; - } - } - return ''; - } - - private hintGlyph(): Resource { - const notice = this.notice(); - if (this.palette.rowReasonKey.length === 0 && notice.visible && notice.retryable) { - return $r('sys.symbol.xmark'); - } - return $r('sys.symbol.info_circle'); - } - - private hintColor(): ResourceColor { - const notice = this.notice(); - if (this.palette.rowReasonKey.length === 0 && notice.visible && notice.retryable) { - return STATUS_DANGER; - } - return MUTED; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CompactMenuButton.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CompactMenuButton.ets deleted file mode 100644 index 5930c89f37..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CompactMenuButton.ets +++ /dev/null @@ -1,46 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { TemplateIcon } from './TemplateIcon'; -import { CARD, SHADOW_SUBTLE } from './Theme'; - -const MENU_SURFACE_SIZE: number = 42; - -@ComponentV2 -export struct CompactMenuButton { - @Param controlSize: number = 48; - @Event onOpen: () => void = () => {}; - @Local pressed: boolean = false; - - build() { - Stack({ alignContent: Alignment.Center }) { - Stack({ alignContent: Alignment.Center }) { - TemplateIcon({ - src: $r('app.media.gpt_home_menu_glyph'), - iconWidth: 23, - iconHeight: 16 - }) - } - .width(MENU_SURFACE_SIZE) - .height(MENU_SURFACE_SIZE) - .backgroundColor(CARD) - .borderRadius(MENU_SURFACE_SIZE / 2) - .shadow({ radius: 30, color: SHADOW_SUBTLE, offsetY: 7 }) - .scale({ x: this.pressed ? 0.96 : 1, y: this.pressed ? 0.96 : 1 }) - .animation({ duration: 120, curve: Curve.EaseOut }) - .hitTestBehavior(HitTestMode.None) - } - .width(this.controlSize) - .height(this.controlSize) - .accessibilityText(RemoteI18n.t('sidebar.more')) - .onTouch((event: TouchEvent) => { - if (event.type === TouchType.Down) { - this.pressed = true; - } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) { - this.pressed = false; - } - }) - .onClick(() => { - this.pressed = false; - this.onOpen(); - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets deleted file mode 100644 index d128c0833e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets +++ /dev/null @@ -1,1137 +0,0 @@ -import { KeyboardReleaseService } from '../../services/KeyboardReleaseService'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MobileDesignGeometry, MobileDesignMotion, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { ChatComposerPolicy, ComposerPrimaryAction } from '../../services/ChatComposerPolicy'; -import { CommandPalettePolicy } from '../../services/CommandPalettePolicy'; -import { ChatComposerCapabilities, REMOTE_CHAT_COMPOSER_CAPABILITIES } from '../state/ChatComposerCapabilities'; -import { - ConversationUiModel, - ConversationUiModelCatalog, - ConversationUiSelectedImage -} from '../state/ConversationUiModels'; -import { - ConversationModelPresentationPolicy, - ConversationUiModelRoleEntry -} from '../policy/ConversationModelPresentationPolicy'; -import { TemplateIcon } from './TemplateIcon'; -import { - CARD, - CARD_OVERLAY, - INK, - LINE, - MEDIA_SCRIM, - MUTED, - SHADOW_SUBTLE, - SOFT, - STATUS_SUCCESS, - TRANSPARENT -} from './Theme'; - -export enum ComposerPresentation { - Compact = 'compact', - Floating = 'floating' -} - -const COMPOSER_ACTION_SIZE: number = MobileDesignGeometry.composerActionSize; -/** The optical primary surface is separate from its full touch target. */ -const COMPOSER_PRIMARY_SURFACE_SIZE: number = 32; -const COMPOSER_SEND_TRANSITION_DURATION: number = 200; -const COMPOSER_INPUT_HEIGHT: number = MobileDesignGeometry.composerInputHeight; -const COMPOSER_EXPANDED_INPUT_HEIGHT: number = MobileDesignGeometry.composerExpandedInputHeight; -const COMPOSER_EXPANDED_INPUT_MAX_HEIGHT: number = - MobileDesignTypography.bodyLarge.lineHeight * 4 + 18; -const COMPOSER_COLLAPSED_HEIGHT: number = MobileDesignGeometry.composerCollapsedHeight; -const COMPOSER_COMPACT_COLLAPSED_HEIGHT: number = MobileDesignGeometry.composerCollapsedHeight; -const COMPOSER_EXPANDED_ACTION_ROW_HEIGHT: number = MobileDesignGeometry.composerExpandedActionRowHeight; -const COMPOSER_EXPANDED_HEIGHT: number = MobileDesignGeometry.composerExpandedHeight; -const COMPOSER_COMPACT_HORIZONTAL_GUTTER: number = MobileDesignGeometry.contentGutter; -const COMPOSER_IMAGE_CARD_SIZE: number = 64; -const COMPOSER_IMAGE_STRIP_TOP_GAP: number = 6; -/** Strip height plus its top gap and the parent Column's 2vp row spacing. */ -const COMPOSER_IMAGE_STRIP_BLOCK: number = - COMPOSER_IMAGE_CARD_SIZE + COMPOSER_IMAGE_STRIP_TOP_GAP + 2; -const COMPOSER_TOKEN_HEIGHT: number = 28; -const COMPOSER_TOKEN_STRIP_TOP_GAP: number = 6; -/** The command token's row, sized the same way as the attachment strip's. */ -const COMPOSER_TOKEN_STRIP_BLOCK: number = - COMPOSER_TOKEN_HEIGHT + COMPOSER_TOKEN_STRIP_TOP_GAP + 2; -/** Gap the model popover keeps between its defaults section and the list. */ -const COMPOSER_MODEL_SELECTOR_SECTION_SPACE: number = 10; -const COMPOSER_MODEL_DEFAULTS_DIVIDER_STROKE: number = 0.5; -const COMPOSER_MODEL_DEFAULTS_DIVIDER_MARGIN_TOP: number = 4; - -@ComponentV2 -export struct ComposerBar { - @Param queueAttached: boolean = false; - @Param presentation: ComposerPresentation = ComposerPresentation.Compact; - @Param capabilities: ChatComposerCapabilities = REMOTE_CHAT_COMPOSER_CAPABILITIES; - @Param inputId: string = 'conversation-composer-input'; - @Param chatInput: string = ''; - @Param promptSuggestion: string = ''; - @Local inputText: string = ''; - @Local inputFocused: boolean = false; - @Local primaryActionPressed: boolean = false; - @Local sendTransitionActive: boolean = false; - private sendTransitionTimerId: number = -1; - @Param selectedImages: ConversationUiSelectedImage[] = []; - /** - * The command palette's skill token, empty when the composer carries none. - * - * It is a chip beside the draft rather than text in it, so the field stays - * exactly what the user typed; the send path is what turns it into content. - * The key is the pick's identity and decides whether the strip is drawn; the - * label is the skill's name and is one half of the text the message will carry. - */ - @Param skillId: string = ''; - @Param skillLabel: string = ''; - /** - * Whether the composer sits under the command row. - * - * The row is the only thing that can produce a bare `/goal`, and that is a - * command still waiting for its argument rather than a message, so this is - * what lets the composer withhold Send without changing the local surface. - */ - @Param commandRowActive: boolean = false; - @Param isBusy: boolean = false; - @Param canStop: boolean = false; - @Param connectionState: string = 'connected'; - @Param isVoiceListening: boolean = false; - @Param modelCatalog: ConversationUiModelCatalog = { - version: 0, - models: [], - default_models: {} - }; - @Param selectedModelId: string = ''; - @Local showModelSelectorPopover: boolean = false; - @Local isPreparingModelSelectorPopover: boolean = false; - @Local keepExpandedForModelSelection: boolean = false; - private restoreInputFocusAfterModelSelection: boolean = false; - private restoreInputFocusTimerId: number = -1; - @Event onPickImages: () => void = () => {}; - @Event onRemoveImage: (imageId: string) => void = (_imageId: string) => {}; - @Event onRemoveSkillToken: () => void = () => {}; - @Event onSend: () => void = () => {}; - @Event onStop: () => void = () => {}; - @Event onVoiceInput: () => void = () => {}; - @Event onSelectModel: (modelId: string) => void = (_modelId: string) => {}; - @Event onChatInputChange: (value: string) => void = (_value: string) => {}; - - aboutToAppear(): void { - this.inputText = this.chatInput; - } - - aboutToDisappear(): void { - if (this.sendTransitionTimerId >= 0) { - clearTimeout(this.sendTransitionTimerId); - this.sendTransitionTimerId = -1; - } - if (this.restoreInputFocusTimerId >= 0) { - clearTimeout(this.restoreInputFocusTimerId); - this.restoreInputFocusTimerId = -1; - } - } - - @Monitor('chatInput') - onChatInputParamChanged(): void { - if (this.inputText !== this.chatInput) { - this.inputText = this.chatInput; - } - } - - @Monitor('presentation') - onPresentationChanged(): void { - this.closeModelSelector(); - } - - build() { - Column() { - if (this.canAcceptPromptSuggestion()) { - Button({ type: ButtonType.Normal }) { - Text(this.promptSuggestion) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED) - .width('100%') - .textAlign(TextAlign.Start) - } - .id('composer-prompt-suggestion') - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.controlTouchSize }) - .padding({ left: 12, right: 12, top: 8, bottom: 8 }) - .backgroundColor(TRANSPARENT) - .borderRadius(MobileDesignGeometry.controlTouchSize / 2) - .accessibilityText(this.promptSuggestion) - .accessibilityDescription(RemoteI18n.t('chat.promptSuggestionAccept')) - .onClick(() => { - if (!this.canAcceptPromptSuggestion()) return; - this.inputText = this.promptSuggestion; - this.onChatInputChange(this.promptSuggestion); - this.getUIContext().getFocusController().requestFocus(this.inputId); - }) - } - this.AdaptiveComposer() - } - .width('100%') - .constraintSize({ maxWidth: this.presentation === ComposerPresentation.Floating ? 760 : 10000 }) - .alignSelf(ItemAlign.Center) - .padding({ - left: this.presentation === ComposerPresentation.Floating - ? 24 : MobileDesignGeometry.conversationOverlaySideInset, - right: this.presentation === ComposerPresentation.Floating - ? 24 : MobileDesignGeometry.conversationOverlaySideInset, - top: this.queueAttached ? 0 : 8, - bottom: this.presentation === ComposerPresentation.Floating ? 16 : 12 - }) - .backgroundColor(TRANSPARENT) - } - - private canAcceptPromptSuggestion(): boolean { - return this.promptSuggestion.length > 0 && this.inputText.length === 0 && this.chatInput.length === 0 && - !this.isBusy && !this.canStop && !this.isVoiceListening && this.connectionState === 'connected'; - } - - @Builder - AdaptiveComposer() { - Column({ space: 2 }) { - // The token is not a thumbnail: it sits above the field with the images - // because that is the only strip the composer has, and both are things the - // next send will carry rather than text the user is still writing. - if (this.hasSkillToken()) { - this.CommandTokenStrip() - } - if (this.selectedImages.length > 0) { - this.SelectedImageStrip() - } - Row({ space: this.isComposerExpanded() ? 0 : 5 }) { - if (this.shouldShowAddButton()) { - Row() { - this.AddButton() - } - .width(this.isComposerExpanded() ? 0 : COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - .opacity(this.isComposerExpanded() ? 0 : 1) - .visibility(this.isComposerExpanded() ? Visibility.None : Visibility.Visible) - .clip(true) - } - this.InputField() - Row() { - this.PrimaryActionButton() - } - .width(this.isComposerExpanded() ? 0 : COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - .opacity(this.isComposerExpanded() ? 0 : 1) - .visibility(this.isComposerExpanded() ? Visibility.None : Visibility.Visible) - .clip(true) - } - .width('100%') - .constraintSize({ - minHeight: this.isComposerExpanded() ? MobileDesignGeometry.composerExpandedInputRowHeight : - this.collapsedComposerHeight(), - maxHeight: this.isComposerExpanded() ? COMPOSER_EXPANDED_INPUT_MAX_HEIGHT : - this.collapsedComposerHeight() - }) - - if (this.isComposerExpanded()) { - Row({ space: 6 }) { - if (this.shouldShowAddButton()) { - this.AddButton() - } - if (this.shouldShowModelControl()) { - this.ModelControl() - } - Blank() - // The draft keeps the collapsed field's one line to itself, so the - // supplemental slot is mounted in this row alone. - if (this.shouldShowSupplementalVoice()) { - this.SupplementalVoiceButton() - } - this.PrimaryActionButton() - } - .width('100%') - .height(COMPOSER_EXPANDED_ACTION_ROW_HEIGHT) - .padding({ left: 2, right: 0 }) - .alignItems(VerticalAlign.Center) - .transition(TransitionEffect.translate({ x: 0, y: 8 }) - .combine(TransitionEffect.opacity(0)) - .animation({ duration: MobileDesignMotion.quick, curve: Curve.EaseOut })) - } - } - .width('100%') - .constraintSize({ minHeight: this.composerHeight() }) - .padding({ - left: 8, - right: 8, - top: this.isComposerExpanded() ? 4 : 0, - bottom: this.isComposerExpanded() ? 2 : 0 - }) - // The transcript now runs underneath the pill, so the fill is translucent - // and the blur does the separating. The colour is the floor under it: on a - // device that does not land the blur the pill is still opaque enough to - // read against whatever text is passing behind it. - .backgroundColor(CARD_OVERLAY) - .backgroundBlurStyle(BlurStyle.Thin) - .border({ width: this.presentation === ComposerPresentation.Compact ? 0.5 : 1, color: LINE }) - .borderRadius(this.composerRadius()) - .shadow({ - radius: this.presentation === ComposerPresentation.Floating ? 14 : 18, - color: SHADOW_SUBTLE, - offsetY: this.presentation === ComposerPresentation.Floating ? 4 : 6 - }) - .animation({ duration: MobileDesignMotion.structure, curve: Curve.EaseOut }) - } - - @Builder - ModelControl() { - Row({ space: 3 }) { - Text(this.displaySelectedModel()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .constraintSize({ maxWidth: 192 }) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.isModelSelectorExpanded() ? - $r('sys.symbol.chevron_up') : $r('sys.symbol.chevron_down')) - .fontSize(13) - .fontColor([INK]) - .opacity(0.68) - } - .width(16) - .height(COMPOSER_ACTION_SIZE) - } - .height(COMPOSER_ACTION_SIZE) - .constraintSize({ maxWidth: 220 }) - .padding({ left: 4, right: 4 }) - .backgroundColor(TRANSPARENT) - .accessibilityText(`${RemoteI18n.t('chat.selectModel')} · ${this.displaySelectedModel()}`) - .bindPopup(this.showModelSelectorPopover, { - builder: () => { - this.ModelSelector() - }, - placement: Placement.Top, - popupColor: TRANSPARENT, - enableArrow: false, - autoCancel: true, - mask: false, - targetSpace: 8, - onStateChange: (event) => { - if (!event.isVisible) { - this.showModelSelectorPopover = false; - this.restoreComposerFocusAfterModelSelection(); - } - } - }) - .onTouch((event: TouchEvent) => { - if (event.type === TouchType.Down) { - // Capture focus before the sheet/popover moves it away. Choosing a - // model is part of the current edit, not the end of that edit. - this.beginModelSelectionFromComposer(); - } - }) - .onClick(() => { - this.toggleModelSelectorPopover(); - }) - } - - @Builder - ModelSelector() { - Column({ space: COMPOSER_MODEL_SELECTOR_SECTION_SPACE }) { - if (this.roleEntries().length > 0) { - Column({ space: MobileDesignGeometry.composerModelSelectorRowGap }) { - ForEach(this.roleEntries(), (entry: ConversationUiModelRoleEntry) => { - this.ModelRoleRow(entry) - }, (entry: ConversationUiModelRoleEntry) => entry.role) - Divider() - .strokeWidth(COMPOSER_MODEL_DEFAULTS_DIVIDER_STROKE) - .color(LINE) - .width('100%') - .margin({ top: COMPOSER_MODEL_DEFAULTS_DIVIDER_MARGIN_TOP }) - } - .width('100%') - } - List({ space: MobileDesignGeometry.composerModelSelectorRowGap }) { - ForEach(this.selectorModels(), (model: ConversationUiModel) => { - ListItem() { - this.ModelRow(model) - } - }, (model: ConversationUiModel) => model.id) - } - .width('100%') - .height(this.modelListHeight()) - .scrollBar(BarState.Auto) - .edgeEffect(EdgeEffect.Spring) - .divider(null) - } - .width(MobileDesignGeometry.composerModelSelectorWidth) - .padding({ left: 10, right: 10, top: 10, bottom: 10 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.composerModelSelectorRadius) - .border({ width: 0.5, color: LINE }) - .shadow({ - radius: 18, - color: SHADOW_SUBTLE, - offsetY: 7 - }) - } - - @Builder - ModelRoleRow(entry: ConversationUiModelRoleEntry) { - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - if (this.isSelectedRole(entry.role)) { - SymbolGlyph($r('sys.symbol.checkmark_circle')) - .fontSize(16) - .fontColor([INK]) - } - } - .width(20) - .height(20) - - Column({ space: 2 }) { - Text(RemoteI18n.t(entry.labelKey)) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - if (this.roleMetaText(entry).length > 0) { - Text(this.roleMetaText(entry)) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.composerModelSelectorRowHeight }) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .backgroundColor(this.isSelectedRole(entry.role) ? SOFT : TRANSPARENT) - .borderRadius(MobileDesignGeometry.composerModelSelectorRowRadius) - .accessibilityText(RemoteI18n.t(entry.labelKey)) - .onClick(() => { - this.closeModelSelector(true); - this.onSelectModel(entry.role); - }) - } - - @Builder - ModelRoleBadge(role: string) { - Text(RemoteI18n.t(ConversationModelPresentationPolicy.roleBadgeLabelKey(role))) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .padding({ left: 6, right: 6, top: 1, bottom: 1 }) - .backgroundColor(SOFT) - .borderRadius(4) - } - - @Builder - ModelRow(model: ConversationUiModel) { - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - if (this.isSelectedConcreteModel(model)) { - SymbolGlyph($r('sys.symbol.checkmark_circle')) - .fontSize(16) - .fontColor([INK]) - } - } - .width(20) - .height(20) - - Column({ space: 2 }) { - Row({ space: 6 }) { - Text(ConversationModelPresentationPolicy.primaryLabel(model, RemoteI18n.t('chat.model'))) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - ForEach(this.modelRoles(model), (role: string) => { - this.ModelRoleBadge(role) - }, (role: string) => role) - } - .width('100%') - - Text(ConversationModelPresentationPolicy.secondaryLabel(model, RemoteI18n.t('chat.model'))) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.composerModelSelectorRowHeight }) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .backgroundColor(this.isSelectedConcreteModel(model) ? SOFT : TRANSPARENT) - .borderRadius(MobileDesignGeometry.composerModelSelectorRowRadius) - .onClick(() => { - this.closeModelSelector(true); - this.onSelectModel(model.id); - }) - } - - @Builder - AddButton() { - Stack({ alignContent: Alignment.Center }) { - this.PlusGlyph() - } - .width(COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - .accessibilityText(RemoteI18n.t('chat.addImage')) - .onClick(() => { - if (this.isVoiceListening) { - return; - } - // Images are the only thing a message can carry, so a menu in front of the - // picker would be a menu of one. Straight to the album, same as local chat. - this.onPickImages(); - }) - } - - @Builder - InputField() { - Row({ space: this.isVoiceListening ? 8 : 0 }) { - if (this.isVoiceListening) { - this.ListeningWave() - } - TextArea({ placeholder: this.inputPlaceholder(), text: this.inputText }) - .id(this.inputId) - .layoutWeight(1) - .constraintSize({ - minHeight: this.isComposerExpanded() ? COMPOSER_EXPANDED_INPUT_HEIGHT : COMPOSER_INPUT_HEIGHT, - maxHeight: this.isComposerExpanded() ? COMPOSER_EXPANDED_INPUT_MAX_HEIGHT : COMPOSER_INPUT_HEIGHT - }) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(INK) - .placeholderColor(this.isVoiceListening ? STATUS_SUCCESS : MUTED) - .backgroundColor(TRANSPARENT) - .borderRadius(20) - .align(this.isComposerExpanded() ? Alignment.TopStart : Alignment.Start) - .padding({ - left: this.isVoiceListening ? 0 : 4, - right: 4, - top: this.isComposerExpanded() ? 10 : 0, - bottom: this.isComposerExpanded() ? 8 : 0 - }) - // Limit the viewport, not the editable text. The collapsed field is one - // line tall, so what it cannot show is marked with an ellipsis instead of - // scrolling sideways under the reader's finger; the expanded field keeps - // its scrollable multi-line viewport. - .textOverflow(this.isComposerExpanded() ? TextOverflow.Clip : TextOverflow.Ellipsis) - .maxLines(this.isComposerExpanded() ? 4 : 1, { - overflowMode: this.isComposerExpanded() ? MaxLinesMode.SCROLL : MaxLinesMode.CLIP - }) - .defaultFocus(false) - .onFocus(() => { - this.inputFocused = true; - this.cancelModelSelectionEditingContinuation(); - }) - .onBlur(() => { - this.inputFocused = false; - }) - .onChange((value: string, previewText?: PreviewText) => { - // The first callback value excludes IME pre-edit text. Keep that text - // inside the native field until the IME commits it. - if (previewText && previewText.value.length > 0) { - return; - } - this.inputText = value; - this.onChatInputChange(value); - }) - } - .layoutWeight(1) - .constraintSize({ - minHeight: this.isComposerExpanded() ? COMPOSER_EXPANDED_INPUT_HEIGHT : COMPOSER_INPUT_HEIGHT, - maxHeight: this.isComposerExpanded() ? COMPOSER_EXPANDED_INPUT_MAX_HEIGHT : COMPOSER_INPUT_HEIGHT - }) - .alignItems(VerticalAlign.Center) - .padding({ left: this.isVoiceListening ? 12 : 0, right: 0 }) - .backgroundColor(this.isVoiceListening ? SOFT : TRANSPARENT) - .borderRadius(20) - .border({ width: this.isVoiceListening ? 1 : 0, color: this.isVoiceListening ? STATUS_SUCCESS : TRANSPARENT }) - } - - @Builder - PrimaryActionButton() { - Button() { - Stack({ alignContent: Alignment.Center }) { - if (this.shouldShowActiveActionSurface()) { - Stack({ alignContent: Alignment.Center }) { - if (this.shouldShowStopGlyph()) { - Text('') - .width(10) - .height(10) - .backgroundColor(CARD) - .borderRadius(2.5) - } else { - TemplateIcon({ - src: $r('app.media.gpt_composer_send_arrow'), - iconWidth: 16, - iconHeight: 18, - tint: this.primaryActionForegroundColor() - }) - } - } - .width(COMPOSER_PRIMARY_SURFACE_SIZE) - .height(COMPOSER_PRIMARY_SURFACE_SIZE) - .backgroundColor(this.activeActionSurfaceColor()) - .borderRadius(COMPOSER_PRIMARY_SURFACE_SIZE / 2) - .animation({ duration: COMPOSER_SEND_TRANSITION_DURATION, curve: Curve.EaseOut }) - } else if (this.primaryAction() === ComposerPrimaryAction.Voice || - this.primaryAction() === ComposerPrimaryAction.VoiceBlocked) { - this.MicrophoneGlyph() - } else { - SymbolGlyph($r('sys.symbol.arrow_up')) - .fontSize(23) - .fontWeight(FontWeight.Medium) - .fontColor([this.primaryActionForegroundColor()]) - .opacity(this.primaryAction() === ComposerPrimaryAction.Send ? 1 : 0.38) - } - } - .width(COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - } - .width(COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - .padding(0) - .type(ButtonType.Circle) - .backgroundColor(this.inactiveActionBackgroundColor()) - .borderRadius(COMPOSER_ACTION_SIZE / 2) - .stateEffect(false) - .accessibilityText(RemoteI18n.t(ChatComposerPolicy.primaryActionAccessibilityKey( - this.primaryAction(), this.isVoiceListening))) - .enabled(this.primaryAction() !== ComposerPrimaryAction.Stop || this.isVoiceListening || - ChatComposerPolicy.canStop(this.canStop, this.capabilities.requiresRemoteConnection, this.connectionState)) - .onTouch((event: TouchEvent) => { - if (!this.shouldShowActiveActionSurface()) { - return; - } - if (event.type === TouchType.Down) { - this.primaryActionPressed = true; - } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) { - this.primaryActionPressed = false; - } - }) - // Driven off the same decision that drew the glyph, so the button can never - // do something other than what it is showing. - .onClick(() => { - const action = this.primaryAction(); - if (action === ComposerPrimaryAction.Stop) { - if (this.isVoiceListening) { - this.onVoiceInput(); - } else if (ChatComposerPolicy.canStop(this.canStop, this.capabilities.requiresRemoteConnection, this.connectionState)) { - this.onStop(); - } - return; - } - if (action === ComposerPrimaryAction.Send) { - this.beginSendTransition(); - this.onSend(); - return; - } - if (action === ComposerPrimaryAction.Voice) { - void this.startVoiceInput(); - } - }) - } - - @Builder - PlusGlyph() { - SymbolGlyph($r('sys.symbol.plus')) - .fontSize(22) - .fontColor([INK]) - .opacity(this.isVoiceListening ? 0.36 : 1) - } - - @Builder - MicrophoneGlyph() { - SymbolGlyph($r('sys.symbol.mic')) - .fontSize(22) - .fontColor([this.primaryActionForegroundColor()]) - } - - @Builder - SupplementalVoiceButton() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.mic')) - .fontSize(20) - .fontColor([INK]) - } - .width(COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - .opacity(this.canUseSupplementalVoice() ? 0.72 : 0.32) - .accessibilityText(RemoteI18n.t('chat.voiceInput')) - .onClick(() => { - if (this.canUseSupplementalVoice()) { - void this.startVoiceInput(); - } - }) - } - - @Builder - ListeningWave() { - Row({ space: 3 }) { - Text('') - .width(3) - .height(10) - .backgroundColor(STATUS_SUCCESS) - .borderRadius(2) - Text('') - .width(3) - .height(18) - .backgroundColor(STATUS_SUCCESS) - .borderRadius(2) - Text('') - .width(3) - .height(24) - .backgroundColor(STATUS_SUCCESS) - .borderRadius(2) - Text('') - .width(3) - .height(14) - .backgroundColor(STATUS_SUCCESS) - .borderRadius(2) - } - .width(22) - .height(28) - .justifyContent(FlexAlign.Center) - .alignItems(VerticalAlign.Center) - } - - @Builder - SelectedImageStrip() { - Scroll() { - Row({ space: 10 }) { - ForEach(this.selectedImages, (image: ConversationUiSelectedImage) => { - this.SelectedImageCard(image) - }, (image: ConversationUiSelectedImage) => image.id) - } - .padding({ left: 4, right: 4 }) - } - .scrollable(ScrollDirection.Horizontal) - .scrollBar(BarState.Off) - // Scroll centres content that is narrower than the viewport, which parks a - // lone thumbnail in the middle of the composer instead of at its left edge. - .align(Alignment.Start) - .width('100%') - .height(COMPOSER_IMAGE_CARD_SIZE) - .margin({ top: COMPOSER_IMAGE_STRIP_TOP_GAP }) - } - - /** - * The one skill token a message may carry. - * - * It is removable in place, and it shows the exact text the message will send - * — `[$plan]` — so the token and the wire form cannot drift apart. - */ - @Builder - CommandTokenStrip() { - Row() { - Row({ space: 5 }) { - SymbolGlyph($r('sys.symbol.wrench_and_screwdriver')) - .fontSize(12) - .fontColor([INK]) - .opacity(0.7) - Text(CommandPalettePolicy.skillTokenLabel(this.skillLabel)) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(11) - .fontColor([INK]) - .opacity(0.6) - } - .height(COMPOSER_TOKEN_HEIGHT) - .padding({ left: 9, right: 9 }) - .backgroundColor(SOFT) - .borderRadius(COMPOSER_TOKEN_HEIGHT / 2) - .accessibilityText(`${RemoteI18n.t('commands.skillToken')} · ` + - `${CommandPalettePolicy.skillTokenLabel(this.skillLabel)}`) - .onClick(() => { - this.onRemoveSkillToken(); - }) - Blank() - } - .width('100%') - .height(COMPOSER_TOKEN_HEIGHT) - .padding({ left: 4, right: 4 }) - .margin({ top: COMPOSER_TOKEN_STRIP_TOP_GAP }) - } - - @Builder - SelectedImageCard(image: ConversationUiSelectedImage) { - Stack({ alignContent: Alignment.TopEnd }) { - Image(image.data_url) - .width(COMPOSER_IMAGE_CARD_SIZE) - .height(COMPOSER_IMAGE_CARD_SIZE) - .objectFit(ImageFit.Cover) - .borderRadius(14) - Text('×') - .width(COMPOSER_ACTION_SIZE) - .height(COMPOSER_ACTION_SIZE) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(CARD) - .textAlign(TextAlign.Center) - .backgroundColor(MEDIA_SCRIM) - .borderRadius(16) - .margin({ top: 0, right: 0 }) - .accessibilityText(RemoteI18n.t('chat.removeImage')) - .onClick(() => { - this.onRemoveImage(image.id); - }) - } - .width(COMPOSER_IMAGE_CARD_SIZE) - .height(COMPOSER_IMAGE_CARD_SIZE) - } - - private canUseVoice(): boolean { - return this.capabilities.showVoiceInput && - ChatComposerPolicy.canUseVoice(this.inputText, this.selectedImages.length, this.isBusy); - } - - private shouldShowSupplementalVoice(): boolean { - return ChatComposerPolicy.shouldShowSupplementalVoice( - this.inputText, - this.selectedImages.length, - this.isVoiceListening, - this.capabilities.showVoiceInput - ); - } - - private canUseSupplementalVoice(): boolean { - return ChatComposerPolicy.canUseSupplementalVoice(this.isBusy); - } - - // Dictation runs inside this app rather than in a system dialog, so listening - // outranks the draft here in a way a running turn does not. - private primaryAction(): ComposerPrimaryAction { - const action = ChatComposerPolicy.primaryAction( - this.inputText, - this.selectedImages.length, - this.isBusy, - this.isVoiceListening, - this.canStop, - this.capabilities.supportsMidRunSend, - this.capabilities.requiresRemoteConnection, - this.connectionState, - this.capabilities.showVoiceInput - ); - // A bare `/goal` is a command whose argument has not been written yet, and - // the desktop parses the objective out of the message head, so there is - // nothing to send until the user supplies one. The palette's own face of - // this rule lives in `CommandPalettePolicy.blocksSend`; the send path checks - // it again, because the field can also be typed into directly. - if (action === ComposerPrimaryAction.Send && this.commandRowActive && - CommandPalettePolicy.blocksSend(this.inputText)) { - return ComposerPrimaryAction.SendBlocked; - } - return action; - } - - private shouldShowAddButton(): boolean { - return ChatComposerPolicy.shouldShowAddButton( - this.capabilities.showAddButton, - this.capabilities.supportsAttachments - ); - } - - /** - * Whether the composer is carrying a skill token. - * - * The label is the token's own text, so the two cannot disagree: a pick with - * no name to write would draw an empty chip rather than nothing at all. - */ - private hasSkillToken(): boolean { - return this.skillLabel.length > 0; - } - - // Attachments and the skill token live inside the card, so the card has to - // grow to hold them. - private composerHeight(): number { - const base = this.isComposerExpanded() ? COMPOSER_EXPANDED_HEIGHT : this.collapsedComposerHeight(); - const attachmentBlock = this.selectedImages.length > 0 ? COMPOSER_IMAGE_STRIP_BLOCK : 0; - const tokenBlock = this.hasSkillToken() ? COMPOSER_TOKEN_STRIP_BLOCK : 0; - return base + attachmentBlock + tokenBlock; - } - - private collapsedComposerHeight(): number { - return this.presentation === ComposerPresentation.Compact ? - COMPOSER_COMPACT_COLLAPSED_HEIGHT : COMPOSER_COLLAPSED_HEIGHT; - } - - // The pill radius only reads as a pill while the card is one row tall. - private composerRadius(): number { - if (this.isComposerExpanded() || this.selectedImages.length > 0 || this.hasSkillToken()) { - return MobileDesignGeometry.composerExpandedRadius; - } - return MobileDesignGeometry.composerCollapsedRadius; - } - - private isComposerExpanded(): boolean { - return ChatComposerPolicy.isExpanded( - this.inputText, - this.inputFocused, - this.isModelSelectorExpanded(), - this.keepExpandedForModelSelection - ); - } - - private isModelSelectorExpanded(): boolean { - return this.showModelSelectorPopover || this.isPreparingModelSelectorPopover; - } - - private shouldShowModelControl(): boolean { - return this.enabledModels().length > 0; - } - - private enabledModels(): ConversationUiModel[] { - return ConversationModelPresentationPolicy.enabledModels(this.modelCatalog); - } - - private selectedModel(): ConversationUiModel | undefined { - return ConversationModelPresentationPolicy.selectedModel(this.modelCatalog, this.selectedModelId); - } - - private roleEntries(): ConversationUiModelRoleEntry[] { - return ConversationModelPresentationPolicy.roleEntries(this.modelCatalog); - } - - private isSelectedRole(role: string): boolean { - return ConversationModelPresentationPolicy.resolvedSelectedRole( - this.modelCatalog, this.selectedModelId) === role; - } - - private isSelectedConcreteModel(model: ConversationUiModel): boolean { - return ConversationModelPresentationPolicy.isConcreteModelSelected(this.selectedModelId, model.id); - } - - private modelRoles(model: ConversationUiModel): string[] { - return ConversationModelPresentationPolicy.modelRoles(this.modelCatalog, model.id); - } - - private roleMetaText(entry: ConversationUiModelRoleEntry): string { - const noticeKey = ConversationModelPresentationPolicy.roleMetaNoticeKey(entry); - if (noticeKey.length > 0) { - return RemoteI18n.t(noticeKey); - } - return ConversationModelPresentationPolicy.roleMetaLabel(entry.model, RemoteI18n.t('chat.model')); - } - - private displaySelectedModel(): string { - const roleKey = ConversationModelPresentationPolicy.selectedModelLabelKey(this.modelCatalog, this.selectedModelId); - if (roleKey.length > 0) { - return RemoteI18n.t(roleKey); - } - const selected = this.selectedModel(); - return selected ? ConversationModelPresentationPolicy.primaryLabel(selected, RemoteI18n.t('chat.model')) : - RemoteI18n.t('chat.model'); - } - - private modelListHeight(): number { - // Five rows fit comfortably above the compact composer while the keyboard - // remains visible. The defaults section takes its share of that budget - // first, so the concrete models only get what is left. Larger catalogs - // scroll inside the anchored menu. - const maxVisibleRows = this.presentation === ComposerPresentation.Compact ? 5 : 7; - const rowHeight = MobileDesignGeometry.composerModelSelectorRowHeight; - const rowGap = MobileDesignGeometry.composerModelSelectorRowGap; - const budgetHeight = maxVisibleRows * rowHeight + Math.max(0, maxVisibleRows - 1) * rowGap; - const availableHeight = Math.max(0, budgetHeight - this.modelDefaultsBlockHeight()); - const fittingRows = Math.floor((availableHeight + rowGap) / (rowHeight + rowGap)); - const visibleRows = Math.max(0, Math.min(this.enabledModels().length, fittingRows)); - const rowsHeight = visibleRows * rowHeight + Math.max(0, visibleRows - 1) * rowGap; - // A budget too small for one full row still leaves the list a scrollable - // viewport instead of collapsing it away. The remaining budget is the cap, - // so the popover can never grow past the footprint it had before. - return Math.max(0, Math.min(availableHeight, Math.max(rowHeight, rowsHeight))); - } - - /** Height the defaults section takes above the concrete list, chrome included. */ - private modelDefaultsBlockHeight(): number { - const roleRows = this.roleEntries().length; - if (roleRows === 0) { - return 0; - } - const rowsHeight = roleRows * MobileDesignGeometry.composerModelSelectorRowHeight + - Math.max(0, roleRows - 1) * MobileDesignGeometry.composerModelSelectorRowGap; - const chrome = MobileDesignGeometry.composerModelSelectorRowGap + - COMPOSER_MODEL_DEFAULTS_DIVIDER_STROKE + - COMPOSER_MODEL_DEFAULTS_DIVIDER_MARGIN_TOP + - COMPOSER_MODEL_SELECTOR_SECTION_SPACE; - return rowsHeight + chrome; - } - - private selectorModels(): ConversationUiModel[] { - const models = this.enabledModels(); - const selected = this.selectedModel(); - if (!selected) { - return models; - } - return [selected, ...models.filter((model: ConversationUiModel) => model.id !== selected.id)]; - } - - private closeModelSelector(restoreInputFocus: boolean = false): void { - const shouldRestore = restoreInputFocus && this.restoreInputFocusAfterModelSelection; - this.showModelSelectorPopover = false; - this.isPreparingModelSelectorPopover = false; - if (shouldRestore) { - this.restoreComposerFocusAfterModelSelection(); - } else if (!restoreInputFocus) { - this.cancelModelSelectionEditingContinuation(); - } - } - - private async toggleModelSelectorPopover(): Promise { - if (this.showModelSelectorPopover) { - this.closeModelSelector(true); - return; - } - if (this.isPreparingModelSelectorPopover) { - return; - } - - if (this.presentation === ComposerPresentation.Compact) { - // On a phone this is an in-place upward menu, not a modal sheet. Keep the - // IME visible so model switching does not interrupt prompt composition. - this.showModelSelectorPopover = true; - return; - } - - // Keep the expanded composer and its model-control anchor mounted while the - // IME releases the window. Opening the popup before this completes makes its - // viewport and hit-testing inherit the keyboard-constrained layout. - this.isPreparingModelSelectorPopover = true; - await this.releaseComposerKeyboard(); - - if (!this.isPreparingModelSelectorPopover || this.presentation !== ComposerPresentation.Floating) { - return; - } - this.showModelSelectorPopover = true; - this.isPreparingModelSelectorPopover = false; - } - - private async releaseComposerKeyboard(): Promise { - const hostContext = this.getUIContext().getHostContext(); - if (!hostContext) { - this.getUIContext().getFocusController().clearFocus(); - return; - } - - try { - await KeyboardReleaseService.release(hostContext); - } catch (_error) { - // A draft can keep the composer expanded without an active keyboard or - // window event. Releasing focus still leaves the model anchor mounted. - } - this.getUIContext().getFocusController().clearFocus(); - } - - private beginModelSelectionFromComposer(): void { - if (!this.inputFocused) { - return; - } - this.keepExpandedForModelSelection = true; - this.restoreInputFocusAfterModelSelection = true; - } - - private restoreComposerFocusAfterModelSelection(): void { - if (!this.restoreInputFocusAfterModelSelection || this.showModelSelectorPopover || - this.isPreparingModelSelectorPopover) { - return; - } - if (this.restoreInputFocusTimerId >= 0) { - clearTimeout(this.restoreInputFocusTimerId); - } - // Let the selector release its focus scope first. Retaining the expanded - // layout during this handoff removes the collapse/re-expand jump. - this.restoreInputFocusTimerId = setTimeout(() => { - this.restoreInputFocusTimerId = -1; - try { - this.getUIContext().getFocusController().requestFocus(this.inputId); - } catch (_error) { - // If the route disappeared during dismissal, component teardown owns - // the continuation and clears its timer. - } - }, MobileDesignMotion.structure); - } - - private cancelModelSelectionEditingContinuation(): void { - if (this.restoreInputFocusTimerId >= 0) { - clearTimeout(this.restoreInputFocusTimerId); - this.restoreInputFocusTimerId = -1; - } - this.restoreInputFocusAfterModelSelection = false; - this.keepExpandedForModelSelection = false; - } - - private async startVoiceInput(): Promise { - await this.releaseComposerKeyboard(); - this.onVoiceInput(); - } - - private inputPlaceholder(): string { - return this.isVoiceListening ? - RemoteI18n.t('chat.voiceListeningPlaceholder') : - RemoteI18n.t('chat.inputPlaceholder'); - } - - private inactiveActionBackgroundColor(): ResourceColor { - const action = this.primaryAction(); - if (action === ComposerPrimaryAction.Send || action === ComposerPrimaryAction.Stop || - this.sendTransitionActive) { - return TRANSPARENT; - } - if (action === ComposerPrimaryAction.Voice) { - return CARD; - } - if (action === ComposerPrimaryAction.SendBlocked || action === ComposerPrimaryAction.VoiceBlocked || - action === ComposerPrimaryAction.Idle) { - return SOFT; - } - return TRANSPARENT; - } - - private shouldShowActiveActionSurface(): boolean { - const action = this.primaryAction(); - return this.sendTransitionActive || action === ComposerPrimaryAction.Send || - action === ComposerPrimaryAction.SendBlocked || action === ComposerPrimaryAction.Stop; - } - - private shouldShowStopGlyph(): boolean { - return this.primaryAction() === ComposerPrimaryAction.Stop; - } - - private activeActionSurfaceColor(): ResourceColor { - if (this.primaryAction() === ComposerPrimaryAction.SendBlocked) { - return SOFT; - } - return this.primaryActionPressed || this.sendTransitionActive ? MUTED : INK; - } - - private beginSendTransition(): void { - this.primaryActionPressed = false; - this.sendTransitionActive = true; - if (this.sendTransitionTimerId >= 0) { - clearTimeout(this.sendTransitionTimerId); - } - this.sendTransitionTimerId = setTimeout(() => { - this.sendTransitionActive = false; - this.sendTransitionTimerId = -1; - }, COMPOSER_SEND_TRANSITION_DURATION); - } - - private primaryActionForegroundColor(): ResourceColor { - const action = this.primaryAction(); - if (action === ComposerPrimaryAction.Voice) { - return INK; - } - if (action === ComposerPrimaryAction.Send || action === ComposerPrimaryAction.Stop) { - return CARD; - } - return MUTED; - } -} 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 deleted file mode 100644 index eb33613f06..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectAccountDevicePage.ets +++ /dev/null @@ -1,209 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -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'; - @Event onBack: () => void = () => {}; - @Event cloudListDevices: () => Promise = - async (): Promise => []; - @Event cloudSelectDevice: (device: CloudAccountDevice) => Promise = - async (_device: CloudAccountDevice): Promise => {}; - @Local accountDevicesBusy: boolean = false; - @Local accountDevicesError: string = ''; - @Local switchingDeviceId: string = ''; - - aboutToAppear(): void { - this.refreshAccountDevices(); - } - - build() { - Column() { - Row({ space: 16 }) { - NavigationBackButton({ - controlSize: 48, - onBack: (): void => this.onBack() - }) - Column({ space: 4 }) { - Text(RemoteI18n.t('connect.accountDevicesTitle')) - .fontSize(MobileDesignTypography.headlineLarge.size).fontWeight(FontWeight.Bold).fontColor(INK).width('100%') - Text(RemoteI18n.t('connect.accountDevicesSubtitle')) - .fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).width('100%') - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%').height(92) - .padding({ left: 28, right: 28, top: 18 }) - .alignItems(VerticalAlign.Top) - - Scroll() { - Column({ space: 18 }) { - Text(RemoteI18n.t('connect.accountDevicesBody')) - .fontSize(MobileDesignTypography.bodyMedium.size).lineHeight(MobileDesignTypography.bodyMedium.lineHeight).fontColor(MUTED).width('100%') - this.AccountDeviceList() - } - .width('100%') - .constraintSize({ minHeight: '100%' }) - .padding({ left: 28, right: 28, top: 10, bottom: 34 }) - } - .layoutWeight(1) - .width('100%') - .scrollBar(BarState.Off) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private AccountDeviceList() { - Column({ space: 4 }) { - Row() { - Text(RemoteI18n.t('connect.availableDevices')) - .fontSize(MobileDesignTypography.bodyLarge.size).fontWeight(FontWeight.Bold).fontColor(INK) - Blank() - Text(this.accountDevicesBusy ? RemoteI18n.t('common.loading') : - (this.accountDevicesError.length > 0 ? RemoteI18n.t('common.retry') : RemoteI18n.t('common.refresh'))) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(this.accountDevicesBusy ? MUTED : - (this.accountDevicesError.length > 0 ? STATUS_DANGER : ACCENT)) - .onClick(async () => { await this.refreshAccountDevices(); }) - } - .width('100%').height(38) - - if (this.accountDevicesBusy && this.directoryState.devices.length === 0) { - Column() { - this.AccountDeviceSkeletonRow() - this.AccountDeviceSkeletonRow() - } - .width('100%').height(120) - } else if (this.desktopDevices().length === 0) { - Row() { - Text(this.accountDevicesError || RemoteI18n.t('remote.settings.deviceEmpty')) - .fontSize(MobileDesignTypography.bodyMedium.size).lineHeight(MobileDesignTypography.bodyMedium.lineHeight).fontColor(MUTED).width('100%') - } - .width('100%').height(120).alignItems(VerticalAlign.Center) - } else { - Scroll() { - Column() { - ForEach(this.desktopDevices(), (device: CloudAccountDevice) => { - this.AccountConnectDeviceRow(device) - }, (device: CloudAccountDevice): string => - `${device.deviceId}:${device.online ? 'online' : 'offline'}:${device.lastSeenAt || 0}:${accountDeviceDisplayName(device)}`) - } - .width('100%') - } - .width('100%').height(120).scrollBar(BarState.Off) - } - } - .width('100%').height(174) - .padding({ left: 16, right: 16, top: 8, bottom: 8 }) - .backgroundColor(CARD).borderRadius(8).border({ width: 1, color: LINE }) - } - - @Builder - private AccountDeviceSkeletonRow() { - Row({ space: 12 }) { - Text('').width(26).height(22).backgroundColor(SOFT).borderRadius(5) - Column({ space: 7 }) { - Text('').width('58%').height(12).backgroundColor(SOFT).borderRadius(4) - Text('').width(52).height(9).backgroundColor(SOFT).borderRadius(4) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%').height(60).padding({ left: 4, right: 4 }).alignItems(VerticalAlign.Center) - } - - @Builder - private AccountConnectDeviceRow(device: CloudAccountDevice) { - Row({ space: 12 }) { - SymbolGlyph($r('sys.symbol.desktop')) - .fontSize(22).fontColor([MUTED]).width(26).height(24).opacity(device.online ? 0.68 : 0.38) - Column({ space: 3 }) { - Text(accountDeviceDisplayName(device)) - .fontSize(MobileDesignTypography.titleSmall.size).fontWeight(FontWeight.Medium).fontColor(INK) - .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.accountDeviceStatus(device)) - .fontSize(MobileDesignTypography.bodySmall.size).fontColor(device.online ? STATUS_SUCCESS : MUTED) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - if (this.canSelectAccountDevice(device) && AccountDeviceSelectionPolicy.shouldShowConnectAction( - device.online, device.deviceId, this.deviceId, this.controlTargetDeviceId, this.connectionState - )) { - Text(this.switchingDeviceId === device.deviceId ? - RemoteI18n.t('remote.settings.deviceConnecting') : RemoteI18n.t('connect.connect')) - .fontSize(MobileDesignTypography.bodyMedium.size).fontColor(INK) - .padding({ left: 10, right: 10, top: 6, bottom: 6 }) - .backgroundColor(SOFT).borderRadius(14) - } else if (device.online) { - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(13).fontColor([MUTED]).opacity(0.44) - } - } - .width('100%').height(60).padding({ left: 4, right: 4 }) - .alignItems(VerticalAlign.Center) - .opacity(this.canSelectAccountDevice(device) ? 1 : 0.64) - .onClick(async () => { - if (!this.canSelectAccountDevice(device)) return; - this.switchingDeviceId = device.deviceId; - this.accountDevicesError = ''; - try { - await this.cloudSelectDevice(device); - } catch (err) { - this.accountDevicesError = err instanceof Error ? err.message : - RemoteI18n.t('remote.settings.deviceSwitchFailed'); - } finally { - this.switchingDeviceId = ''; - } - }) - } - - private async refreshAccountDevices(): Promise { - if (this.accountDevicesBusy) return; - this.accountDevicesBusy = true; - this.accountDevicesError = ''; - try { - await this.cloudListDevices(); - } catch (err) { - this.accountDevicesError = err instanceof Error ? err.message : - RemoteI18n.t('remote.settings.deviceLoadFailed'); - } finally { - this.accountDevicesBusy = false; - } - } - - private desktopDevices(): DeviceDirectoryEntry[] { - return this.directoryState.devices.filter((device: DeviceDirectoryEntry): boolean => - device.deviceId !== this.deviceId && device.deviceName !== 'HarmonyOS Phone'); - } - - private canSelectAccountDevice(device: CloudAccountDevice): boolean { - return AccountDeviceSelectionPolicy.canSelectOnline( - device.online, device.deviceId, this.deviceId, this.switchingDeviceId - ); - } - - private accountDeviceStatus(device: CloudAccountDevice): string { - if (device.deviceId === this.switchingDeviceId) { - return RemoteI18n.t('remote.settings.deviceConnecting'); - } - const presence = device.online ? RemoteI18n.t('remote.settings.deviceOnline') : - RemoteI18n.t('remote.settings.deviceOffline'); - if (device.deviceId === this.controlTargetDeviceId && this.connectionState === 'connected') { - return `${RemoteI18n.t('remote.settings.deviceControlling')} · ${presence}`; - } - if (device.deviceId === this.controlTargetDeviceId) { - return `${RemoteI18n.t('connect.deviceLastUsed')} · ${presence}`; - } - return presence; - } -} 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 deleted file mode 100644 index aa0ed54087..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectView.ets +++ /dev/null @@ -1,310 +0,0 @@ -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'; -import { - ConnectSheetLandingPolicy, - ConnectSheetStatusPolicy, - ConnectSheetStep -} from '../policy/ConnectSheetLandingPolicy'; -import { CARD, CONNECT_HERO_ACCENT, CONNECT_HERO_BG, CONNECT_HERO_SECONDARY, - CONNECT_HERO_SURFACE, INK, MUTED, SOFT, STATUS_DANGER, STATUS_SUCCESS, SUBTLE } from './Theme'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; - -/** - * Connect sheet. A signed-in phone picks a desktop from the account device - * directory; a signed-out phone is sent to account sign-in. The phone no - * longer creates pairings from a scanned or pasted link. A link persisted by - * an older version is still shown in the status strip and can be retried. - */ -@ComponentV2 -export struct ConnectView { - @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param remoteUrl: string = ''; - @Param userId: string = ''; - @Param statusText: string = RemoteI18n.t('status.waitingConnection'); - @Param connectionState: string = 'idle'; - @Param connectionFailureKind: string = ''; - @Param isBusy: boolean = false; - @Param isConnected: boolean = false; - @Param desktopName: string = ''; - @Param deviceId: string = ''; - @Param accountUserId: string = ''; - @Param controlTargetDeviceId: string = ''; - @Event onBack: () => void = () => {}; - @Event onOpenAccount: () => void = () => {}; - @Event onConnect: () => void = () => {}; - @Event cloudListDevices: () => Promise = async (): Promise => []; - @Event cloudSelectDevice: (device: CloudAccountDevice) => Promise = - async (_device: CloudAccountDevice): Promise => {}; - /** - * The sheet's own bottom edge, in vp. The connect sheet is full-height and - * its status strip is the fixed control at that edge, so the strip keeps the - * navigation bar clear itself. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Stack() { - if (this.currentStep() === ConnectSheetStep.Account) { - this.AccountDeviceSelectionPage() - } else { - this.IntroPairingPage() - } - } - .width('100%') - .height('100%') - .backgroundColor(CARD) - } - - @Builder - AccountDeviceSelectionPage() { - ConnectAccountDevicePage({ - directoryState: this.directoryState, - deviceId: this.deviceId, - controlTargetDeviceId: this.controlTargetDeviceId, - connectionState: this.connectionState, - cloudListDevices: this.cloudListDevices, - cloudSelectDevice: this.cloudSelectDevice, - onBack: () => { - this.onBack(); - }, - }) - } - - @Builder - IntroPairingPage() { - Column() { - Stack() { - this.HeroWash() - this.BackButton() - } - .width('100%') - .height(250) - - Column({ space: 18 }) { - this.DesktopGlyph() - Text(RemoteI18n.t('connect.chooseConnectionTitle')) - .fontSize(MobileDesignTypography.displayLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(INK) - .textAlign(TextAlign.Center) - .width('100%') - - AppActionButton({ - label: RemoteI18n.t('sidebar.signInOpenBitFunAccount'), - style: AppActionStyle.Secondary, - actionHeight: 58, - onAction: (): void => { - this.onOpenAccount(); - } - }) - .width('82%') - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Center) - .margin({ top: -24 }) - - if (this.shouldShowStatusStrip()) { - this.StatusStrip() - } - } - .width('100%') - .height('100%') - // The sheet's fill runs to its bottom edge; the status strip is the fixed - // control there, and it keeps the navigation bar clear itself. - .padding({ bottom: this.insets.bottomPadding(28) }) - .backgroundColor(CARD) - } - - @Builder - HeroWash() { - Stack() { - Text('') - .width('100%') - .height(282) - .backgroundColor(CONNECT_HERO_BG) - .borderRadius(36) - Text('') - .width(260) - .height(142) - .backgroundColor(CONNECT_HERO_SURFACE) - .opacity(0.7) - .borderRadius(72) - .position({ x: 112, y: 26 }) - Text('') - .width(188) - .height(134) - .backgroundColor(CONNECT_HERO_ACCENT) - .opacity(0.42) - .borderRadius(68) - .position({ x: -42, y: 198 }) - Text('') - .width(188) - .height(126) - .backgroundColor(CONNECT_HERO_SECONDARY) - .opacity(0.54) - .borderRadius(64) - .position({ x: 258, y: 0 }) - } - .width('100%') - .height(282) - } - - @Builder - BackButton() { - NavigationBackButton({ - controlSize: 48, - onBack: (): void => { - this.onBack(); - } - }) - .position({ x: 28, y: 18 }) - } - - @Builder - DesktopGlyph() { - Stack() { - Text('') - .width(58) - .height(39) - .borderRadius(8) - .border({ width: 5, color: INK }) - .position({ x: 5, y: 0 }) - Text('') - .width(26) - .height(13) - .border({ width: 5, color: INK }) - .position({ x: 21, y: 38 }) - } - .width(68) - .height(55) - .margin({ bottom: 4 }) - } - - @Builder - StatusStrip() { - Column({ space: 8 }) { - Row({ space: 8 }) { - Text('●') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(this.statusDotColor()) - Text(this.statusDetail()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.isConnectError() ? INK : MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .height(30) - .padding({ left: 12, right: 12 }) - .backgroundColor(SOFT) - .borderRadius(15) - .onClick(() => { - this.handleStatusClick(); - }) - if (this.isConnectError() && this.failureHint().length > 0) { - Text(this.failureHint()) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .width('78%') - } - } - .width('100%') - .alignItems(HorizontalAlign.Center) - } - - private statusDotColor(): ResourceColor { - if (this.isConnected) { - return STATUS_SUCCESS; - } - if (this.isConnectError()) { - return STATUS_DANGER; - } - if (this.isBusy || this.connectionState === 'parsing' || this.connectionState === 'pairing' || this.connectionState === 'reconnecting') { - return INK; - } - return SUBTLE; - } - - private statusDetail(): string { - if (this.remoteUrl.trim().length === 0) { - return RemoteI18n.t('connect.noDesktopDetail'); - } - if (this.isConnected) { - return RemoteI18n.f2('connect.connectedTo', this.userId || this.deviceId, this.desktopName); - } - if (this.isBusy || this.connectionState === 'parsing' || this.connectionState === 'pairing' || this.connectionState === 'reconnecting') { - return this.statusText || RemoteI18n.t('connect.connecting'); - } - if (this.isConnectError()) { - return this.statusText || RemoteI18n.t('connect.cannotConnectDesktop'); - } - if (this.connectionState === 'disconnected') { - return this.statusText || RemoteI18n.t('connect.desktopDisconnected'); - } - return RemoteI18n.t('connect.waitingDesktop'); - } - - private handleStatusClick(): void { - if (this.isBusy) { - return; - } - if (this.remoteUrl.trim().length > 0) { - this.onConnect(); - return; - } - if (!this.isAccountAuthenticated()) { - this.onOpenAccount(); - } - } - - private currentStep(): string { - return ConnectSheetLandingPolicy.step(this.isAccountAuthenticated()); - } - - private isAccountAuthenticated(): boolean { - return this.accountUserId.trim().length > 0; - } - - private shouldShowStatusStrip(): boolean { - return this.remoteUrl.trim().length > 0 || - this.isBusy || - this.isConnected || - this.isConnectError() || - this.connectionState === 'disconnected' || - this.connectionState === 'reconnecting'; - } - - private isConnectError(): boolean { - return ConnectSheetStatusPolicy.isConnectError( - this.connectionState, - this.isBusy, - this.isConnected, - this.statusText, - RemoteI18n.t('common.failed'), - RemoteI18n.t('errors.remoteUrlMissingParams'), - RemoteI18n.t('errors.remoteUrlRequired') - ); - } - - private failureHint(): string { - const key = ConnectSheetStatusPolicy.failureHintKey(this.connectionFailureKind); - return key.length > 0 ? RemoteI18n.t(key) : ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationHeader.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationHeader.ets deleted file mode 100644 index 59c83ec861..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationHeader.ets +++ /dev/null @@ -1,258 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { - ACCENT, - CARD, - CONTENT_ON_ACTION, - INK, - LINE, - MUTED, - PAGE_BG, - SHADOW_SUBTLE, - SOFT, - TRANSPARENT, -} from './Theme'; -import { CompactMenuButton } from './CompactMenuButton'; -import { NavigationBackButton } from './NavigationBackButton'; -import { TemplateIcon } from './TemplateIcon'; -import { SidebarToggleButton } from './SidebarToggleButton'; - -const HEADER_ACTION_SURFACE_SIZE: number = 42; - -@ComponentV2 -export struct ConversationHeader { - @Param title: string = ''; - @Param subtitle: string = ''; - @Param titleFallback: string = ''; - @Param allowRename: boolean = false; - @Param showActions: boolean = false; - @Param showSidebarButton: boolean = true; - @Param showBackButton: boolean = false; - /** - * Set when something behind the header is meant to show through — a - * conversation whose transcript scrolls underneath it. The caller owns the - * fill and the blur in that case; painting an opaque page colour here would - * cover both. - */ - @Param translucent: boolean = false; - @Param showSidebarRestoreButton: boolean = false; - @Param showActionsMenu: boolean = false; - @BuilderParam actionsMenu: () => void = this.EmptyBuilder; - @Event onOpenSidebar: () => void = () => {}; - @Event onRestoreSidebar: () => void = () => {}; - @Event onBack: () => void = () => {}; - @Event onOpenActions: () => void = () => {}; - @Event onActionsMenuStateChange: (visible: boolean) => void = (_visible: boolean) => {}; - @Event onRenameSession: (title: string) => void = (_title: string) => {}; - @Local showTitleEditor: boolean = false; - @Local renameTitle: string = ''; - - build() { - Column() { - this.HeaderRow() - if (this.showTitleEditor) { - this.TitleEditor() - } - } - .width('100%') - .backgroundColor(this.translucent ? TRANSPARENT : PAGE_BG) - } - - @Builder - private HeaderRow() { - Row({ space: 8 }) { - this.LeadingControl() - this.TitleBlock() - this.TrailingControl() - } - .width('100%') - .height(MobileDesignGeometry.conversationHeaderHeight) - .alignItems(VerticalAlign.Center) - .padding({ - left: MobileDesignGeometry.contentGutter, - right: MobileDesignGeometry.contentGutter, - top: 8, - bottom: 8 - }) - .backgroundColor(this.translucent ? TRANSPARENT : PAGE_BG) - } - - @Builder - private TitleBlock() { - Column({ space: 3 }) { - Text(this.resolvedTitle()) - .fontSize(this.hasSubtitle() ? MobileDesignTypography.conversationHeaderTitle.size : - MobileDesignTypography.titleMedium.size) - .lineHeight(this.hasSubtitle() ? MobileDesignTypography.conversationHeaderTitle.lineHeight : - MobileDesignTypography.titleMedium.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .textAlign(TextAlign.Center) - .onClick(() => { - if (!this.allowRename) { - return; - } - this.renameTitle = this.title; - this.showTitleEditor = true; - }) - if (this.hasSubtitle()) { - Text(this.subtitle) - .fontSize(MobileDesignTypography.labelMedium.size) - .lineHeight(MobileDesignTypography.labelMedium.lineHeight) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .textAlign(TextAlign.Center) - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Center) - } - - @Builder - private LeadingControl() { - if (this.showSidebarRestoreButton) { - SidebarToggleButton({ - restore: true, - controlSize: MobileDesignGeometry.controlTouchSize, - onToggle: this.onRestoreSidebar - }) - } else if (this.showBackButton) { - NavigationBackButton({ - controlSize: MobileDesignGeometry.controlTouchSize, - onBack: (): void => { - this.onBack(); - } - }) - } else if (this.showSidebarButton) { - CompactMenuButton({ - controlSize: MobileDesignGeometry.controlTouchSize, - onOpen: () => { - this.onOpenSidebar(); - } - }) - } else { - Blank() - .width(MobileDesignGeometry.controlTouchSize) - .height(MobileDesignGeometry.controlTouchSize) - } - } - - @Builder - private TrailingControl() { - if (this.showActions) { - Button() { - Stack({ alignContent: Alignment.Center }) { - TemplateIcon({ - src: $r('app.media.remote_ref_more'), - iconWidth: 23, - iconHeight: 7 - }) - } - .width(HEADER_ACTION_SURFACE_SIZE) - .height(HEADER_ACTION_SURFACE_SIZE) - .backgroundColor(CARD) - .borderRadius(HEADER_ACTION_SURFACE_SIZE / 2) - .shadow({ radius: 30, color: SHADOW_SUBTLE, offsetY: 7 }) - .hitTestBehavior(HitTestMode.None) - } - .width(MobileDesignGeometry.controlTouchSize) - .height(MobileDesignGeometry.controlTouchSize) - .padding(0) - .backgroundColor(TRANSPARENT) - .borderRadius(MobileDesignGeometry.controlTouchSize / 2) - .stateEffect(true) - .accessibilityText(RemoteI18n.t('sidebar.more')) - .bindPopup(this.showActionsMenu, { - builder: () => { - this.actionsMenu(); - }, - placement: Placement.BottomRight, - popupColor: TRANSPARENT, - enableArrow: false, - autoCancel: true, - mask: false, - targetSpace: 8, - onStateChange: (event) => { - this.onActionsMenuStateChange(event.isVisible); - } - }) - .onClick(() => { - this.showTitleEditor = false; - this.onOpenActions(); - }) - } else { - Blank() - .width(MobileDesignGeometry.controlTouchSize) - .height(MobileDesignGeometry.controlTouchSize) - } - } - - @Builder - private TitleEditor() { - Row({ space: 8 }) { - TextInput({ placeholder: RemoteI18n.t('chat.sessionTitle'), text: this.renameTitle }) - .layoutWeight(1) - .height(42) - .fontSize(MobileDesignTypography.bodyMedium.size) - .backgroundColor(CARD) - .borderRadius(14) - .padding({ left: 12, right: 12 }) - .border({ width: 1, color: LINE }) - .defaultFocus(false) - .onChange((value: string) => { - this.renameTitle = value; - }) - Text(RemoteI18n.t('common.save')) - .width(52) - .height(42) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(CONTENT_ON_ACTION) - .textAlign(TextAlign.Center) - .backgroundColor(this.renameTitle.trim().length > 0 ? ACCENT : SOFT) - .borderRadius(14) - .onClick(() => { - if (this.renameTitle.trim().length > 0) { - this.onRenameSession(this.renameTitle.trim()); - this.showTitleEditor = false; - } - }) - Text(RemoteI18n.t('common.cancel')) - .width(52) - .height(42) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(INK) - .textAlign(TextAlign.Center) - .backgroundColor(SOFT) - .borderRadius(14) - .onClick(() => { - this.showTitleEditor = false; - }) - } - .width('100%') - .padding({ - left: MobileDesignGeometry.contentGutter, - right: MobileDesignGeometry.contentGutter, - top: 10, - bottom: 8 - }) - .backgroundColor(PAGE_BG) - } - - private resolvedTitle(): string { - if (this.title.length > 0) { - return this.title; - } - return this.titleFallback; - } - - private hasSubtitle(): boolean { - return this.subtitle.length > 0; - } - - @Builder - private EmptyBuilder() { - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationLoadingState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationLoadingState.ets deleted file mode 100644 index 1d8fb95753..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationLoadingState.ets +++ /dev/null @@ -1,59 +0,0 @@ -import { LINE, SOFT } from './Theme'; - -@ComponentV2 -export struct ConversationLoadingState { - @Param maxContentWidth: number = 0; - @Param topInset: number = 0; - - build() { - Row() { - Column({ space: 18 }) { - this.AssistantSkeleton(78, '72%') - this.UserSkeleton(42, '46%') - this.AssistantSkeleton(112, '84%') - } - .width('100%') - .constraintSize({ maxWidth: this.maxContentWidth > 0 ? this.maxContentWidth : '100%' }) - .padding({ left: 22, right: 22, top: this.topInset + 28, bottom: 28 }) - } - .width('100%') - .height('100%') - .justifyContent(FlexAlign.Center) - .alignItems(VerticalAlign.Top) - } - - @Builder - private AssistantSkeleton(height: number, width: string) { - Row() { - Column({ space: 9 }) { - Text('').width('74%').height(10).backgroundColor(LINE).borderRadius(5) - Text('').width('92%').height(10).backgroundColor(LINE).borderRadius(5) - Text('').width('58%').height(10).backgroundColor(LINE).borderRadius(5) - } - .width(width) - .height(height) - .padding({ left: 14, right: 14, top: 14, bottom: 14 }) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Start) - .backgroundColor(SOFT) - .borderRadius(10) - Blank().layoutWeight(1) - } - .width('100%') - .height(height) - } - - @Builder - private UserSkeleton(height: number, width: string) { - Row() { - Blank().layoutWeight(1) - Text('') - .width(width) - .height(height) - .backgroundColor(SOFT) - .borderRadius(10) - } - .width('100%') - .height(height) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationRouteSurface.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationRouteSurface.ets deleted file mode 100644 index a1190d4590..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationRouteSurface.ets +++ /dev/null @@ -1,97 +0,0 @@ -import { ConversationIntent } from '../actions/ConversationIntent'; -import { - AppRootPresentationActions, - emptyAppRootPresentationActions -} from '../actions/AppRootPresentationActions'; -import { AppRoute } from '../navigation/AppRouteContract'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { FilePreviewPhase, FilePreviewState } from '../state/FilePreviewState'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { RemotePageState } from '../state/RemotePageState'; -import { ComposerPresentation } from './ComposerBar'; -import { ConversationViewHost } from './ConversationViewHost'; -import { - RemoteSurfaceHost, - RemoteSurfaceMode, - RemoteSurfaceState -} from './remote/RemoteSurfaceHost'; -import { ConversationViewState } from '../state/ConversationViewState'; -import { PAGE_BG } from './Theme'; - -@ComponentV2 -export struct ConversationRouteSurface { - @Param route: AppRoute = AppRoute.RemoteHome; - @Param remotePageState: RemotePageState = new RemotePageState(); - @Param generalPageState: GeneralChatPageState = new GeneralChatPageState(); - @Param filePreviewState: FilePreviewState = new FilePreviewState(); - @Param remoteSurfaceState: RemoteSurfaceState = new RemoteSurfaceState(); - @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - @Param showSidebarButton: boolean = true; - @Param showBackButton: boolean = false; - @Param showSidebarRestoreButton: boolean = false; - @Param useWidePresentation: boolean = false; - @Param hoverOperateMode: boolean = false; - @Param fullTextSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - @Param skillPickerSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SkillPicker); - @Param usageReportSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UsageReport); - @Event onRestoreSidebar: () => void = () => {}; - - build() { - Column() { - if (this.route !== AppRoute.RemoteChat) { - RemoteSurfaceHost({ - mode: RemoteSurfaceMode.CompactHome, - remotePageState: this.remotePageState, - presentationState: this.remoteSurfaceState, - actions: this.actions, - onOpenSidebar: this.actions.onRemoteHome.openSidebar - }) - } else { - ConversationViewHost({ - viewState: ConversationViewState.project( - this.route, - this.remotePageState, - this.generalPageState, - this.actions.generalStatus() - ), - activeFilePreviewPath: this.route === AppRoute.RemoteChat && this.filePreviewState.visible ? - this.filePreviewState.target.remotePath : '', - activeFilePreviewLoading: this.route === AppRoute.RemoteChat && this.filePreviewState.visible && - this.filePreviewState.phase === FilePreviewPhase.Loading, - showSidebarButton: this.showSidebarButton, - showBackButton: this.showBackButton, - showSidebarRestoreButton: this.showSidebarRestoreButton, - composerPresentation: this.composerPresentation(), - composerInputId: 'conversation-composer-input', - hoverOperateMode: this.hoverOperateMode, - fullTextSheetPlacement: this.fullTextSheetPlacement, - skillPickerSheetPlacement: this.skillPickerSheetPlacement, - usageReportSheetPlacement: this.usageReportSheetPlacement, - onRestoreSidebar: this.onRestoreSidebar, - onIntent: (intent: ConversationIntent) => this.dispatchConversationIntent(intent) - }) - } - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - private composerPresentation(): ComposerPresentation { - if (this.useWidePresentation) { - return ComposerPresentation.Floating; - } - return ComposerPresentation.Compact; - } - - private dispatchConversationIntent(intent: ConversationIntent): void { - this.actions.onConversationIntent(this.route, intent); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets deleted file mode 100644 index f31af5689b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets +++ /dev/null @@ -1,1170 +0,0 @@ -import { MessageQueuePanel } from './MessageQueuePanel'; -import { MessageQueueAction } from '../../model/MessageQueue'; -import { InteractionMailboxPanel } from './InteractionMailboxPanel'; -import { InteractionMailboxAction } from '../../model/InteractionMailbox'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { KeyboardAvoidMode } from '@kit.ArkUI'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ChatTimelineItem, ChatTimelineRevisionTracker, ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ConnectionStatusPresenter } from '../../services/ConnectionStatusPresenter'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { ChatComposerCapabilities } from '../state/ChatComposerCapabilities'; -import { ChatSurface } from '../state/ChatSurface'; -import { ConversationViewState } from '../state/ConversationViewState'; -import { - CommandPaletteAction, - CommandPaletteRequest, - ConversationIntent, - ConversationIntents, - ConversationIntentType, - MessageCopyScope -} from '../actions/ConversationIntent'; -import { CommandPalettePresentation } from '../state/CommandPaletteState'; -import { SettingsPlacement } from '../policy/SettingsPlacementPolicy'; -import { - RollbackBarPresentation, - RollbackGhostRow, - RollbackPresentationPolicy -} from '../policy/RollbackPresentationPolicy'; -import { - SessionRollbackEffect, - SessionRollbackEffectType, - SessionRollbackEvent, - SessionRollbackEventType, - SessionRollbackIdleState, - SessionRollbackPolicy, - SessionRollbackStage, - SessionRollbackState, - SessionRollbackStagingState -} from '../policy/SessionRollbackPolicy'; -import { RollbackStagingBar } from './RollbackStagingBar'; -import { AdaptiveSheetOptions } from './AdaptiveSheetOptions'; -import { ChatTimeline } from './ChatTimeline'; -import { CommandChipRow } from './CommandChipRow'; -import { ConversationLoadingState } from './ConversationLoadingState'; -import { SkillPickerSheet } from './SkillPickerSheet'; -import { UsageReportSheet } from './UsageReportSheet'; -import { UserMessageFullTextSheet } from './UserMessageFullTextSheet'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { - ConversationViewContract, - ConversationViewOptions -} from './ConversationViewContract'; -import { - ConversationUiModelCatalog, - ConversationUiQuestionAnswer, - ConversationUiSelectedImage, - ConversationUiSession -} from '../state/ConversationUiModels'; -import { ComposerBar, ComposerPresentation } from './ComposerBar'; -import { ConversationHeader } from './ConversationHeader'; -import { ConversationHeaderPolicy, ConversationHeaderPresentation } from '../policy/ConversationHeaderPolicy'; -import { - CARD, - INK, - LINE, - MUTED, - PAGE_BG, - PAGE_BG_FADE, - PAGE_BG_OVERLAY, - SHADOW_SUBTLE, - SOFT, - STATUS_DANGER, - STATUS_SUCCESS, - TRANSPARENT, -} from './Theme'; - -/** - * The overlay sheets the conversation can present, one at a time. - * - * The root node carries a single sheet binding, so which sheet is up has to be - * named rather than counted: a second `bindSheet` on the same node is dropped, - * and with it every sheet that node was meant to open. - */ -const CONVERSATION_SHEET_NONE: string = ''; -const CONVERSATION_SHEET_FULL_TEXT: string = 'full_text'; -const CONVERSATION_SHEET_SKILLS: string = 'skills'; -const CONVERSATION_SHEET_USAGE: string = 'usage'; - -@ComponentV2 -export struct ConversationView { - @Param state: ConversationViewState = new ConversationViewState(); - @Param options: ConversationViewOptions = new ConversationViewOptions(); - @Event onIntent: (intent: ConversationIntent) => void = (_intent: ConversationIntent) => {}; - @Event onRestoreSidebar: () => void = () => {}; - @Local showHeaderActions: boolean = false; - /** - * Which overlay sheet this pane is presenting, and whether one is up. - * - * A node carries exactly one sheet binding, so the three sheets the - * conversation can open take turns on the root's single `bindSheet` rather - * than each adding a binding beside it: a second binding on the same node is - * dropped, which silently costs every sheet on it. The kind is what the - * content and the options switch on, and the flag is what the framework - * writes back when the user drags the sheet away. - * - * This is state of the conversation rather than of the row that was - * long-pressed: the rows are virtualized and reused, and a sheet bound per row - * would fight the pool instead of the message it belongs to. It is view state, - * so it never becomes a projected field or an intent: nothing outside this pane - * reads it. - */ - @Local activeSheet: string = CONVERSATION_SHEET_NONE; - @Local sheetPresented: boolean = false; - @Local fullTextMessage: string = ''; - /** - * The turn the open full-text panel belongs to. - * - * The panel is a second rollback entry on the same message, and a rollback - * addresses the turn rather than what the message displays, so the turn travels - * with the text that opened the panel. - */ - @Local fullTextTurnId: string = ''; - /** - * The staged rollback, held as three primitives rather than as one state object. - * - * The reducer stays the owner of the staging rules — which exits exist, what - * each one does to the composer, what a host outcome means after the exit — and - * these three fields are only what this pane has to keep between events: - * `stagingTargetTurnId` also answers "is a rollback staged", since the entry - * refuses to stage a message that has no turn to address. They are re-projected - * into a `SessionRollbackState` for every event, so the snapshot rule (the first - * snapshot wins, a second entry keeps it) is still applied in exactly one place. - */ - @Local stagingTargetTurnId: string = ''; - @Local stagingTargetText: string = ''; - @Local composerSnapshot: string = ''; - /** - * The last host rollback outcome this pane has already acted on. - * - * A confirm leaves staging before the host answers, so the refusal has to come - * back through projected state and be consumed exactly once — compared by - * sequence, because the same refusal twice is two outcomes. - */ - @Local handledRollbackOutcomeSeq: number = 0; - private rollbackContextIdentity: string = ''; - /** - * How much of the pane the two floating layers cover, measured rather than - * assumed: the composer grows with multiline text and attachments, and the - * mailbox appears without warning. The transcript runs the full height behind - * them and borrows these as its content insets, so a stale number would leave - * the first or last message stuck under a capsule. - */ - @Local topInset: number = 0; - @Local bottomInset: number = 0; - /** - * The window's own insets, in vp. The shell is immersive, so the page draws - * from the top of the window and the composer keeps its distance from the - * bottom edge itself, which is what lets the transcript and its fade run to the - * very bottom of the screen without carrying the composer down with them. The - * header band reserves the top strip for the same reason: the band's own box is - * what the transcript borrows as its content start offset. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - private previousKeyboardAvoidMode: KeyboardAvoidMode = KeyboardAvoidMode.OFFSET; - - private get topSafeInset(): number { - return this.insets.top; - } - - private get bottomSafeInset(): number { - return this.insets.bottom; - } - - aboutToAppear(): void { - RemoteLogger.info(`conversation view mounted surface=${this.surface}`); - this.previousKeyboardAvoidMode = this.getUIContext().getKeyboardAvoidMode(); - this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - // Anything the host reported while this pane was away is already in the past - // for it: mounting is not a reason to resync a transcript it never showed, or - // to repeat a refusal the reader was already told about. - this.handledRollbackOutcomeSeq = this.state.rollbackOutcomeSeq; - this.rollbackContextIdentity = `${this.state.surface}:${this.state.activeSession.sessionId}:${this.state.sessionContextRevision}`; - } - - aboutToDisappear(): void { - RemoteLogger.info('conversation view disposed'); - this.insets.unbind(); - this.getUIContext().setKeyboardAvoidMode(this.previousKeyboardAvoidMode); - } - - build() { - Stack({ alignContent: Alignment.Top }) { - if (this.hoverOperateMode) { - this.HalfFoldedLayout() - } else { - this.FloatingLayout() - } - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .bindSheet($$this.sheetPresented, this.ActiveSheet(), this.activeSheetOptions()) - } - - /** - * The sheet that is up, built from the same kind the flag was opened with. - * - * Every branch closes by clearing the flag, because the sheet is dismissed by - * the framework and by its own affordances both. - */ - @Builder - private ActiveSheet() { - if (this.activeSheet === CONVERSATION_SHEET_FULL_TEXT) { - UserMessageFullTextSheet({ - text: this.fullTextMessage, - onClose: () => { - this.closeSheet(); - }, - onRollback: () => { - this.onRollbackMessage(this.fullTextTurnId, this.fullTextMessage); - } - }) - } else if (this.activeSheet === CONVERSATION_SHEET_SKILLS) { - SkillPickerSheet({ - palette: this.commandPalette, - onSelect: (skillId: string, skillLabel: string) => { - this.closeSheet(); - this.onIntent(ConversationIntents.commandPalette( - new CommandPaletteRequest(CommandPaletteAction.SelectSkill, skillId, '', skillLabel))); - }, - onRefresh: () => { - this.onIntent(ConversationIntents.commandPalette( - new CommandPaletteRequest(CommandPaletteAction.RefreshCatalog))); - }, - onClose: () => { - this.closeSheet(); - } - }) - } else if (this.activeSheet === CONVERSATION_SHEET_USAGE) { - UsageReportSheet({ - palette: this.commandPalette, - onRetry: () => { - this.onIntent(ConversationIntents.commandPalette( - new CommandPaletteRequest(CommandPaletteAction.RetryUsage))); - }, - onClose: () => { - this.closeSheet(); - } - }) - } - } - - private activeSheetOptions(): SheetOptions { - if (this.activeSheet === CONVERSATION_SHEET_FULL_TEXT) { - return this.adaptiveSheetOptions(this.fullTextSheetPlacement); - } - if (this.activeSheet === CONVERSATION_SHEET_SKILLS) { - return this.adaptiveSheetOptions(this.skillPickerSheetPlacement); - } - return this.adaptiveSheetOptions(this.usageReportSheetPlacement); - } - - private openSheet(kind: string): void { - this.activeSheet = kind; - this.sheetPresented = true; - } - - private closeSheet(): void { - this.sheetPresented = false; - } - - /** - * The transcript owns the whole pane; the header and the composer float over - * it and the transcript scrolls underneath both, fading out as it reaches - * either edge. Stack paints in order, so the body goes down first and the two - * overlay layers land on top of it. - */ - @Builder - private FloatingLayout() { - Column() { - this.ConversationBody() - } - .width('100%') - .height('100%') - - // A full-height layer that pins its content to the bottom. Stack aligns - // every child the same way, so the bottom layer carries its own alignment - // rather than fighting `alignContent`. It is see-through to touches above - // the composer, otherwise it would swallow every tap on the transcript. - Column() { - this.BottomOverlay() - } - .width('100%') - .height('100%') - .justifyContent(FlexAlign.End) - .hitTestBehavior(HitTestMode.Transparent) - - Column() { - this.TopOverlay() - } - .width('100%') - } - - /** - * Half-folded on a foldable the screen is physically two panes, and the - * transcript and the composer already have one each. Floating one over the - * other has nothing left to win there, so this layout stays stacked. - */ - @Builder - private HalfFoldedLayout() { - Column() { - this.Header() - this.Mailbox() - FolderStack() { - Column() { - this.ConversationBody() - } - .width('100%') - .height('100%') - .padding({ bottom: 12 }) - Column() { - this.InlineStatusLine() - this.Composer() - } - .width('100%') - // The composer pane of a half-folded screen is the bottom edge too, so it - // keeps the same distance from it as the floating layer does. - .padding({ bottom: this.bottomSafeInset }) - } - .alignContent(Alignment.Bottom) - .layoutWeight(1) - .width('100%') - .enableAnimation(true) - .autoHalfFold(true) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - @Builder - private TopOverlay() { - Column() { - Column() { - this.Header() - this.Mailbox() - } - .width('100%') - // Carried by the band that owns the background, not by the wrapper: the - // band is what has to reach the status bar, and its measured height is - // what the transcript borrows as its content start offset. Its sides are - // the window's wherever this page *is* the window — the compact layout, - // and the wide compositions that put it flush against an edge — so it - // reserves the side strips as well; the header's own gutter lives inside - // it and is not restated here. - // - // In the usual wide layout this page is the detail pane instead, and then - // only its right edge is the window's: the left one is the master pane's. - // A layout dump of that posture reads the left strip as a 21.14vp indent - // on a band that never touches that edge (see the note on `FlowPlaceholder` - // in RemoteSurfaceHost — the padding model cannot drop one side per edge, - // and dropping both would put the compact header back under the cutout). - .padding({ left: this.insets.leftPadding(0), right: this.insets.rightPadding(0), top: this.topSafeInset }) - .backgroundColor(PAGE_BG_OVERLAY) - .backgroundBlurStyle(BlurStyle.Thin) - // Named so a layout dump can be read against the pixels, the way the - // bottom fade is: this band's own box is what says where the page's top - // edge sits, and the side padding it carries is only visible in a dump as - // an offset between the box and its first child. - .id('conversation-top-band') - this.TopEdgeFade() - } - .width('100%') - .onAreaChange((_oldArea: Area, newArea: Area) => { - this.topInset = newArea.height as number; - }) - } - - @Builder - private BottomOverlay() { - Column() { - this.InlineStatusLine() - this.Composer() - } - .width('100%') - // The composer keeps the distance from the screen edge it had while the page - // area ended above the navigation bar, and the layer's own box grows by that - // strip: the gradient below is the layer's background, so it fills the strip - // and the transcript behind it reaches the bottom of the screen. Wherever the - // layer's sides are the window's — the compact layout, and the wide - // compositions that put the page flush against an edge — they are the - // layer's own business as well: the composer's gutter is inside it, and on a - // rotated device the camera cutout would otherwise sit over the first control - // of the row. In the usual wide layout the layer is the detail pane's width - // instead, so only its right edge is the window's and the left strip is an - // indent nothing needs; see the note on `TopOverlay` above. - .padding({ - left: this.insets.leftPadding(0), - right: this.insets.rightPadding(0), - bottom: this.bottomSafeInset - }) - // The fade covers the whole layer, not just a strip above it: the transcript - // runs behind the composer, so anything short of that leaves a line of text - // sitting crisp and legible beside the pill after it has already faded out - // higher up. It stops short of the page colour so the pill's blur still has - // something to work with. - .linearGradient({ - angle: 180, - colors: [[PAGE_BG_FADE, 0.0], [PAGE_BG_OVERLAY, 0.45], [PAGE_BG_OVERLAY, 1.0]] - }) - // This layer owns the bottom edge of the screen, so it is allowed to paint - // into it. Where the immersive layout already puts the page area there the - // two overlap and nothing extra is drawn; on a window that still ends above - // the navigation bar this is what keeps the strip from being bare page - // colour under the fade. The cutout is a separate avoid area, so the fade - // claims it as well: a device that rotated its camera onto an edge the fade - // reaches would otherwise show the page colour beside the gradient. Both of - // its sides are named because `expandSafeArea` is per edge and only takes - // effect where this box's own boundary meets that edge's safe-area - // boundary: a side the compact layer owns expands, and the same claim on the - // detail pane's left side — where the master pane is in between — draws - // nothing. `TOP` is deliberately absent: this layer is only as tall as the - // status line and the composer and sits at the bottom of the pane, so its - // top edge is nowhere near the window's top avoid area and naming it would - // claim a strip the fade never touches. - .expandSafeArea([SafeAreaType.SYSTEM, SafeAreaType.CUTOUT], - [SafeAreaEdge.START, SafeAreaEdge.END, SafeAreaEdge.BOTTOM]) - // Named so a layout dump can be read against the pixels: the fade's own box - // is what says where the chat page's bottom edge sits and how far the - // transcript can scroll, and neither is visible in the composer's bounds. - .id('conversation-bottom-fade') - .onAreaChange((_oldArea: Area, newArea: Area) => { - this.bottomInset = newArea.height as number; - }) - } - - /** - * Carries the header's opaque band down into the transcript. Without it a - * line of text is cut in half at the band's edge and reads as clipped rather - * than as continuing underneath. Never takes a touch: the transcript below - * it is still the thing being pointed at. The bottom layer needs no strip of - * its own — its whole background is the gradient. - */ - @Builder - private TopEdgeFade() { - Column() - .width('100%') - .height(MobileDesignGeometry.conversationEdgeFadeHeight) - .hitTestBehavior(HitTestMode.None) - .linearGradient({ - angle: 180, - colors: [[PAGE_BG, 0.0], [PAGE_BG_FADE, 1.0]] - }) - } - - @Builder - private InlineStatusLine() { - if (this.inlineStatusText.length > 0 && !this.shouldCenterInlineStatus()) { - Text(this.inlineStatusText) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .width('100%') - .padding({ left: 20, right: 20, bottom: 8 }) - } - } - - @Builder - private Mailbox() { - if (this.surface === ChatSurface.Remote && this.state.interactionMailbox.sessionId === this.state.activeSession.sessionId) { - InteractionMailboxPanel({ state: this.state.interactionMailbox, - onAction: (action: InteractionMailboxAction): void => this.onIntent(ConversationIntents.mailbox(action)) }) - } - } - - @Builder - private ConversationBody() { - if (this.shouldCenterInlineStatus()) { - this.CenteredInlineStatus() - } else { - // Keep the list subtree alive while a slow transcript is loading. The - // former top-level conditional destroyed and rebuilt ChatTimeline every - // time the 140 ms loading gate opened, losing its scroll state and making - // rapid session switches visibly flash. - Stack() { - Column() { - this.MessageList() - } - .width('100%') - .height('100%') - if (this.isLoadingTranscript) { - ConversationLoadingState({ - maxContentWidth: this.composerPresentation === ComposerPresentation.Floating ? 760 : 0, - topInset: this.hoverOperateMode ? 0 : this.topInset - }) - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - } - .width('100%') - .height('100%') - } - } - - @Builder - Header() { - ConversationHeader({ - translucent: true, - title: this.headerTitle(), - subtitle: this.headerSubtitle(), - titleFallback: this.headerFallback(), - allowRename: this.headerAllowRename(), - showActions: this.headerShowActions(), - showSidebarButton: this.showSidebarButton, - showBackButton: this.showBackButton, - showSidebarRestoreButton: this.showSidebarRestoreButton, - showActionsMenu: this.showHeaderActions, - actionsMenu: () => { - this.HeaderActionsPopover(); - }, - onOpenSidebar: () => { - this.onOpenSidebar(); - }, - onRestoreSidebar: () => { - this.onRestoreSidebar(); - }, - onBack: () => { - this.onBack(); - }, - onOpenActions: () => { - this.showHeaderActions = !this.showHeaderActions; - }, - onActionsMenuStateChange: (visible: boolean) => { - this.showHeaderActions = visible; - }, - onRenameSession: (title: string) => { - this.onRenameSession(title); - } - }) - } - - @Builder - MessageList() { - ChatTimeline({ - interactionMailbox: this.state.interactionMailbox, - surface: this.surface, - timelineItems: this.visibleTimelineItems(), - timelineRevision: this.timelineRevision, - hasMoreMessages: this.hasMoreMessages, - historyLoading: this.state.historyLoading, - historyFailed: this.state.historyFailed, - isBusy: this.isBusy || this.isLoadingConversation, - connectionState: this.connectionState, - statusText: this.statusText, - downloadingFilePath: this.downloadingFilePath, - downloadedFilePath: this.downloadedFilePath, - fileDownloadStatus: this.fileDownloadStatus, - activeFilePreviewPath: this.activeFilePreviewPath, - activeFilePreviewLoading: this.activeFilePreviewLoading, - maxContentWidth: this.composerPresentation === ComposerPresentation.Floating ? 760 : 0, - subagentBranches: this.state.subagentBranches, - topInset: this.hoverOperateMode ? 0 : this.topInset, - bottomInset: this.hoverOperateMode ? 0 : this.bottomInset, - ghostRowKeys: this.ghostRowKeys(), - rollbackNotice: this.state.rollbackNotice, - onLoadOlder: () => { - this.onLoadOlder(); - }, - onApproveTool: (toolId: string, updatedInput?: Object) => { - this.onApproveTool(toolId, updatedInput); - }, - onRejectTool: (toolId: string) => { - this.onRejectTool(toolId); - }, - onCancelTool: (toolId: string) => { - this.onCancelTool(toolId); - }, - onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => { - this.onAnswerQuestion(toolId, answers); - }, - onCopyMessage: (text: string) => { - this.onCopyMessage(text); - }, - onCopyMessageScoped: (text: string, scope: MessageCopyScope) => { - this.onCopyMessageScoped(text, scope); - }, - onOpenFullText: (text: string, turnId: string) => { - this.onOpenFullText(text, turnId); - }, - onRollbackMessage: (turnId: string, text: string) => { - this.onRollbackMessage(turnId, text); - }, - onRetryMessage: (text: string) => { - this.onRetryMessage(text); - }, - onOpenFilePreview: (path: string, label: string) => { - this.onOpenFilePreview(path, label); - }, - onBuildPlan: (path: string, name: string) => { - this.onBuildPlan(path, name); - }, - onDownloadFile: (path: string) => { - this.onDownloadFile(path); - }, - onBranchExpanded: (branchId: string) => { - this.onIntent(ConversationIntents.branchExpanded(branchId)); - } - }) - } - - @Builder - CenteredInlineStatus() { - Stack({ alignContent: Alignment.Center }) { - Text(this.inlineStatusText) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .maxLines(2) - } - .width('100%') - .height('100%') - .padding({ left: 32, right: 32, bottom: 48 }) - } - - @Builder - Composer() { - Column() { - // The command row floats above the composer and is mounted here rather than - // in either layout, so the compact overlay, the half-folded pane and the - // wide detail pane all get the same row from the same subtree. - if (this.commandPalette.visible) { - CommandChipRow({ - palette: this.commandPalette, - presentation: this.composerPresentation, - onRequest: (request: CommandPaletteRequest) => { - this.onCommandPaletteRequest(request); - } - }) - } - // Above the composer in both presentations: the compact pill and the wide - // floating one both live in this column, so one placement covers both. The - // bar draws nothing at all while no rollback is staged. - RollbackStagingBar({ - presentation: this.composerPresentation, - bar: this.rollbackBar(), - onConfirm: () => { - this.applyRollbackEvent({ type: SessionRollbackEventType.ConfirmRollback }); - }, - onClose: () => { - this.applyRollbackEvent({ type: SessionRollbackEventType.CloseStaging }); - } - }) - if (this.surface === ChatSurface.Remote && this.state.messageQueue.sessionId === this.state.activeSession.sessionId) { - MessageQueuePanel({ state: this.state.messageQueue, onAction: (action: MessageQueueAction): void => { this.onIntent(ConversationIntents.queue(action)); } }) - } - ComposerBar({ - queueAttached: this.surface === ChatSurface.Remote && this.state.messageQueue.sessionId === this.state.activeSession.sessionId && (this.state.messageQueue.items.length > 0 || this.state.messageQueue.failure.length > 0), - presentation: this.composerPresentation, - capabilities: this.composerCapabilities, - inputId: this.composerInputId, - chatInput: this.chatInput, - promptSuggestion: this.stagingTargetTurnId.length > 0 ? '' : this.state.promptSuggestion, - selectedImages: this.selectedImages, - skillId: this.commandPalette.skillId, - skillLabel: this.commandPalette.skillLabel, - commandRowActive: this.commandPalette.visible, - isBusy: this.isBusy, - canStop: this.canStop, - connectionState: this.connectionState, - isVoiceListening: this.isVoiceListening, - modelCatalog: this.modelCatalog, - selectedModelId: this.selectedModelId, - onPickImages: () => { - this.onPickImages(); - }, - onRemoveImage: (imageId: string) => { - this.onRemoveImage(imageId); - }, - onRemoveSkillToken: () => { - this.onIntent(ConversationIntents.commandPalette( - new CommandPaletteRequest(CommandPaletteAction.ClearSkill))); - }, - onSend: () => { - this.onSend(); - }, - onStop: () => { - this.onStop(); - }, - onVoiceInput: () => { - this.onVoiceInput(); - }, - onSelectModel: (modelId: string) => { - this.onSelectModel(modelId); - }, - onChatInputChange: (value: string) => { - this.onChatInputChange(value); - } - }) - } - .width('100%') - } - - /** - * Hands one command-row tap to the conversation. - * - * The row's own sheets are view state, the way the full-text panel is: nothing - * outside this pane reads them, so opening one is a local decision. Everything - * else — the verbs, the catalog read, the draft edits — leaves as the one - * typed intent. - */ - private onCommandPaletteRequest(request: CommandPaletteRequest): void { - if (request.action === CommandPaletteAction.OpenSkills) { - this.openSheet(CONVERSATION_SHEET_SKILLS); - } else if (request.action === CommandPaletteAction.OpenUsage) { - this.openSheet(CONVERSATION_SHEET_USAGE); - } - this.onIntent(ConversationIntents.commandPalette(request)); - } - - private adaptiveSheetOptions(placement: SettingsPlacement): SheetOptions { - // The same adaptive contract as the full-text panel: the content draws the - // surface, the sheet supplies transparency, the scrim, and a drag bar - // wherever the placement resolves to a bottom sheet. - return AdaptiveSheetOptions.fromPlacement(placement, true); - } - - @Builder - HeaderActionsPopover() { - Column() { - this.HeaderActionsContent() - } - .width(292) - .padding({ left: 12, right: 12, top: 10, bottom: 10 }) - .backgroundColor(CARD) - .border({ width: 0.5, color: LINE }) - .borderRadius(16) - .shadow({ radius: 18, color: SHADOW_SUBTLE, offsetY: 7 }) - .transition(TransitionEffect.translate({ x: 8, y: -8 }) - .combine(TransitionEffect.opacity(0)) - .animation({ duration: 180, curve: Curve.EaseOut })) - } - - @Builder - HeaderActionsContent() { - Text(RemoteI18n.t('chat.sessionSection')) - .fontSize(MobileDesignTypography.bodySmall.size).fontWeight(FontWeight.Medium).fontColor(MUTED) - .width('100%').height(28).padding({ left: 8 }) - if (this.surface === ChatSurface.General) { - this.RemoteStyleMenuItem('remote_actions_check', - this.isSessionPinned ? RemoteI18n.t('chat.unpin') : RemoteI18n.t('chat.pin'), - () => this.onTogglePinSession(), this.isSessionPinned) - } - this.RemoteStyleMenuItem('remote_actions_cloud', RemoteI18n.t('chat.uploadedFiles'), - () => this.onShowUploadedFiles()) - if (this.surface === ChatSurface.General) { - Divider().strokeWidth(1).color(LINE).margin({ top: 8, bottom: 8 }) - this.RemoteStyleMenuItem('remote_actions_folder', RemoteI18n.t('sidebar.archive'), - () => this.onArchiveSession()) - this.RemoteStyleMenuItem('remote_actions_settings', RemoteI18n.t('common.delete'), - () => this.onDeleteSession()) - } else if (this.canStop && this.connectionState === 'connected') { - Divider().strokeWidth(1).color(LINE).margin({ top: 8, bottom: 8 }) - this.RemoteStyleMenuItem('remote_actions_settings', RemoteI18n.t('chat.stop'), () => this.onStop()) - } - } - - @Builder - RemoteStyleMenuItem(icon: string, label: string, action: () => void, selected: boolean = false) { - Row({ space: 10 }) { - this.MenuIcon(icon) - Text(label) - .fontSize(MobileDesignTypography.titleSmall.size).fontColor(INK).layoutWeight(1) - .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%').height(48) - .padding({ left: 8, right: 8 }) - .borderRadius(10) - .backgroundColor(selected ? SOFT : TRANSPARENT) - .onClick(() => { - action() - this.showHeaderActions = false - }) - } - - @Builder - MenuIcon(icon: string) { - if (icon === 'remote_actions_link') { - SymbolGlyph($r('sys.symbol.link')).fontSize(20).fontColor([MUTED]).width(23).height(23) - } else if (icon === 'remote_actions_check') { - SymbolGlyph($r('sys.symbol.checkmark_circle')).fontSize(20).fontColor([MUTED]).width(23).height(23) - } else if (icon === 'remote_actions_folder') { - SymbolGlyph($r('sys.symbol.folder')).fontSize(20).fontColor([MUTED]).width(23).height(23) - } else if (icon === 'remote_actions_cloud') { - SymbolGlyph($r('sys.symbol.cloud')).fontSize(20).fontColor([MUTED]).width(23).height(23) - } else { - SymbolGlyph($r('sys.symbol.gearshape')).fontSize(20).fontColor([MUTED]).width(23).height(23) - } - } - - private shouldCenterInlineStatus(): boolean { - return this.inlineStatusText.length > 0 && - !this.isBusy && - !ConversationViewContract.hasRealTimelineItem(this.timelineItems); - } - - private visibleTimelineItems(): ObservableChatTimelineItem[] { - return ConversationViewContract.visibleTimelineItems(this.timelineItems); - } - - /** - * The staged rollback as the reducer sees it. - * - * Rebuilt per event rather than stored, so this pane owns only what it must - * remember between events and the policy keeps every rule about transitions. - */ - private rollbackState(): SessionRollbackState { - if (this.stagingTargetTurnId.length === 0) { - return new SessionRollbackIdleState(); - } - return new SessionRollbackStagingState( - this.stagingTargetTurnId, - this.stagingTargetText, - this.composerSnapshot - ); - } - - /** Adopts the reducer's state back into the three locals that stand for it. */ - private adoptRollbackState(state: SessionRollbackState): void { - if (state.stage === SessionRollbackStage.Staging) { - this.stagingTargetTurnId = state.targetTurnId; - this.stagingTargetText = state.targetText; - this.composerSnapshot = state.composerSnapshot; - return; - } - // Leaving staging is what clears the preview: the ghost rows are derived from - // the target, so dropping it clears them without a second list to keep. - this.stagingTargetTurnId = ''; - this.stagingTargetText = ''; - this.composerSnapshot = ''; - } - - /** - * One staged-rollback event: reduce, adopt the new state, then apply the effects. - * - * The send-while-staging exit states itself as two effects in order — rollback, - * then send — and the viewmodel runs both inside one command, because the host - * has to retire the turn before a message may be appended to it. The text is - * therefore read out of the second effect and handed over with the first. - */ - private applyRollbackEvent(event: SessionRollbackEvent): void { - const transition = SessionRollbackPolicy.reduce(this.rollbackState(), event); - this.adoptRollbackState(transition.state); - let sendText: string = ''; - for (let index = 0; index < transition.effects.length; index++) { - const effect = transition.effects[index]; - if (effect.type === SessionRollbackEffectType.SendMessageAfterRollback) { - sendText = effect.text || ''; - } - } - for (let index = 0; index < transition.effects.length; index++) { - this.runRollbackEffect(transition.effects[index], sendText); - } - } - - private runRollbackEffect(effect: SessionRollbackEffect, sendText: string): void { - switch (effect.type) { - case SessionRollbackEffectType.RefillComposer: - case SessionRollbackEffectType.RestoreComposerSnapshot: - this.onChatInputChange(effect.text || ''); - return; - case SessionRollbackEffectType.KeepComposerText: - return; - case SessionRollbackEffectType.ShowGhostRows: - this.stagingTargetTurnId = effect.targetTurnId || this.stagingTargetTurnId; - return; - case SessionRollbackEffectType.ClearGhostRows: - // Already done by adopting the idle state: no ghost row outlives staging. - return; - case SessionRollbackEffectType.SendRollbackCommand: - this.onIntent(ConversationIntents.rollback(effect.targetTurnId || '', sendText)); - return; - case SessionRollbackEffectType.SendMessageAfterRollback: - // Handed to the rollback command above; sending here would append the - // message before the host retired the turn. - return; - case SessionRollbackEffectType.ResyncTimeline: - this.onIntent(ConversationIntents.rollbackResync()); - return; - case SessionRollbackEffectType.ShowDegradeNotice: - this.onIntent(ConversationIntents.rollbackNotice(RollbackPresentationPolicy.FAILED_KEY)); - return; - default: - return; - } - } - - /** - * The rollback entry on a user message was tapped. - * - * The decision is resolved here, at tap time, rather than when the row was - * drawn: a session that became busy in between is judged as it is now. A - * refusal is always said out loud — an entry that silently does nothing is - * indistinguishable from a broken one — while an allowed tap stages locally and - * sends nothing. - */ - private onRollbackMessage(turnId: string, text: string): void { - const decision = this.state.rollbackGate.resolve(); - if (!decision.allowed) { - this.onIntent(ConversationIntents.rollbackNotice(RollbackPresentationPolicy.denyMessageKey(decision.reason))); - return; - } - const target = turnId.trim(); - if (target.length === 0) { - // The entry is still offered here — the session is usable, this message is - // just not addressable as a turn — so the refusal is the honest answer. - this.onIntent(ConversationIntents.rollbackNotice(RollbackPresentationPolicy.FAILED_KEY)); - return; - } - // Staging takes the pane over: the panel that was opened from this message - // closes, because the preview belongs to the conversation behind it. - if (this.activeSheet === CONVERSATION_SHEET_FULL_TEXT) { - this.closeSheet(); - } - this.applyRollbackEvent({ - type: SessionRollbackEventType.EnterStaging, - targetTurnId: target, - targetText: text, - composerSnapshot: this.chatInput - }); - } - - /** - * The rows the staged preview weakens: the target turn and every row after it. - * - * Derived, never stored: the rows are virtualized and their identity is the - * only thing stable about them, so the cut is expressed as row keys against the - * list the pane is showing right now. - */ - private ghostRowKeys(): string[] { - if (this.stagingTargetTurnId.length === 0) { - return []; - } - const rows: RollbackGhostRow[] = this.visibleTimelineItems().map( - (row: ObservableChatTimelineItem): RollbackGhostRow => new RollbackGhostRow( - ChatTimelineRevisionTracker.itemKey(row), - row.message ? row.message.turnId || '' : '' - ) - ); - return RollbackPresentationPolicy.ghostRowKeys(rows, this.stagingTargetTurnId); - } - - private rollbackBar(): RollbackBarPresentation { - return RollbackPresentationPolicy.bar(this.rollbackState()); - } - - /** - * Consumes a host outcome that arrived after staging was already over. - * - * Confirm and send leave staging before the host answers, which is the point: - * the preview is local and must react instantly. The answer therefore comes - * back through projected state rather than through the transition that sent it, - * and it must be applied even while idle — a stale target and a refusal both - * mean this client's transcript is describing history the host no longer has. - */ - @Monitor('state') - onViewStateChanged(): void { - const identity = `${this.state.surface}:${this.state.activeSession.sessionId}:${this.state.sessionContextRevision}`; - if (identity !== this.rollbackContextIdentity) { - this.rollbackContextIdentity = identity; - // A reused wide pane must drop A's preview without restoring its draft - // through an intent now routed to B. Resizing the same session keeps it. - this.stagingTargetTurnId = ''; - this.stagingTargetText = ''; - this.composerSnapshot = ''; - // Any sheet up belongs to the previous context, so none survives the switch. - this.sheetPresented = false; - this.fullTextMessage = ''; - this.fullTextTurnId = ''; - this.showHeaderActions = false; - this.handledRollbackOutcomeSeq = this.state.rollbackOutcomeSeq; - return; - } - const sequence = this.state.rollbackOutcomeSeq; - if (sequence <= this.handledRollbackOutcomeSeq) { - return; - } - this.handledRollbackOutcomeSeq = sequence; - if (this.state.rollbackOutcome === SessionRollbackEventType.StaleViewDetected) { - this.applyRollbackEvent({ type: SessionRollbackEventType.StaleViewDetected }); - return; - } - if (this.state.rollbackOutcome === SessionRollbackEventType.RollbackFailed) { - this.applyRollbackEvent({ type: SessionRollbackEventType.RollbackFailed }); - } - } - - private statusLine(): string { - if (this.canStop && this.connectionState === 'connected') { - return RemoteI18n.t('chat.executing'); - } - return ConnectionStatusPresenter.detail(this.connectionState, this.statusText, '', ''); - } - - private headerTitle(): string { - return this.headerPresentation().title; - } - - private headerSubtitle(): string { - return this.headerPresentation().subtitle; - } - - private headerFallback(): string { - return RemoteI18n.t(this.headerPresentation().fallbackKey); - } - - private headerAllowRename(): boolean { - return this.headerPresentation().allowRename; - } - - private headerShowActions(): boolean { - return this.headerPresentation().showActions; - } - - private headerPresentation(): ConversationHeaderPresentation { - return ConversationHeaderPolicy.present( - this.surface, - this.activeSession.title, - this.desktopName, - this.workspaceBranch, - ConversationViewContract.hasRealTimelineItem(this.timelineItems) - ); - } - - private connectionColor(): ResourceColor { - const tone = ConnectionStatusPresenter.tone(this.connectionState); - if (tone === 'ok') { - return STATUS_SUCCESS; - } - if (tone === 'error') { - return STATUS_DANGER; - } - return MUTED; - } - - private get surface(): ChatSurface { return this.state.surface; } - private get activeSession(): ConversationUiSession { return this.state.activeSession; } - private get desktopName(): string { return this.state.desktopName; } - private get workspaceBranch(): string { return this.state.workspaceBranch; } - private get statusText(): string { return this.state.statusText; } - private get inlineStatusText(): string { return this.state.inlineStatusText; } - private get connectionState(): string { return this.state.connectionState; } - private get composerCapabilities(): ChatComposerCapabilities { return this.state.composerCapabilities; } - private get isBusy(): boolean { return this.state.isBusy; } - private get isLoadingConversation(): boolean { return this.state.isLoadingConversation; } - /** - * The skeleton stands for a body with nothing in it yet, which is true both - * while the session is being identified and while its transcript is still - * crossing the relay. Only the first of those blanks the header. - */ - private get isLoadingTranscript(): boolean { - return this.state.isLoadingConversation || this.state.isLoadingTranscript; - } - private get canStop(): boolean { return this.state.canStop; } - private get hasMoreMessages(): boolean { return this.state.hasMoreMessages; } - private get timelineItems(): ObservableChatTimelineItem[] { return this.state.timelineItems; } - private get timelineRevision(): number { return this.state.timelineRevision; } - private get modelCatalog(): ConversationUiModelCatalog { return this.state.modelCatalog; } - private get selectedModelId(): string { return this.state.selectedModelId; } - private get downloadingFilePath(): string { return this.state.downloadingFilePath; } - private get downloadedFilePath(): string { return this.state.downloadedFilePath; } - private get fileDownloadStatus(): string { return this.state.fileDownloadStatus; } - private get selectedImages(): ConversationUiSelectedImage[] { return this.state.selectedImages; } - private get isVoiceListening(): boolean { return this.state.isVoiceListening; } - private get chatInput(): string { return this.state.chatInput; } - private get commandPalette(): CommandPalettePresentation { return this.state.commandPalette; } - private get isSessionPinned(): boolean { return this.state.isSessionPinned; } - private get activeFilePreviewPath(): string { return this.options.activeFilePreviewPath; } - private get activeFilePreviewLoading(): boolean { return this.options.activeFilePreviewLoading; } - private get showSidebarButton(): boolean { return this.options.showSidebarButton; } - private get showBackButton(): boolean { return this.options.showBackButton; } - private get showSidebarRestoreButton(): boolean { return this.options.showSidebarRestoreButton; } - private get composerPresentation(): ComposerPresentation { return this.options.composerPresentation; } - private get composerInputId(): string { return this.options.composerInputId; } - private get hoverOperateMode(): boolean { return this.options.hoverOperateMode; } - private get fullTextSheetPlacement(): SettingsPlacement { return this.options.fullTextSheetPlacement; } - private get skillPickerSheetPlacement(): SettingsPlacement { return this.options.skillPickerSheetPlacement; } - private get usageReportSheetPlacement(): SettingsPlacement { return this.options.usageReportSheetPlacement; } - private onOpenSidebar(): void { this.dispatchSimple(ConversationIntentType.OpenSidebar); } - private onBack(): void { this.dispatchSimple(ConversationIntentType.Back); } - private onTogglePinSession(): void { this.dispatchSimple(ConversationIntentType.TogglePin); } - private onArchiveSession(): void { this.dispatchSimple(ConversationIntentType.Archive); } - private onDeleteSession(): void { this.dispatchSimple(ConversationIntentType.Delete); } - private onShowUploadedFiles(): void { this.dispatchSimple(ConversationIntentType.ShowUploadedFiles); } - private onStop(): void { this.dispatchSimple(ConversationIntentType.Stop); } - private onLoadOlder(): void { this.dispatchSimple(ConversationIntentType.LoadOlder); } - private onApproveTool(toolId: string, updatedInput?: Object): void { - this.onIntent(ConversationIntents.approveTool(toolId, updatedInput)); - } - private onRejectTool(toolId: string): void { - this.onIntent(ConversationIntents.tool(ConversationIntentType.RejectTool, toolId)); - } - private onCancelTool(toolId: string): void { - this.onIntent(ConversationIntents.tool(ConversationIntentType.CancelTool, toolId)); - } - private onAnswerQuestion(toolId: string, answers: ConversationUiQuestionAnswer): void { - this.onIntent(ConversationIntents.answerQuestion(toolId, answers)); - } - private onRenameSession(title: string): void { - this.dispatchValue(ConversationIntentType.RenameSession, title); - } - private onCopyMessage(text: string): void { this.dispatchValue(ConversationIntentType.CopyMessage, text); } - private onCopyMessageScoped(text: string, scope: MessageCopyScope): void { - this.onIntent(ConversationIntents.copyMessage(text, scope)); - } - private onRetryMessage(text: string): void { this.dispatchValue(ConversationIntentType.RetryMessage, text); } - private onOpenFullText(text: string, turnId: string): void { - if (text.length === 0) { - return; - } - this.fullTextMessage = text; - this.fullTextTurnId = turnId; - this.openSheet(CONVERSATION_SHEET_FULL_TEXT); - } - private onOpenFilePreview(path: string, label: string): void { - this.onIntent(ConversationIntents.openFilePreview(path, label)); - } - private onBuildPlan(path: string, name: string): void { - this.onIntent(ConversationIntents.buildPlan(path, name)); - } - private onSelectModel(modelId: string): void { this.dispatchValue(ConversationIntentType.SelectModel, modelId); } - private onPickImages(): void { this.dispatchSimple(ConversationIntentType.PickImages); } - private onRemoveImage(imageId: string): void { this.dispatchValue(ConversationIntentType.RemoveImage, imageId); } - private onDownloadFile(path: string): void { this.dispatchValue(ConversationIntentType.DownloadFile, path); } - /** - * Send is the third exit of the staged rollback. - * - * While a rollback is staged the button means "roll back first, then send what - * is in the composer from there": the reducer states those two steps in that - * order and the viewmodel runs them as one command, so the message can never - * beat the rollback it was sent after. - */ - private onSend(): void { - if (this.stagingTargetTurnId.length > 0) { - this.applyRollbackEvent({ - type: SessionRollbackEventType.SendWhileStaging, - text: this.chatInput.trim() - }); - return; - } - this.dispatchSimple(ConversationIntentType.Send); - } - private onVoiceInput(): void { this.dispatchSimple(ConversationIntentType.VoiceInput); } - private onChatInputChange(value: string): void { - this.dispatchValue(ConversationIntentType.ChatInputChanged, value); - } - - private dispatchSimple(type: ConversationIntentType): void { - this.onIntent(ConversationIntents.simple(type)); - } - - private dispatchValue(type: ConversationIntentType, value: string): void { - this.onIntent(ConversationIntents.value(type, value)); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewContract.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewContract.ets deleted file mode 100644 index 3b9113ddb8..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewContract.ets +++ /dev/null @@ -1,72 +0,0 @@ -import { ChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ConversationMessageRenderPolicy } from '../policy/ConversationMessageRenderPolicy'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { ChatSurface } from '../state/ChatSurface'; -import { toConversationUiMessage } from '../state/ConversationUiModels'; -import { ComposerPresentation } from './ComposerBar'; - -/** Layout and host chrome that vary independently from conversation data. */ -export class ConversationViewOptions { - activeFilePreviewPath: string = ''; - activeFilePreviewLoading: boolean = false; - showSidebarButton: boolean = true; - showBackButton: boolean = true; - showSidebarRestoreButton: boolean = false; - composerPresentation: ComposerPresentation = ComposerPresentation.Compact; - composerInputId: string = 'conversation-composer-input'; - hoverOperateMode: boolean = false; - /** - * Placement for the full-text panel. The page owns the geometry it comes - * from, so the conversation consumes it instead of re-deriving sheets from a - * width of its own — which is what keeps the panel inside the operate half - * of a half-folded screen and inside a foldable's trailing leaf. - */ - fullTextSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - /** - * Placement for the composer's command palette sheets. Same contract as the - * full-text panel: the page owns the geometry, so the conversation consumes it - * instead of re-deriving sheets from a width of its own. - */ - skillPickerSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SkillPicker); - usageReportSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UsageReport); -} - -export class ConversationViewContract { - static surfaceForRoute(isRemoteChat: boolean): ChatSurface { - return isRemoteChat ? ChatSurface.Remote : ChatSurface.General; - } - - static shouldShowSuggestions( - showSuggestionsWhenEmpty: boolean, - isBusy: boolean, - timelineItems: ChatTimelineItem[] - ): boolean { - return showSuggestionsWhenEmpty && !isBusy && !ConversationViewContract.hasRealTimelineItem(timelineItems); - } - - static visibleTimelineItems(timelineItems: T[]): T[] { - // Repeat.virtualScroll requires every input entry to create one child. A - // hollow assistant is deliberately invisible, so passing it through and - // conditionally omitting its ListItem corrupts the virtual index/height - // map and can move adjacent user bubbles outside the viewport. Keep the - // renderability fence at the view contract instead: everything handed to - // the virtual list is guaranteed to own a visible row. - return timelineItems.filter((item: T) => { - if (item.type === 'empty_state' || !item.message) { - return false; - } - return ConversationMessageRenderPolicy.shouldRender(toConversationUiMessage(item.message)); - }); - } - - static hasRealTimelineItem(timelineItems: ChatTimelineItem[]): boolean { - return timelineItems.some((item: ChatTimelineItem) => item.type !== 'empty_state'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewHost.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewHost.ets deleted file mode 100644 index cc444c0a6e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewHost.ets +++ /dev/null @@ -1,60 +0,0 @@ -import { ConversationViewState } from '../state/ConversationViewState'; -import { ConversationView } from './ConversationView'; -import { ConversationIntent } from '../actions/ConversationIntent'; -import { ComposerPresentation } from './ComposerBar'; -import { ConversationViewOptions } from './ConversationViewContract'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; - -@ComponentV2 -export struct ConversationViewHost { - @Param viewState: ConversationViewState = new ConversationViewState(); - @Param activeFilePreviewPath: string = ''; - @Param activeFilePreviewLoading: boolean = false; - @Param showSidebarButton: boolean = true; - @Param showBackButton: boolean = true; - @Param showSidebarRestoreButton: boolean = false; - @Param composerPresentation: ComposerPresentation = ComposerPresentation.Compact; - @Param composerInputId: string = 'conversation-composer-input'; - @Param hoverOperateMode: boolean = false; - @Param fullTextSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - @Param skillPickerSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SkillPicker); - @Param usageReportSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UsageReport); - @Param onRestoreSidebar: () => void = () => {}; - @Param onIntent: (intent: ConversationIntent) => void = (_intent: ConversationIntent) => {}; - - build() { - ConversationView({ - state: this.viewState, - options: this.viewOptions(), - onRestoreSidebar: this.onRestoreSidebar, - onIntent: (intent: ConversationIntent) => this.dispatch(intent) - }) - } - - private viewOptions(): ConversationViewOptions { - const options = new ConversationViewOptions(); - options.activeFilePreviewPath = this.activeFilePreviewPath; - options.activeFilePreviewLoading = this.activeFilePreviewLoading; - options.showSidebarButton = this.showSidebarButton; - options.showBackButton = this.showBackButton; - options.showSidebarRestoreButton = this.showSidebarRestoreButton; - options.composerPresentation = this.composerPresentation; - options.composerInputId = this.composerInputId; - options.hoverOperateMode = this.hoverOperateMode; - options.fullTextSheetPlacement = this.fullTextSheetPlacement; - options.skillPickerSheetPlacement = this.skillPickerSheetPlacement; - options.usageReportSheetPlacement = this.usageReportSheetPlacement; - return options; - } - - private dispatch(intent: ConversationIntent): void { - this.onIntent(intent); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewSettings.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewSettings.ets deleted file mode 100644 index 0cc7be016f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationViewSettings.ets +++ /dev/null @@ -1,420 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RecentWorkspaceEntry, RemoteSession } from '../../model/RemoteModels'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { ConversationSessionFilterPolicy } from '../policy/ConversationSessionFilterPolicy'; -import { - CARD, - INK, - LINE, - MUTED, - PAGE_BG, - TRANSPARENT, -} from './Theme'; - -@ComponentV2 -struct WorkspaceFilterSection { - @Param options: RecentWorkspaceEntry[] = []; - @Param selectedValue: string = ''; - @Event onSelect: (value: string) => void = (_value: string) => {}; - @Local currentValue: string = ''; - - aboutToAppear(): void { - this.currentValue = this.selectedValue; - } - - build() { - Column() { - Row({ space: 12 }) { - SymbolGlyph(this.currentValue.length === 0 ? $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle')) - .fontSize(20) - .fontColor([this.currentValue.length === 0 ? INK : MUTED]) - .width(22) - Text(RemoteI18n.t('viewSettings.allWorkspaces')) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - } - .width('100%') - .height(46) - .padding({ left: 10, right: 10 }) - .backgroundColor(this.currentValue.length === 0 ? CARD : TRANSPARENT) - .border({ width: { bottom: 1 }, color: LINE }) - .onClick(() => this.selectWorkspace('')) - ForEach(this.options, (item: RecentWorkspaceEntry) => { - Row({ space: 12 }) { - SymbolGlyph(ConversationSessionFilterPolicy.workspacePathsEqual(this.currentValue, item.path) - ? $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle')) - .fontSize(20) - .fontColor([ConversationSessionFilterPolicy.workspacePathsEqual(this.currentValue, item.path) ? INK : MUTED]) - .width(22) - Text(item.name || this.basename(item.path)) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .height(46) - .padding({ left: 10, right: 10 }) - .backgroundColor(ConversationSessionFilterPolicy.workspacePathsEqual(this.currentValue, item.path) - ? CARD : TRANSPARENT) - .border({ width: { bottom: 1 }, color: LINE }) - .onClick(() => this.selectWorkspace(item.path)) - }, (item: RecentWorkspaceEntry): string => item.path) - } - .width('100%') - } - - private selectWorkspace(value: string): void { - this.currentValue = value; - setTimeout(() => this.onSelect(value), 0); - } - - private basename(path: string): string { - const parts = path.split('/'); - return parts.length > 0 ? parts[parts.length - 1] : path; - } -} - -@ComponentV2 -export struct ConversationViewSettings { - @Param sessions: RemoteSession[] = []; - @Param workspaceName: string = ''; - @Param workspacePath: string = ''; - @Param workspaceKind: string = 'normal'; - @Param recentWorkspaces: RecentWorkspaceEntry[] = []; - @Param sortMode: string = 'project'; - @Param workspaceFilter: string = ''; - @Param agentFilter: string = ''; - @Param statusFilter: string = ''; - @Param showWorkspaceMetadata: boolean = false; - @Param showUpdatedMetadata: boolean = false; - @Param showStatusMetadata: boolean = false; - @Local selectedSortMode: string = ''; - @Local selectedWorkspaceFilter: string = ''; - @Local selectedAgentFilter: string = ''; - @Local selectedStatusFilter: string = ''; - @Local selectionRevision: number = 0; - @Event onSortModeChange: (mode: string) => void = (_mode: string) => {}; - @Event onWorkspaceFilterChange: (value: string) => void = (_value: string) => {}; - @Event onAgentFilterChange: (value: string) => void = (_value: string) => {}; - @Event onStatusFilterChange: (value: string) => void = (_value: string) => {}; - @Event onWorkspaceMetadataChange: (value: boolean) => void = (_value: boolean) => {}; - @Event onUpdatedMetadataChange: (value: boolean) => void = (_value: boolean) => {}; - @Event onStatusMetadataChange: (value: boolean) => void = (_value: boolean) => {}; - @Event onClose: () => void = () => {}; - // In its compact placement this surface is a bottom sheet under the immersive - // shell: the scrolling column runs to the screen edge and ends in a tail that - // rests the last control above the navigation bar. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - this.syncSelectionState(); - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column() { - Row() { - Column({ space: 3 }) { - Text(RemoteI18n.t('viewSettings.title')) - .fontSize(MobileDesignTypography.headlineSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(RemoteI18n.t('viewSettings.subtitle')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(17) - .fontColor([MUTED]) - } - .width(44) - .height(44) - .accessibilityText(RemoteI18n.t('common.close')) - .onClick(() => this.onClose()) - } - .width('100%') - .height(64) - .padding({ left: 20, right: 10 }) - - Divider().color(LINE) - - Scroll() { - Column({ space: 0 }) { - this.SectionTitle(RemoteI18n.t('viewSettings.grouping')) - this.SortRow('project', RemoteI18n.t('remote.menu.byProject'), this.selectionRevision) - this.SortRow('time', RemoteI18n.t('remote.menu.byTime'), this.selectionRevision) - this.SortRow('chat', RemoteI18n.t('remote.menu.chatFirst'), this.selectionRevision) - this.SectionTitle(RemoteI18n.t('viewSettings.filters')) - this.FilterLabel(RemoteI18n.t('viewSettings.workspace')) - WorkspaceFilterSection({ - options: this.workspaceFilterOptions(), - selectedValue: this.workspaceFilter, - onSelect: (value: string) => this.selectWorkspaceFilter(value) - }) - this.FilterLabel(RemoteI18n.t('viewSettings.agentType')) - this.ChoiceRow('', RemoteI18n.t('viewSettings.allAgentTypes'), this.selectedAgentFilter.length === 0, - (value: string) => this.selectAgentFilter(value), this.selectionRevision) - ForEach(this.agentFilterOptions(), (value: string) => { - this.ChoiceRow(value, this.agentFilterLabel(value), this.selectedAgentFilter === value, - (nextValue: string) => this.selectAgentFilter(nextValue), this.selectionRevision) - }, (value: string): string => value) - this.FilterLabel(RemoteI18n.t('viewSettings.status')) - this.ChoiceRow('', RemoteI18n.t('viewSettings.allStatuses'), this.selectedStatusFilter.length === 0, - (value: string) => this.selectStatusFilter(value), this.selectionRevision) - ForEach(this.statusFilterOptions(), (value: string) => { - this.ChoiceRow(value, this.statusFilterLabel(value), this.selectedStatusFilter === value, - (nextValue: string) => this.selectStatusFilter(nextValue), this.selectionRevision) - }, (value: string): string => value) - this.SectionTitle(RemoteI18n.t('viewSettings.metadata')) - this.ToggleRow(RemoteI18n.t('viewSettings.workspace'), this.showWorkspaceMetadata, - this.onWorkspaceMetadataChange) - this.ToggleRow(RemoteI18n.t('viewSettings.updated'), this.showUpdatedMetadata, - this.onUpdatedMetadataChange) - this.ToggleRow(RemoteI18n.t('viewSettings.status'), this.showStatusMetadata, - this.onStatusMetadataChange) - } - .width('100%') - .padding({ left: 20, right: 20, bottom: this.insets.tailSpacing(24) }) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .borderRadius(16) - } - - @Builder - private FilterLabel(label: string) { - Text(label) - .width('100%') - .height(34) - .padding({ left: 10, top: 10 }) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - - @Builder - private SectionTitle(title: string) { - Text(title) - .width('100%') - .height(38) - .padding({ left: 4, top: 12 }) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - } - - @Builder - private SortRow(mode: string, label: string, _revision: number) { - Row({ space: 12 }) { - SymbolGlyph(this.selectedSortMode === mode ? $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle')) - .fontSize(20) - .fontColor([this.selectedSortMode === mode ? INK : MUTED]) - Text(label) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - } - .width('100%') - .height(48) - .padding({ left: 10, right: 10 }) - .backgroundColor(this.selectedSortMode === mode ? CARD : TRANSPARENT) - .opacity(_revision % 2 === 0 ? 1 : 0.999) - .border({ width: { bottom: 1 }, color: LINE }) - .onClick(() => this.selectSortMode(mode)) - } - - @Builder - private ChoiceRow(value: string, label: string, selected: boolean, action: (value: string) => void, - _revision: number) { - Row({ space: 12 }) { - SymbolGlyph(selected ? $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle')) - .fontSize(20) - .fontColor([selected ? INK : MUTED]) - .width(22) - Text(label) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .height(46) - .padding({ left: 10, right: 10 }) - .backgroundColor(selected ? CARD : TRANSPARENT) - .opacity(_revision % 2 === 0 ? 1 : 0.999) - .border({ width: { bottom: 1 }, color: LINE }) - .onClick(() => action(value)) - } - - @Builder - private ToggleRow(label: string, value: boolean, action: (value: boolean) => void) { - Row({ space: 12 }) { - Text(label) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - Toggle({ type: ToggleType.Switch, isOn: value }) - .selectedColor(INK) - .onChange(action) - } - .width('100%') - .height(52) - .padding({ left: 10, right: 6 }) - .border({ width: { bottom: 1 }, color: LINE }) - } - - private workspaceFilterOptions(): RecentWorkspaceEntry[] { - const result: RecentWorkspaceEntry[] = []; - if (this.workspacePath.length > 0) { - result.push({ path: this.workspacePath, name: this.workspaceName, lastOpened: '', workspaceKind: 'normal' }); - } - this.recentWorkspaces.forEach((item: RecentWorkspaceEntry) => { - if (item.path.length > 0 && !result.some((entry: RecentWorkspaceEntry) => { - return ConversationSessionFilterPolicy.workspacePathsEqual(entry.path, item.path); - })) { - result.push(item); - } - }); - this.sessions.forEach((session: RemoteSession) => { - const path = session.workspacePath || ''; - if (path.length > 0 && !result.some((entry: RecentWorkspaceEntry) => { - return ConversationSessionFilterPolicy.workspacePathsEqual(entry.path, path); - })) { - result.push({ - path, - name: session.workspaceName || this.basename(path), - lastOpened: session.updatedAt, - workspaceKind: 'normal' - }); - } - }); - return result; - } - - private syncSelectionState(): void { - this.selectedSortMode = this.sortMode; - this.selectedWorkspaceFilter = this.workspaceFilter; - this.selectedAgentFilter = this.agentFilter; - this.selectedStatusFilter = this.statusFilter; - } - - private selectSortMode(mode: string): void { - this.selectedSortMode = mode; - this.selectionRevision += 1; - } - - private selectWorkspaceFilter(value: string): void { - RemoteLogger.info(`view-settings select workspace path=${value.length > 0 ? value : ''}`); - this.selectedWorkspaceFilter = value; - this.selectionRevision += 1; - this.onWorkspaceFilterChange(value); - } - - private selectAgentFilter(value: string): void { - this.selectedAgentFilter = value; - this.selectionRevision += 1; - } - - private selectStatusFilter(value: string): void { - this.selectedStatusFilter = value; - this.selectionRevision += 1; - } - - private applySelectionAndClose(): void { - RemoteLogger.info(`view-settings apply workspace=${this.selectedWorkspaceFilter.length > 0 ? - this.selectedWorkspaceFilter : ''}`); - this.onSortModeChange(this.selectedSortMode); - this.onWorkspaceFilterChange(this.selectedWorkspaceFilter); - this.onAgentFilterChange(this.selectedAgentFilter); - this.onStatusFilterChange(this.selectedStatusFilter); - this.onClose(); - } - - private agentFilterOptions(): string[] { - const values: string[] = []; - this.sessions.forEach((session: RemoteSession) => { - const value = this.agentGroup(session); - if (value.length > 0 && values.indexOf(value) < 0) { - values.push(value); - } - }); - return ['chat', 'code', 'cowork'].filter((value: string) => values.indexOf(value) >= 0); - } - - private statusFilterOptions(): string[] { - const values: string[] = []; - this.sessions.forEach((session: RemoteSession) => { - const value = (session.status || '').trim().toLowerCase(); - if (value.length > 0 && values.indexOf(value) < 0) { - values.push(value); - } - }); - return values.sort(); - } - - private agentGroup(session: RemoteSession): string { - const value = (session.agentType || '').toLowerCase(); - if (value === 'claw' || value === 'assistant' || value === 'chat' || - this.isAssistantWorkspace(session.workspacePath || '')) { - return 'chat'; - } - return value === 'cowork' ? 'cowork' : 'code'; - } - - private agentFilterLabel(value: string): string { - if (value === 'chat') { - return RemoteI18n.t('remote.newChat'); - } - return value === 'cowork' ? 'Cowork' : 'Code'; - } - - private statusFilterLabel(value: string): string { - if (value === 'active' || value === 'running') { - return RemoteI18n.t('common.running'); - } - if (value === 'ready' || value === 'idle') { - return RemoteI18n.t('common.ready'); - } - if (value === 'archived') { - return RemoteI18n.t('sidebar.archived'); - } - return value; - } - - private basename(path: string): string { - const parts = path.split('/'); - return parts.length > 0 ? parts[parts.length - 1] : path; - } - - private isAssistantWorkspace(path: string): boolean { - if (path.length === 0) { - return this.workspaceKind.toLowerCase() === 'assistant'; - } - if (path === this.workspacePath && this.workspaceKind.toLowerCase() === 'assistant') { - return true; - } - return this.recentWorkspaces.some((item: RecentWorkspaceEntry) => { - return item.path === path && item.workspaceKind.toLowerCase() === 'assistant'; - }); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CurrentControlSection.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CurrentControlSection.ets deleted file mode 100644 index 36d0886915..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/CurrentControlSection.ets +++ /dev/null @@ -1,150 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CARD, INK, LINE, MUTED, SOFT, STATUS_DANGER } from './Theme'; - -/** - * Current control target card on the single settings page. Legacy room - * targets stay readable and can still be disconnected; only the account - * device directory creates new targets. - */ -@ComponentV2 -export struct CurrentControlSection { - @Param desktopName: string = ''; - @Param desktopId: string = ''; - @Param controlTargetType: string = 'none'; - @Param connectionState: string = 'idle'; - @Param statusText: string = ''; - @Event onDisconnect: () => void = () => {}; - @Event onClearPairing: () => void = () => {}; - @Event onReconnect: () => void = () => {}; - - build() { - Column({ space: 0 }) { - if (this.hasControlTarget()) { - Text(RemoteI18n.t('remote.settings.currentControl')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .width('100%') - .margin({ left: 8, bottom: 10 }) - this.Card() - } - } - .width('100%') - } - - @Builder - private Card() { - Column() { - Row({ space: 14 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.desktop')) - .fontSize(22) - .fontColor([MUTED]) - .opacity(0.68) - } - .width(28) - .height(28) - - Column({ space: 3 }) { - Text(this.connectionTitle()) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .width('100%') - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.connectionDetail()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .width('100%') - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .constraintSize({ minHeight: 68 }) - .padding({ left: 18, right: 18, top: 12, bottom: 12 }) - .alignItems(VerticalAlign.Center) - - if (this.hasControlTarget()) { - Divider().strokeWidth(1).color(LINE).margin({ left: 18, right: 18 }) - - Row({ space: 8 }) { - Text(this.connectionSourceLabel()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .padding({ left: 10, right: 10, top: 5, bottom: 5 }) - .backgroundColor(SOFT) - .borderRadius(12) - Blank() - // Same rule as Android and iOS: one action. A link that is up or coming - // up can be left; once it is down, re-binding the selection is the offer. - // A legacy room can only be cleared, whatever its link state. - if (this.controlTargetType === 'account_device' && !this.isConnectedOrConnecting()) { - Text(RemoteI18n.t('remote.settings.reconnect')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .onClick(() => this.onReconnect()) - } else { - Text(this.controlTargetType === 'room' ? - RemoteI18n.t('remote.settings.disconnectTemporary') : - RemoteI18n.t('remote.settings.disconnect')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(STATUS_DANGER) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .onClick(() => { - if (this.controlTargetType === 'room') { - this.onClearPairing(); - } else { - this.onDisconnect(); - } - }) - } - } - .width('100%') - .constraintSize({ minHeight: 54 }) - .padding({ left: 18, right: 10 }) - .alignItems(VerticalAlign.Center) - } - } - .width('100%') - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .margin({ bottom: 24 }) - } - - private hasControlTarget(): boolean { - return this.controlTargetType === 'room' || this.controlTargetType === 'account_device'; - } - - private isConnectedOrConnecting(): boolean { - return this.connectionState === 'connected' || this.connectionState === 'reconnecting' || - this.connectionState === 'pairing' || this.connectionState === 'parsing'; - } - - private connectionTitle(): string { - return this.desktopName || this.desktopId || RemoteI18n.t('remote.settings.noDesktop'); - } - - private connectionDetail(): string { - if (this.connectionState === 'connected') { - return RemoteI18n.t('connection.connected'); - } - if (this.connectionState === 'reconnecting') { - return RemoteI18n.t('connection.reconnecting'); - } - return this.statusText || RemoteI18n.t('connection.disconnected'); - } - - private connectionSourceLabel(): string { - return this.controlTargetType === 'room' ? RemoteI18n.t('remote.settings.qrPairing') : - RemoteI18n.t('remote.settings.accountDevice'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DefaultAccountAvatar.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DefaultAccountAvatar.ets deleted file mode 100644 index ccacabea2c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DefaultAccountAvatar.ets +++ /dev/null @@ -1,28 +0,0 @@ -import { MUTED, SOFT } from './Theme'; - -@ComponentV2 -export struct DefaultAccountAvatar { - @Param avatarSize: number = 34; - @Param avatarUrl: string = ''; - @Local failedUrl: string = ''; - - build() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.person')) - .fontSize(this.avatarSize * 0.52) - .fontColor([MUTED]) - if (this.avatarUrl.length > 0 && this.failedUrl !== this.avatarUrl) { - Image(this.avatarUrl) - .width(this.avatarSize) - .height(this.avatarSize) - .objectFit(ImageFit.Cover) - .borderRadius(this.avatarSize / 2) - .onError(() => { this.failedUrl = this.avatarUrl; }) - } - } - .width(this.avatarSize) - .height(this.avatarSize) - .backgroundColor(SOFT) - .borderRadius(this.avatarSize / 2) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DeviceModelDefaultsPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DeviceModelDefaultsPanel.ets deleted file mode 100644 index 802934e527..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/DeviceModelDefaultsPanel.ets +++ /dev/null @@ -1,514 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - RemoteModelDefaultsRole, - RemoteModelDefaultsState -} from '../../services/RemoteModelDefaultsController'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { ConversationModelPresentationPolicy } from '../policy/ConversationModelPresentationPolicy'; -import { ModelRoleCandidatesPolicy, ModelRoleRowProjection } from '../policy/ModelRoleCandidatesPolicy'; -import { toConversationUiModel } from '../state/ConversationUiModels'; -import { DeviceModelDefaultsSheetState } from '../state/DeviceModelDefaultsSheetState'; -import { SettingsSheetState } from '../state/SettingsSheetState'; -import { ModelUnavailableCard } from './ModelUnavailableCard'; -import { NavigationBackButton } from './NavigationBackButton'; -import { SheetCloseButton } from './SheetCloseButton'; -import { SHEET_HEADER_HEIGHT, SHEET_HEADER_SIDE_PADDING, SHEET_HORIZONTAL_PADDING } from './SheetLayout'; -import { - CARD, - INK, - LINE, - MUTED, - PAGE_BG, - SOFT, - STATUS_DANGER, - STATUS_SUCCESS, - SUBTLE, - TRANSPARENT -} from './Theme'; - -/** The three roles in the order the page lists them. */ -const ROLE_ORDER: RemoteModelDefaultsRole[] = ['primary', 'fast', 'image_understanding']; - -/** - * The device model settings page: the three role slots of the desktop this phone - * is driving, on the same sheet, one level above the settings list. - * - * It is a page of the sheet rather than a stand-alone service panel: the header - * carries back and close, the rows are the settings list's row language, and the - * write feedback happens in place. The desktop owns the values, so a row shows - * the last device read and never the tap that is still in flight: selecting a - * model returns here and the value changes only when the read-back lands. - * - * Control flow stays in the sheet's state object the whole time — an older - * desktop that cannot answer, a desktop that stopped answering, and a phone that - * is simply not connected are three different states, and all three are stated - * in the page instead of failing the tap silently. - */ -@ComponentV2 -export struct DeviceModelDefaultsPanel { - @Param sheetState: SettingsSheetState = new SettingsSheetState(); - @Param deviceModels: DeviceModelDefaultsSheetState = new DeviceModelDefaultsSheetState(); - @Param desktopName: string = ''; - @Param desktopId: string = ''; - @Param controlTargetType: string = 'none'; - @Param connectionState: string = 'idle'; - @Event onClose: () => void = () => {}; - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - // The page is where the device is actually read: opening the sheet only arms - // the gate, so a user who never comes here never spends the read. - void this.deviceModels.ensureLoaded(); - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column({ space: 0 }) { - this.PageHeader() - Scroll() { - Column({ space: 0 }) { - this.DeviceSummaryCard() - if (this.deviceModels.state.available) { - this.RoleSection() - } else { - this.UnavailableCard() - } - this.ScopeCard() - } - .width('100%') - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: 22, - bottom: this.insets.tailSpacing(34) - }) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - /** - * The page header, in the one header language the sheet has: a quiet control on - * each side and the page's identity between them. Back is a real second level — - * this page was pushed from the settings list — so it sits next to the close - * that leaves the sheet entirely. - */ - @Builder - private PageHeader() { - Row() { - NavigationBackButton({ - isEnabled: !this.locked(), - onBack: (): void => { - this.sheetState.setPage('main'); - } - }) - Column({ space: 3 }) { - Text(RemoteI18n.t('settings.model.settingsTitle')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.deviceLabel()) - .width('100%') - .fontSize(MobileDesignTypography.headlineSmall.size) - .lineHeight(MobileDesignTypography.headlineSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - SheetCloseButton({ - isEnabled: !this.locked(), - onClose: this.onClose - }) - } - .width('100%') - .height(SHEET_HEADER_HEIGHT) - .padding({ left: SHEET_HEADER_SIDE_PADDING, right: SHEET_HEADER_SIDE_PADDING }) - .alignItems(VerticalAlign.Center) - .border({ width: { bottom: 1 }, color: LINE }) - } - - /** - * Which desktop these values belong to. This page edits a device, not a - * session, so the device is stated once at the top rather than repeated on - * every row. - */ - @Builder - private DeviceSummaryCard() { - Row({ space: 12 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.desktop')) - .fontSize(20) - .fontColor([INK]) - .opacity(0.9) - } - .width(28) - .height(28) - Column({ space: 2 }) { - Text(this.deviceLabel()) - .width('100%') - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.summaryStatus()) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.connectionState === 'connected' ? STATUS_SUCCESS : MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.modelSourceRowHeight }) - .padding({ left: 18, right: 18, top: 10, bottom: 10 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .margin({ bottom: 24 }) - } - - @Builder - private RoleSection() { - Column({ space: 0 }) { - if (!this.deviceModels.state.loaded) { - this.ReadingCard() - } else { - Text(RemoteI18n.t('settings.model.section')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .margin({ left: 8, bottom: 10 }) - Column() { - ForEach(ROLE_ORDER, (role: RemoteModelDefaultsRole) => { - this.RoleRow(role) - }, (role: RemoteModelDefaultsRole): string => role) - } - .width('100%') - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - if (this.deviceModels.state.error.length > 0 || this.deviceModels.feedbackVisible) { - this.WriteFeedback() - } - if (ModelRoleCandidatesPolicy.isEmptyCatalog(this.deviceModels.state.catalog)) { - this.EmptyCatalogCard() - } - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - - @Builder - private ReadingCard() { - Text(this.readingText()) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .padding({ left: 18, right: 18, top: 16, bottom: 16 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - } - - /** - * One role slot. The row is the settings list's own row language — a leading - * mark, a two-line body and a trailing control — because these three rows sit - * on the same sheet as the permission rows above them. - * - * The mark states whether the role resolves to a model at all, the meta line - * states which one, and the row is the way into that role's picker. Nothing is - * written from here: the picker is the only place a model is chosen. - */ - @Builder - private RoleRow(role: RemoteModelDefaultsRole) { - Row({ space: 12 }) { - Stack({ alignContent: Alignment.Center }) { - if (this.roleBusy(role)) { - LoadingProgress() - .width(16) - .height(16) - .color(INK) - } else if (this.roleProjection(role).resolved) { - SymbolGlyph($r('sys.symbol.checkmark_circle_fill')) - .fontSize(19) - .fontColor([INK]) - .width(20) - .height(20) - } - } - .width(22) - .height(24) - Column({ space: 3 }) { - Text(RemoteI18n.t(ModelRoleCandidatesPolicy.roleLabelKey(role))) - .width('100%') - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.roleMeta(role)) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - Row({ space: 4 }) { - if (this.roleUpdated(role)) { - Text(RemoteI18n.t('status.modelDefaultsUpdated')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(STATUS_SUCCESS) - .maxLines(1) - } - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(14) - .fontColor([MUTED]) - } - .alignItems(VerticalAlign.Center) - } - .width('100%') - .height(72) - .padding({ left: 18, right: 18 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.roleBusy(role) ? SOFT : TRANSPARENT) - .opacity(this.locked() ? 0.6 : 1) - .id(`device-model-role-${role}`) - .enabled(!this.locked()) - .onClick(() => { - this.sheetState.openModelPick(role); - }) - } - - /** - * What the write did, in the two shapes it has: the host's own rejection with a - * way to answer it again, or a confirmed write whose value has already been - * read back. Neither is a place to show the value that was asked for — that is - * the point of reading the desktop back. - */ - @Builder - private WriteFeedback() { - Row({ space: 10 }) { - if (this.deviceModels.state.error.length > 0) { - Text(this.deviceModels.state.error) - .layoutWeight(1) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(STATUS_DANGER) - .maxLines(3) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .padding({ left: 10, right: 10, top: 6, bottom: 6 }) - .backgroundColor(SOFT) - .borderRadius(14) - .id('device-model-retry') - .enabled(!this.locked()) - .onClick(() => { - void this.deviceModels.retry(); - }) - } else if (this.deviceModels.feedbackVisible) { - Text(RemoteI18n.f('settings.model.updatedResult', this.writtenValue())) - .layoutWeight(1) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(STATUS_SUCCESS) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .id('device-model-updated') - } - } - .width('100%') - .padding({ left: 8, right: 8, top: 10 }) - .alignItems(VerticalAlign.Center) - } - - /** - * The desktop has no models at all. The rows stay where they are — the user - * came here for three slots and three slots are what the device has — and this - * card says what to do about it, because nothing on this page can add a model. - */ - @Builder - private EmptyCatalogCard() { - Column({ space: 6 }) { - SymbolGlyph($r('sys.symbol.desktop')) - .fontSize(26) - .fontColor([SUBTLE]) - Text(RemoteI18n.t('settings.model.emptyTitle')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .textAlign(TextAlign.Center) - Text(RemoteI18n.t('settings.model.emptyText')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width('100%') - .padding({ left: 18, right: 18, top: 26, bottom: 22 }) - .alignItems(HorizontalAlign.Center) - .margin({ top: 24 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - } - - /** - * The page's one scope card, in every state it has: an older desktop is told - * why in place of the rows, and the rules that hold regardless are still true - * once it is upgraded. - */ - @Builder - private ScopeCard() { - Column({ space: 4 }) { - this.ScopeLine(RemoteI18n.t('settings.model.scopeNewSessions')) - this.ScopeLine(RemoteI18n.t('settings.model.scopeFastFollowsPrimary')) - this.ScopeLine(RemoteI18n.t('settings.model.scopeImageUnderstanding')) - } - .width('100%') - .padding({ left: 18, right: 18, top: 14, bottom: 14 }) - .alignItems(HorizontalAlign.Start) - .margin({ top: 24 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - } - - @Builder - private ScopeLine(text: string) { - Text(text) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - } - - /** - * The desktop cannot answer this page. The entry that led here is greyed for - * the same reason, but the page is reachable from a stale capability set too, - * so it states the reason itself — the controller already decided which of the - * two it is, and this card does not re-judge it. - * - * The card is shared with the picker, which reaches it in one more state: a - * read that failed while the device could still answer. This page shows that - * case above its own rows instead, so the retry here never has work to do. - */ - @Builder - private UnavailableCard() { - ModelUnavailableCard({ - reason: this.deviceModels.state.error.length > 0 ? this.deviceModels.state.error : - RemoteI18n.t('status.remoteUnavailable'), - canRetry: ModelRoleCandidatesPolicy.canRepeatRead(this.deviceModelState()), - busy: this.deviceModels.state.loading || this.locked(), - cardId: 'device-model-unavailable', - onRetry: (): void => { - void this.deviceModels.retry(); - } - }) - } - - private deviceLabel(): string { - return this.desktopName.length > 0 ? this.desktopName : this.desktopId; - } - - /** The desktop this page belongs to, and how the phone reached it. */ - private summaryStatus(): string { - const presence = this.connectionState === 'connected' ? - RemoteI18n.t('connect.connected') : RemoteI18n.t('connect.disconnected'); - const source = this.controlTargetType === 'account_device' ? - RemoteI18n.t('settings.modelService.accountSource') : - RemoteI18n.t('settings.modelService.localSource'); - return `${presence} · ${source}`; - } - - private readingText(): string { - const status = this.deviceModels.state.statusText; - return status.length > 0 ? status : RemoteI18n.t('status.loadingModelDefaults'); - } - - /** A write in flight owns the page: both header controls and every row wait for it. */ - private locked(): boolean { - return this.deviceModels.state.busy; - } - - private deviceModelState(): RemoteModelDefaultsState { - return this.deviceModels.state; - } - - private roleProjection(role: RemoteModelDefaultsRole): ModelRoleRowProjection { - return ModelRoleCandidatesPolicy.roleRow( - this.deviceModelState().roles, role, this.deviceModelState().catalog); - } - - private roleBusy(role: RemoteModelDefaultsRole): boolean { - return this.locked() && this.deviceModels.pendingRole === role; - } - - /** True while the just-written role row carries the transient result word. */ - private roleUpdated(role: RemoteModelDefaultsRole): boolean { - return this.deviceModels.feedbackVisible && this.deviceModels.pendingRole === role; - } - - /** - * The role's value line: the model the desktop returned, or the placeholder - * for a role that has none, with its fallback hint. A model the desktop holds - * but no longer lists is shown by id — the value is real even when the catalog - * cannot describe it. - */ - private roleMeta(role: RemoteModelDefaultsRole): string { - const base = this.roleValue(role); - const projection = this.roleProjection(role); - if (projection.hintKey.length > 0) { - return `${base} · ${RemoteI18n.t(projection.hintKey)}`; - } - return base; - } - - private roleValue(role: RemoteModelDefaultsRole): string { - const projection = this.roleProjection(role); - if (projection.model) { - return ConversationModelPresentationPolicy.roleMetaLabel( - toConversationUiModel(projection.model), projection.modelId); - } - if (projection.modelId.length > 0) { - return projection.modelId; - } - return RemoteI18n.t(projection.unsetKey); - } - - /** The value the confirmed write left behind, read back from the device. */ - private writtenValue(): string { - const role = this.deviceModels.pendingRole; - return role === '' ? RemoteI18n.t('status.modelDefaultsUpdated') : this.roleValue(role); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FilePreviewSurface.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FilePreviewSurface.ets deleted file mode 100644 index 88eb84c805..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FilePreviewSurface.ets +++ /dev/null @@ -1,571 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - CodeSyntaxHighlightCache, - CodeSyntaxHighlighter, - CodeSyntaxToken, - CodeSyntaxTokenKind -} from '../../services/CodeSyntaxHighlighter'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { - FilePreviewPhase, - FilePreviewRendererKind, - FilePreviewState -} from '../state/FilePreviewState'; -import { MarkdownContent } from './MarkdownContent'; -import { NavigationBackButton } from './NavigationBackButton'; -import { - CARD, - CODE_COMMENT, - CODE_CONSTANT, - CODE_FUNCTION, - CODE_KEYWORD, - CODE_LINE_NUMBER, - CODE_NUMBER, - CODE_PROPERTY, - CODE_STRING, - CODE_TARGET_BG, - CODE_TYPE, - INK, - LINE, - MUTED, - PAGE_BG, - SOFT, - TRANSPARENT, -} from './Theme'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; - -@ComponentV2 -export struct FilePreviewSurface { - private readonly textScroller: Scroller = new Scroller(); - private readonly markdownScroller: Scroller = new Scroller(); - private readonly syntaxHighlightCache: CodeSyntaxHighlightCache = new CodeSyntaxHighlightCache(); - private restoreScrollTimerId: number = 0; - /** - * The surface's own bottom edge, in vp. The preview scrollers run to the - * screen edge — content rolls under the navigation indicator while it is - * moving — and their tail padding is what rests the last line above the bar. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - @Local imageOriginalSizeTarget: string = ''; - @Param state: FilePreviewState = new FilePreviewState(); - @Param remoteAvailable: boolean = true; - @Param downloadPath: string = ''; - @Param downloadedPath: string = ''; - @Param downloadStatus: string = ''; - @Param previewExpanded: boolean = false; - @Param canToggleExpanded: boolean = false; - @Event onClose: () => void = () => {}; - @Event onRefresh: () => void = () => {}; - @Event onDownload: (path: string) => void = (_path: string) => {}; - @Event onOpenLink: (reference: string, label: string) => void = (_reference: string, _label: string) => {}; - @Event onToggleExpanded: () => void = () => {}; - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - this.clearRestoreScrollTimer(); - } - - build() { - Column() { - this.Header() - this.DownloadStatus() - this.Body() - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - @Builder - Header() { - Row({ space: 10 }) { - NavigationBackButton({ - controlSize: 44, - onBack: (): void => { - this.onClose(); - } - }) - - Column({ space: 2 }) { - Text(this.state.fileName || this.state.target.displayName || RemoteI18n.t('filePreview.title')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.headerDetail()) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - - if (this.isImageReady()) { - Stack({ alignContent: Alignment.Center }) { - Text('1:1') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(this.isImageOriginalSize() ? CODE_FUNCTION : INK) - } - .width(44) - .height(44) - .accessibilityText(RemoteI18n.t( - this.isImageOriginalSize() ? 'filePreview.fitImage' : 'filePreview.actualImageSize' - )) - .onClick(() => { - this.toggleImageSize(); - }) - } - - if (this.canToggleExpanded) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.previewExpanded ? - $r('sys.symbol.arrow_down_right_and_arrow_up_left') : - $r('sys.symbol.arrow_up_left_and_arrow_down_right')) - .fontSize(20) - .fontColor([INK]) - } - .width(44) - .height(44) - .accessibilityText(RemoteI18n.t( - this.previewExpanded ? 'filePreview.restoreSize' : 'filePreview.expand' - )) - .onClick(() => { - this.onToggleExpanded(); - }) - } - - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.arrow_clockwise')) - .fontSize(20) - .fontColor([this.canUseRemoteAction() ? INK : MUTED]) - } - .width(44) - .height(44) - .accessibilityText(RemoteI18n.t('common.refresh')) - .opacity(this.canUseRemoteAction() ? 1 : 0.45) - .onClick(() => { - if (this.canUseRemoteAction()) { - this.onRefresh(); - } - }) - - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.arrow_down_to_line')) - .fontSize(20) - .fontColor([this.canDownload() ? INK : MUTED]) - } - .width(44) - .height(44) - .accessibilityText(RemoteI18n.t('chat.download')) - .opacity(this.canDownload() ? 1 : 0.45) - .onClick(() => { - if (this.canDownload()) { - this.onDownload(this.state.target.rawReference || this.state.target.remotePath); - } - }) - } - .width('100%') - .height(68 + this.insets.top) - // The header band is the surface's top edge in both hosts — the compact - // full-page overlay and the wide preview pane — so it carries the status bar - // strip itself: the band's fill still reaches the top of the window and the - // back control and title sit below the clock and the indicators. It spans - // the window horizontally, so it carries the side strips the same way: on a - // rotated device the back control is what the camera cutout would cover. - .padding({ - left: this.insets.leftPadding(8), - right: this.insets.rightPadding(8), - top: 8 + this.insets.top, - bottom: 8 - }) - .alignItems(VerticalAlign.Center) - .border({ width: { bottom: 1 }, color: LINE }) - .backgroundColor(PAGE_BG) - } - - @Builder - Body() { - if (this.state.phase === FilePreviewPhase.Loading && !this.remoteAvailable) { - this.OfflineLoadingState() - } else if (this.state.phase === FilePreviewPhase.Loading) { - this.LoadingState() - } else if (this.state.phase === FilePreviewPhase.Error) { - this.ErrorState() - } else if (this.state.phase === FilePreviewPhase.Unsupported) { - this.UnsupportedState() - } else if (this.state.phase === FilePreviewPhase.Ready && - this.state.rendererKind === FilePreviewRendererKind.Image) { - this.ImagePreview() - } else if (this.state.phase === FilePreviewPhase.Ready && - this.state.rendererKind === FilePreviewRendererKind.Markdown) { - this.MarkdownPreview() - } else if (this.state.phase === FilePreviewPhase.Ready) { - this.TextPreview() - } else { - this.EmptyState() - } - } - - @Builder - DownloadStatus() { - if (this.downloadStatus.length > 0 && this.downloadMatchesTarget()) { - Row() { - Text(this.downloadStatus) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .padding({ left: 14, right: 14, top: 8, bottom: 8 }) - .backgroundColor(SOFT) - .border({ width: { bottom: 1 }, color: LINE }) - } - } - - @Builder - LoadingState() { - Column({ space: 12 }) { - LoadingProgress() - .width(28) - .height(28) - .color(MUTED) - Text(RemoteI18n.t('filePreview.loading')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - } - - @Builder - OfflineLoadingState() { - Column({ space: 10 }) { - Text(RemoteI18n.t('filePreview.loadFailed')) - .fontSize(MobileDesignTypography.titleMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(RemoteI18n.t('filePreview.offline')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width('100%') - .layoutWeight(1) - .padding({ left: 32, right: 32 }) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - } - - @Builder - ErrorState() { - Column({ space: 12 }) { - Text(RemoteI18n.t('filePreview.loadFailed')) - .fontSize(MobileDesignTypography.titleMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(this.state.errorText) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .maxLines(4) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.state.errorRetryable) { - Button(RemoteI18n.t('common.retry')) - .height(42) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(CARD) - .backgroundColor(INK) - .borderRadius(21) - .enabled(this.remoteAvailable) - .opacity(this.remoteAvailable ? 1 : 0.45) - .onClick(() => { - this.onRefresh(); - }) - } - } - .width('100%') - .layoutWeight(1) - .padding({ left: 32, right: 32 }) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - } - - @Builder - UnsupportedState() { - Column({ space: 10 }) { - SymbolGlyph($r('sys.symbol.doc')) - .fontSize(38) - .fontColor([MUTED]) - Text(RemoteI18n.t('filePreview.unsupported')) - .fontSize(MobileDesignTypography.titleMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(this.metadataDetail()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - Button(RemoteI18n.t('chat.download')) - .height(42) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(CARD) - .backgroundColor(INK) - .borderRadius(21) - .enabled(this.remoteAvailable) - .opacity(this.remoteAvailable ? 1 : 0.45) - .onClick(() => { - this.onDownload(this.state.target.rawReference || this.state.target.remotePath); - }) - } - .width('100%') - .layoutWeight(1) - .padding({ left: 32, right: 32 }) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - } - - @Builder - TextPreview() { - Column() { - if (this.state.truncated) { - Text(RemoteI18n.f('filePreview.truncated', RemoteUiState.formatBytes(this.state.loadedBytes))) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .padding({ left: 14, right: 14, top: 7, bottom: 7 }) - .backgroundColor(SOFT) - .border({ width: { bottom: 1 }, color: LINE }) - } - Scroll(this.textScroller) { - Text() { - ForEach(this.syntaxTokens(), (token: CodeSyntaxToken) => { - Span(token.text) - .fontColor(this.syntaxTokenColor(token.kind)) - .textBackgroundStyle({ - color: this.isTargetLine(token.lineNumber) ? CODE_TARGET_BG : TRANSPARENT - }) - }, (token: CodeSyntaxToken) => token.id) - } - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(INK) - .fontFamily('monospace') - .textSelectable(TextSelectableMode.SELECTABLE_UNFOCUSABLE) - .padding({ left: 12, right: 12, top: 14, bottom: this.insets.tailSpacing(24) }) - .constraintSize({ minWidth: '100%' }) - } - .scrollable(ScrollDirection.FREE) - .scrollBar(BarState.Auto) - .layoutWeight(1) - .width('100%') - .align(Alignment.TopStart) - .onAppear(() => { - this.restoreTextScroll(); - }) - .onDidScroll((xOffset: number, yOffset: number, _scrollState: ScrollState) => { - this.state.recordScroll(xOffset, yOffset); - }) - } - .layoutWeight(1) - .width('100%') - .backgroundColor(SOFT) - } - - @Builder - MarkdownPreview() { - Scroll(this.markdownScroller) { - MarkdownContent({ - text: this.state.textContent, - onCopyText: (_text: string) => {}, - onOpenLink: (reference: string, label: string) => { - this.onOpenLink(reference, label); - } - }) - .width('100%') - .padding({ left: 16, right: 16, top: 16, bottom: this.insets.tailSpacing(28) }) - } - .scrollable(ScrollDirection.Vertical) - .scrollBar(BarState.Auto) - .layoutWeight(1) - .width('100%') - .align(Alignment.TopStart) - .onAppear(() => { - this.restoreMarkdownScroll(); - }) - .onDidScroll((xOffset: number, yOffset: number, _scrollState: ScrollState) => { - this.state.recordScroll(xOffset, yOffset); - }) - } - - @Builder - ImagePreview() { - Stack({ alignContent: Alignment.Center }) { - Image(`data:${this.state.mimeType};base64,${this.state.contentBase64}`) - .width('100%') - .height('100%') - .objectFit(this.isImageOriginalSize() ? ImageFit.None : ImageFit.Contain) - .onClick(() => { - this.toggleImageSize(); - }) - .onError((_error: ImageError) => { - this.imageOriginalSizeTarget = ''; - this.state.phase = FilePreviewPhase.Error; - this.state.errorText = RemoteI18n.t('filePreview.imageDecodeFailed'); - this.state.errorRetryable = true; - }) - } - .layoutWeight(1) - .width('100%') - .padding(18) - .backgroundColor(SOFT) - } - - @Builder - EmptyState() { - Column() { - } - .layoutWeight(1) - .width('100%') - } - - private canUseRemoteAction(): boolean { - return this.remoteAvailable && this.state.visible && this.state.phase !== FilePreviewPhase.Loading && - (this.state.phase !== FilePreviewPhase.Error || this.state.errorRetryable) && - this.state.target.isValid(); - } - - private canDownload(): boolean { - return this.remoteAvailable && this.state.visible && !this.isDownloadingTarget() && this.state.target.isValid(); - } - - private isDownloadingTarget(): boolean { - return this.downloadPath.length > 0 && this.downloadMatchesTarget() && this.downloadedPath.length === 0; - } - - private downloadMatchesTarget(): boolean { - const target = this.state.target.rawReference || this.state.target.remotePath; - return target.length > 0 && (target === this.downloadPath || target === this.downloadedPath); - } - - private isImageReady(): boolean { - return this.state.phase === FilePreviewPhase.Ready && - this.state.rendererKind === FilePreviewRendererKind.Image; - } - - private isImageOriginalSize(): boolean { - return this.imageOriginalSizeTarget.length > 0 && - this.imageOriginalSizeTarget === this.state.target.remotePath; - } - - private toggleImageSize(): void { - this.imageOriginalSizeTarget = this.isImageOriginalSize() ? '' : this.state.target.remotePath; - } - - private headerDetail(): string { - if (!this.remoteAvailable) { - return RemoteI18n.t('filePreview.offline'); - } - if (this.state.phase === FilePreviewPhase.Loading) { - return RemoteI18n.t('filePreview.loading'); - } - return this.metadataDetail(); - } - - private metadataDetail(): string { - const size = this.state.fileSize > 0 ? RemoteUiState.formatBytes(this.state.fileSize) : ''; - if (this.state.mimeType.length > 0 && size.length > 0) { - return `${this.state.mimeType} · ${size}`; - } - return this.state.mimeType || size || this.state.target.remotePath; - } - - private syntaxTokens(): CodeSyntaxToken[] { - return this.syntaxHighlightCache.tokensFor( - this.state.textContent, - this.state.fileName || this.state.target.remotePath - ); - } - - private syntaxTokenColor(kind: CodeSyntaxTokenKind): ResourceColor { - if (kind === CodeSyntaxTokenKind.LineNumber) { - return CODE_LINE_NUMBER; - } - if (kind === CodeSyntaxTokenKind.Keyword) { - return CODE_KEYWORD; - } - if (kind === CodeSyntaxTokenKind.String) { - return CODE_STRING; - } - if (kind === CodeSyntaxTokenKind.Number) { - return CODE_NUMBER; - } - if (kind === CodeSyntaxTokenKind.Comment) { - return CODE_COMMENT; - } - if (kind === CodeSyntaxTokenKind.Function) { - return CODE_FUNCTION; - } - if (kind === CodeSyntaxTokenKind.Type) { - return CODE_TYPE; - } - if (kind === CodeSyntaxTokenKind.Constant) { - return CODE_CONSTANT; - } - if (kind === CodeSyntaxTokenKind.Property) { - return CODE_PROPERTY; - } - return INK; - } - - private isTargetLine(lineNumber: number): boolean { - if (lineNumber <= 0 || this.state.target.lineStart <= 0) { - return false; - } - const end = this.state.target.lineEnd > 0 ? this.state.target.lineEnd : this.state.target.lineStart; - return lineNumber >= this.state.target.lineStart && lineNumber <= end; - } - - private restoreTextScroll(): void { - this.clearRestoreScrollTimer(); - this.restoreScrollTimerId = setTimeout(() => { - this.restoreScrollTimerId = 0; - const xOffset = this.state.initialScrollX(); - const yOffset = this.state.initialScrollY(); - this.textScroller.scrollTo({ xOffset, yOffset, animation: false }); - this.state.recordScroll(xOffset, yOffset); - }, 30); - } - - private restoreMarkdownScroll(): void { - this.clearRestoreScrollTimer(); - this.restoreScrollTimerId = setTimeout(() => { - this.restoreScrollTimerId = 0; - const xOffset = this.state.initialScrollX(); - const yOffset = this.state.hasRecordedScroll ? this.state.initialScrollY() : 0; - this.markdownScroller.scrollTo({ xOffset, yOffset, animation: false }); - this.state.recordScroll(xOffset, yOffset); - }, 30); - } - - private clearRestoreScrollTimer(): void { - if (this.restoreScrollTimerId !== 0) { - clearTimeout(this.restoreScrollTimerId); - this.restoreScrollTimerId = 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FileReferenceCard.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FileReferenceCard.ets deleted file mode 100644 index 4931c6d771..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/FileReferenceCard.ets +++ /dev/null @@ -1,86 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { CARD, FILE_LINK, INK, LINE, MUTED, SOFT } from './Theme'; - -@ComponentV2 -export struct FileReferenceCard { - @Param path: string = ''; - @Param label: string = ''; - @Param status: string = ''; - @Param previewLabel: string = ''; - @Param buttonLabel: string = ''; - @Param disabled: boolean = false; - @Param selected: boolean = false; - @Param previewLoading: boolean = false; - @Event onPreview: (path: string, label: string) => void = (_path: string, _label: string) => {}; - @Event onDownload: (path: string) => void = (_path: string) => {}; - - build() { - Row({ space: 10 }) { - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - if (this.previewLoading) { - LoadingProgress() - .width(17) - .height(17) - .color(FILE_LINK) - } else { - Text('▤') - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(INK) - } - } - .width(34) - .height(34) - .backgroundColor(SOFT) - .borderRadius(12) - Column({ space: 3 }) { - Text(this.label) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.status) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(FILE_LINK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .layoutWeight(1) - .height(44) - .accessibilityText(`${this.previewLabel} ${this.label}`) - .onClick(() => { - this.onPreview(this.path, this.label); - }) - Stack({ alignContent: Alignment.Center }) { - if (this.disabled) { - LoadingProgress() - .width(18) - .height(18) - .color(MUTED) - } else { - SymbolGlyph($r('sys.symbol.arrow_down_to_line')) - .fontSize(19) - .fontColor([INK]) - } - } - .width(44) - .height(44) - .accessibilityText(this.buttonLabel) - .opacity(this.disabled ? 0.55 : 1) - .onClick(() => { - if (!this.disabled) { - this.onDownload(this.path); - } - }) - } - .width('100%') - .padding(12) - .backgroundColor(this.selected ? SOFT : CARD) - .borderRadius(14) - .border({ width: 1, color: this.selected ? FILE_LINK : LINE }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/HarnessProfileMenu.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/HarnessProfileMenu.ets deleted file mode 100644 index 53266cf7ed..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/HarnessProfileMenu.ets +++ /dev/null @@ -1,94 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { HarnessProfilePolicy } from '../policy/HarnessProfilePolicy'; -import { CARD, INK, LINE, MUTED, SHADOW_SUBTLE, TRANSPARENT } from './Theme'; - -/** Compact creation-time selector for the supported Harness profiles. */ -@ComponentV2 -export struct HarnessProfileMenu { - @Param showTitle: boolean = true; - @Param includeCowork: boolean = false; - @Param menuWidth: number = 160; - @Event onSelect: (agentType: string) => void = (_agentType: string) => {}; - - build() { - Column({ space: 2 }) { - if (this.showTitle) { - Text(RemoteI18n.t('remote.harness.title')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .width('100%') - .height(30) - .padding({ left: 14, right: 14 }) - } - this.ProfileRow('minimal', RemoteI18n.t('remote.harness.minimal')) - this.ProfileRow('standard', RemoteI18n.t('remote.harness.standard')) - this.ProfileRow('ultimate', RemoteI18n.t('remote.harness.ultimate')) - this.ProfileRow('creative', RemoteI18n.t('remote.harness.creative')) - if (this.includeCowork) { - Divider().strokeWidth(0.5).color(LINE).margin({ top: 4, bottom: 4 }) - this.AgentRow('Cowork', 'Cowork') - } - } - .width(this.menuWidth) - .padding({ top: 8, bottom: 8 }) - .backgroundColor(CARD) - .borderRadius(16) - .border({ width: 0.5, color: LINE }) - .shadow({ radius: 20, color: SHADOW_SUBTLE, offsetY: 8 }) - } - - @Builder - private ProfileRow(profileId: string, label: string) { - Row({ space: 12 }) { - this.ProfileIcon(profileId) - Text(label) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - } - .width('100%') - .height(46) - .padding({ left: 14, right: 14 }) - .borderRadius(10) - .backgroundColor(TRANSPARENT) - .onClick(() => { - this.onSelect(HarnessProfilePolicy.agentType(profileId)); - }) - } - - @Builder - private AgentRow(label: string, agentType: string) { - Row({ space: 12 }) { - SymbolGlyph($r('sys.symbol.person_2')) - .fontSize(17) - .fontColor([INK]) - .width(22) - .height(22) - Text(label) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - } - .width('100%') - .height(46) - .padding({ left: 14, right: 14 }) - .borderRadius(10) - .backgroundColor(TRANSPARENT) - .onClick(() => this.onSelect(agentType)) - } - - @Builder - private ProfileIcon(profileId: string) { - if (profileId === 'minimal') { - Image($r('app.media.harness_minimal')).width(22).height(22).objectFit(ImageFit.Contain).draggable(false) - } else if (profileId === 'standard') { - Image($r('app.media.harness_standard')).width(22).height(22).objectFit(ImageFit.Contain).draggable(false) - } else if (profileId === 'ultimate') { - Image($r('app.media.harness_ultimate')).width(22).height(22).objectFit(ImageFit.Contain).draggable(false) - } else { - Image($r('app.media.harness_creative')).width(22).height(22).objectFit(ImageFit.Contain).draggable(false) - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/InteractionMailboxPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/InteractionMailboxPanel.ets deleted file mode 100644 index 34331610d7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/InteractionMailboxPanel.ets +++ /dev/null @@ -1,88 +0,0 @@ -import { MobileDesignTypography, MobileDesignGeometry } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - InteractionMailboxAction, InteractionMailboxActionType, InteractionMailboxState, - PendingPermission, PendingQuestion -} from '../../model/InteractionMailbox'; -import { ConversationUiQuestionAnswer, toRemoteQuestionAnswer } from '../state/ConversationUiModels'; -import { ToolConfirmationPanel, ToolQuestionAnswerPanel } from './ToolInteractionPanels'; -import { CARD, INK, LINE, MUTED, SOFT, STATUS_DANGER } from './Theme'; - -@ComponentV2 -export struct InteractionMailboxPanel { - @Param state: InteractionMailboxState = new InteractionMailboxState(); - @Event onAction: (action: InteractionMailboxAction) => void = (_action: InteractionMailboxAction) => {}; - @Local editingId: string = ''; - - build() { - if (this.state.requests.length > 0 || this.state.questions.length > 0 || this.state.failure.length > 0) { - Scroll() { - Column({ space: 12 }) { - if (this.state.failure.length > 0) { - Row({ space: 8 }) { - Text(RemoteI18n.t(this.state.failure === 'load' ? 'chat.interactionLoadFailed' : 'chat.approvalFailed')) - .fontSize(MobileDesignTypography.bodySmall.size).fontColor(STATUS_DANGER).layoutWeight(1) - Button(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.labelMedium.size).fontColor(INK) - .backgroundColor(SOFT).height(32).borderRadius(16) - .border({ width: 1, color: LINE }) - .enabled(!this.state.busy) - .onClick(() => this.onAction({ sessionId: this.state.sessionId, type: InteractionMailboxActionType.Refresh })) - }.width('100%') - } - ForEach(this.state.questions, (question: PendingQuestion) => { - ToolQuestionAnswerPanel({ - toolId: question.toolId, questionsJson: JSON.stringify(question.questions), isBusy: this.state.busy, - onAnswerQuestion: (id: string, answers: ConversationUiQuestionAnswer): void => { - this.onAction({ sessionId: this.state.sessionId, type: InteractionMailboxActionType.Answer, - id, answers: toRemoteQuestionAnswer(answers) }); - } - }) - .onTouch((event: TouchEvent): void => { - if (event.type === TouchType.Down) this.onAction({ sessionId: this.state.sessionId, - type: InteractionMailboxActionType.StartQuestion, id: question.toolId }); - }) - }, (question: PendingQuestion): string => `${this.state.sessionId}:${question.toolId}`) - ForEach(this.state.requests, (request: PendingPermission) => { - Column({ space: MobileDesignGeometry.approvalCardGap }) { - Row({ space: 8 }) { - // Rasterized from the desktop glyph with the shared warning token (same in both themes). - Image($r('app.media.approval_shield')).width(16).height(16) - Text(request.source?.identity || request.action || RemoteI18n.t('chat.approvalRequired')) - .fontSize(MobileDesignTypography.bodySmall.size).fontColor(INK) - .fontWeight(FontWeight.Medium).layoutWeight(1) - Button(this.editingId === request.requestId ? RemoteI18n.t('chat.hideApprovalInput') : RemoteI18n.t('chat.editApprovalInput')) - .fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED) - .backgroundColor(CARD).height(32).padding({ left: 8, right: 8 }) - .enabled(!this.state.busy) - .onClick(() => { this.editingId = this.editingId === request.requestId ? '' : request.requestId; }) - }.width('100%') - Column({ space: 6 }) { - if (request.action && request.source?.identity && request.action.toLowerCase() !== request.source.identity.toLowerCase()) { - Text(request.action).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED) - } - if ((request.resources || []).length > 0) { - Text((request.resources || []).join('\n')) - .fontSize(MobileDesignTypography.labelSmall.size).fontFamily('monospace').fontColor(INK) - .width('100%').padding(10).backgroundColor(SOFT).borderRadius(8) - } - }.width('100%').alignItems(HorizontalAlign.Start) - ToolConfirmationPanel({ - toolId: request.requestId, defaultInputText: '{}', leadingInset: 0, compactActions: true, - hasEditableInput: this.editingId === request.requestId, isBusy: this.state.busy, - onApproveTool: (id: string, updatedInput?: Object): void => { - this.onAction({ sessionId: this.state.sessionId, type: InteractionMailboxActionType.Approve, id, updatedInput }); - }, - onRejectTool: (id: string): void => { - this.onAction({ sessionId: this.state.sessionId, type: InteractionMailboxActionType.Reject, id }); - } - }) - }.width('100%').padding(MobileDesignGeometry.approvalCardPadding).alignItems(HorizontalAlign.Start) - .backgroundColor(CARD).borderRadius(MobileDesignGeometry.approvalCardRadius) - .border({ width: 1, color: LINE }) - }, (request: PendingPermission): string => `${this.state.sessionId}:${request.requestId}`) - }.width('100%').padding({ left: 16, right: 16, top: 8, bottom: 8 }) - }.width('100%').constraintSize({ maxHeight: '40%' }).scrollBar(BarState.Auto) - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LanguageSettingsPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LanguageSettingsPanel.ets deleted file mode 100644 index 77e89d8f20..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/LanguageSettingsPanel.ets +++ /dev/null @@ -1,97 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { AppLocale } from '../../i18n/AppLocale'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ModelServiceSettingsPolicy } from '../policy/ModelServiceSettingsPolicy'; -import { CARD, INK } from './Theme'; -import { SheetCloseHeader } from './SheetCloseHeader'; - -@ComponentV2 -export struct LanguageSettingsPanel { - @Param selectedLanguage: string = AppLocale.DEFAULT; - @Event onClose: () => void = () => {}; - @Event onSelect: (language: string) => Promise = async (_language: string) => {}; - @Local pendingLanguage: string = ''; - - aboutToAppear(): void { - this.pendingLanguage = ''; - } - - build() { - Column({ space: 0 }) { - this.Header() - this.LanguageList() - } - .width('100%') - .height('100%') - .backgroundColor(CARD) - .borderRadius({ - topLeft: MobileDesignGeometry.sheetTopRadius, - topRight: MobileDesignGeometry.sheetTopRadius - }) - } - - @Builder - Header() { - SheetCloseHeader({ - title: RemoteI18n.t('settings.language.choose'), - showDivider: true, - isEnabled: this.pendingLanguage.length === 0, - onClose: (): void => { - if (this.pendingLanguage.length === 0) { - this.onClose(); - } - } - }) - } - - @Builder - LanguageList() { - Column() { - ForEach(AppLocale.supported(), (language: string) => { - this.LanguageRow(language) - }, (language: string) => `${language}:${RemoteI18n.revision()}`) - } - .width('100%') - .padding({ - top: ModelServiceSettingsPolicy.LANGUAGE_LIST_TOP_PADDING, - bottom: ModelServiceSettingsPolicy.LANGUAGE_LIST_BOTTOM_PADDING - }) - } - - @Builder - LanguageRow(language: string) { - Row() { - Text(RemoteI18n.translate(language, AppLocale.nativeNameKey(language))) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .layoutWeight(1) - if (language === this.selectedLanguage) { - SymbolGlyph($r('sys.symbol.checkmark')) - .fontSize(18) - .fontColor([INK]) - } - } - .width('100%') - .height(ModelServiceSettingsPolicy.LANGUAGE_ROW_HEIGHT) - .padding({ left: 16, right: 16 }) - .alignItems(VerticalAlign.Center) - .opacity(this.pendingLanguage.length > 0 && this.pendingLanguage !== language ? 0.45 : 1) - .onClick(() => { - void this.select(language); - }) - } - - private async select(language: string): Promise { - if (language === this.selectedLanguage || this.pendingLanguage.length > 0) { - return; - } - this.pendingLanguage = language; - try { - await this.onSelect(language); - this.onClose(); - } finally { - this.pendingLanguage = ''; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MarkdownContent.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MarkdownContent.ets deleted file mode 100644 index 35ee702020..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MarkdownContent.ets +++ /dev/null @@ -1,390 +0,0 @@ -// `SelectionContainerAttribute` is not decoration: the ArkUI compiler resolves -// the attribute type of a component that lives in an api/ declaration through -// this file's imports, so dropping it fails CompileArkTS. -import { SelectionContainer, SelectionContainerAttribute, SelectionContainerTextJoinStyle } from '@kit.ArkUI'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { DeviceApiLevelService } from '../../services/DeviceApiLevelService'; -import { - MarkdownParseCache, - ParsedMarkdownBlock, - ParsedMarkdownInline, - ParsedMarkdownListItem, - ParsedMarkdownTableCell, - ParsedMarkdownTableRow -} from '../../services/MarkdownParser'; -import { SelectionCapabilityPolicy } from '../policy/SelectionCapabilityPolicy'; -import { CARD, FILE_LINK, INK, LINE, MUTED, SOFT } from './Theme'; - -@ComponentV2 -export struct MarkdownContent { - private readonly parseCache: MarkdownParseCache = new MarkdownParseCache(); - /** - * Whether this device can select across blocks. Resolved once: a running - * process cannot change its API level. - */ - private readonly crossBlockSelection: boolean = - SelectionCapabilityPolicy.supportsCrossBlockSelection(DeviceApiLevelService.sdkApiVersion()); - @Param text: string = ''; - // Explicit primitive invalidation for retained Repeat rows. The text remains - // the source of truth; this revision only ensures parameter propagation on - // ArkUI builds that do not observe nested object mutations across children. - @Param renderRevision: number = 0; - @Event onCopyText: (text: string) => void = (_text: string) => {}; - @Event onOpenLink: (reference: string, label: string) => void = (_reference: string, _label: string) => {}; - - build() { - if (this.crossBlockSelection) { - // API 26 only: the container is what lets one long press span several - // `Text` children. Its `copyOption` and join style govern the system - // selection menu, which copies the selected range with a line break - // between the blocks it covers. The children keep their own `copyOption` - // as well: that is the documented shape, and it is also what keeps each - // block copyable on its own. - // - // Colors are deliberately left to the platform. The app has no caret or - // selection-highlight token, and native color resources are generated from - // the shared mobile token contract, so inventing one here would rewrite - // the Android, iOS and design-preview token outputs. The platform paints - // its own interactive-selection state, which is what the approved UI draft - // specifies for the missing tokens; the handles take the app's information - // accent so selection reads as this app's. - SelectionContainer() { - this.MarkdownBlockColumn() - } - .width('100%') - .copyOption(CopyOptions.LocalDevice) - .textJoinStyle(SelectionContainerTextJoinStyle.NEWLINE) - .caretColor(FILE_LINK) - } else { - this.MarkdownBlockColumn() - } - } - - /** - * The rendered answer. Both selection paths draw this exact subtree; only the - * wrapper differs, so the fallback below API 26 cannot drift from the API 26 - * presentation. - */ - @Builder - MarkdownBlockColumn() { - Column({ space: 5 }) { - ForEach(this.parseCache.blocksFor(this.text), (block: ParsedMarkdownBlock) => { - this.MarkdownBlockView(block) - }, (block: ParsedMarkdownBlock) => block.renderKey) - } - .width('100%') - } - - @Builder - MarkdownBlockView(block: ParsedMarkdownBlock) { - if (block.type === 'code') { - this.CodeBlock(block.language, block.text) - } else if (block.type === 'frontmatter') { - this.FrontmatterBlock(block.text) - } else if (block.type === 'heading') { - this.InlineText(block.inlines, this.headingFontSize(block.level), this.headingLineHeight(block.level), INK, true) - } else if (block.type === 'quote') { - Column() { - this.InlineText( - block.inlines, - MobileDesignTypography.bodySmall.size, - MobileDesignTypography.bodySmall.lineHeight, - MUTED, - false - ) - } - .width('100%') - .padding({ left: 9 + Math.max(0, block.level - 1) * 10 }) - .border({ width: { left: 2 }, color: LINE }) - } else if (block.type === 'list') { - this.MarkdownList(block.items, this.listMarkerWidth(block.items)) - } else if (block.type === 'table') { - this.MarkdownTable(block.tableRows) - } else if (block.type === 'divider') { - Text('') - .width('100%') - .height(1) - .backgroundColor(LINE) - } else { - this.InlineText( - block.inlines, - MobileDesignTypography.bodyLarge.size, - MobileDesignTypography.bodyLarge.lineHeight, - INK, - false - ) - } - } - - @Builder - FrontmatterBlock(body: string) { - Text(body) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .fontFamily('monospace') - // `copyOption` is what carries selection; without it `textSelectable` - // alone is inert. Kept alongside it because it states the intent that this - // surface is read-only: selectable, never focusable. - .copyOption(CopyOptions.LocalDevice) - .textSelectable(TextSelectableMode.SELECTABLE_UNFOCUSABLE) - } - - @Builder - InlineText(inlines: ParsedMarkdownInline[], fontSize: number, lineHeight: number, color: ResourceColor, bold: boolean) { - Text() { - ForEach(inlines, (inline: ParsedMarkdownInline) => { - this.InlineSpan(inline, color, bold) - }, (inline: ParsedMarkdownInline) => inline.id) - } - .fontSize(fontSize) - .lineHeight(lineHeight) - .fontColor(color) - .width('100%') - // Paragraphs, headings, quotes and list items all render through this one - // Text, so its `copyOption` is the fallback path for every prose block: one - // block per long press on a device without `SelectionContainer`. - .copyOption(CopyOptions.LocalDevice) - } - - @Builder - InlineSpan(inline: ParsedMarkdownInline, color: ResourceColor, bold: boolean) { - if (inline.type === 'strong') { - Span(inline.text) - .fontWeight(FontWeight.Bold) - .fontColor(color) - } else if (inline.type === 'emphasis') { - Span(inline.text) - .fontStyle(FontStyle.Italic) - .fontWeight(bold ? FontWeight.Bold : FontWeight.Regular) - .fontColor(color) - } else if (inline.type === 'code') { - Span(inline.text) - .fontFamily('monospace') - .fontWeight(bold ? FontWeight.Bold : FontWeight.Regular) - .fontColor(INK) - } else if (inline.type === 'delete') { - Span(inline.text) - .fontWeight(bold ? FontWeight.Bold : FontWeight.Regular) - .fontColor(color) - .decoration({ type: TextDecorationType.LineThrough, color }) - } else if (inline.type === 'link') { - Span(inline.text) - .fontWeight(bold ? FontWeight.Bold : FontWeight.Regular) - .fontColor(FILE_LINK) - .decoration({ type: TextDecorationType.Underline, color: FILE_LINK }) - .onClick(() => { - this.onOpenLink(inline.url, inline.text); - }) - } else { - Span(inline.text) - .fontWeight(bold ? FontWeight.Bold : FontWeight.Regular) - .fontColor(color) - } - } - - private listMarkerWidth(items: ParsedMarkdownListItem[]): number { - const context = this.getUIContext(); - let width: number = 20; - for (const item of items) { - if (item.checked >= 0) continue; - const size = context.getMeasureUtils().measureTextSize({ - textContent: item.marker, - fontSize: `${MobileDesignTypography.bodyLarge.size}fp` - }); - width = Math.max(width, Math.ceil(context.px2vp(Number(size.width)))); - } - return width; - } - - @Builder - MarkdownList(items: ParsedMarkdownListItem[], markerWidth: number) { - Column({ space: 4 }) { - ForEach(items, (item: ParsedMarkdownListItem) => { - Row({ space: 7 }) { - if (item.checked >= 0) { - Stack({ alignContent: Alignment.Center }) { - Text(item.checked === 1 ? '✓' : '') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Bold) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width(16) - .height(16) - .margin({ left: 2, right: 2, top: 2 }) - .border({ width: 1, color: LINE }) - .borderRadius(4) - } else { - Text(item.marker) - .width(markerWidth) - .maxLines(1) - .flexShrink(0) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.End) - } - Column() { - this.InlineText( - item.inlines, - MobileDesignTypography.bodyLarge.size, - MobileDesignTypography.bodyLarge.lineHeight, - INK, - false - ) - } - .layoutWeight(1) - } - .width('100%') - .padding({ left: item.depth * 16 }) - .alignItems(VerticalAlign.Top) - }, (item: ParsedMarkdownListItem) => item.id) - } - .width('100%') - } - - @Builder - MarkdownTable(rows: ParsedMarkdownTableRow[]) { - Scroll() { - Column() { - ForEach(rows, (row: ParsedMarkdownTableRow, rowIndex: number) => { - Row() { - ForEach(row.cells, (cell: ParsedMarkdownTableCell) => { - this.MarkdownTableCell(cell, row.header) - }, (cell: ParsedMarkdownTableCell) => cell.id) - } - .constraintSize({ minWidth: '100%' }) - .backgroundColor(this.tableRowBackground(row.header, rowIndex)) - .border({ - width: { bottom: rowIndex < rows.length - 1 ? 1 : 0 }, - color: LINE - }) - }, (row: ParsedMarkdownTableRow) => row.id) - } - .constraintSize({ minWidth: '100%' }) - } - .scrollable(ScrollDirection.Horizontal) - .scrollBar(BarState.Off) - .width('100%') - .backgroundColor(CARD) - .borderRadius(10) - .border({ width: 1, color: LINE }) - .clip(true) - } - - @Builder - MarkdownTableCell(cell: ParsedMarkdownTableCell, header: boolean) { - Column() { - Text() { - ForEach(cell.inlines, (inline: ParsedMarkdownInline) => { - this.InlineSpan(inline, INK, false) - }, (inline: ParsedMarkdownInline) => inline.id) - } - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(header ? FontWeight.Medium : FontWeight.Regular) - .fontColor(INK) - .textAlign(this.tableTextAlign(cell.alignment)) - // A cell is its own Text because the table lays cells out in Rows, so it - // needs its own copyOption to be selectable inside the container and on - // the fallback path alike. - .copyOption(CopyOptions.LocalDevice) - } - .layoutWeight(1) - .constraintSize({ minWidth: 132, minHeight: 42 }) - .padding({ left: 12, right: 12, top: 10, bottom: 10 }) - .justifyContent(FlexAlign.Center) - } - - @Builder - CodeBlock(language: string, body: string) { - Column({ space: 7 }) { - Row() { - Text(language.length > 0 ? language : 'code') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .textSelectable(TextSelectableMode.UNSELECTABLE) - Blank() - Text(RemoteI18n.t('common.copy')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .textSelectable(TextSelectableMode.UNSELECTABLE) - .onClick(() => { - this.onCopyText(body); - }) - } - .width('100%') - Scroll() { - Text(body) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(INK) - .fontFamily('monospace') - .constraintSize({ minWidth: '100%' }) - // The code body scrolls horizontally inside the block, so it carries - // its own copyOption rather than relying on the container to reach it. - // The language label and the copy action above stay outside the - // selection: measured on device, a container selection that spans the - // block copied those two labels as well, so the block's chrome reached - // the clipboard as text. `UNSELECTABLE` is what keeps a label out of a - // selection the container drives; the copy action's click still fires. - .copyOption(CopyOptions.LocalDevice) - } - .scrollable(ScrollDirection.Horizontal) - .scrollBar(BarState.Off) - .width('100%') - } - .width('100%') - .padding({ left: 9, right: 9, top: 8, bottom: 8 }) - .backgroundColor(SOFT) - .borderRadius(12) - .border({ width: 1, color: LINE }) - } - - private headingFontSize(level: number): number { - if (level <= 1) { - return MobileDesignTypography.headlineSmall.size; - } - if (level === 2) { - return MobileDesignTypography.titleMedium.size; - } - if (level === 3) { - return MobileDesignTypography.titleSmall.size; - } - return MobileDesignTypography.bodyLarge.size; - } - - private headingLineHeight(level: number): number { - if (level <= 1) { - return MobileDesignTypography.headlineSmall.lineHeight; - } - if (level === 2) { - return MobileDesignTypography.titleMedium.lineHeight; - } - if (level === 3) { - return MobileDesignTypography.titleSmall.lineHeight; - } - return MobileDesignTypography.bodyLarge.lineHeight; - } - - private tableTextAlign(alignment: string): TextAlign { - if (alignment === 'center') { - return TextAlign.Center; - } - if (alignment === 'right') { - return TextAlign.End; - } - return TextAlign.Start; - } - - private tableRowBackground(header: boolean, rowIndex: number): ResourceColor { - if (header || rowIndex % 2 === 0) { - return SOFT; - } - return CARD; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets deleted file mode 100644 index 4e78f67c5a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets +++ /dev/null @@ -1,91 +0,0 @@ -import { MessageQueueAction, MessageQueueItem, MessageQueueState } from '../../model/MessageQueue'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MobileDesignTypography, MobileDesignGeometry } from '../../generated/MobileDesignTokens'; -import { INK, LINE, MUTED, TRANSPARENT, CARD } from './Theme'; - -@ComponentV2 -export struct MessageQueuePanel { - @Param state: MessageQueueState = new MessageQueueState(); - @Event onAction: (action: MessageQueueAction) => void = (_action: MessageQueueAction): void => {}; - @Local expanded: boolean = true; - @Local dragging: string = ''; - @Local dragOffset: number = 0; - @Local before: string = ''; - @Local dragRevision: string = ''; - @Monitor('state.revisionKey', 'state.busy', 'state.failure') - resetGesture(): void { this.dragging = ''; this.dragOffset = 0; } - - private queued(): MessageQueueItem[] { return this.state.items.filter((item: MessageQueueItem): boolean => item.status === 'queued'); } - private canMove(item: MessageQueueItem): boolean { return this.state.supportsReorder && !this.state.busy && !this.state.failure && item.status === 'queued' && this.queued().length > 1; } - private move(item: MessageQueueItem, delta: number): void { - const items = this.queued(); - const index = items.findIndex((value: MessageQueueItem): boolean => value.turnId === item.turnId); - if (!this.canMove(item) || index + delta < 0 || index + delta >= items.length) return; - this.onAction({ sessionId: this.state.sessionId, action: 'reorder', turnId: item.turnId, beforeTurnId: delta < 0 ? items[index - 1].turnId : items[index + 2]?.turnId }); - } - @Builder - Actions(item: MessageQueueItem) { - Menu() { - MenuItem({ content: item.displayContent }).enabled(false) - if (!this.state.supportsReorder) { MenuItem({ content: RemoteI18n.t('queue.unsupported') }).enabled(false) } - MenuItem({ content: RemoteI18n.t('queue.moveUp') }).enabled(this.canMove(item) && this.queued()[0]?.turnId !== item.turnId).onClick((): void => this.move(item, -1)) - MenuItem({ content: RemoteI18n.t('queue.moveDown') }).enabled(this.canMove(item) && this.queued().slice(-1)[0]?.turnId !== item.turnId).onClick((): void => this.move(item, 1)) - MenuItem({ content: RemoteI18n.t('queue.remove') }).enabled(!this.state.busy && !this.state.failure && item.status !== 'steering_pending') - .onClick((): void => this.onAction({ sessionId: this.state.sessionId, action: 'cancel', turnId: item.turnId })) - } - } - @Builder - MessageRow(item: MessageQueueItem, index: number) { - Column() { - Divider().color(LINE).strokeWidth(0.5).margin({ left: 8, right: 8 }) - Row({ space: 4 }) { - if (this.state.supportsReorder) { - Column({ space: 3 }) { ForEach([0, 1, 2], (): void => { Divider().color(MUTED).strokeWidth(1).width(14) }) } - .width(44).height(48).justifyContent(FlexAlign.Center).accessibilityText(RemoteI18n.t('queue.reorder')) - .gesture(PanGesture({ direction: PanDirection.Vertical, distance: 6 }) - .onActionStart((): void => { if (this.canMove(item)) { this.dragging = item.turnId; this.dragRevision = this.state.revisionKey; this.dragOffset = 0; this.before = ''; } }) - .onActionUpdate((event: GestureEvent): void => { - if (this.dragging !== item.turnId || !this.canMove(item)) return; - this.dragOffset = event.offsetY; - const target = Math.max(0, Math.min(this.state.items.length - 1, index + Math.round(this.dragOffset / 49))); - const rest = this.state.items.filter((value: MessageQueueItem): boolean => value.turnId !== item.turnId); - this.before = rest.slice(target).find((value: MessageQueueItem): boolean => value.status === 'queued')?.turnId || ''; - }) - .onActionEnd((): void => { - if (this.dragging === item.turnId && this.dragRevision === this.state.revisionKey && this.canMove(item) && Math.abs(this.dragOffset) > 24) this.onAction({ sessionId: this.state.sessionId, action: 'reorder', turnId: item.turnId, beforeTurnId: this.before || undefined }); - this.dragging = ''; this.dragOffset = 0; - }).onActionCancel((): void => { this.dragging = ''; this.dragOffset = 0; })) - } - Column({ space: 2 }) { - Row({ space: 6 }) { - Text(item.displayContent).fontSize(MobileDesignTypography.bodyMedium.size).fontColor(INK).maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }).flexShrink(1) - if (item.attachmentCount > 0) { Text(RemoteI18n.f('queue.attachments', `${item.attachmentCount}`)).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).flexShrink(0) } - }.width('100%') - if (item.status !== 'queued') { Text(RemoteI18n.t('queue.waiting')).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED) } - }.layoutWeight(1).alignItems(HorizontalAlign.Start) - Button({ type: ButtonType.Normal }) { SymbolGlyph($r('sys.symbol.arrow_up')).fontSize(16).fontColor([MUTED]) } - .width(44).height(48).backgroundColor(TRANSPARENT).accessibilityText(RemoteI18n.t('queue.sendNow')).enabled(!this.state.busy && !this.state.failure && item.status !== 'steering_pending') - .onClick((): void => this.onAction({ sessionId: this.state.sessionId, action: 'promote', turnId: item.turnId })) - Button({ type: ButtonType.Normal }) { Image($r('app.media.remote_ref_more')).width(16).height(16).fillColor(MUTED).renderMode(ImageRenderMode.Template) } - .width(44).height(48).backgroundColor(TRANSPARENT).accessibilityText(RemoteI18n.t('queue.more')).bindMenu(this.Actions(item)) - }.width('100%').height(48) - }.width('100%').translate({ y: this.dragging === item.turnId ? this.dragOffset : 0 }).backgroundColor(this.dragging === item.turnId ? CARD : TRANSPARENT).zIndex(this.dragging === item.turnId ? 1 : 0) - } - build() { - if (this.state.items.length > 0 || this.state.failure.length > 0) { - Column() { - Row({ space: 6 }) { - Text(RemoteI18n.f('queue.title', `${this.state.items.length}`)).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED) - SymbolGlyph(this.expanded ? $r('sys.symbol.chevron_down') : $r('sys.symbol.chevron_up')).fontSize(12).fontColor([MUTED]) - }.width('100%').height(40).onClick((): void => { this.expanded = !this.expanded; }) - if (this.state.failure.length > 0) { - Row() { - Text(RemoteI18n.t(this.state.failure === 'unsupported' ? 'queue.unsupported' : 'queue.refreshRequired')).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).layoutWeight(1) - Button(RemoteI18n.t('queue.refresh')).fontColor(INK).backgroundColor(TRANSPARENT).height(44).onClick((): void => this.onAction({ sessionId: this.state.sessionId, action: 'list' })) - } - } - if (this.expanded) { Scroll() { Column() { ForEach(this.state.items, (item: MessageQueueItem, index: number): void => { this.MessageRow(item, index) }, (item: MessageQueueItem): string => item.turnId) } }.constraintSize({ maxHeight: 196 }).scrollBar(BarState.Auto) } - }.width('100%').padding({ left: MobileDesignGeometry.contentGutter, right: MobileDesignGeometry.contentGutter }) - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppSurface.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppSurface.ets deleted file mode 100644 index 65dc7d9f44..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppSurface.ets +++ /dev/null @@ -1,133 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { MiniAppActions, MiniAppSummary, emptyMiniAppActions } from '../../model/MiniAppModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MiniAppState } from '../state/MiniAppState'; -import { MiniAppWebView } from './MiniAppWebView'; -import { NavigationBackButton } from './NavigationBackButton'; -import { PAGE_BG, INK, MUTED, SOFT, LINE, TRANSPARENT } from './Theme'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; - -@ComponentV2 -export struct MiniAppSurface { - @Param state: MiniAppState = new MiniAppState(); - @Param actions: MiniAppActions = emptyMiniAppActions(); - @Local galleryWidth: number = 0; - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column() { - // The gallery is a full-screen surface, so its header band owns the top - // edge of the window: the box grows by the status bar strip and the - // controls keep the 56 the design gives them below it, instead of sitting - // under the clock and the indicators. The band spans the window - // horizontally, so it reserves the side strips too — a rotated device puts - // the camera cutout on the back control's edge. - Row({ space: 8 }) { - NavigationBackButton({ onBack: (): void => { - if (this.state.appId) this.actions.back(); - else this.actions.close(); - } }) - Text(this.state.appId ? this.state.name : RemoteI18n.t('miniapp.title')) - .fontSize(MobileDesignTypography.bodyLarge.size).fontWeight(FontWeight.Medium) - .fontColor(INK).maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) - .textAlign(TextAlign.Center).layoutWeight(1) - Blank().width(48) - }.width('100%').height(56 + this.insets.top) - .padding({ left: this.insets.leftPadding(12), right: this.insets.rightPadding(12), top: this.insets.top }) - if (this.state.document) { - MiniAppWebView({ document: this.state.document, revision: this.state.revision, request: this.actions.request }) - .layoutWeight(1) - } else { - Column() { - Row() { - Text(RemoteI18n.t('miniapp.allApps')) - .fontSize(MobileDesignTypography.titleSmall.size).fontWeight(FontWeight.Medium).fontColor(INK) - .padding({ left: 16, right: 16, top: 10, bottom: 10 }).backgroundColor(SOFT).borderRadius(24) - Blank() - Text(RemoteI18n.t('miniapp.availableOffline')) - .fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED) - }.width('100%').padding({ top: 16, bottom: 20 }) - if (this.state.loading) { - LoadingProgress().width(32).height(32).margin(24) - } else if (this.state.error) { - Text(this.state.error).fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED).padding({ top: 16, bottom: 16 }).copyOption(CopyOptions.InApp) - Button(RemoteI18n.t('miniapp.refresh')) - .fontColor(INK).backgroundColor(SOFT).onClick(() => this.actions.refresh()) - } else if (this.state.apps.length === 0) { - Text(RemoteI18n.t('miniapp.empty')).fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED).padding(24) - } else { - Grid() { - ForEach(this.state.apps, (app: MiniAppSummary) => { - GridItem() { this.PreviewTile(app) } - }, (app: MiniAppSummary) => app.id) - // The gallery's tail spacer: the strip plus the design's own - // breathing, as one full-width, untouchable row. The grid's - // viewport runs to the screen edge — tiles roll under the - // navigation indicator while they are moving — and the last row - // of tiles still rests above the bar. - GridItem() { - Column() - .width('100%') - .height(this.insets.tailSpacing(24)) - } - .columnStart(0) - .columnEnd(this.galleryColumns() - 1) - .hitTestBehavior(HitTestMode.None) - }.columnsTemplate(this.galleryColumnsTemplate()) - .columnsGap(14).rowsGap(20).layoutWeight(1).width('100%').scrollBar(BarState.Off) - } - }.width('100%').constraintSize({ maxWidth: 1000 }).layoutWeight(1) - // The gallery is the surface's bottom edge: its scrolling viewport - // runs to the screen edge, and the grid's own tail spacer is what - // keeps the last row of tiles out of the navigation bar. - .alignItems(HorizontalAlign.Start) - .padding({ left: 16, right: 16 }) - .onAreaChange((_oldArea: Area, area: Area) => { this.galleryWidth = Number(area.width); }) - } - }.width('100%').height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private PreviewTile(app: MiniAppSummary) { - Button({ type: ButtonType.Normal }) { - Column({ space: 10 }) { - Image(this.preview(app.id)).width('100%').aspectRatio(1).objectFit(ImageFit.Cover) - .backgroundColor(SOFT).borderRadius(24).border({ width: 0.5, color: LINE }) - .draggable(false).accessibilityLevel('no') - Text(app.name).fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium).fontColor(INK).maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }).width('100%').padding({ left: 4, right: 4 }) - }.width('100%').alignItems(HorizontalAlign.Start) - }.width('100%').padding(0).backgroundColor(TRANSPARENT).borderRadius(24) - .stateEffect(true).accessibilityText(`${app.name}, ${app.description}`) - .onClick(() => this.actions.select(app.id)) - } - - private preview(id: string): Resource { - if (id === 'builtin-gomoku') return $r('app.media.miniapp_gomoku_preview'); - if (id === 'builtin-regex-playground') return $r('app.media.miniapp_regex_preview'); - return $r('app.media.miniapp_divination_preview'); - } - - /** Columns of the gallery grid: 3 once it is wide, 2 on a phone. */ - private galleryColumns(): number { - return this.galleryWidth >= 600 ? 3 : 2; - } - - private galleryColumnsTemplate(): string { - return this.galleryColumns() === 3 ? '1fr 1fr 1fr' : '1fr 1fr'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppWebView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppWebView.ets deleted file mode 100644 index 7f63c34e53..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MiniAppWebView.ets +++ /dev/null @@ -1,61 +0,0 @@ -import { webview } from '@kit.ArkWeb'; - -// A synthetic origin for in-memory HTML; no document is fetched from this URL. -const MINIAPP_DOCUMENT_URL: string = 'https://miniapp.invalid/'; - -/** Platform leaf. ArkWeb exposes proxies to frames; the ViewModel treats every request as untrusted. */ -class MiniAppNativeBridge { - private readonly dispatch: (raw: string) => void; - constructor(dispatch: (raw: string) => void) { this.dispatch = dispatch; } - request(raw: string): void { this.dispatch(raw); } -} - -@ComponentV2 -export struct MiniAppWebView { - @Param document: string = ''; - @Param revision: number = 0; - @Param request: (raw: string, revision: number) => Promise = async (_raw: string, _revision: number): Promise => ''; - private controller: webview.WebviewController = new webview.WebviewController(); - private active: boolean = true; - private bridge: MiniAppNativeBridge = new MiniAppNativeBridge((raw: string): void => { - void this.reply(raw); - }); - - private async reply(raw: string): Promise { - if (!this.active) return; - const revision = this.revision; - const response = await this.request(raw, revision); - if (!this.active || revision !== this.revision || !response) return; - try { - await this.controller.runJavaScript(`window.__miniappReply(JSON.parse(${JSON.stringify(response)}))`); - } catch (_error) { - // Navigation/close invalidates replies; never replay a host mutation. - } - } - - aboutToDisappear(): void { this.active = false; } - - build() { - // A nonempty initial src can overwrite loadData after controller attachment. - Web({ src: '', controller: this.controller }) - .javaScriptAccess(true) - .darkMode(WebDarkMode.Auto) - .forceDarkAccess(false) - .domStorageAccess(false) - .fileAccess(false) - .javaScriptProxy({ object: this.bridge, name: 'miniappNative', methodList: ['request'], controller: this.controller }) - .onControllerAttached(() => { - this.active = true; - // Without an HTTP(S) base, ArkWeb interprets raw HTML as a data URL: - // CSS hashes become URL fragments and truncate the page before its script. - this.controller.loadData(this.document, 'text/html', 'UTF-8', MINIAPP_DOCUMENT_URL); - }) - .onOverrideUrlLoading((request: WebResourceRequest) => { - // Only the wrapper and its sandboxed blob child may navigate here. - const url = request.getRequestUrl(); - return request.isMainFrame() ? url !== 'about:blank' && url !== MINIAPP_DOCUMENT_URL : !url.startsWith('blob:'); - }) - .width('100%') - .height('100%') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelRolePickerPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelRolePickerPanel.ets deleted file mode 100644 index 273734ed27..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelRolePickerPanel.ets +++ /dev/null @@ -1,421 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteModelConfig } from '../../model/RemoteModels'; -import { RemoteModelDefaultsRole } from '../../services/RemoteModelDefaultsController'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { ConversationModelPresentationPolicy } from '../policy/ConversationModelPresentationPolicy'; -import { ModelPickerView, ModelRoleCandidatesPolicy } from '../policy/ModelRoleCandidatesPolicy'; -import { toConversationUiModel } from '../state/ConversationUiModels'; -import { DeviceModelDefaultsSheetState } from '../state/DeviceModelDefaultsSheetState'; -import { SettingsSheetState } from '../state/SettingsSheetState'; -import { ModelUnavailableCard } from './ModelUnavailableCard'; -import { NavigationBackButton } from './NavigationBackButton'; -import { SheetCloseButton } from './SheetCloseButton'; -import { SHEET_HEADER_HEIGHT, SHEET_HEADER_SIDE_PADDING, SHEET_HORIZONTAL_PADDING } from './SheetLayout'; -import { CARD, INK, LINE, MUTED, PAGE_BG, SOFT, TRANSPARENT } from './Theme'; - -/** - * The role picker: the second level of the sheet's model settings stack, for one - * role at a time. - * - * Candidates are the desktop's own catalog, filtered to what the role can - * actually run and kept in the order the desktop reports, so the list here and - * the list on the desktop describe the same device. The pinned row is the "no - * model" value, which is a value: for `fast` it means "follow the primary" and - * for the multimodal slot it means the capability is off. The primary model has - * no such row — it is the one slot the desktop must always be able to resolve. - * - * Selecting does not draw the selection: it asks the controller to write and - * leaves for the settings page, which then shows the value the desktop read - * back. A picker that checked the row the user tapped would be promising a - * configuration that may have been repaired while it was stored. - */ -@ComponentV2 -export struct ModelRolePickerPanel { - @Param sheetState: SettingsSheetState = new SettingsSheetState(); - @Param deviceModels: DeviceModelDefaultsSheetState = new DeviceModelDefaultsSheetState(); - @Param desktopName: string = ''; - @Param desktopId: string = ''; - @Event onClose: () => void = () => {}; - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - // The picker never opens before the page that pushes it, but it can be the - // first thing a restored sheet shows: reading here keeps that state answered. - void this.deviceModels.ensureLoaded(); - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column({ space: 0 }) { - this.PageHeader() - Scroll() { - Column({ space: 0 }) { - // The card comes first: it is why the list below is what it is, and on a - // device that cannot answer there is no list at all. - if (this.view().reason) { - this.ReasonCard() - } - if (this.view().reading) { - this.ReadingCard() - } - if (this.view().list) { - this.FilterLine() - if (this.allowsUnset()) { - this.UnsetRow() - } - ForEach(this.candidates(), (model: RemoteModelConfig) => { - this.CandidateRow(model) - }, (model: RemoteModelConfig): string => model.id) - // Only a list the device itself answered may be explained away: after a - // failed read it is short for a reason the card above already states. - if (this.view().answered && this.candidates().length === 0) { - this.NoCandidatesLine() - } - } - } - .width('100%') - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: 12, - bottom: this.insets.tailSpacing(34) - }) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - /** Same header language as the page below it: back one level, close the sheet. */ - @Builder - private PageHeader() { - Row() { - NavigationBackButton({ - isEnabled: !this.locked(), - onBack: (): void => { - this.sheetState.backFromModelPick(); - } - }) - Column({ space: 3 }) { - Text(RemoteI18n.t('settings.model.settingsTitle')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.roleLabel()) - .width('100%') - .fontSize(MobileDesignTypography.headlineSmall.size) - .lineHeight(MobileDesignTypography.headlineSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - SheetCloseButton({ - isEnabled: !this.locked(), - onClose: this.onClose - }) - } - .width('100%') - .height(SHEET_HEADER_HEIGHT) - .padding({ left: SHEET_HEADER_SIDE_PADDING, right: SHEET_HEADER_SIDE_PADDING }) - .alignItems(VerticalAlign.Center) - .border({ width: { bottom: 1 }, color: LINE }) - } - - /** - * Why the list is as short as it is. Filtering silently is what makes a user - * think the device lost its models, so the rule is stated above the rows - * together with the device it applies to. - */ - @Builder - private FilterLine() { - Text(RemoteI18n.f(ModelRoleCandidatesPolicy.filterKey(this.role()), this.deviceLabel())) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .padding({ left: 4, right: 4 }) - .margin({ bottom: 12 }) - } - - /** - * The "no model" value of this role, pinned above the candidates and separated - * from them, because it is not one of them: it is the state of having none. - */ - @Builder - private UnsetRow() { - Column({ space: 0 }) { - Row({ space: 10 }) { - this.SelectionMark(this.pinSelected()) - Column({ space: 2 }) { - Text(RemoteI18n.t(ModelRoleCandidatesPolicy.unsetLabelKey(this.role()))) - .width('100%') - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(RemoteI18n.t(ModelRoleCandidatesPolicy.unsetHintKey(this.role()))) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.modelAccountRowHeight }) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.pinSelected() ? SOFT : TRANSPARENT) - .borderRadius(MobileDesignGeometry.composerModelSelectorRowRadius) - .id('device-model-pick-unset') - .enabled(!this.locked()) - .opacity(this.locked() ? 0.6 : 1) - .onClick(() => { - this.select(null); - }) - // The pinned value is a different kind of answer from a model, so the list - // says so with a rule instead of letting it read as the first candidate. - if (this.candidates().length > 0) { - Divider() - .strokeWidth(1) - .color(LINE) - .margin({ top: 6, bottom: 6 }) - } - } - .width('100%') - } - - /** One candidate model: what it is called, what it runs on, and its capability. */ - @Builder - private CandidateRow(model: RemoteModelConfig) { - Row({ space: 10 }) { - this.SelectionMark(this.candidateSelected(model.id)) - Column({ space: 2 }) { - Row({ space: 6 }) { - Text(this.modelLabel(model)) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.showsCapabilityBadge()) { - Text(RemoteI18n.t('settings.model.capabilityImageUnderstanding')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .padding({ left: 6, right: 6, top: 1, bottom: 1 }) - .backgroundColor(SOFT) - .borderRadius(4) - } - } - .width('100%') - Text(this.modelMeta(model)) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.modelAccountRowHeight }) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.candidateSelected(model.id) ? SOFT : TRANSPARENT) - .borderRadius(MobileDesignGeometry.composerModelSelectorRowRadius) - .id(`device-model-pick-${model.id}`) - .enabled(!this.locked()) - .opacity(this.locked() ? 0.6 : 1) - .onClick(() => { - this.select(model.id); - }) - } - - /** - * A candidate row's leading mark. The outline glyph is deliberate: every row - * would carry a check if the filled one were used, and the selected row is - * already told apart by its fill, so the mark only has to point at the choice - * the role currently holds. - */ - @Builder - private SelectionMark(selected: boolean) { - Stack({ alignContent: Alignment.Center }) { - if (selected) { - SymbolGlyph($r('sys.symbol.checkmark_circle')) - .fontSize(16) - .fontColor([INK]) - } - } - .width(20) - .height(20) - } - - /** - * No model on this device can serve the role. The pinned row above already - * says what the role is left at, so this line only states that the emptiness - * is the device's answer rather than a failed read. - */ - @Builder - private NoCandidatesLine() { - Text(RemoteI18n.t('settings.model.pickEmpty')) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .padding({ left: 10, right: 10, top: 10, bottom: 10 }) - } - - /** - * The device stopped answering this page — the link dropped, the desktop was - * replaced by an older one, or the read itself failed — so the picker states - * the reason instead of a list. Without this a dropped link read as an empty - * catalog, and the null roles of the closed gate read as the user's choices. - */ - @Builder - private ReasonCard() { - ModelUnavailableCard({ - reason: this.reasonText(), - canRetry: this.view().retry, - busy: this.locked(), - cardId: 'device-model-pick-unavailable', - onRetry: (): void => { - void this.deviceModels.retry(); - } - }) - } - - /** Nothing has been read for this device yet, so there is nothing to list. */ - @Builder - private ReadingCard() { - Text(this.deviceModels.state.statusText.length > 0 ? - this.deviceModels.state.statusText : RemoteI18n.t('status.loadingModelDefaults')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .padding({ left: 18, right: 18, top: 16, bottom: 16 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .id('device-model-pick-reading') - } - - /** - * The two labels a candidate row carries. The catalog is the protocol's own - * shape, so it is projected through the shared presentation mapper before the - * shared label policy reads it — one boundary, one naming rule. - */ - private modelLabel(model: RemoteModelConfig): string { - return ConversationModelPresentationPolicy.primaryLabel( - toConversationUiModel(model), RemoteI18n.t('chat.model')); - } - - private modelMeta(model: RemoteModelConfig): string { - return ConversationModelPresentationPolicy.modelContextLabel(toConversationUiModel(model)); - } - - private role(): RemoteModelDefaultsRole { - const role = this.sheetState.pickRole; - if (role === 'primary' || role === 'fast' || role === 'image_understanding') { - return role; - } - return 'primary'; - } - - /** The picker knows which slot it is editing; without one it must not write. */ - private hasRole(): boolean { - return this.role() === this.sheetState.pickRole; - } - - private allowsUnset(): boolean { - return ModelRoleCandidatesPolicy.allowsUnset(this.role()); - } - - private showsCapabilityBadge(): boolean { - return ModelRoleCandidatesPolicy.showsCapabilityBadge(this.role()); - } - - private candidates(): RemoteModelConfig[] { - return ModelRoleCandidatesPolicy.candidatesForRole(this.role(), this.deviceModels.state.catalog); - } - - /** What this frame may show, decided from the one state the page renders. */ - private view(): ModelPickerView { - return ModelRoleCandidatesPolicy.pickerView(this.deviceModels.state); - } - - /** - * The reason the card carries: the controller's own sentence for a state it - * judged, or the host's words when a read failed. The page never invents one. - */ - private reasonText(): string { - const error = this.deviceModels.state.error; - return error.length > 0 ? error : RemoteI18n.t('status.remoteUnavailable'); - } - - /** - * Whether the pinned row carries the check. A role's value is only an answer - * while the device is answering: after the link dropped, every role reads as - * null, and drawing that as "this is your setting" would state a choice the - * user never made and the device never confirmed. - */ - private pinSelected(): boolean { - return this.view().answered && - ModelRoleCandidatesPolicy.isUnsetSelected(this.deviceModels.state.roles, this.role()); - } - - private candidateSelected(modelId: string): boolean { - return this.view().answered && ModelRoleCandidatesPolicy.isCandidateSelected( - this.deviceModels.state.roles, this.role(), modelId); - } - - private locked(): boolean { - return this.deviceModels.state.busy; - } - - private roleLabel(): string { - return RemoteI18n.t(ModelRoleCandidatesPolicy.roleLabelKey(this.role())); - } - - private deviceLabel(): string { - return this.desktopName.length > 0 ? this.desktopName : this.desktopId; - } - - /** - * Writes the role and returns to the page that shows the result. The write is - * not awaited here: the settings page is what reports it, and it is the page - * the user is left looking at. - */ - private select(modelId: string | null): void { - if (this.locked() || !this.hasRole()) { - return; - } - void this.deviceModels.selectRole(this.role(), modelId); - this.sheetState.backFromModelPick(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelServiceSettingsPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelServiceSettingsPanel.ets deleted file mode 100644 index 006ea2e27c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelServiceSettingsPanel.ets +++ /dev/null @@ -1,703 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { KeyboardAvoidMode } from '@kit.ArkUI'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteModelCatalog, RemoteModelConfig } from '../../model/RemoteModels'; -import { GENERAL_CHAT_LOCAL_MODEL_ID } from '../../services/general-chat/GeneralChatConfigStore'; -import { ModelServiceSettingsPolicy } from '../policy/ModelServiceSettingsPolicy'; -import { SettingsSheetState } from '../state/SettingsSheetState'; -import { - CARD, - INK, - LINE, - MUTED, - SHADOW_FAINT, - SOFT, - STATUS_DANGER, - STATUS_SUCCESS, - SUBTLE, - TRANSPARENT -} from './Theme'; -import { SheetCloseHeader } from './SheetCloseHeader'; -import { AppActionButton, AppActionStyle } from './AppActionButton'; - -@ComponentV2 -export struct ModelServiceSettingsPanel { - private readonly contentScroller: Scroller = new Scroller(); - private focusScrollTimerId: number = 0; - private blurResetTimerId: number = 0; - private previousKeyboardAvoidMode: KeyboardAvoidMode = KeyboardAvoidMode.OFFSET; - @Param page: string = 'overview'; - @Param sheetState: SettingsSheetState = new SettingsSheetState(); - @Param apiUrl: string = ''; - @Param modelName: string = ''; - @Param hasApiKey: boolean = false; - @Param modelCatalog: RemoteModelCatalog = { - version: 0, - models: [], - default_models: {} - }; - @Param selectedModelId: string = ''; - @Event onClose: () => void = () => {}; - @Event onOpenAccountModels: () => void = () => {}; - @Event onOpenLocalEditor: () => void = () => {}; - @Event onSelectModel: (modelId: string) => void = (_modelId: string) => {}; - @Event onSaved: (apiUrl: string, modelName: string, hasApiKey: boolean) => void = () => {}; - @Event onTest: ( - apiUrl: string, - apiKey: string, - modelName: string, - clearApiKey: boolean - ) => Promise = async ( - _apiUrl: string, - _apiKey: string, - _modelName: string, - _clearApiKey: boolean - ) => ''; - @Event onSave: ( - apiUrl: string, - apiKey: string, - modelName: string, - clearApiKey: boolean - ) => Promise = async ( - _apiUrl: string, - _apiKey: string, - _modelName: string, - _clearApiKey: boolean - ) => ''; - @Local isSaving: boolean = false; - @Local isTesting: boolean = false; - @Local feedbackText: string = ''; - @Local feedbackIsError: boolean = false; - @Local focusedFieldKind: string = ''; - - aboutToAppear(): void { - if (this.sheetPage() === 'local') { - this.previousKeyboardAvoidMode = this.getUIContext().getKeyboardAvoidMode(); - this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); - this.resetEditorDraft(); - } - } - - aboutToDisappear(): void { - this.clearFocusScrollTimer(); - this.clearBlurResetTimer(); - if (this.sheetPage() === 'local') { - this.getUIContext().setKeyboardAvoidMode(this.previousKeyboardAvoidMode); - } - } - - build() { - Column({ space: 0 }) { - this.Header() - if (this.sheetPage() === 'local') { - this.LocalEditor() - } else if (this.sheetPage() === 'account') { - this.AccountModelList() - } else { - this.ModelOverview() - } - } - .width('100%') - .height('100%') - .backgroundColor(CARD) - .borderRadius({ - topLeft: MobileDesignGeometry.sheetTopRadius, - topRight: MobileDesignGeometry.sheetTopRadius - }) - } - - @Builder - Header() { - SheetCloseHeader({ - title: this.headerTitle(), - showDivider: true, - isEnabled: !this.isSaving && !this.isTesting, - onClose: (): void => { - if (!this.isSaving && !this.isTesting) { - this.onClose(); - } - } - }) - } - - @Builder - ModelOverview() { - Column({ space: ModelServiceSettingsPolicy.OVERVIEW_SECTION_GAP }) { - Column({ space: 8 }) { - this.SectionHeader(RemoteI18n.t('settings.modelService.currentModel')) - this.CurrentModelRow() - } - .width('100%') - - Column({ space: 8 }) { - this.SectionHeader(RemoteI18n.t('settings.modelService.modelSources')) - this.ModelSourceGroup() - } - .width('100%') - } - .width('100%') - .padding({ - left: 16, - right: 16, - top: ModelServiceSettingsPolicy.OVERVIEW_TOP_PADDING, - bottom: ModelServiceSettingsPolicy.OVERVIEW_BOTTOM_PADDING - }) - .justifyContent(FlexAlign.Start) - } - - @Builder - ModelSourceGroup() { - Column() { - this.AccountModelsSummaryRow() - Divider() - .color(LINE) - .strokeWidth(ModelServiceSettingsPolicy.SOURCE_DIVIDER_HEIGHT) - .margin({ left: 56 }) - this.LocalModelRow() - } - .width('100%') - .backgroundColor(SOFT) - .borderRadius(8) - } - - @Builder - AccountModelList() { - if (this.accountModels().length === 0) { - Text(RemoteI18n.t('settings.modelService.accountEmpty')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED) - .width('100%') - .height(ModelServiceSettingsPolicy.EMPTY_ACCOUNT_HEIGHT) - .padding({ - left: 16, - right: 16, - top: ModelServiceSettingsPolicy.LIST_TOP_PADDING - }) - .textAlign(TextAlign.Start) - } else { - List({ space: ModelServiceSettingsPolicy.ACCOUNT_MODEL_ROW_GAP }) { - ForEach(this.accountModels(), (model: RemoteModelConfig) => { - ListItem() { - this.AccountModelRow(model) - } - }, (model: RemoteModelConfig) => model.id) - } - .width('100%') - .height(ModelServiceSettingsPolicy.accountListContentHeight(this.accountModels().length)) - .padding({ - left: 10, - right: 10, - top: ModelServiceSettingsPolicy.LIST_TOP_PADDING, - bottom: ModelServiceSettingsPolicy.LIST_BOTTOM_PADDING - }) - .scrollBar(BarState.Auto) - .edgeEffect(EdgeEffect.Spring) - .divider(null) - } - } - - @Builder - AccountModelRow(model: RemoteModelConfig) { - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - if (this.isSelectedModel(model)) { - SymbolGlyph($r('sys.symbol.checkmark_circle')) - .fontSize(16) - .fontColor([INK]) - } - } - .width(20) - .height(20) - Column({ space: 2 }) { - Text(this.modelLabel(model)) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(RemoteI18n.t('settings.modelService.accountSource')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .height(ModelServiceSettingsPolicy.ACCOUNT_MODEL_ROW_HEIGHT) - .padding({ left: 10, right: 10 }) - .backgroundColor(this.isSelectedModel(model) ? SOFT : TRANSPARENT) - .borderRadius(9) - .onClick(() => { - this.onSelectModel(model.id); - }) - } - - @Builder - LocalEditor() { - Scroll(this.contentScroller) { - Column({ space: 20 }) { - this.ConfigField( - RemoteI18n.t('settings.modelService.apiUrl'), - RemoteI18n.t('settings.modelService.apiUrlPlaceholder'), - 'url' - ) - this.ApiKeyField() - this.ConfigField( - RemoteI18n.t('settings.modelService.modelName'), - RemoteI18n.t('settings.modelService.modelPlaceholder'), - 'model' - ) - Row({ space: 12 }) { - AppActionButton({ - label: this.isTesting ? RemoteI18n.t('common.loading') : - RemoteI18n.t('settings.modelService.testConnection'), - style: AppActionStyle.Quiet, - actionHeight: 50, - isEnabled: !this.isSaving && !this.isTesting && this.hasTestableApiKey(), - onAction: (): void => { - this.testConnection(); - } - }) - .layoutWeight(1) - AppActionButton({ - label: this.isSaving ? RemoteI18n.t('common.loading') : RemoteI18n.t('common.save'), - style: AppActionStyle.Primary, - actionHeight: 50, - isEnabled: !this.isSaving && !this.isTesting, - onAction: (): void => { - this.save(); - } - }) - .layoutWeight(1) - } - .width('100%') - - if (!this.hasTestableApiKey()) { - Text(RemoteI18n.t('settings.modelService.testNeedsKey')) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - .width('100%') - } - - if (this.feedbackText.length > 0) { - Text(this.feedbackText) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(this.feedbackIsError ? STATUS_DANGER : STATUS_SUCCESS) - .width('100%') - } - } - .width('100%') - .padding({ - left: 16, - right: 16, - top: 18, - bottom: this.focusedFieldKind.length > 0 ? 360 : 30 - }) - .justifyContent(FlexAlign.Start) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - - @Builder - SectionHeader(title: string) { - Text(title) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .width('100%') - } - - @Builder - CurrentModelRow() { - Row({ space: 12 }) { - SymbolGlyph($r('sys.symbol.checkmark_circle_fill')) - .fontSize(23) - .fontColor([this.currentModel() ? INK : MUTED]) - .width(28) - .height(28) - Column({ space: 3 }) { - Text(this.currentModelLabel()) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.currentModel()) { - Text(this.modelSourceLabel(this.currentModel())) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .height(ModelServiceSettingsPolicy.CURRENT_ROW_HEIGHT) - .padding({ left: 16, right: 16 }) - .backgroundColor(SOFT) - .borderRadius(8) - } - - @Builder - AccountModelsSummaryRow() { - Row({ space: 12 }) { - SymbolGlyph($r('sys.symbol.cloud')) - .fontSize(21) - .fontColor([this.accountModels().length > 0 ? MUTED : SUBTLE]) - .width(28) - .height(28) - Column({ space: 3 }) { - Text(RemoteI18n.t('settings.modelService.accountModelSummary')) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.accountModels().length > 0 ? - RemoteI18n.f('settings.modelService.syncedCount', String(this.accountModels().length)) : - RemoteI18n.t('settings.modelService.accountEmpty')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(14) - .fontColor([MUTED]) - } - .width('100%') - .height(ModelServiceSettingsPolicy.SOURCE_ROW_HEIGHT) - .padding({ left: 16, right: 16 }) - .onClick(() => { - this.onOpenAccountModels(); - }) - } - - @Builder - LocalModelRow() { - Row({ space: 12 }) { - SymbolGlyph($r('sys.symbol.wrench_and_screwdriver')) - .fontSize(21) - .fontColor([MUTED]) - .width(28) - .height(28) - Column({ space: 3 }) { - Text(this.hasCompleteLocalModel() ? this.modelName : RemoteI18n.t('settings.modelService.notConfigured')) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.hasCompleteLocalModel()) { - Text(RemoteI18n.t('settings.modelService.localSource')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - .onClick(() => { - if (this.localRowSelectsOnBodyTap()) { - this.onSelectModel(GENERAL_CHAT_LOCAL_MODEL_ID); - return; - } - this.onOpenLocalEditor(); - }) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(14) - .fontColor([MUTED]) - } - .width(28) - .height(28) - .onClick(() => { - this.onOpenLocalEditor(); - }) - } - .width('100%') - .height(ModelServiceSettingsPolicy.SOURCE_ROW_HEIGHT) - .padding({ left: 16, right: 16 }) - } - - @Builder - ConfigField(label: string, placeholder: string, kind: string) { - Column({ space: 8 }) { - Text(label) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .width('100%') - TextInput({ - placeholder, - text: kind === 'url' ? this.sheetState.draftApiUrl : this.sheetState.draftModelName - }) - .width('100%') - .height(52) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .placeholderColor(SUBTLE) - .backgroundColor(CARD) - .border({ width: 0.5, color: LINE }) - .borderRadius(12) - .shadow({ radius: 12, color: SHADOW_FAINT, offsetY: 4 }) - .padding({ left: 14, right: 14 }) - .onFocus(() => { - this.scrollFocusedFieldIntoView(kind); - }) - .onBlur(() => { - this.scheduleFocusedFieldReset(); - }) - .onChange((value: string) => { - if (kind === 'url') { - this.sheetState.draftApiUrl = value; - } else { - this.sheetState.draftModelName = value; - } - this.clearFeedback(); - }) - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - - @Builder - ApiKeyField() { - Column({ space: 8 }) { - Row() { - Text(RemoteI18n.t('settings.modelService.apiKey')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Blank() - if (this.hasApiKey && !this.sheetState.draftClearApiKey) { - Text(RemoteI18n.t('settings.modelService.keySaved')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - } - .width('100%') - TextInput({ - placeholder: this.apiKeyPlaceholder(), - text: this.sheetState.draftApiKey - }) - .type(InputType.Password) - .showPasswordIcon(true) - .width('100%') - .height(52) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .placeholderColor(SUBTLE) - .backgroundColor(CARD) - .border({ width: 0.5, color: LINE }) - .borderRadius(12) - .shadow({ radius: 12, color: SHADOW_FAINT, offsetY: 4 }) - .padding({ left: 14, right: 10 }) - .onFocus(() => { - this.scrollFocusedFieldIntoView('key'); - }) - .onBlur(() => { - this.scheduleFocusedFieldReset(); - }) - .onChange((value: string) => { - this.sheetState.draftApiKey = value; - if (value.length > 0) { - this.sheetState.draftClearApiKey = false; - } - this.clearFeedback(); - }) - if (this.hasApiKey) { - Text(this.sheetState.draftClearApiKey ? - RemoteI18n.t('settings.modelService.keepKey') : - RemoteI18n.t('settings.modelService.clearKey')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(this.sheetState.draftClearApiKey ? INK : STATUS_DANGER) - .width('100%') - .onClick(() => { - this.sheetState.draftClearApiKey = !this.sheetState.draftClearApiKey; - this.sheetState.draftApiKey = ''; - this.clearFeedback(); - }) - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - - private sheetPage(): string { - return ModelServiceSettingsPolicy.sheetPage(this.page); - } - - private headerTitle(): string { - const page = this.sheetPage(); - if (page === 'local') { - return RemoteI18n.t('settings.modelService.localTitle'); - } - if (page === 'account') { - return RemoteI18n.t('settings.modelService.chooseAccountModel'); - } - return RemoteI18n.t('settings.modelService.manageTitle'); - } - - private accountModels(): RemoteModelConfig[] { - return ModelServiceSettingsPolicy.accountModels(this.modelCatalog); - } - - private currentModel(): RemoteModelConfig | undefined { - return ModelServiceSettingsPolicy.currentModel(this.modelCatalog, this.selectedModelId); - } - - private currentModelLabel(): string { - return ModelServiceSettingsPolicy.modelLabel( - this.currentModel(), - RemoteI18n.t('settings.modelService.notConfigured') - ); - } - - private modelLabel(model: RemoteModelConfig): string { - return ModelServiceSettingsPolicy.modelLabel(model, model.id); - } - - private modelSourceLabel(model?: RemoteModelConfig): string { - if (!model) { - return ''; - } - return ModelServiceSettingsPolicy.isLocalModel(model) ? - RemoteI18n.t('settings.modelService.localSource') : - RemoteI18n.t('settings.modelService.accountSource'); - } - - private isSelectedModel(model: RemoteModelConfig): boolean { - const current = this.currentModel(); - return current !== undefined && current.id === model.id; - } - - private hasCompleteLocalModel(): boolean { - return ModelServiceSettingsPolicy.hasCompleteLocalModel(this.apiUrl, this.modelName, this.hasApiKey); - } - - private localRowSelectsOnBodyTap(): boolean { - return ModelServiceSettingsPolicy.localRowSelectsOnBodyTap(this.apiUrl, this.modelName, this.hasApiKey); - } - - private resetEditorDraft(): void { - this.sheetState.hydrateEditorDraft(this.apiUrl, this.modelName); - this.isTesting = false; - this.clearFeedback(); - this.resetEditorScroll(); - } - - private resetEditorScroll(): void { - this.clearFocusScrollTimer(); - this.clearBlurResetTimer(); - this.focusedFieldKind = ''; - this.contentScroller.scrollTo({ xOffset: 0, yOffset: 0, animation: false }); - } - - private apiKeyPlaceholder(): string { - return this.hasApiKey && !this.sheetState.draftClearApiKey ? - RemoteI18n.t('settings.modelService.apiKeyKeepPlaceholder') : - RemoteI18n.t('settings.modelService.apiKeyPlaceholder'); - } - - private async save(): Promise { - if (this.isSaving || this.isTesting) { - return; - } - this.isSaving = true; - this.clearFeedback(); - const error = await this.onSave( - this.sheetState.draftApiUrl, - this.sheetState.draftApiKey, - this.sheetState.draftModelName, - this.sheetState.draftClearApiKey - ); - this.isSaving = false; - if (error.length > 0) { - this.feedbackText = error; - this.feedbackIsError = true; - return; - } - this.onSaved( - this.sheetState.draftApiUrl.trim(), - this.sheetState.draftModelName.trim(), - !this.sheetState.draftClearApiKey && - (this.sheetState.draftApiKey.trim().length > 0 || this.hasApiKey) - ); - this.onClose(); - } - - private async testConnection(): Promise { - if (this.isSaving || this.isTesting || !this.hasTestableApiKey()) { - return; - } - this.isTesting = true; - this.clearFeedback(); - const error = await this.onTest( - this.sheetState.draftApiUrl, - this.sheetState.draftApiKey, - this.sheetState.draftModelName, - this.sheetState.draftClearApiKey - ); - this.isTesting = false; - if (error.length > 0) { - this.feedbackText = error; - this.feedbackIsError = true; - return; - } - this.feedbackText = RemoteI18n.t('settings.modelService.testSuccess'); - this.feedbackIsError = false; - } - - private hasTestableApiKey(): boolean { - return this.sheetState.draftApiKey.trim().length > 0 || - (this.hasApiKey && !this.sheetState.draftClearApiKey); - } - - private clearFeedback(): void { - this.feedbackText = ''; - this.feedbackIsError = false; - } - - private scrollFocusedFieldIntoView(kind: string): void { - this.clearFocusScrollTimer(); - this.clearBlurResetTimer(); - this.focusedFieldKind = kind; - const yOffset = kind === 'key' ? 118 : (kind === 'model' ? 244 : 0); - this.focusScrollTimerId = setTimeout(() => { - this.contentScroller.scrollTo({ xOffset: 0, yOffset, animation: true }); - this.focusScrollTimerId = 0; - }, 280); - } - - private scheduleFocusedFieldReset(): void { - this.clearBlurResetTimer(); - this.blurResetTimerId = setTimeout(() => { - this.focusedFieldKind = ''; - this.contentScroller.scrollTo({ xOffset: 0, yOffset: 0, animation: true }); - this.blurResetTimerId = 0; - }, 180); - } - - private clearFocusScrollTimer(): void { - if (this.focusScrollTimerId !== 0) { - clearTimeout(this.focusScrollTimerId); - this.focusScrollTimerId = 0; - } - } - - private clearBlurResetTimer(): void { - if (this.blurResetTimerId !== 0) { - clearTimeout(this.blurResetTimerId); - this.blurResetTimerId = 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelUnavailableCard.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelUnavailableCard.ets deleted file mode 100644 index fd6f75d6c5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ModelUnavailableCard.ets +++ /dev/null @@ -1,63 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CARD, INK, SOFT, STATUS_DANGER } from './Theme'; - -/** - * Why a model page cannot be answered, and the way to ask again. - * - * Both pages of the device model settings can be open when the desktop stops - * answering: the settings page when the phone is not connected to it, and the - * picker on top of it when the link drops while the list is up. The reason - * belongs to neither page — the controller already decided which sentence - * describes the state — so it is rendered here, once, in the sheet's own card - * language. - * - * The retry is offered only when repeating the read can actually help, which the - * caller decides: a gate that is closed re-arms by itself when the desktop comes - * back, and a button that cannot do anything is worse than no button. - */ -@ComponentV2 -export struct ModelUnavailableCard { - /** The controller's resolved reason, or the host's own words for a failed read. */ - @Param reason: string = ''; - /** Repeat the read that failed. */ - @Param canRetry: boolean = false; - /** A request is in flight, so the page does not take a second one. */ - @Param busy: boolean = false; - /** Distinguishes the two pages' cards in the layout hierarchy. */ - @Param cardId: string = 'model-unavailable'; - @Event onRetry: () => void = () => {}; - - build() { - Column({ space: 10 }) { - Text(this.reason) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(STATUS_DANGER) - .maxLines(3) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.canRetry) { - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .padding({ left: 10, right: 10, top: 6, bottom: 6 }) - .backgroundColor(SOFT) - .borderRadius(14) - .id(`${this.cardId}-retry`) - .enabled(!this.busy) - .opacity(this.busy ? 0.6 : 1) - .onClick(() => { - this.onRetry(); - }) - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - .padding({ left: 18, right: 18, top: 16, bottom: 16 }) - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .id(this.cardId) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/NavigationBackButton.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/NavigationBackButton.ets deleted file mode 100644 index fa1b16d2dc..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/NavigationBackButton.ets +++ /dev/null @@ -1,33 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { TemplateIcon } from './TemplateIcon'; -import { TRANSPARENT } from './Theme'; - -/** App-wide floating page return affordance. */ -@ComponentV2 -export struct NavigationBackButton { - @Param controlSize: number = 48; - @Param isEnabled: boolean = true; - @Event onBack: () => void = () => {}; - - build() { - Button() { - TemplateIcon({ - src: $r('app.media.remote_ref_back'), - iconWidth: 15, - iconHeight: 23 - }) - } - .width(this.controlSize) - .height(this.controlSize) - .padding(0) - .backgroundColor(TRANSPARENT) - .borderRadius(12) - .stateEffect(true) - .opacity(this.isEnabled ? 1 : 0.4) - .enabled(this.isEnabled) - .accessibilityText(RemoteI18n.t('common.back')) - .onClick(() => { - this.onBack(); - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/OpenBitFunAccountLoginPage.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/OpenBitFunAccountLoginPage.ets deleted file mode 100644 index b93ef32669..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/OpenBitFunAccountLoginPage.ets +++ /dev/null @@ -1,121 +0,0 @@ -import { AccountLoginErrorPolicy } from '../policy/AccountLoginErrorPolicy'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { DEFAULT_CLOUD_RELAY_URL } from '../../services/CloudAccountClient'; -import { - CARD, - INK, - LINE, - MUTED, - PAGE_BG_FADE, - SHADOW_FAINT, - STATUS_DANGER, - SUBTLE -} from './Theme'; -import { SheetActionFooter } from './SheetActionFooter'; -import { SheetCloseHeader } from './SheetCloseHeader'; -import { - SHEET_CONTENT_BOTTOM_PADDING, - SHEET_CONTENT_MAX_WIDTH, - SHEET_HORIZONTAL_PADDING -} from './SheetLayout'; - -const CREDENTIAL_ROW_HEIGHT: number = 60; - -@ComponentV2 -export struct OpenBitFunAccountLoginPage { - @Event cloudLogin: () => Promise = - async (): Promise => ''; - @Event cloudCancelLogin: () => void = () => {}; - @Event onClose: () => void = () => {}; - @Event onLoginSuccess: () => void = () => {}; - @Local errorText: string = ''; - @Local isBusy: boolean = false; - - aboutToDisappear(): void { this.cloudCancelLogin(); } - - build() { - Column({ space: 0 }) { - SheetCloseHeader({ onClose: this.onClose, uniformGlyph: true }) - - Scroll() { - Column() { - this.LoginForm() - } - .width('100%') - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: 0, - bottom: 0 - }) - .alignItems(HorizontalAlign.Center) - } - .width('100%') - .scrollBar(BarState.Off) - - SheetActionFooter({ - label: this.isBusy ? RemoteI18n.t('remote.settings.accountSigningIn') : - RemoteI18n.t('remote.settings.accountSignIn'), - primary: true, - elevated: false, - isEnabled: this.canSubmit(), - onAction: (): void => { - void this.submit(); - } - }) - } - .width('100%') - - } - - @Builder - private LoginForm() { - Column({ space: 0 }) { - Text(RemoteI18n.t('remote.settings.accountLoginTitle')) - .fontSize(MobileDesignTypography.displayMedium.size) - .lineHeight(MobileDesignTypography.displayMedium.lineHeight) - .fontWeight(FontWeight.Bold) - .fontColor(INK) - .width('100%') - .textAlign(TextAlign.Center) - - Text(RemoteI18n.t('remote.settings.accountLoginBody')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(MUTED) - .width('100%') - .textAlign(TextAlign.Center) - .margin({ top: 8 }) - - - if (this.errorText.length > 0) { - Text(this.errorText) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(STATUS_DANGER) - .width('100%') - .margin({ top: 12, left: 4, right: 4 }) - } - } - .width('100%') - .constraintSize({ maxWidth: SHEET_CONTENT_MAX_WIDTH, minHeight: MobileDesignGeometry.loginSheetBodyMinHeight }) - .alignItems(HorizontalAlign.Center) - } - - private canSubmit(): boolean { return !this.isBusy; } - - private async submit(): Promise { - if (!this.canSubmit()) return; - this.isBusy = true; - this.errorText = ''; - try { - await this.cloudLogin(); - this.onLoginSuccess(); - } catch (err) { - this.errorText = RemoteI18n.t(AccountLoginErrorPolicy.messageKey(err)); - } finally { - this.isBusy = false; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RecentRemoteHome.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RecentRemoteHome.ets deleted file mode 100644 index 433d22bfff..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RecentRemoteHome.ets +++ /dev/null @@ -1,91 +0,0 @@ -import { ColdStartPresentationState } from '../state/ColdStartPresentationState'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { WelcomeBrandFlow } from './WelcomeBrandFlow'; -import { RemoteCompactHomePolicy } from '../policy/RemoteCompactHomePolicy'; -import { RemoteSession } from '../../model/RemoteModels'; -import { INK, MUTED, SOFT, LINE, TRANSPARENT } from './Theme'; - -/** Current-device landing page. Session activation stays with the remote owner. */ -@ComponentV2 -export struct RecentRemoteHome { - @Consumer() coldStartGeometry: ColdStartPresentationState = new ColdStartPresentationState(); - @Param connected: boolean = false; - @Param busy: boolean = false; - @Param sessions: RemoteSession[] = []; - @Param desktopName: string = ''; - @Event onOpen: (session: RemoteSession) => void = () => {}; - @Event onBrowse: () => void = () => {}; - @Event onConnect: () => void = () => {}; - - // Keyed rows keep their identity; resolve their content from the latest snapshot. - @Computed - get sessionIndex(): Map { - const index = new Map(); - this.sessions.forEach((item: RemoteSession) => { index.set(`${item.deviceId || ''}:${item.id}`, item); }); - return index; - } - - private currentSession(item: RemoteSession): RemoteSession { - return this.sessionIndex.get(`${item.deviceId || ''}:${item.id}`) || item; - } - - private sessionContext(session: RemoteSession): string { - const workspace = session.workspaceName || (session.workspacePath || '').replace(/\/+$/, '').split('/').pop() || ''; - return [this.desktopName, workspace].filter((value: string): boolean => value.length > 0).join(' · '); - } - - aboutToDisappear(): void { this.coldStartGeometry.targetSize = 0; } - - build() { - Scroll() { - Column() { - Column() { - WelcomeBrandFlow({ markSize: MobileDesignGeometry.recentHomeMarkSize, sweep: true }) - .onAreaChange((_old: Area, area: Area) => { - this.coldStartGeometry.targetX = Number(area.globalPosition.x) + Number(area.width) / 2; - this.coldStartGeometry.targetY = Number(area.globalPosition.y) + Number(area.height) / 2; - this.coldStartGeometry.targetSize = Number(area.width); - }) - .margin({ top: 20, bottom: 8 }) - Text(RemoteI18n.t('home.recent_title')).fontSize(MobileDesignTypography.headlineLarge.size) - .fontWeight(FontWeight.Medium).fontColor(INK).textAlign(TextAlign.Center) - }.width('100%').margin({ bottom: 32 }) - if (this.busy) { - LoadingProgress().width(24).height(24).color(MUTED).margin({ bottom: 16 }) - } - if (!RemoteCompactHomePolicy.shouldShowRecentSessions(this.connected, this.sessions.length)) { - Text(RemoteI18n.t('home.recent_connect')).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).margin({ bottom: 16 }) - Button(RemoteI18n.t('home.connectComputer')).onClick(this.onConnect) - .backgroundColor(SOFT).fontColor(INK).height(48).width('100%').margin({ bottom: 16 }) - } - if (RemoteCompactHomePolicy.shouldShowRecentSessions(this.connected, this.sessions.length)) { - Row() { - Text(RemoteI18n.t('home.recent_recent')).fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED).layoutWeight(1) - Button(RemoteI18n.t('home.recent_all')).fontSize(MobileDesignTypography.labelSmall.size).fontColor(INK) - .backgroundColor(TRANSPARENT).height(44).onClick(this.onBrowse) - }.width('100%') - ForEach(this.sessions, (row: RemoteSession) => { - Column({ space: 6 }) { - Text(this.currentSession(row).title).fontSize(MobileDesignTypography.titleSmall.size).fontColor(INK).maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }).width('100%') - Text(this.sessionContext(this.currentSession(row))).fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED).maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }).width('100%') - }.width('100%').alignItems(HorizontalAlign.Start) - .padding({ top: MobileDesignGeometry.recentHomeRowPadding, bottom: MobileDesignGeometry.recentHomeRowPadding }) - .onClick(() => { if (this.connected) this.onOpen(this.currentSession(row)); }) - .accessibilityGroup(true).accessibilityText(this.currentSession(row).title) - Divider().color(LINE) - }, (session: RemoteSession): string => `${session.deviceId || ''}:${session.id}`) - if (this.sessions.length === 0 && !this.busy) { - Text(RemoteI18n.t('home.recent_empty')).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED) - .padding({ top: 18, bottom: 18 }) - } - } - - }.alignItems(HorizontalAlign.Start).width('100%') - .constraintSize({ maxWidth: MobileDesignGeometry.recentHomeMaxWidth }) - .padding({ left: MobileDesignGeometry.recentHomeGutter, right: MobileDesignGeometry.recentHomeGutter, bottom: 28 }) - }.width('100%').height('100%').align(Alignment.Top).scrollBar(BarState.Off) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteConnectionPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteConnectionPanel.ets deleted file mode 100644 index 0a19975d07..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteConnectionPanel.ets +++ /dev/null @@ -1,62 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { BrandMark } from './BrandMark'; -import { INK, MUTED, TRANSPARENT } from './Theme'; - -/** Shared welcome composition for phone home and an empty wide master pane. */ -@ComponentV2 -export struct RemoteConnectionPanel { - @Param title: string = ''; - @Param detail: string = ''; - @Param busy: boolean = false; - @BuilderParam primaryAction: () => void = this.EmptyAction; - @Event onMiniApps: () => void = () => {}; - - build() { - Column() { - Scroll() { - Column({ space: 16 }) { - BrandMark({ markSize: 104 }) - .margin({ bottom: 12 }) - Text(this.title) - .fontSize(MobileDesignTypography.headlineLarge.size).fontWeight(FontWeight.Medium).fontColor(INK) - .textAlign(TextAlign.Center) - Text(this.detail) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(23).fontColor(MUTED).textAlign(TextAlign.Center) - .constraintSize({ maxWidth: 300 }) - if (this.busy) { - LoadingProgress().width(20).height(20).color(MUTED) - } - } - .width('100%').padding({ top: 32, bottom: 32, left: 12, right: 12 }) - } - .width('100%').layoutWeight(1).scrollBar(BarState.Off) - .align(Alignment.Center) - - Column({ space: 10 }) { - this.primaryAction() - Button({ type: ButtonType.Normal }) { - Row({ space: 9 }) { - SymbolGlyph($r('sys.symbol.square_grid_2x2')).fontSize(18).fontColor([MUTED]) - Text(RemoteI18n.t('home.exploreMiniApps')) - .fontSize(MobileDesignTypography.bodyMedium.size).fontColor(MUTED) - } - .justifyContent(FlexAlign.Center) - } - .width('100%').height(48).backgroundColor(TRANSPARENT) - .borderRadius(24).onClick(this.onMiniApps) - Text(RemoteI18n.t('home.miniAppsHint')) - .fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width('100%').constraintSize({ maxWidth: 360 }) - .padding({ top: 12, bottom: 24 }) - } - .width('100%').height('100%').constraintSize({ maxWidth: 560 }) - .padding({ left: 24, right: 24 }).alignItems(HorizontalAlign.Center) - } - - @Builder - private EmptyAction() { Row() {} } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemotePermissionSection.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemotePermissionSection.ets deleted file mode 100644 index fa688e0f6c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemotePermissionSection.ets +++ /dev/null @@ -1,261 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CARD, INK, LINE, MUTED, STATUS_DANGER } from './Theme'; -import { RemotePermissionMode } from '../../model/RemoteModels'; -import { AppActionButton, AppActionStyle } from './AppActionButton'; - -/** - * Remote permission mode section of the single settings page. It is always - * visible; without a connected desktop the rows are disabled and the status - * line explains that a connection is required. The mode is read from the - * desktop when the page opens connected, and again when the connection comes - * up while the page is open. Full access keeps its explicit confirmation. - */ -@ComponentV2 -export struct RemotePermissionSection { - @Param connectionState: string = 'idle'; - @Event getPermissionMode: () => Promise = async (): Promise => 'ask'; - @Event setPermissionMode: (mode: RemotePermissionMode) => Promise = - async (mode: RemotePermissionMode): Promise => mode; - @Local permissionMode: RemotePermissionMode = 'ask'; - @Local permissionModeBusy: boolean = false; - @Local permissionModeLoaded: boolean = false; - @Local permissionModeError: string = ''; - @Local confirmFullAccess: boolean = false; - - aboutToAppear(): void { - if (this.canManagePermissions()) { - this.refreshPermissionMode(); - } - } - - @Monitor('connectionState') - onConnectionStateChanged(): void { - if (this.canManagePermissions()) { - this.refreshPermissionMode(); - return; - } - this.confirmFullAccess = false; - this.permissionModeLoaded = false; - this.permissionModeError = ''; - } - - build() { - Column({ space: 0 }) { - this.PermissionSectionHeader() - this.PermissionModeCard() - } - .width('100%') - } - - @Builder - private PermissionSectionHeader() { - Row() { - Text(RemoteI18n.t('remote.permissions.title')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Blank() - if (this.canManagePermissions()) { - Text(RemoteI18n.t('common.refresh')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.permissionModeBusy ? MUTED : INK) - .onClick(() => this.refreshPermissionMode()) - } - } - .width('100%') - .padding({ left: 8, right: 8 }) - .margin({ bottom: 10 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - private PermissionModeCard() { - Column() { - Text(RemoteI18n.t('remote.permissions.scope')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .padding({ left: 18, right: 18, top: 16, bottom: 8 }) - - this.PermissionModeRow( - 'ask', - RemoteI18n.t('remote.permissions.ask'), - RemoteI18n.t('remote.permissions.askDescription') - ) - Divider().strokeWidth(1).color(LINE).margin({ left: 18, right: 18 }) - this.PermissionModeRow( - 'auto', - RemoteI18n.t('remote.permissions.auto'), - RemoteI18n.t('remote.permissions.autoDescription') - ) - Divider().strokeWidth(1).color(LINE).margin({ left: 18, right: 18 }) - this.PermissionModeRow( - 'full_access', - RemoteI18n.t('remote.permissions.fullAccess'), - RemoteI18n.t('remote.permissions.fullAccessDescription') - ) - - Text(this.permissionStatusText()) - .width('100%') - .height(28) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(this.permissionModeError.length > 0 ? STATUS_DANGER : MUTED) - .padding({ left: 18, right: 18, top: 4 }) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - - if (this.confirmFullAccess) { - this.FullAccessConfirmation() - } - } - .width('100%') - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .margin({ bottom: 24 }) - } - - @Builder - private PermissionModeRow(mode: RemotePermissionMode, label: string, description: string) { - Row({ space: 12 }) { - Stack({ alignContent: Alignment.Center }) { - if (this.permissionModeLoaded && this.permissionMode === mode) { - SymbolGlyph($r('sys.symbol.checkmark_circle_fill')) - .fontSize(19) - .fontColor([INK]) - .width(20) - .height(20) - } - } - .width(22) - .height(24) - Column({ space: 3 }) { - Text(label) - .width('100%') - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(description) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .maxLines(2) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .height(72) - .padding({ left: 18, right: 18 }) - .opacity(this.canChangePermissionMode() ? 1 : 0.54) - .onClick(() => this.selectPermissionMode(mode)) - } - - @Builder - private FullAccessConfirmation() { - Column({ space: 10 }) { - Text(RemoteI18n.t('remote.permissions.fullAccessWarningTitle')) - .width('100%') - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Bold) - .fontColor(STATUS_DANGER) - Text(RemoteI18n.t('remote.permissions.fullAccessWarningBody')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(INK) - Row({ space: 10 }) { - AppActionButton({ - label: RemoteI18n.t('remote.permissions.cancel'), - style: AppActionStyle.Quiet, - actionHeight: 42, - onAction: (): void => { this.confirmFullAccess = false; } - }) - .layoutWeight(1) - AppActionButton({ - label: RemoteI18n.t('remote.permissions.confirmFullAccess'), - style: AppActionStyle.Destructive, - actionHeight: 42, - onAction: (): void => { void this.applyPermissionMode('full_access'); } - }) - .layoutWeight(1) - } - .width('100%') - } - .width('100%') - .padding({ left: 16, right: 16, top: 14, bottom: 16 }) - .backgroundColor(CARD) - .border({ width: 1, color: STATUS_DANGER }) - .borderRadius(18) - .margin({ left: 12, right: 12, bottom: 14 }) - } - - private canManagePermissions(): boolean { - return this.connectionState === 'connected'; - } - - private canChangePermissionMode(): boolean { - return this.canManagePermissions() && !this.permissionModeBusy; - } - - private async refreshPermissionMode(): Promise { - if (!this.canManagePermissions() || this.permissionModeBusy) { - return; - } - this.permissionModeBusy = true; - this.permissionModeError = ''; - try { - this.permissionMode = await this.getPermissionMode(); - this.permissionModeLoaded = true; - } catch (err) { - this.permissionModeError = err instanceof Error ? err.message : - RemoteI18n.t('remote.permissions.loadFailed'); - } finally { - this.permissionModeBusy = false; - } - } - - private selectPermissionMode(mode: RemotePermissionMode): void { - if (!this.canChangePermissionMode() || - (this.permissionModeLoaded && this.permissionMode === mode)) { - return; - } - if (mode === 'full_access') { - this.confirmFullAccess = true; - return; - } - this.confirmFullAccess = false; - this.applyPermissionMode(mode); - } - - private async applyPermissionMode(mode: RemotePermissionMode): Promise { - if (!this.canChangePermissionMode()) { - return; - } - this.permissionModeBusy = true; - this.permissionModeError = ''; - try { - this.permissionMode = await this.setPermissionMode(mode); - this.permissionModeLoaded = true; - this.confirmFullAccess = false; - } catch (err) { - this.permissionModeError = err instanceof Error ? err.message : - RemoteI18n.t('remote.permissions.saveFailed'); - } finally { - this.permissionModeBusy = false; - } - } - - private permissionStatusText(): string { - if (!this.canManagePermissions()) { - return RemoteI18n.t('remote.permissions.connectionRequired'); - } - if (this.permissionModeBusy) { - return RemoteI18n.t('remote.permissions.loading'); - } - return this.permissionModeError; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionList.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionList.ets deleted file mode 100644 index 944d9a0c97..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionList.ets +++ /dev/null @@ -1,791 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RecentWorkspaceEntry, RemoteSession } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - CARD, - INK, - LINE, - MUTED, - SCRIM, - SHADOW_SUBTLE, - SOFT, - TRANSPARENT, -} from './Theme'; -import { SessionActionPresentation, SessionActionSurface } from './SessionActionSurface'; -import { AdaptiveSheetOptions } from './AdaptiveSheetOptions'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { SessionActionCapabilities, SessionActionPolicy, SessionActionScope } from '../policy/SessionActionPolicy'; -import { SessionDetailsView } from './SessionDetailsView'; -import { RemoteSessionRow } from './RemoteSessionRow'; -import { HarnessProfileMenu } from './HarnessProfileMenu'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { - SessionListInputs, - SessionListProjection, - SessionListProjectionCache, - SessionListProjector -} from '../policy/SessionListProjection'; - -@ComponentV2 -export struct RemoteSessionList { - @Param sessions: RemoteSession[] = []; - @Param query: string = ''; - @Param sortMode: string = 'project'; - @Param hasMoreSessions: boolean = false; - @Param isBusy: boolean = false; - @Param selectedSessionId: string = ''; - @Param workspaceName: string = ''; - @Param workspacePath: string = ''; - /** Stable record ID of the active workspace; empty for pre-ID hosts. */ - @Param workspaceId: string = ''; - @Param workspaceConnectionId: string = ''; - @Param workspaceSshHost: string = ''; - @Param workspaceKind: string = 'normal'; - @Param recentWorkspaces: RecentWorkspaceEntry[] = []; - @Param actionPresentation: SessionActionPresentation = SessionActionPresentation.BottomSheet; - @Param sessionDetailsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SessionDetails); - @Param workspaceFilter: string = ''; - @Param agentFilter: string = ''; - @Param statusFilter: string = ''; - @Param showWorkspaceMetadata: boolean = false; - @Param showUpdatedMetadata: boolean = false; - @Param showStatusMetadata: boolean = false; - @Param supportsHarnessProfiles: boolean = false; - @Event onCreate: () => void = () => {}; - @Event onOpenSession: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onDeleteSession: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onLoadMore: () => void = () => {}; - @Event onCreateAssistantSession: () => void = () => {}; - /** Project rows report their catalog identity; the ID is what the host resolves by. */ - @Event onCreateInWorkspace: (path: string, agentType: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = - (_path: string, _agentType: string) => {}; - @Event onSelectWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = - (_path: string) => {}; - // Disclosure state is keyed by the project's section key: its workspace ID - // when the catalog supplies one, the legacy triple otherwise. - @Local collapsedWorkspaceKeys: string[] = []; - @Local projectVisibleSteps: string[] = []; - @Local visibleProjectCount: number = 3; - @Local chatsCollapsed: boolean = false; - @Local chatVisibleCount: number = 3; - @Local todayCollapsed: boolean = false; - @Local yesterdayCollapsed: boolean = false; - @Local earlierCollapsed: boolean = false; - @Local createMenuKey: string = ''; - @Local activeActionSessionId: string = ''; - @Local showSessionActionSheet: boolean = false; - @Local detailsSessionId: string = ''; - @Local showSessionDetails: boolean = false; - @Local optimisticSelectedSessionId: string = ''; - // The list owns two window-level sheets whose content ends at the screen - // edge, so it reads the strip itself: the action sheet's rows are fixed - // controls that keep the bar clear, and the details sheet scrolls under it. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - // Selecting a row reruns this whole builder tree, and the tree asks for the - // grouped lists far more often than it changes them. The cache answers from - // the last projection unless the sessions, the workspaces or a filter moved — - // none of which a selection touches. - private readonly projectionCache: SessionListProjectionCache = new SessionListProjectionCache(); - - // Keyed rows keep their identity; resolve their content from the latest snapshot. - @Computed - get sessionIndex(): Map { - const index = new Map(); - this.sessions.forEach((item: RemoteSession) => { index.set(`${item.deviceId || ''}:${item.id}`, item); }); - return index; - } - - private currentSession(item: RemoteSession): RemoteSession { - return this.sessionIndex.get(`${item.deviceId || ''}:${item.id}`) || item; - } - - // Keyed rows keep their identity; resolve their content from the latest snapshot. - @Computed - get projectIndex(): Map { - const index = new Map(); - this.projectEntries().forEach((item: RecentWorkspaceEntry) => { index.set(this.sectionKey(item), item); }); - return index; - } - - private currentProject(item: RecentWorkspaceEntry): RecentWorkspaceEntry { - return this.projectIndex.get(this.sectionKey(item)) || item; - } - - @Monitor('isBusy', 'workspacePath') - onWorkspaceContextChanged(): void { - this.createMenuKey = ''; - } - - @Monitor('selectedSessionId') - onSelectedSessionChanged(): void { - this.optimisticSelectedSessionId = ''; - } - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column() { - // A node carries at most one bindSheet: chaining the action sheet and - // the details sheet on one node left the first sheet unopenable, so the - // action sheet binds on its own zero-height carrier row — the same - // pattern the sidebar's section uses for its own pair of sheets. - Row() {}.height(0) - .bindSheet($$this.showSessionActionSheet, this.SessionActionSheet(), this.sessionActionSheetOptions()) - Scroll() { - Column() { - if (this.filteredSessions().length === 0) { - if (this.hasActiveListFilter()) { - this.FilteredEmptySessions() - } else { - this.EmptySessions() - } - } else if (this.sortMode === 'time') { - this.TimeSection() - } else if (this.sortMode === 'chat') { - if (this.visibleChatSessions().length > 0) { - this.ChatSection() - } - if (this.projectEntries().length > 0) { - this.ProjectSection() - } - } else { - if (this.projectEntries().length > 0) { - this.ProjectSection() - } - if (this.visibleChatSessions().length > 0) { - this.ChatSection() - } - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - .layoutWeight(1) - .width('100%') - .align(Alignment.TopStart) - .scrollable(ScrollDirection.Vertical) - .scrollBar(BarState.Off) - } - .width('100%') - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - .bindSheet($$this.showSessionDetails, this.SessionDetailsSheet(), this.sessionDetailsSheetOptions()) - } - - @Builder - private TimeSection() { - Column() { - if (this.sessionsByTime().length === 0) { - this.EmptySessions() - } else { - if (this.sessionsForTimeBucket('today').length > 0) { - this.TodayGroup() - } - if (this.sessionsForTimeBucket('yesterday').length > 0) { - this.YesterdayGroup() - } - if (this.sessionsForTimeBucket('earlier').length > 0) { - this.EarlierGroup() - } - } - } - .width('100%') - .margin({ top: 10, bottom: 16 }) - } - - @Builder - private TodayGroup() { - Column() { - this.TimeGroupHeader(RemoteI18n.t('remote.time.today'), this.todayCollapsed, () => { - this.todayCollapsed = !this.todayCollapsed; - }) - if (!this.todayCollapsed) { - ForEach(this.sessionsForTimeBucket('today'), (row: RemoteSession) => { - this.SessionRow(row) - }, (item: RemoteSession): string => `${item.deviceId || ''}:${item.id}`) - } - } - .width('100%') - .margin({ bottom: 8 }) - } - - @Builder - private YesterdayGroup() { - Column() { - this.TimeGroupHeader(RemoteI18n.t('remote.time.yesterday'), this.yesterdayCollapsed, () => { - this.yesterdayCollapsed = !this.yesterdayCollapsed; - }) - if (!this.yesterdayCollapsed) { - ForEach(this.sessionsForTimeBucket('yesterday'), (row: RemoteSession) => { - this.SessionRow(row) - }, (item: RemoteSession): string => `${item.deviceId || ''}:${item.id}`) - } - } - .width('100%') - .margin({ bottom: 8 }) - } - - @Builder - private EarlierGroup() { - Column() { - this.TimeGroupHeader(RemoteI18n.t('remote.time.earlier'), this.earlierCollapsed, () => { - this.earlierCollapsed = !this.earlierCollapsed; - }) - if (!this.earlierCollapsed) { - ForEach(this.sessionsForTimeBucket('earlier'), (row: RemoteSession) => { - this.SessionRow(row) - }, (item: RemoteSession): string => `${item.deviceId || ''}:${item.id}`) - } - } - .width('100%') - .margin({ bottom: 8 }) - } - - @Builder - private TimeGroupHeader(title: string, collapsed: boolean, action: () => void) { - Row({ space: 8 }) { - Text(title) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - if (collapsed) { - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(14) - .fontColor([MUTED]) - .opacity(0.55) - } else { - SymbolGlyph($r('sys.symbol.chevron_down')) - .fontSize(14) - .fontColor([MUTED]) - .opacity(0.55) - } - } - .width('100%') - .height(42) - .alignItems(VerticalAlign.Center) - .onClick(action) - } - - @Builder - private ProjectSection() { - Column({ space: 4 }) { - Row() { - Row({ space: 8 }) { - Text(RemoteI18n.t('sidebar.projects')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Text(`${this.projectEntries().length}`) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - Blank() - } - .width('100%') - .height(44) - .alignItems(VerticalAlign.Center) - ForEach(this.visibleProjectEntries(), (row: RecentWorkspaceEntry) => { - Column({ space: 2 }) { - Row({ space: 10 }) { - SymbolGlyph($r('sys.symbol.folder')) - .fontSize(22) - .fontColor([INK]) - .width(24) - .height(24) - Text(this.currentProject(row).name || this.basename(this.currentProject(row).path)) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - // The Stack keeps the 18vp slot stable across both states; the - // glyph stays unsized because a chevron_right is drawn against - // the left edge of any box forced wider than its natural, - // half-width advance box. - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.isWorkspaceCollapsed(this.sectionKey(this.currentProject(row))) ? - $r('sys.symbol.chevron_right') : $r('sys.symbol.chevron_down')) - .fontSize(14) - .fontColor([MUTED]) - } - .width(18) - .height(18) - if (this.currentProject(row).path.length > 0) { - SymbolGlyph($r('sys.symbol.square_and_pencil')) - .fontSize(18) - .fontColor([MUTED]) - .width(22) - .height(22) - .opacity(0.52) - .bindPopup(this.createMenuKey.length > 0 && this.createMenuKey === this.sectionKey(this.currentProject(row)), { - builder: () => { - this.ProjectCreateMenu(row) - }, - placement: Placement.Top, - popupColor: TRANSPARENT, - enableArrow: false, - autoCancel: true, - mask: false, - targetSpace: 6, - onStateChange: (event) => { - if (!event.isVisible) { - this.createMenuKey = ''; - } - } - }) - .onClick(() => { - const key = this.sectionKey(this.currentProject(row)); - this.createMenuKey = this.createMenuKey === key ? '' : key; - }) - } - } - .width('100%') - .height(44) - .onClick(() => { - this.toggleWorkspace(this.sectionKey(this.currentProject(row))); - }) - if (!this.isWorkspaceCollapsed(this.sectionKey(this.currentProject(row)))) { - this.projectPreview(row) - } - } - .width('100%') - .margin({ bottom: 8 }) - }, (project: RecentWorkspaceEntry): string => this.sectionKey(project)) - if (this.visibleProjectCount < this.projectEntries().length) { - Text(RemoteI18n.f('remote.projects.showMore', String(this.nextProjectEntryBatchSize()))) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .height(40) - .width('100%') - .textAlign(TextAlign.Center) - .onClick(() => { - this.visibleProjectCount += 3; - }) - } - } - .width('100%') - .margin({ top: 12 }) - } - - @Builder - private ProjectCreateMenu(row: RecentWorkspaceEntry) { - if (this.supportsHarnessProfiles) { - HarnessProfileMenu({ - includeCowork: true, - onSelect: (agentType: string) => { - this.createMenuKey = ''; - this.onCreateInWorkspace(this.currentProject(row).path, agentType, this.currentProject(row).remoteConnectionId, this.currentProject(row).remoteSshHost, this.currentProject(row).workspaceId); - } - }) - } else { - Column({ space: 2 }) { - this.ProjectCreateMenuItem('Code', 'code', row) - this.ProjectCreateMenuItem('Cowork', 'Cowork', row) - } - .width(150) - .padding({ top: 8, bottom: 8 }) - .backgroundColor(CARD) - .borderRadius(14) - .border({ width: 0.5, color: LINE }) - .shadow({ radius: 20, color: SHADOW_SUBTLE, offsetY: 8 }) - } - } - - @Builder - private ProjectCreateMenuItem(label: string, agentType: string, project: RecentWorkspaceEntry) { - Row() { - Text(label) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .fontWeight(FontWeight.Medium) - } - .width('100%') - .height(42) - .padding({ left: 18, right: 18 }) - .onClick(() => { - this.createMenuKey = ''; - this.onCreateInWorkspace(this.currentProject(project).path, agentType, this.currentProject(project).remoteConnectionId, this.currentProject(project).remoteSshHost, this.currentProject(project).workspaceId); - }) - } - - @Builder - private ChatSection() { - Column() { - Row() { - Row({ space: 8 }) { - Text(RemoteI18n.t('remote.chats')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.chatsCollapsed ? - $r('sys.symbol.chevron_right') : $r('sys.symbol.chevron_down')) - .fontSize(14) - .fontColor([MUTED]) - } - .width(18) - .height(18) - } - .onClick(() => { - this.chatsCollapsed = !this.chatsCollapsed; - }) - Blank() - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.square_and_pencil')) - .fontSize(18) - .fontColor([MUTED]) - .opacity(0.52) - } - .width(40) - .height(40) - .accessibilityText(RemoteI18n.t('remote.newChat')) - .onClick(() => { - this.onCreateAssistantSession(); - }) - } - .width('100%') - .height(44) - .alignItems(VerticalAlign.Center) - if (this.visibleChatSessions().length === 0) { - this.EmptySessions() - } else if (!this.chatsCollapsed) { - ForEach(this.visibleChatSessions().slice(0, this.chatVisibleCount), (row: RemoteSession) => { - this.SessionRow(row) - }, (item: RemoteSession): string => `${item.deviceId || ''}:${item.id}`) - if (this.chatVisibleCount < this.visibleChatSessions().length) { - Text(RemoteI18n.f('remote.sessions.showMore', String(this.nextChatBatchSize()))) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .height(40) - .width('100%') - .textAlign(TextAlign.Center) - .onClick(() => { - this.chatVisibleCount += 3; - }) - } - } - } - .width('100%') - .margin({ top: 8, bottom: 16 }) - } - - @Builder - private projectPreview(row: RecentWorkspaceEntry) { - ForEach(this.visibleProjectSessions(this.currentProject(row)), (row: RemoteSession) => { - this.SessionRow(row, true) - }, (item: RemoteSession): string => `${item.deviceId || ''}:${item.id}`) - if (this.projectVisibleCount(this.currentProject(row)) < this.projectSessions(this.currentProject(row)).length) { - Text(RemoteI18n.f('remote.sessions.showMore', String(this.nextProjectBatchSize(this.currentProject(row))))) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(MUTED) - .height(44) - .width('100%') - .textAlign(TextAlign.Center) - .onClick(() => { - this.projectVisibleSteps = this.projectVisibleSteps.concat([this.sectionKey(this.currentProject(row))]); - }) - } - } - - /** - * The grouped session list, computed at most once per change to its inputs. - * - * Every derived accessor below reads through here rather than deriving - * anything itself, so calling them repeatedly across the builder tree — which - * is what the tree does — costs a map lookup instead of a full scan. - */ - private view(): SessionListProjection { - const inputs: SessionListInputs = { - sessions: this.sessions, - query: this.query, - sortMode: this.sortMode, - workspaceName: this.workspaceName, - workspacePath: this.workspacePath, - workspaceId: this.workspaceId, - workspaceConnectionId: this.workspaceConnectionId, - workspaceSshHost: this.workspaceSshHost, - workspaceKind: this.workspaceKind, - recentWorkspaces: this.recentWorkspaces, - workspaceFilter: this.workspaceFilter, - agentFilter: this.agentFilter, - statusFilter: this.statusFilter, - showWorkspaceMetadata: this.showWorkspaceMetadata, - showUpdatedMetadata: this.showUpdatedMetadata, - showStatusMetadata: this.showStatusMetadata - }; - return this.projectionCache.get(inputs); - } - - private projectEntries(): RecentWorkspaceEntry[] { - return this.view().projects; - } - - private visibleProjectEntries(): RecentWorkspaceEntry[] { - return this.projectEntries().slice(0, this.visibleProjectCount); - } - - private nextProjectEntryBatchSize(): number { - return Math.min(3, this.projectEntries().length - this.visibleProjectCount); - } - - private basename(path: string): string { - const parts = path.split('/'); - return parts.length > 0 ? parts[parts.length - 1] : path; - } - - private visibleChatSessions(): RemoteSession[] { - return this.view().chats; - } - - private sessionsByTime(): RemoteSession[] { - return this.view().byTime; - } - - private sessionsForTimeBucket(bucket: string): RemoteSession[] { - const projection = this.view(); - if (bucket === 'today') { - return projection.today; - } - return bucket === 'yesterday' ? projection.yesterday : projection.earlier; - } - - private sectionKey(project: RecentWorkspaceEntry): string { - return SessionListProjector.sectionKeyFor(project); - } - - private projectSessions(project: RecentWorkspaceEntry): RemoteSession[] { - return SessionListProjector.sessionsForProject(this.view(), project); - } - - private filteredSessions(): RemoteSession[] { - return this.view().filtered; - } - - private hasActiveListFilter(): boolean { - return this.view().hasActiveFilter; - } - - private visibleProjectSessions(project: RecentWorkspaceEntry): RemoteSession[] { - return this.projectSessions(project).slice(0, this.projectVisibleCount(project)); - } - - private projectVisibleCount(project: RecentWorkspaceEntry): number { - const key = this.sectionKey(project); - const additionalSteps = this.projectVisibleSteps.filter((item: string) => item === key).length; - return 3 + additionalSteps * 3; - } - - private nextProjectBatchSize(project: RecentWorkspaceEntry): number { - return Math.min(3, this.projectSessions(project).length - this.projectVisibleCount(project)); - } - - private nextChatBatchSize(): number { - return Math.min(3, this.visibleChatSessions().length - this.chatVisibleCount); - } - - private isWorkspaceCollapsed(key: string): boolean { - return this.collapsedWorkspaceKeys.indexOf(key) >= 0; - } - - private toggleWorkspace(key: string): void { - if (this.isWorkspaceCollapsed(key)) { - this.collapsedWorkspaceKeys = this.collapsedWorkspaceKeys.filter((item: string) => item !== key); - } else { - this.collapsedWorkspaceKeys = this.collapsedWorkspaceKeys.concat([key]); - } - } - - @Builder - private SessionRow(row: RemoteSession, nested: boolean = false) { - RemoteSessionRow({ - session: this.currentSession(row), - metadata: this.metadataText(this.currentSession(row)), - nested, - selected: this.isSessionSelected(this.currentSession(row).id), - busy: this.isBusy, - actionPresentation: this.actionPresentation, - showActionPopover: this.activeActionSessionId === this.currentSession(row).id, - actionsPopup: () => { this.SessionActionPopover() }, - onPressStateChange: (pressed: boolean) => { - this.optimisticSelectedSessionId = pressed ? this.currentSession(row).id : ''; - }, - onOpen: (session: RemoteSession) => { - this.optimisticSelectedSessionId = session.id; - this.onOpenSession(session); - }, - onOpenActions: (session: RemoteSession) => this.openSessionActions(session), - onCloseActions: () => this.closeSessionActions() - }) - } - - private isSessionSelected(sessionId: string): boolean { - const selectedSessionId = this.optimisticSelectedSessionId.length > 0 ? - this.optimisticSelectedSessionId : this.selectedSessionId; - return selectedSessionId === sessionId; - } - - @Builder - private SessionActionSheet() { - this.SessionActionContent(SessionActionPresentation.BottomSheet) - } - - @Builder - private SessionActionPopover() { - this.SessionActionContent(SessionActionPresentation.Popover) - } - - @Builder - private SessionActionContent(presentation: SessionActionPresentation) { - SessionActionSurface({ - presentation, - sessionTitle: this.actionSessionTitle(), - // Only the bottom-sheet presentation sits at the screen edge; a popover - // floats at its anchor and keeps the plain design spacing. - bottomPadding: presentation === SessionActionPresentation.BottomSheet ? - this.insets.bottomPadding(18) : 18, - canViewDetails: this.actionCapabilities().canViewDetails, - canDelete: this.actionCapabilities().canDelete, - onViewDetails: () => this.openActionSessionDetails(), - onDelete: () => this.deleteActionSession(), - onClose: () => this.closeSessionActions() - }) - } - - @Builder - private SessionDetailsSheet() { - SessionDetailsView({ - session: this.detailsSession(), - onClose: () => this.closeSessionDetails() - }) - } - - @Builder - private EmptySessions() { - Column({ space: 8 }) { - Text(this.isBusy ? RemoteI18n.t('home.emptyLoadingTitle') : RemoteI18n.t('remote.emptyTitle')) - .fontSize(MobileDesignTypography.titleMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(this.isBusy ? RemoteI18n.t('home.emptyLoadingText') : RemoteI18n.t('remote.emptyText')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - .padding({ left: 36, right: 36, bottom: 80 }) - } - - @Builder - private FilteredEmptySessions() { - Column({ space: 8 }) { - Text(this.isBusy ? RemoteI18n.t('home.emptyLoadingTitle') : RemoteI18n.t('remote.emptyTitle')) - .fontSize(MobileDesignTypography.titleMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(this.isBusy ? RemoteI18n.t('home.emptyLoadingText') : RemoteI18n.t('remote.emptyText')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width('100%') - .alignItems(HorizontalAlign.Center) - .padding({ left: 24, right: 24, top: 24, bottom: 16 }) - } - - private openSessionActions(item: RemoteSession): void { - if (this.isBusy || item.id.length === 0) { - return; - } - this.activeActionSessionId = item.id; - if (this.actionPresentation === SessionActionPresentation.BottomSheet) { - this.showSessionActionSheet = true; - } - } - - private closeSessionActions(): void { - this.showSessionActionSheet = false; - this.activeActionSessionId = ''; - } - - private actionSession(): RemoteSession | undefined { - return this.sessions.find((item: RemoteSession) => item.id === this.activeActionSessionId); - } - - private actionSessionTitle(): string { - const session = this.actionSession(); - return session ? session.title : ''; - } - - private metadataText(item: RemoteSession): string { - return SessionListProjector.metadataFor(this.view(), item.id); - } - - private actionCapabilities(): SessionActionCapabilities { - const session = this.actionSession(); - return SessionActionPolicy.resolve( - SessionActionScope.Remote, - session ? session.agentType : '', - this.isBusy || session === undefined - ); - } - - private deleteActionSession(): void { - const session = this.actionSession(); - if (session) { - this.onDeleteSession(session); - } - } - - private openActionSessionDetails(): void { - const session = this.actionSession(); - if (session) { - this.detailsSessionId = session.id; - this.showSessionDetails = true; - } - } - - private closeSessionDetails(): void { - this.showSessionDetails = false; - this.detailsSessionId = ''; - } - - private detailsSession(): RemoteSession { - const session = this.sessions.find((item: RemoteSession) => item.id === this.detailsSessionId); - return session || { - id: '', title: '', agentType: '', status: '', updatedAt: '', createdAt: '', messageCount: 0 - }; - } - - private sessionActionSheetOptions(): SheetOptions { - return { - height: 300, - backgroundColor: TRANSPARENT, - maskColor: SCRIM, - showClose: false, - dragBar: false - }; - } - - private sessionDetailsSheetOptions(): SheetOptions { - return AdaptiveSheetOptions.fromPlacement(this.sessionDetailsPlacement); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionLoadingView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionLoadingView.ets deleted file mode 100644 index ab8fdbf3e4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionLoadingView.ets +++ /dev/null @@ -1,40 +0,0 @@ -import { SOFT } from './Theme'; - -/** Initial remote-home loading state, matching the rounded-line reference layout. */ -@ComponentV2 -export struct RemoteSessionLoadingView { - build() { - Scroll() { - Column({ space: 30 }) { - this.SkeletonBar('28%'); - this.SkeletonBar('58%'); - this.SkeletonBar('90%'); - this.SkeletonBar('34%'); - this.SkeletonBar('65%'); - this.SkeletonBar('92%'); - this.SkeletonBar('40%'); - this.SkeletonBar('70%'); - this.SkeletonBar('14%'); - this.SkeletonBar('28%'); - this.SkeletonBar('58%'); - this.SkeletonBar('90%'); - this.SkeletonBar('34%'); - } - .width('100%') - .padding({ top: 30, bottom: 16 }) - } - .layoutWeight(1) - .width('100%') - .scrollable(ScrollDirection.Vertical) - .scrollBar(BarState.Off) - } - - @Builder - private SkeletonBar(width: string) { - Text('') - .width(width) - .height(50) - .borderRadius(25) - .backgroundColor(SOFT) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionRow.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionRow.ets deleted file mode 100644 index abd78bdd6a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RemoteSessionRow.ets +++ /dev/null @@ -1,108 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteSession } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { SessionActionPresentation } from './SessionActionSurface'; -import { - INK, - MUTED, - SOFT, - TRANSPARENT, -} from './Theme'; - -@ComponentV2 -export struct RemoteSessionRow { - @Param session: RemoteSession = { - id: '', - title: '', - workspacePath: '', - agentType: 'code', - status: '', - updatedAt: '', - createdAt: '', - messageCount: 0 - }; - @Param metadata: string = ''; - @Param nested: boolean = false; - @Param selected: boolean = false; - @Param busy: boolean = false; - @Param actionPresentation: SessionActionPresentation = SessionActionPresentation.BottomSheet; - @Param showActionPopover: boolean = false; - @Event onOpen: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onPressStateChange: (pressed: boolean) => void = (_pressed: boolean) => {}; - @Event onOpenActions: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onCloseActions: () => void = () => {}; - @BuilderParam actionsPopup: () => void = this.EmptyPopup; - - build() { - Row({ space: 8 }) { - Column({ space: 2 }) { - Text(this.session.title || RemoteI18n.t('sidebar.untitled')) - .width('100%') - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(this.selected ? FontWeight.Medium : FontWeight.Regular) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.metadata.length > 0) { - Text(this.metadata) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - this.MoreButton() - } - .width('100%') - .height(this.metadata.length > 0 ? 56 : 46) - .padding({ left: this.nested ? 0 : 10, right: 4 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.selected ? SOFT : TRANSPARENT) - .borderRadius(10) - .onTouch((event: TouchEvent) => { - if (this.busy) return; - if (event.type === TouchType.Down) this.onPressStateChange(true); - if (event.type === TouchType.Cancel) this.onPressStateChange(false); - }) - .onClick(() => { - if (!this.busy) this.onOpen(this.session); - }) - .gesture(LongPressGesture({ repeat: false }).onAction(() => this.onOpenActions(this.session))) - .bindPopup(this.actionPresentation === SessionActionPresentation.Popover && this.showActionPopover, { - builder: () => { this.actionsPopup() }, - placement: Placement.Right, - popupColor: TRANSPARENT, - enableArrow: false, - autoCancel: true, - mask: false, - targetSpace: 6, - onStateChange: (event) => { - if (!event.isVisible) this.onCloseActions(); - } - }) - } - - @Builder - private MoreButton() { - Stack({ alignContent: Alignment.Center }) { - Row({ space: 3 }) { - Text('').width(3.5).height(3.5).backgroundColor(MUTED).borderRadius(2) - Text('').width(3.5).height(3.5).backgroundColor(MUTED).borderRadius(2) - Text('').width(3.5).height(3.5).backgroundColor(MUTED).borderRadius(2) - } - .height(8) - .alignItems(VerticalAlign.Center) - } - .width(34) - .height(40) - .opacity(0.62) - .accessibilityText(RemoteI18n.t('session.actions')) - .onClick(() => this.onOpenActions(this.session)) - } - - @Builder - private EmptyPopup() {} -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackSelectionMenu.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackSelectionMenu.ets deleted file mode 100644 index 97da155b76..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackSelectionMenu.ets +++ /dev/null @@ -1,59 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RollbackPresentationPolicy } from '../policy/RollbackPresentationPolicy'; - -/** - * The rollback entry inside a user message's system selection menu. - * - * Two user-message surfaces raise that menu — the short bubble's own `Text` and - * the full-text panel's — and the entry has to be the same one on both, so the - * menu item is built once here instead of twice: the item's id is what the click - * callback matches on, and two copies of that string would be two entries the day - * one of them is renamed. - * - * `onCreateMenu` appends the item to the items the system offered, which is what - * keeps copy and select-all intact; `onMenuItemClick` claims only its own id and - * returns false for everything else, so the system runs its own logic untouched - * (`Text.editMenuOptions`, API 12+). - * - * The item closes the menu it was tapped in before it asks for the rollback. - * Measured on device, an extended item that only returns true leaves the system - * overlay open over the staged preview it just asked for — the tap cannot dismiss - * a menu the app does not own — so the surface's own `TextController` does it - * here, once, for every surface that raises this menu. - */ -export class RollbackSelectionMenu { - /** - * Id this app's extended item answers to. - * - * `TextMenuItemId.of` takes it as its whole identity, so the value is only ever - * compared against itself and never shown to a user. - */ - private static readonly ITEM_ID: string = 'openbitfun_rollback_to_message'; - - /** - * Options for one surface's `Text`. - * - * `controller` is the controller that `Text` was built with: dismissing the - * menu needs the component the menu belongs to. - */ - static options(controller: TextController, onRollback: () => void): EditMenuOptions { - return { - onCreateMenu: (menuItems: Array): Array => { - const items: Array = menuItems.slice(); - items.push({ - content: RemoteI18n.t(RollbackPresentationPolicy.ROLLBACK_ITEM_KEY), - id: TextMenuItemId.of(RollbackSelectionMenu.ITEM_ID) - }); - return items; - }, - onMenuItemClick: (menuItem: TextMenuItem, _range: TextRange): boolean => { - if (!menuItem.id.equals(TextMenuItemId.of(RollbackSelectionMenu.ITEM_ID))) { - return false; - } - controller.closeSelectionMenu(); - onRollback(); - return true; - } - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackStagingBar.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackStagingBar.ets deleted file mode 100644 index 46630ba9d8..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/RollbackStagingBar.ets +++ /dev/null @@ -1,134 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RollbackBarPresentation, RollbackPresentationPolicy } from '../policy/RollbackPresentationPolicy'; -import { ComposerPresentation } from './ComposerBar'; -import { INK, MUTED, SOFT } from './Theme'; - -/** - * Height of the bar, and of the two icon-only controls inside it. - * - * Frozen in the approved artboard (H): a 48-high SOFT capsule whose right edge - * holds two 40-vp controls, four apart, so the confirm glyph clears the capsule's - * corner by its own padding rather than by a margin of its own. - */ -const ROLLBACK_BAR_HEIGHT: number = 48; -const ROLLBACK_ICON_BUTTON_SIZE: number = 40; -const ROLLBACK_GLYPH_SIZE: number = 20; -const ROLLBACK_BAR_RADIUS: number = 16; -const ROLLBACK_BAR_LEADING_PADDING: number = 12; -const ROLLBACK_BAR_TRAILING_PADDING: number = 4; -/** Gap between the label block and the controls, and between the two glyphs. */ -const ROLLBACK_BAR_ACTION_GAP: number = 4; -const ROLLBACK_BAR_TEXT_GAP: number = 8; -/** The composer's own constrained width, which the bar sits directly above. */ -const ROLLBACK_BAR_MAX_WIDTH: number = 760; - -/** - * The staged rollback's bar, pinned directly above the composer. - * - * It says what is about to be withdrawn and offers the two exits with no copy of - * their own: the confirm glyph is the main-action ink, the close glyph is muted, - * and each carries its label for accessibility instead of on screen. Both exits - * live in a centered `Stack` that owns the touch target, so the glyph keeps its - * natural advance box (see the SymbolGlyph rules in AGENTS.md). - * - * The bar is drawn in both responsive presentations: the compact composer and the - * wide floating one, with the same horizontal inset each of them uses, so the bar - * and the pill it sits above share both edges. - */ -@ComponentV2 -export struct RollbackStagingBar { - @Param presentation: ComposerPresentation = ComposerPresentation.Compact; - @Param bar: RollbackBarPresentation = new RollbackBarPresentation(false, '', ''); - @Event onConfirm: () => void = () => {}; - @Event onClose: () => void = () => {}; - - build() { - // The whole box is conditional, not just its contents: a hidden bar that still - // occupied its gap would push the composer down for the entire session. - if (this.bar.visible) { - Column() { - Row({ space: ROLLBACK_BAR_TEXT_GAP }) { - Row({ space: ROLLBACK_BAR_TEXT_GAP }) { - Text(RemoteI18n.t(this.bar.titleKey)) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - Text(this.bar.preview) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(VerticalAlign.Center) - - Row({ space: ROLLBACK_BAR_ACTION_GAP }) { - this.ConfirmButton() - this.CloseButton() - } - .alignItems(VerticalAlign.Center) - } - .width('100%') - .height(ROLLBACK_BAR_HEIGHT) - .padding({ left: ROLLBACK_BAR_LEADING_PADDING, right: ROLLBACK_BAR_TRAILING_PADDING }) - .backgroundColor(SOFT) - .borderRadius(ROLLBACK_BAR_RADIUS) - .transition(TransitionEffect.translate({ x: 0, y: 8 }) - .combine(TransitionEffect.opacity(0)) - .animation({ duration: 180, curve: Curve.EaseOut })) - } - .width('100%') - .constraintSize({ - maxWidth: this.presentation === ComposerPresentation.Floating ? ROLLBACK_BAR_MAX_WIDTH : 10000 - }) - .alignSelf(ItemAlign.Center) - // The composer below already keeps its own distance from the edge, so the bar - // only carries the gap above itself. - .padding({ - left: this.insetForPresentation(), - right: this.insetForPresentation(), - top: 8 - }) - } - } - - @Builder - private ConfirmButton() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.arrow_counterclockwise')) - .fontSize(ROLLBACK_GLYPH_SIZE) - .fontColor([INK]) - } - .width(ROLLBACK_ICON_BUTTON_SIZE) - .height(ROLLBACK_ICON_BUTTON_SIZE) - .accessibilityText(RemoteI18n.t(RollbackPresentationPolicy.ROLLBACK_ITEM_KEY)) - .onClick(() => { - this.onConfirm(); - }) - } - - @Builder - private CloseButton() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(ROLLBACK_GLYPH_SIZE) - .fontColor([MUTED]) - } - .width(ROLLBACK_ICON_BUTTON_SIZE) - .height(ROLLBACK_ICON_BUTTON_SIZE) - .accessibilityText(RemoteI18n.t('common.close')) - .onClick(() => { - this.onClose(); - }) - } - - private insetForPresentation(): number { - return this.presentation === ComposerPresentation.Floating ? - 24 : MobileDesignGeometry.conversationOverlaySideInset; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionActionSurface.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionActionSurface.ets deleted file mode 100644 index 4ba5f56c58..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionActionSurface.ets +++ /dev/null @@ -1,199 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CARD, INK, LINE, MUTED, SHADOW_SUBTLE, STATUS_DANGER, TRANSPARENT } from './Theme'; -import { AppActionButton, AppActionStyle } from './AppActionButton'; - -export enum SessionActionPresentation { - BottomSheet = 'bottom_sheet', - Popover = 'popover' -} - -@ComponentV2 -export struct SessionActionSurface { - @Param presentation: SessionActionPresentation = SessionActionPresentation.BottomSheet; - @Param sessionTitle: string = ''; - /** - * Bottom padding in vp. The bottom-sheet presentation sits at the screen - * edge under the immersive shell, so its host passes the strip-aware value - * (`insets.bottomPadding(18)`); a popover keeps the plain design spacing. - */ - @Param bottomPadding: number = 18; - @Param archived: boolean = false; - @Param canViewDetails: boolean = false; - @Param canArchive: boolean = false; - @Param canExport: boolean = false; - @Param canDelete: boolean = false; - @Event onArchive: () => void = () => {}; - @Event onViewDetails: () => void = () => {}; - @Event onExport: () => void = () => {}; - @Event onDelete: () => void = () => {}; - @Event onClose: () => void = () => {}; - @Local confirmingDelete: boolean = false; - - build() { - Column() { - if (this.presentation === SessionActionPresentation.BottomSheet) { - Text('') - .width(36) - .height(4) - .backgroundColor(LINE) - .borderRadius(2) - .margin({ bottom: 10 }) - } - - Row({ space: 12 }) { - Column({ space: 3 }) { - Text(RemoteI18n.t('session.actions')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Text(this.sessionTitle || RemoteI18n.t('sidebar.untitled')) - .width('100%') - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(16) - .fontColor([MUTED]) - } - .width(40) - .height(40) - .accessibilityText(RemoteI18n.t('common.close')) - .onClick(() => this.onClose()) - } - .width('100%') - .height(52) - .alignItems(VerticalAlign.Center) - - Divider().color(LINE).margin({ top: 6, bottom: 8 }) - - if (this.confirmingDelete) { - this.DeleteConfirmation() - } else { - if (this.canViewDetails) { - this.ActionRow('details', RemoteI18n.t('session.viewDetails'), () => { - this.onViewDetails(); - this.onClose(); - }) - } - if (this.canArchive) { - this.ActionRow('archive', this.archived ? RemoteI18n.t('sidebar.unarchive') : - RemoteI18n.t('sidebar.archive'), () => { - this.onArchive(); - this.onClose(); - }) - } - if (this.canExport) { - this.ActionRow('export', RemoteI18n.t('sidebar.exportMarkdown'), () => { - this.onExport(); - this.onClose(); - }) - } - if (this.canDelete) { - if (this.canArchive || this.canExport) { - Divider().color(LINE).margin({ top: 6, bottom: 6 }) - } - this.ActionRow('delete', RemoteI18n.t('common.delete'), () => { - this.confirmingDelete = true; - }, true) - } - } - } - .width(this.presentation === SessionActionPresentation.Popover ? 300 : '100%') - // The card's fill still reaches the sheet's bottom edge; the padding is - // what keeps the last action row out of the navigation bar's strip. - .padding({ left: 16, right: 16, top: 10, bottom: this.bottomPadding }) - .backgroundColor(CARD) - .border({ width: this.presentation === SessionActionPresentation.Popover ? 0.5 : 1, color: LINE }) - .borderRadius(16) - .shadow({ - radius: this.presentation === SessionActionPresentation.Popover ? 20 : 0, - color: this.presentation === SessionActionPresentation.Popover ? SHADOW_SUBTLE : TRANSPARENT, - offsetY: this.presentation === SessionActionPresentation.Popover ? 8 : 0 - }) - .alignItems(HorizontalAlign.Center) - } - - @Builder - private ActionRow(kind: string, label: string, action: () => void, destructive: boolean = false) { - Row({ space: 12 }) { - this.ActionIcon(kind, destructive) - Text(label) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(destructive ? STATUS_DANGER : INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .height(46) - .padding({ left: 10, right: 10 }) - .borderRadius(8) - .backgroundColor(TRANSPARENT) - .onClick(action) - } - - @Builder - private ActionIcon(kind: string, destructive: boolean) { - if (kind === 'details') { - SymbolGlyph($r('sys.symbol.info_circle')) - .fontSize(19) - .fontColor([MUTED]) - } else if (kind === 'archive') { - SymbolGlyph($r('sys.symbol.archivebox')) - .fontSize(19) - .fontColor([destructive ? STATUS_DANGER : MUTED]) - } else if (kind === 'export') { - SymbolGlyph($r('sys.symbol.cloud')) - .fontSize(19) - .fontColor([MUTED]) - } else { - SymbolGlyph($r('sys.symbol.trash')) - .fontSize(19) - .fontColor([STATUS_DANGER]) - } - } - - @Builder - private DeleteConfirmation() { - Column({ space: 12 }) { - Text(RemoteI18n.t('sidebar.deleteConfirm')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - Row({ space: 10 }) { - AppActionButton({ - label: RemoteI18n.t('common.cancel'), - style: AppActionStyle.Quiet, - actionHeight: 44, - onAction: (): void => { - this.confirmingDelete = false; - } - }) - .layoutWeight(1) - AppActionButton({ - label: RemoteI18n.t('common.delete'), - style: AppActionStyle.Destructive, - actionHeight: 44, - onAction: (): void => { - this.onDelete(); - this.onClose(); - } - }) - .layoutWeight(1) - } - .width('100%') - } - .width('100%') - .padding({ top: 4, bottom: 4 }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionDetailsView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionDetailsView.ets deleted file mode 100644 index 8710f1b173..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SessionDetailsView.ets +++ /dev/null @@ -1,168 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteSession } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { TimeFormat } from '../../services/TimeFormat'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { CARD, INK, LINE, MUTED, PAGE_BG, SOFT } from './Theme'; - -@ComponentV2 -export struct SessionDetailsView { - @Param session: RemoteSession = { - id: '', - title: '', - agentType: '', - status: '', - updatedAt: '', - createdAt: '', - messageCount: 0 - }; - @Event onClose: () => void = () => {}; - // The sheet is a bottom sheet under the immersive shell, so the scrolling - // column reads the strip itself and ends in a tail that rests the last row - // above the navigation bar. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column() { - Row({ space: 12 }) { - Column({ space: 3 }) { - Text(RemoteI18n.t('session.details')) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Text(this.session.title || RemoteI18n.t('sidebar.untitled')) - .width('100%') - .fontSize(MobileDesignTypography.headlineSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(17) - .fontColor([MUTED]) - } - .width(44) - .height(44) - .backgroundColor(SOFT) - .borderRadius(22) - .accessibilityText(RemoteI18n.t('common.close')) - .onClick(() => this.onClose()) - } - .width('100%') - .padding({ left: 20, right: 16, top: 18, bottom: 16 }) - - Divider().color(LINE) - - Scroll() { - Column() { - this.DetailRow(RemoteI18n.t('session.agentType'), this.agentTypeLabel()) - if ((this.session.workspaceName || '').length > 0) { - this.DetailRow(RemoteI18n.t('session.workspace'), this.session.workspaceName || '') - } - if ((this.session.workspacePath || '').length > 0) { - this.PathRow(RemoteI18n.t('session.workspacePath'), this.session.workspacePath || '') - } - if (this.validTime(this.session.createdAt)) { - this.DetailRow(RemoteI18n.t('session.createdAt'), TimeFormat.relative(this.session.createdAt)) - } - if (this.validTime(this.session.updatedAt)) { - this.DetailRow(RemoteI18n.t('session.updatedAt'), TimeFormat.relative(this.session.updatedAt)) - } - this.DetailRow(RemoteI18n.t('session.messageCount'), `${Math.max(0, this.session.messageCount)}`) - if (this.session.status.length > 0) { - this.DetailRow(RemoteI18n.t('session.status'), this.statusLabel()) - } - } - .width('100%') - .padding({ left: 20, right: 20, top: 8, bottom: this.insets.tailSpacing(24) }) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .borderRadius(16) - } - - @Builder - private DetailRow(label: string, value: string) { - Row({ space: 16 }) { - Text(label) - .width(104) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - Text(value) - .layoutWeight(1) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(INK) - .textAlign(TextAlign.End) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .constraintSize({ minHeight: 52 }) - .padding({ top: 8, bottom: 8 }) - .border({ width: { bottom: 1 }, color: LINE }) - .alignItems(VerticalAlign.Center) - } - - @Builder - private PathRow(label: string, value: string) { - Column({ space: 8 }) { - Text(label) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - Text(value) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(INK) - .padding({ left: 10, right: 10, top: 8, bottom: 8 }) - .backgroundColor(CARD) - .border({ width: 1, color: LINE }) - .borderRadius(6) - .copyOption(CopyOptions.LocalDevice) - } - .width('100%') - .padding({ top: 12, bottom: 12 }) - .border({ width: { bottom: 1 }, color: LINE }) - .alignItems(HorizontalAlign.Start) - } - - private validTime(value: string): boolean { - return !Number.isNaN(TimeFormat.timestampMs(value)); - } - - private agentTypeLabel(): string { - return this.session.agentType.length > 0 ? this.session.agentType : RemoteI18n.t('common.unknown'); - } - - private statusLabel(): string { - if (this.session.status === 'archived') { - return RemoteI18n.t('sidebar.archived'); - } - if (this.session.status === 'active') { - return RemoteI18n.t('chat.executing'); - } - return this.session.status; - } -} 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 deleted file mode 100644 index 9630ebc114..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SettingsSheet.ets +++ /dev/null @@ -1,389 +0,0 @@ -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'; -import { AccountProfilePanel } from './AccountProfilePanel'; -import { DeviceModelDefaultsPanel } from './DeviceModelDefaultsPanel'; -import { ModelRolePickerPanel } from './ModelRolePickerPanel'; -import { LanguageSettingsPanel } from './LanguageSettingsPanel'; -import { SheetCloseHeader } from './SheetCloseHeader'; -import { SHEET_HORIZONTAL_PADDING, SHEET_TOP_RADIUS } from './SheetLayout'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { RemoteDefaultModels, RemoteModelCatalog, RemotePermissionMode } from '../../model/RemoteModels'; -import { RemotePermissionSection } from './RemotePermissionSection'; - -@ComponentV2 -export struct SettingsSheet { - @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param sheetState: SettingsSheetState = new SettingsSheetState(); - @Param accountUsername: string = ''; - @Param accountAvatarUrl: string = ''; - @Param authenticatedUserId: string = ''; - @Param fallbackUserId: string = ''; - @Param desktopName: string = ''; - @Param desktopId: string = ''; - @Param deviceId: string = ''; - @Param controlTargetType: string = 'none'; - @Param controlTargetDeviceId: string = ''; - @Param connectionState: string = 'idle'; - /** The connected desktop advertises `device_model_defaults_v1`. */ - @Param supportsDeviceModelDefaults: boolean = false; - @Param statusText: string = ''; - @Event onClose: () => void = () => {}; - @Event onOpenAccount: () => void = () => {}; - @Event onDisconnect: () => void = () => {}; - @Event onClearPairing: () => void = () => {}; - @Event onReconnect: () => void = () => {}; - @Event cloudLogout: () => Promise = async (): Promise => {}; - @Event cloudListDevices: () => Promise = - async (): Promise => []; - @Event cloudSelectDevice: (device: CloudAccountDevice) => Promise = - async (_device: CloudAccountDevice): Promise => {}; - @Event getPermissionMode: () => Promise = async (): Promise => 'ask'; - @Event setPermissionMode: (mode: RemotePermissionMode) => Promise = - async (mode: RemotePermissionMode): Promise => mode; - /** Device-level model catalog of the connected desktop (no session id). */ - @Event getDeviceModelCatalog: () => Promise = - async (): Promise => ({ version: 0, models: [], default_models: {} }); - /** Whole-object write of the three phone-managed model slots. */ - @Event setDeviceModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ) => Promise = async ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise => { - return { - primary, - fast, - image_understanding: imageUnderstanding - }; - }; - @Event onSetLanguage: (language: string) => Promise = async (_language: string) => {}; - /** The sheet's own bottom edge, so its scrolling rows can run under the bar and still rest above it. */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - // The device model pages are answered by the sheet, not by themselves: the - // desktop they read and write is whichever one this sheet is open on, so the - // request path is bound here before either page can mount. - const modelDefaultsClient: DeviceModelDefaultsRequestPath = { - getModelCatalog: (): Promise => this.getDeviceModelCatalog(), - setModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise => { - return this.setDeviceModelDefaults(primary, fast, imageUnderstanding); - } - }; - this.sheetState.deviceModels.bind(modelDefaultsClient); - this.applyDeviceModelGate(); - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - /** - * Re-gates the device model pages whenever the desktop, the link or its - * capability set changes. - * - * Arming the gate is not reading: the page spends the read when it opens, so a - * sheet that is opened for the language setting does not ask the desktop about - * its models. A gate that changes while one of the two pages is already open is - * the other case — what is on screen belongs to the previous desktop — so that - * one is read again immediately. - */ - private applyDeviceModelGate(): void { - const needsRead = this.sheetState.deviceModels.setGate({ - supported: this.supportsDeviceModelDefaults, - connected: this.connectionState === 'connected', - deviceId: this.controlTargetDeviceId - }); - if (needsRead && this.onDeviceModelPage()) { - void this.sheetState.deviceModels.load(); - } - } - - private onDeviceModelPage(): boolean { - const page = this.sheetState.page; - return page === 'deviceModels' || page === 'modelPick'; - } - - @Monitor('connectionState', 'supportsDeviceModelDefaults', 'controlTargetDeviceId') - private onDeviceModelTargetChanged(): void { - this.applyDeviceModelGate(); - } - - build() { - Stack({ alignContent: Alignment.TopEnd }) { - if (this.sheetState.page === 'language') { - this.LanguagePanel() - } else if (this.sheetState.page === 'deviceModels') { - this.DeviceModelSettingsPage() - } else if (this.sheetState.page === 'modelPick') { - this.ModelRolePickerPage() - } else { - this.SettingsHome() - } - } - .width('100%') - .height('100%') - // The sheet's fill is the shell's bottom edge and runs to the screen edge, - // and so does its scrolling viewport: the rows are content, and they roll - // under the navigation indicator while they are still moving instead of - // stopping short of it above a band of bare page colour. What stops above - // the bar is the column's own tail padding, which brings the last row to - // rest there once the sheet is scrolled to its end. The framework does not - // inset a bottom sheet for the app while the window is immersive, so the - // sheet does it itself. - .backgroundColor(PAGE_BG) - .borderRadius({ topLeft: SHEET_TOP_RADIUS, topRight: SHEET_TOP_RADIUS }) - } - - @Builder - SettingsHome() { - Column() { - SheetCloseHeader({ - title: RemoteI18n.t('settings.title'), - showDivider: true, - onClose: this.onClose - }) - - Scroll() { - Column({ space: 0 }) { - AccountProfilePanel({ - directoryState: this.directoryState, - accountUsername: this.accountUsername, - accountAvatarUrl: this.accountAvatarUrl, - accountUserId: this.authenticatedUserId, - fallbackUserId: this.fallbackUserId, - deviceId: this.deviceId, - controlTargetType: this.controlTargetType, - controlTargetDeviceId: this.controlTargetDeviceId, - connectionState: this.connectionState, - supportsDeviceModelDefaults: this.supportsDeviceModelDefaults, - cloudLogout: this.cloudLogout, - cloudListDevices: this.cloudListDevices, - cloudSelectDevice: this.cloudSelectDevice, - onReconnect: this.onReconnect, - onOpenAccount: this.onOpenAccount, - onOpenDeviceModelSettings: () => { - this.sheetState.setPage('deviceModels'); - }, - onLoggedOut: this.onClose, - connection: () => { - this.CurrentConnectionSection() - this.PermissionSection() - }, - preferences: () => { - this.GeneralSettingsSection() - }, - about: () => { - this.AboutSettingsSection() - } - }) - } - .width('100%') - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: 22, - // The sheet's tail spacer: the strip plus its own breathing, so the - // last row rests above the navigation bar once the scroll ends. - bottom: this.insets.tailSpacing(34) - }) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - .width('100%') - .height('100%') - } - - @Builder - private CurrentConnectionSection() { - CurrentControlSection({ - desktopName: this.desktopName, - desktopId: this.desktopId, - controlTargetType: this.controlTargetType, - connectionState: this.connectionState, - statusText: this.statusText, - onDisconnect: this.onDisconnect, - onClearPairing: this.onClearPairing, - onReconnect: this.onReconnect - }) - } - - @Builder - private PermissionSection() { - RemotePermissionSection({ - connectionState: this.connectionState, - getPermissionMode: this.getPermissionMode, - setPermissionMode: this.setPermissionMode - }) - } - - @Builder - private GeneralSettingsSection() { - this.SectionTitle(RemoteI18n.t('settings.general.section')) - this.GeneralCard() - } - - @Builder - private AboutSettingsSection() { - this.SectionTitle(RemoteI18n.t('settings.about.section')) - this.AboutCard() - } - - @Builder - SectionTitle(title: string) { - Text(title) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .width('100%') - .margin({ left: 8, bottom: 10 }) - } - - @Builder - GeneralCard() { - Column() { - this.SettingsRow( - RemoteI18n.t('settings.language.title'), - RemoteI18n.nativeName(), - true, - () => { - this.sheetState.setPage('language'); - }, - $r('sys.symbol.textformat') - ) - } - .width('100%') - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - .margin({ bottom: 24 }) - } - - @Builder - AboutCard() { - Column() { - this.StaticRow(RemoteI18n.t('settings.about.openbitfun'), 'HarmonyOS') - Text('') - .width('84%') - .height(1) - .backgroundColor(LINE) - this.StaticRow(RemoteI18n.t('settings.about.version'), '1.0.0') - } - .width('100%') - .backgroundColor(CARD) - .borderRadius(MobileDesignGeometry.settingsCardRadius) - } - - @Builder - StaticRow(title: string, value: string) { - Row({ space: 16 }) { - Text(title) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Blank() - Text(value) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .constraintSize({ minHeight: 56 }) - .padding({ left: 18, right: 18, top: 12, bottom: 12 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - SettingsRow(title: string, value: string, showChevron: boolean, action: () => void, icon: Resource) { - Row({ space: 16 }) { - SymbolGlyph(icon) - .fontSize(20) - .fontColor([MUTED]) - .width(23) - .height(23) - Text(title) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Blank() - Text(value) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .constraintSize({ maxWidth: 130 }) - if (showChevron) { - SymbolGlyph($r('sys.symbol.chevron_right')) - .fontSize(14) - .fontColor([MUTED]) - } - } - .width('100%') - .constraintSize({ minHeight: 56 }) - .padding({ left: 18, right: 18, top: 12, bottom: 12 }) - .alignItems(VerticalAlign.Center) - .onClick(action) - } - - @Builder - LanguagePanel() { - LanguageSettingsPanel({ - selectedLanguage: RemoteI18n.language(), - onClose: () => { - this.sheetState.setPage('main'); - }, - onSelect: (language: string) => { - return this.onSetLanguage(language); - } - }) - } - - /** - * Device model role settings, reached from the connected device row: the second - * level of the sheet's own page stack. - */ - @Builder - DeviceModelSettingsPage() { - DeviceModelDefaultsPanel({ - sheetState: this.sheetState, - deviceModels: this.sheetState.deviceModels, - desktopName: this.desktopName, - desktopId: this.desktopId, - controlTargetType: this.controlTargetType, - connectionState: this.connectionState, - onClose: this.onClose - }) - } - - /** The role picker pushed above it; both pages share the sheet's controller. */ - @Builder - ModelRolePickerPage() { - ModelRolePickerPanel({ - sheetState: this.sheetState, - deviceModels: this.sheetState.deviceModels, - desktopName: this.desktopName, - desktopId: this.desktopId, - onClose: this.onClose - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetActionFooter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetActionFooter.ets deleted file mode 100644 index 2d02724a7f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetActionFooter.ets +++ /dev/null @@ -1,44 +0,0 @@ -import { - SHEET_ACTION_HEIGHT, - SHEET_CONTENT_MAX_WIDTH, - SHEET_FOOTER_BOTTOM_PADDING, - SHEET_FOOTER_TOP_PADDING, - SHEET_HORIZONTAL_PADDING -} from './SheetLayout'; -import { AppActionButton, AppActionStyle } from './AppActionButton'; - -/** Standard single-action footer for full-height modal sheets. */ -@ComponentV2 -export struct SheetActionFooter { - @Param label: string = ''; - @Param primary: boolean = false; - @Param isEnabled: boolean = true; - @Param elevated: boolean = true; - @Event onAction: () => void = () => {}; - - build() { - Column() { - Row() { - AppActionButton({ - label: this.label, - style: this.primary ? AppActionStyle.Primary : AppActionStyle.Secondary, - actionHeight: SHEET_ACTION_HEIGHT, - isEnabled: this.isEnabled, - elevated: this.elevated, - onAction: this.onAction - }) - .layoutWeight(1) - } - .width('100%') - .constraintSize({ maxWidth: SHEET_CONTENT_MAX_WIDTH }) - } - .width('100%') - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: SHEET_FOOTER_TOP_PADDING, - bottom: SHEET_FOOTER_BOTTOM_PADDING - }) - .alignItems(HorizontalAlign.Center) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseButton.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseButton.ets deleted file mode 100644 index ef2e9d6d02..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseButton.ets +++ /dev/null @@ -1,44 +0,0 @@ -import { MobileDesignGeometry } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { INK, TRANSPARENT } from './Theme'; - -/** Quiet top-right close affordance with a full-size touch target. */ -@ComponentV2 -export struct SheetCloseButton { - @Param uniformGlyph: boolean = false; - @Param touchSize: number = MobileDesignGeometry.controlTouchSize; - @Param isEnabled: boolean = true; - @Event onClose: () => void = () => {}; - - build() { - Button() { - if (this.uniformGlyph) { - Path().commands(this.closeGlyphPath()) - .width(18).height(18).fill(TRANSPARENT).stroke(INK).strokeWidth(1.5).strokeLineCap(LineCapStyle.Round) - } else { - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(18) - .fontWeight(FontWeight.Medium) - .fontColor([INK]) - } - } - .width(this.touchSize) - .height(this.touchSize) - .padding(0) - .backgroundColor(TRANSPARENT) - .borderRadius(12) - .stateEffect(true) - .opacity(this.isEnabled ? 1 : 0.4) - .enabled(this.isEnabled) - .accessibilityText(RemoteI18n.t('common.close')) - .onClick(() => { - this.onClose(); - }) - } - private closeGlyphPath(): string { - const a = this.getUIContext().vp2px(2); - const b = this.getUIContext().vp2px(16); - return `M${a} ${a} L${b} ${b} M${b} ${a} L${a} ${b}`; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseHeader.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseHeader.ets deleted file mode 100644 index 5803dbb5b3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetCloseHeader.ets +++ /dev/null @@ -1,39 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { SHEET_HEADER_HEIGHT, SHEET_HEADER_SIDE_PADDING } from './SheetLayout'; -import { SheetCloseButton } from './SheetCloseButton'; -import { INK, LINE } from './Theme'; - -/** Standard top-right dismissal header for modal and replace-in-place Sheet pages. */ -@ComponentV2 -export struct SheetCloseHeader { - @Param uniformGlyph: boolean = false; - @Param title: string = ''; - @Param showDivider: boolean = false; - @Param isEnabled: boolean = true; - @Event onClose: () => void = () => {}; - - build() { - Row() { - if (this.title.length > 0) { - Text(this.title) - .fontSize(MobileDesignTypography.conversationHeaderTitle.size) - .lineHeight(MobileDesignTypography.conversationHeaderTitle.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - Blank() - SheetCloseButton({ - isEnabled: this.isEnabled, - uniformGlyph: this.uniformGlyph, - onClose: this.onClose - }) - } - .width('100%') - .height(SHEET_HEADER_HEIGHT) - .padding({ left: SHEET_HEADER_SIDE_PADDING + 8, right: SHEET_HEADER_SIDE_PADDING }) - .alignItems(VerticalAlign.Center) - .border({ width: { bottom: this.showDivider ? 1 : 0 }, color: LINE }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetLayout.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetLayout.ets deleted file mode 100644 index ab08d2aee9..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SheetLayout.ets +++ /dev/null @@ -1,18 +0,0 @@ -import { MobileDesignGeometry } from '../../generated/MobileDesignTokens'; - -/** - * HarmonyOS layout aliases for the cross-platform mobile Sheet contract. - * - * Keep only Harmony-specific constraints here. Shared geometry must continue - * to come from mobile-tokens.json through MobileDesignGeometry. - */ -export const SHEET_CONTENT_MAX_WIDTH: number = 520; -export const SHEET_HORIZONTAL_PADDING: number = MobileDesignGeometry.sheetHorizontalPadding; -export const SHEET_HEADER_HEIGHT: number = MobileDesignGeometry.sheetHeaderHeight; -export const SHEET_ACTION_HEIGHT: number = MobileDesignGeometry.sheetActionHeight; -export const SHEET_TOP_RADIUS: number = MobileDesignGeometry.sheetTopRadius; -export const SHEET_SIDE_RADIUS: number = MobileDesignGeometry.sheetSideRadius; -export const SHEET_HEADER_SIDE_PADDING: number = 8; -export const SHEET_CONTENT_BOTTOM_PADDING: number = 18; -export const SHEET_FOOTER_TOP_PADDING: number = 10; -export const SHEET_FOOTER_BOTTOM_PADDING: number = 24; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets deleted file mode 100644 index 89e05ff221..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarDeviceGroup.ets +++ /dev/null @@ -1,631 +0,0 @@ -import { remoteWorkspaceIdentityMatches, remoteWorkspaceKey, remoteSessionBelongsToWorkspace } from '../../services/RemoteSessionIdentity'; -import { WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RecentWorkspaceEntry, RemoteSession, RemoteWorkspaceIdentity } from '../../model/RemoteModels'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - DeviceDirectoryEntry, - DeviceDirectoryState, - WorkspaceDirectoryStatus -} from '../state/DeviceDirectoryState'; -import { - SessionListInputs, - SessionListProjection, - SessionListProjectionCache -} from '../policy/SessionListProjection'; -import { ConversationSessionFilterPolicy } from '../policy/ConversationSessionFilterPolicy'; -import { SidebarDirectoryPreviewPolicy } from '../policy/SidebarDirectoryPreviewPolicy'; -import { HarnessProfileMenu } from './HarnessProfileMenu'; -import { - SIDEBAR_INK, - SIDEBAR_MUTED, - SIDEBAR_SELECTION, - STATUS_SUCCESS, - TRANSPARENT, -} from './Theme'; - -/** - * One keyed disclosure boundary per workspace. Disclosure and request state - * live on DeviceDirectoryEntry so navigation can rebuild this component without - * collapsing the branch or forgetting an in-flight lazy load. - */ -@ComponentV2 -struct SidebarWorkspaceGroup { - @Param sshHost: string = ''; - @Param connectionId: string = ''; - /** Stable record ID of this row; empty only for rows from pre-ID hosts. */ - @Param workspaceId: string = ''; - @Param workspaceKind: string = 'normal'; - @Event onWorkspaceTools: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - @Param deviceId: string = ''; - @Param path: string = ''; - @Param name: string = ''; - @Param sessions: RemoteSession[] = []; - @Param selectedSessionId: string = ''; - @Param runningSessionId: string = ''; - @Param currentWorkspace: boolean = false; - @Param activeDevice: boolean = false; - @Param bodyIndent: number = 10; - @Param expanded: boolean = false; - @Param loadStatus: WorkspaceDirectoryStatus = 'idle'; - @Param hasLoadedSessions: boolean = false; - @Param supportsHarnessProfiles: boolean = false; - @Event onOpenWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = (_path: string) => {}; - @Event onExpandWorkspace: (path: string) => Promise = async (_path: string) => {}; - @Event onExpandedChange: (path: string, expanded: boolean) => void = - (_path: string, _expanded: boolean) => {}; - @Event onCreateInWorkspace: (path: string, agentType: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = - (_path: string, _agentType: string) => {}; - @Event onOpenSession: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onSessionActions: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Local visibleSessionCount: number = SidebarDirectoryPreviewPolicy.PREVIEW_COUNT; - @Local showCreateMenu: boolean = false; - - // Keyed rows keep their identity; resolve their content from the latest snapshot. - @Computed - get sessionIndex(): Map { - const index = new Map(); - this.sessions.forEach((item: RemoteSession) => { index.set(`${item.deviceId || ''}:${item.id}`, item); }); - return index; - } - - private currentSession(item: RemoteSession): RemoteSession { - return this.sessionIndex.get(`${item.deviceId || ''}:${item.id}`) || item; - } - - private workspaceIdOrUndefined(): string | undefined { - return this.workspaceId.length > 0 ? this.workspaceId : undefined; - } - - build() { - Column() { - this.WorkspaceRow() - if (this.expanded) { - if (this.loadStatus === 'loading' && !this.hasLoadedSessions && this.sessions.length === 0) { - this.SessionLoadingRow() - } else if (this.loadStatus === 'failed') { - this.SessionRetryRow() - } - ForEach(this.visibleSessions(), (row: RemoteSession) => { - this.SessionRow(row) - }, (item: RemoteSession): string => `${item.deviceId || this.deviceId}:${item.id}`) - if (this.hiddenSessionCount() > 0) { - this.MoreSessionsRow() - } - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - .margin({ bottom: 6 }) - } - - @Builder - private WorkspaceRow() { - Row({ space: 6 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.expanded ? - $r('sys.symbol.chevron_down') : $r('sys.symbol.chevron_right')) - .fontSize(13) - .fontColor([SIDEBAR_MUTED]) - .hitTestBehavior(HitTestMode.None) - } - .width(24) - .height(54) - .accessibilityText(this.expanded ? - RemoteI18n.t('chat.showLess') : RemoteI18n.t('chat.showMore')) - .onClick(() => { - void this.toggleExpanded(); - }) - - Row({ space: 10 }) { - SymbolGlyph($r('sys.symbol.folder')) - .fontSize(19) - .fontColor([this.currentWorkspace ? SIDEBAR_INK : SIDEBAR_MUTED]) - .width(21) - .height(21) - .hitTestBehavior(HitTestMode.None) - Column({ space: 2 }) { - Text(this.workspaceLabel()) - .fontSize(MobileDesignTypography.titleSmall.size) - .fontWeight(this.currentWorkspace ? FontWeight.Medium : FontWeight.Regular) - .fontColor(SIDEBAR_INK) - .width('100%') - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .wordBreak(WordBreak.BREAK_ALL) - .hitTestBehavior(HitTestMode.None) - if (this.sshHost.trim().length > 0) { - Text(this.sshHost.trim()) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - .width('100%') - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .hitTestBehavior(HitTestMode.None) - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .layoutWeight(1) - .height(54) - .alignItems(VerticalAlign.Center) - .onClick(() => { - void this.toggleExpanded(); - }) - .gesture(LongPressGesture({ repeat: false }).onAction(() => { - this.onOpenWorkspace(this.path, this.connectionId, this.sshHost, this.workspaceIdOrUndefined()); - })) - - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.plus')) - .fontSize(17) - .fontColor([SIDEBAR_INK]) - .hitTestBehavior(HitTestMode.None) - } - .width(30) - .height(40) - .accessibilityText(RemoteI18n.t('sidebar.newInWorkspace')) - .bindPopup(this.showCreateMenu, { - builder: () => { - this.CreateModeMenu() - }, - placement: Placement.Top, - popupColor: TRANSPARENT, - enableArrow: false, - autoCancel: true, - mask: false, - targetSpace: 6, - onStateChange: (event) => { - if (!event.isVisible) { - this.showCreateMenu = false; - } - } - }) - .onClick(() => { - if (this.workspaceKind === 'assistant') { - this.showCreateMenu = false; - this.onCreateInWorkspace(this.path, 'claw', this.connectionId, this.sshHost, this.workspaceIdOrUndefined()); - } else { - this.showCreateMenu = !this.showCreateMenu; - } - }) - } - .width('100%') - .height(54) - .padding({ left: Math.max(0, this.bodyIndent - 4), right: 6 }) - .alignItems(VerticalAlign.Center) - .borderRadius(10) - } - - @Builder - private CreateModeMenu() { - HarnessProfileMenu({ showTitle: false, onSelect: (agentType: string) => { - this.showCreateMenu = false; - this.onCreateInWorkspace(this.path, agentType, this.connectionId, this.sshHost, this.workspaceIdOrUndefined()); - } }) - } - - @Builder - private SessionLoadingRow() { - Row({ space: 8 }) { - LoadingProgress() - .width(13) - .height(13) - .color(SIDEBAR_MUTED) - Text(RemoteI18n.t('common.loading')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - } - .width('100%') - .height(40) - .padding({ left: this.bodyIndent + 34, right: 10 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - private SessionRetryRow() { - Row({ space: 8 }) { - Text(RemoteI18n.t('sidebar.deviceLoadFailed')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - .layoutWeight(1) - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_INK) - } - .width('100%') - .height(40) - .padding({ left: this.bodyIndent + 34, right: 10 }) - .alignItems(VerticalAlign.Center) - .onClick(() => { - void this.loadSessions(); - }) - } - - @Builder - private SessionRow(row: RemoteSession) { - Row({ space: 8 }) { - Stack({ alignContent: Alignment.BottomStart }) { - SymbolGlyph(this.sessionGlyph(this.currentSession(row))) - .fontSize(17) - .fontColor([SIDEBAR_MUTED]) - .width(19) - .height(19) - if (this.activeDevice && this.currentSession(row).id === this.runningSessionId) { - Text('') - .width(7) - .height(7) - .backgroundColor(STATUS_SUCCESS) - .borderRadius(4) - } - } - .width(19) - .height(19) - Text(this.currentSession(row).title || RemoteI18n.t('sidebar.untitled')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(this.currentSession(row).id === this.selectedSessionId ? FontWeight.Bold : FontWeight.Regular) - .fontColor(SIDEBAR_INK) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .wordBreak(WordBreak.BREAK_ALL) - } - .width('100%') - .height(44) - .padding({ left: this.bodyIndent + 34, right: 10 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.currentSession(row).id === this.selectedSessionId ? SIDEBAR_SELECTION : TRANSPARENT) - .borderRadius(10) - .onClick(() => { - this.onOpenSession(this.currentSession(row)); - }) - .gesture(LongPressGesture({ repeat: false }).onAction(() => { - this.onSessionActions(this.currentSession(row)); - })) - } - - @Builder - private MoreSessionsRow() { - Row({ space: 8 }) { - Text('···') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - Text(RemoteI18n.f('sidebar.moreSessions', String(this.hiddenSessionCount()))) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - } - .width('100%') - .height(40) - .padding({ left: this.bodyIndent + 34 }) - .alignItems(VerticalAlign.Center) - .onClick(() => { - this.visibleSessionCount = SidebarDirectoryPreviewPolicy.nextVisibleCount( - this.visibleSessionCount, - this.sessions.length - ); - }) - } - - private visibleSessions(): RemoteSession[] { - return SidebarDirectoryPreviewPolicy.visibleSlice(this.sessions, this.visibleSessionCount); - } - - private async toggleExpanded(): Promise { - const expanded = !this.expanded; - this.onExpandedChange(this.path, expanded); - if (!expanded || this.sessions.length > 0 || this.loadStatus === 'ready' || - this.loadStatus === 'loading') { - return; - } - await this.loadSessions(); - } - - private async loadSessions(): Promise { - try { - await this.onExpandWorkspace(this.path); - } catch (_err) { - // The request owner records failure without clearing cached rows. - } - } - - private hiddenSessionCount(): number { - return SidebarDirectoryPreviewPolicy.hiddenCount(this.sessions.length, this.visibleSessionCount); - } - - private sessionGlyph(item: RemoteSession): Resource { - const agentType = (item.agentType ? item.agentType : '').toLowerCase(); - if (agentType === 'code') { - return $r('sys.symbol.code_square'); - } - if (agentType === 'claw' || agentType === 'assistant' || agentType === 'chat') { - return $r('sys.symbol.message'); - } - return $r('sys.symbol.doc_text'); - } - - private basename(path: string): string { - const normalized = path.replace(/\/+$/, ''); - const index = normalized.lastIndexOf('/'); - return index >= 0 ? normalized.substring(index + 1) : normalized; - } - - private workspaceLabel(): string { - const path = this.path.trim(); - if (path === '/' && this.workspaceKind.toLowerCase() === 'remote') { - return RemoteI18n.t('sidebar.browseRemoteRoot'); - } - const value = this.name.trim(); - const host = this.sshHost.trim(); - const connection = this.connectionId.trim(); - if (value.length > 0 && value !== host && value !== connection) { - return value; - } - return this.basename(path); - } -} - -/** - * One desktop's workspaces and sessions. - * - * The projection cache is a single slot whose key includes the current - * workspace path, so one instance cannot serve two devices without missing - * every rebuild. Its parent therefore keys this component boundary by device. - */ -@ComponentV2 -export struct SidebarDeviceGroup { - @Event onWorkspaceTools: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - @Param device: DeviceDirectoryEntry = new DeviceDirectoryEntry(); - @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param sessions: RemoteSession[] = []; - @Param workspaceName: string = ''; - @Param workspacePath: string = ''; - @Param workspaceConnectionId: string = ''; - @Param workspaceSshHost: string = ''; - /** Stable record ID of the desktop's active workspace; empty for pre-ID hosts. */ - @Param workspaceId: string = ''; - @Param workspaceKind: string = 'normal'; - @Param selectedSessionId: string = ''; - @Param runningSessionId: string = ''; - @Param query: string = ''; - @Param isActive: boolean = false; - @Param supportsHarnessProfiles: boolean = false; - @Event onRetry: () => void = () => {}; - @Event onOpenSession: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onSessionActions: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onCreateInWorkspace: (path: string, agentType: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = - (_path: string, _agentType: string) => {}; - @Event onOpenWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = (_path: string) => {}; - @Event onExpandWorkspace: (path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string) => Promise = async (_path: string) => {}; - @Event onWorkspaceExpandedChange: (path: string, expanded: boolean, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string) => void = - (_path: string, _expanded: boolean) => {}; - @Local visibleWorkspaceCount: number = SidebarDirectoryPreviewPolicy.PREVIEW_COUNT; - private readonly projectionCache: SessionListProjectionCache = new SessionListProjectionCache(); - - // Keyed rows keep their identity; resolve their content from the latest snapshot. - @Computed - get workspaceIndex(): Map { - const index = new Map(); - this.device.workspaces.forEach((item: RecentWorkspaceEntry) => { index.set(remoteWorkspaceKey(item), item); }); - return index; - } - - private currentWorkspace(item: RecentWorkspaceEntry): RecentWorkspaceEntry { - return this.workspaceIndex.get(remoteWorkspaceKey(item)) || item; - } - - @Computed - get deviceSessions(): RemoteSession[] { - return this.isActive ? RemoteUiState.mergeSessions(this.sessions, this.device.sessions) : this.device.sessions; - } - - build() { - Column() { - if (this.device.status === 'failed') { - this.FailedRow() - } else if (this.workspaceEntries().length === 0) { - if (this.device.status === 'ready') { - this.EmptyWorkspaces() - } else if (this.device.status === 'cached') { - this.EmptyWorkspaces() - } else { - this.LoadingRow() - } - } else { - ForEach(this.visibleWorkspaceEntries(), (row: RecentWorkspaceEntry) => { - SidebarWorkspaceGroup({ - connectionId: this.currentWorkspace(row).remoteConnectionId || '', - sshHost: this.currentWorkspace(row).remoteSshHost || '', - workspaceId: this.currentWorkspace(row).workspaceId || '', - workspaceKind: this.currentWorkspace(row).workspaceKind || 'normal', - onWorkspaceTools: this.onWorkspaceTools, - deviceId: this.device.deviceId, - path: this.currentWorkspace(row).path, - // The device row already identifies the remote host. Keep the - // workspace row focused on the workspace name instead of appending - // an IP address to it. - name: this.currentWorkspace(row).name, - sessions: this.sessionsFor(this.currentWorkspace(row)), - selectedSessionId: this.selectedSessionId, - runningSessionId: this.runningSessionId, - currentWorkspace: this.isCurrentWorkspace(this.currentWorkspace(row)), - activeDevice: this.isActive, - supportsHarnessProfiles: this.supportsHarnessProfiles, - bodyIndent: 10, - expanded: this.directoryState.workspaceExpanded( - this.device.deviceId, this.currentWorkspace(row).path, this.currentWorkspace(row).remoteConnectionId, this.currentWorkspace(row).remoteSshHost, this.currentWorkspace(row).workspaceId), - loadStatus: this.directoryState.workspaceStatus( - this.device.deviceId, this.currentWorkspace(row).path, this.currentWorkspace(row).remoteConnectionId, this.currentWorkspace(row).remoteSshHost, this.currentWorkspace(row).workspaceId), - hasLoadedSessions: this.directoryState.workspaceHasLoadedSessions( - this.device.deviceId, this.currentWorkspace(row).path, this.currentWorkspace(row).remoteConnectionId, this.currentWorkspace(row).remoteSshHost, this.currentWorkspace(row).workspaceId), - onOpenWorkspace: this.onOpenWorkspace, - onExpandWorkspace: (path: string): Promise => - this.onExpandWorkspace(path, this.currentWorkspace(row).remoteConnectionId, this.currentWorkspace(row).remoteSshHost, this.currentWorkspace(row).workspaceId), - onExpandedChange: (path: string, expanded: boolean): void => - this.onWorkspaceExpandedChange(path, expanded, this.currentWorkspace(row).remoteConnectionId, this.currentWorkspace(row).remoteSshHost, this.currentWorkspace(row).workspaceId), - onCreateInWorkspace: this.onCreateInWorkspace, - onOpenSession: this.onOpenSession, - onSessionActions: this.onSessionActions - }) - }, (entry: RecentWorkspaceEntry): string => `${this.device.deviceId}:${remoteWorkspaceKey(entry)}`) - if (this.hiddenWorkspaceCount() > 0) { - this.MoreWorkspacesRow() - } - if (this.device.status === 'loading') { - this.LoadingRow() - } - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - - @Builder - private LoadingRow() { - Row({ space: 8 }) { - LoadingProgress() - .width(14) - .height(14) - .color(SIDEBAR_MUTED) - Text(RemoteI18n.t('common.loading')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - } - .width('100%') - .height(40) - .padding({ left: 10, right: 10 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - private FailedRow() { - Row({ space: 8 }) { - Text(this.device.errorText.length > 0 ? - this.device.errorText : RemoteI18n.t('sidebar.deviceLoadFailed')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - .layoutWeight(1) - Text(RemoteI18n.t('common.retry')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_INK) - .onClick(() => { - this.onRetry(); - }) - } - .width('100%') - .height(40) - .padding({ left: 10, right: 10 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - private EmptyWorkspaces() { - Text(RemoteI18n.t('sidebar.emptyWorkspaces')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(SIDEBAR_MUTED) - .width('100%') - .padding({ left: 10, top: 6, bottom: 6 }) - } - - @Builder - private MoreWorkspacesRow() { - Row({ space: 8 }) { - Text('···') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - Text(RemoteI18n.f('sidebar.moreWorkspaces', String(this.hiddenWorkspaceCount()))) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - } - .width('100%') - .height(40) - .padding({ left: 10 }) - .alignItems(VerticalAlign.Center) - .onClick(() => { - this.visibleWorkspaceCount = SidebarDirectoryPreviewPolicy.nextVisibleCount( - this.visibleWorkspaceCount, - this.workspaceEntries().length - ); - }) - } - - private projection(): SessionListProjection { - const inputs: SessionListInputs = { - sessions: this.deviceSessions, - query: this.query, - sortMode: 'project', - workspaceName: this.workspaceName, - workspacePath: this.workspacePath, - workspaceId: this.workspaceId, - workspaceConnectionId: this.workspaceConnectionId, - workspaceSshHost: this.workspaceSshHost, - workspaceKind: this.workspaceKind, - recentWorkspaces: this.device.workspaces, - workspaceFilter: '', - agentFilter: '', - statusFilter: '', - showWorkspaceMetadata: false, - showUpdatedMetadata: false, - showStatusMetadata: false - }; - return this.projectionCache.get(inputs); - } - - private workspaceEntries(): RecentWorkspaceEntry[] { - // Device catalog membership is authoritative, even when empty. Selection - // and historical sessions cannot reopen a workspace in the sidebar. - // Read the traced catalog at the rendering boundary. A separate array - // parameter forwarded through the keyed parent builder can still contain - // the handshake's empty snapshot when this device becomes ready. - const entries = this.device.workspaces.slice(); - const query = this.query.trim().toLowerCase(); - if (query.length === 0) { - return entries; - } - return entries.filter((entry: RecentWorkspaceEntry): boolean => { - const label = (entry.name || this.basename(entry.path)).toLowerCase(); - return label.indexOf(query) >= 0 || entry.path.toLowerCase().indexOf(query) >= 0 || - this.sessionsFor(entry).length > 0; - }); - } - - private visibleWorkspaceEntries(): RecentWorkspaceEntry[] { - return SidebarDirectoryPreviewPolicy.visibleSlice( - this.workspaceEntries(), - this.visibleWorkspaceCount - ); - } - - private hiddenWorkspaceCount(): number { - return SidebarDirectoryPreviewPolicy.hiddenCount( - this.workspaceEntries().length, - this.visibleWorkspaceCount - ); - } - - private sessionsFor(entry: RecentWorkspaceEntry): RemoteSession[] { - return this.projection().filtered.filter((item: RemoteSession): boolean => - remoteSessionBelongsToWorkspace(item, entry, this.device.workspaces)); - } - - private isCurrentWorkspace(entry: RecentWorkspaceEntry): boolean { - if (!this.isActive || entry.path.length === 0) { - return false; - } - const current: RemoteWorkspaceIdentity = { - workspaceId: this.workspaceId.length > 0 ? this.workspaceId : undefined, - path: this.workspacePath, - remoteConnectionId: this.workspaceConnectionId.length > 0 ? this.workspaceConnectionId : undefined, - remoteSshHost: this.workspaceSshHost.length > 0 ? this.workspaceSshHost : undefined - }; - return remoteWorkspaceIdentityMatches(entry, current, this.device.workspaces); - } - - private basename(path: string): string { - const normalized = path.replace(/\/+$/, ''); - const index = normalized.lastIndexOf('/'); - return index >= 0 ? normalized.substring(index + 1) : normalized; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarGlyphs.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarGlyphs.ets deleted file mode 100644 index fc1b3b1ae5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarGlyphs.ets +++ /dev/null @@ -1,152 +0,0 @@ -import { SIDEBAR_INK, SIDEBAR_MUTED, SIDEBAR_RAISED, STATUS_SUCCESS } from './Theme'; -import { TemplateIcon } from './TemplateIcon'; - -@ComponentV2 -export struct SidebarGlyph { - @Param kind: string = ''; - @Param connectionState: string = ''; - @Param tint: ResourceColor = SIDEBAR_INK; - - build() { - if (this.kind === 'session_more') { - this.MoreDots() - } else if (this.kind === 'remote') { - this.Remote() - } else if (this.kind === 'search') { - this.Search() - } else if (this.kind === 'notebook') { - this.Notebook() - } else if (this.kind === 'clock') { - this.Clock() - } else if (this.kind === 'apps') { - this.Apps() - } else if (this.kind === 'code_flower') { - this.CodeFlower() - } else if (this.kind === 'more') { - this.More() - } else if (this.kind === 'edit') { - this.Edit() - } else if (this.kind === 'settings') { - this.Settings() - } - } - - @Builder - private MoreDots() { - Row({ space: 3 }) { - Text('').width(3.5).height(3.5).backgroundColor(SIDEBAR_MUTED).borderRadius(2) - Text('').width(3.5).height(3.5).backgroundColor(SIDEBAR_MUTED).borderRadius(2) - Text('').width(3.5).height(3.5).backgroundColor(SIDEBAR_MUTED).borderRadius(2) - } - .height(8) - .alignItems(VerticalAlign.Center) - } - - @Builder - private Remote() { - Stack({ alignContent: Alignment.Center }) { - if (this.connectionState === 'connected' || this.connectionState === 'reconnecting') { - TemplateIcon({ src: $r('app.media.remote_ref_sidebar_connected'), iconWidth: 35, iconHeight: 34 }) - Text('').width(8).height(8).backgroundColor(STATUS_SUCCESS).borderRadius(4) - .position({ x: 24, y: 22 }) - } else { - TemplateIcon({ src: $r('app.media.remote_logo'), iconWidth: 34, iconHeight: 34, tint: SIDEBAR_MUTED }) - } - } - .width(35).height(34) - } - - @Builder - private Search() { - SymbolGlyph($r('sys.symbol.magnifyingglass')) - .fontSize(22).fontColor([SIDEBAR_INK]).width(24).height(24) - } - - @Builder - private Notebook() { - Stack() { - Text('').width(22).height(24).borderRadius(5).border({ width: 1.5, color: SIDEBAR_INK }) - .position({ x: 8, y: 5 }) - Text('').width(4).height(4).borderRadius(2).backgroundColor(SIDEBAR_INK) - .position({ x: 5, y: 11 }) - Text('').width(4).height(4).borderRadius(2).backgroundColor(SIDEBAR_INK) - .position({ x: 5, y: 20 }) - } - .width(34).height(34) - } - - @Builder - private Clock() { - Stack() { - Text('').width(26).height(26).borderRadius(13).border({ width: 1.5, color: SIDEBAR_INK }) - .position({ x: 4, y: 4 }) - Text('').width(1.5).height(9).backgroundColor(SIDEBAR_INK).borderRadius(2) - .position({ x: 18, y: 10 }) - Text('').width(9).height(1.5).backgroundColor(SIDEBAR_INK).borderRadius(2) - .position({ x: 18, y: 20 }) - } - .width(34).height(34) - } - - @Builder - private Apps() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.square_grid_2x2')) - .fontSize(24) - .fontColor([this.tint]) - } - .width(24).height(24) - } - - @Builder - private CodeFlower() { - Stack() { - Text('').width(16).height(16).borderRadius(8).border({ width: 1.5, color: SIDEBAR_INK }) - .backgroundColor(SIDEBAR_RAISED).position({ x: 9, y: 1 }) - Text('').width(16).height(16).borderRadius(8).border({ width: 1.5, color: SIDEBAR_INK }) - .backgroundColor(SIDEBAR_RAISED).position({ x: 17, y: 9 }) - Text('').width(16).height(16).borderRadius(8).border({ width: 1.5, color: SIDEBAR_INK }) - .backgroundColor(SIDEBAR_RAISED).position({ x: 9, y: 17 }) - Text('').width(16).height(16).borderRadius(8).border({ width: 1.5, color: SIDEBAR_INK }) - .backgroundColor(SIDEBAR_RAISED).position({ x: 1, y: 9 }) - Text('').width(14).height(14).borderRadius(7).backgroundColor(SIDEBAR_RAISED) - .position({ x: 10, y: 10 }) - } - .width(34).height(34) - } - - @Builder - private More() { - Row({ space: 5 }) { this.Dot(); this.Dot(); this.Dot(); } - .width(30).height(22) - .justifyContent(FlexAlign.Center) - .alignItems(VerticalAlign.Center) - } - - @Builder - private Dot() { - Text('').width(5).height(5).borderRadius(3).backgroundColor(SIDEBAR_INK) - } - - @Builder - private Edit() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.square_and_pencil')) - .fontSize(20) - .fontColor([this.tint]) - } - .width(22) - .height(22) - } - - @Builder - private Settings() { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.gearshape')) - .fontSize(24) - .fontColor([this.tint]) - } - .width(26) - .height(26) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarNavigationIcons.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarNavigationIcons.ets deleted file mode 100644 index 726de9139d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarNavigationIcons.ets +++ /dev/null @@ -1,85 +0,0 @@ -import { SIDEBAR_INK, SIDEBAR_MUTED } from './Theme'; -import { TemplateIcon } from './TemplateIcon'; - -/** Desktop-provided device artwork normalized as a theme-tinted template icon. */ -@ComponentV2 -export struct SidebarDeviceIcon { - @Param deviceName: string = ''; - @Param iconSize: number = 24; - @Param tint: ResourceColor = SIDEBAR_INK; - - build() { - Stack({ alignContent: Alignment.Center }) { - TemplateIcon({ - src: this.deviceResource(), - iconWidth: this.deviceIconWidth(), - iconHeight: this.iconSize, - tint: this.tint - }) - .translate({ - x: this.deviceOpticalOffsetX(), - y: this.deviceOpticalOffsetY() - }) - } - .width(this.iconSize + 8) - .height(this.iconSize + 4) - } - - private deviceResource(): Resource { - const normalizedName = this.deviceName.trim().toLowerCase(); - if (normalizedName.includes('macbook') || normalizedName.includes('laptop') || - normalizedName.includes('notebook')) { - return $r('app.media.sidebar_device_laptop'); - } - if (normalizedName.includes('server') || normalizedName.includes('ecs') || - normalizedName.includes('host')) { - return $r('app.media.sidebar_device_server'); - } - return $r('app.media.sidebar_device_desktop'); - } - - private deviceIconWidth(): number { - const normalizedName = this.deviceName.trim().toLowerCase(); - if (normalizedName.includes('server') || normalizedName.includes('ecs') || - normalizedName.includes('host')) { - return this.iconSize + 8; - } - return this.iconSize + 4; - } - - // The laptop and server artwork has asymmetric transparent padding. Keep the - // row's layout slot stable and compensate only the visible glyph's center. - private deviceOpticalOffsetX(): number { - const normalizedName = this.deviceName.trim().toLowerCase(); - if (normalizedName.includes('server') || normalizedName.includes('ecs') || - normalizedName.includes('host')) { - return -3; - } - return 0; - } - - private deviceOpticalOffsetY(): number { - const normalizedName = this.deviceName.trim().toLowerCase(); - if (normalizedName.includes('macbook') || normalizedName.includes('laptop') || - normalizedName.includes('notebook') || normalizedName.includes('server') || - normalizedName.includes('ecs') || normalizedName.includes('host')) { - return 2; - } - return 0; - } -} - -/** HarmonyOS disclosure symbol kept in a stable slot by the caller. */ -@ComponentV2 -export struct SidebarChevronIcon { - @Param expanded: boolean = false; - @Param iconSize: number = 14; - @Param tint: ResourceColor = SIDEBAR_MUTED; - - build() { - SymbolGlyph(this.expanded ? - $r('sys.symbol.chevron_down') : $r('sys.symbol.chevron_right')) - .fontSize(this.iconSize) - .fontColor([this.tint]) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToggleButton.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToggleButton.ets deleted file mode 100644 index 341d421f9c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToggleButton.ets +++ /dev/null @@ -1,56 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - CARD, - INK, - LINE, - MUTED, - SHADOW_SUBTLE, - TRANSPARENT, -} from './Theme'; - -@ComponentV2 -export struct SidebarToggleButton { - @Param restore: boolean = false; - @Param controlSize: number = 44; - @Event onToggle: () => void = () => {}; - - build() { - Stack({ alignContent: Alignment.Center }) { - Row() { - Text('') - .width(6) - .height(14) - .backgroundColor(INK) - .opacity(0.18) - .borderRadius({ topLeft: 2, bottomLeft: 2 }) - Divider() - .vertical(true) - .height(14) - .color(INK) - .opacity(0.7) - Blank() - .layoutWeight(1) - } - .width(20) - .height(18) - .padding({ left: 2, right: 2 }) - .alignItems(VerticalAlign.Center) - .border({ width: 1.5, color: INK }) - .borderRadius(3) - } - .width(this.controlSize) - .height(this.controlSize) - .backgroundColor(this.restore ? CARD : TRANSPARENT) - .border({ width: this.restore ? 1 : 0, color: LINE }) - .borderRadius(this.restore ? this.controlSize / 2 : 8) - .shadow({ - radius: this.restore ? 14 : 0, - color: this.restore ? SHADOW_SUBTLE : TRANSPARENT, - offsetY: this.restore ? 5 : 0 - }) - .accessibilityText(RemoteI18n.t(this.restore ? 'sidebar.restore' : 'sidebar.collapse')) - .onClick(() => { - this.onToggle(); - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToolsFooter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToolsFooter.ets deleted file mode 100644 index d8b1db08d0..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarToolsFooter.ets +++ /dev/null @@ -1,60 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { SIDEBAR_INK, SIDEBAR_LINE, SIDEBAR_RAISED } from './Theme'; - -/** Pure navigation controls reused in compact and wide sidebars. */ -@ComponentV2 -export struct SidebarToolsFooter { - @Param toolsEnabled: boolean = false; - @Event onOpenTools: () => void = () => {}; - @Event onOpenSettings: () => void = () => {}; - - build() { - Row() { - Button() { - Row({ space: 8 }) { - Stack() { - SymbolGlyph($r('sys.symbol.wrench_and_screwdriver')) - .fontSize(20) - .fontColor([SIDEBAR_INK]) - }.width(24).height(24) - Text(RemoteI18n.t('workspaceTools.title')) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Medium) - .fontColor(SIDEBAR_INK) - .maxLines(1) - } - } - .constraintSize({ minWidth: 104 }) - .height(48) - .padding({ left: 14, right: 14 }) - .backgroundColor(SIDEBAR_RAISED) - .border({ width: 0.5, color: SIDEBAR_LINE }) - .borderRadius(24) - .enabled(this.toolsEnabled) - .opacity(this.toolsEnabled ? 1 : 0.45) - .accessibilityText(RemoteI18n.t('workspaceTools.title')) - .stateEffect(true) - .onClick(() => this.onOpenTools()) - Blank() - Button() { - SymbolGlyph($r('sys.symbol.gearshape')) - .fontSize(20) - .fontColor([SIDEBAR_INK]) - } - .width(48) - .height(48) - .padding(0) - .backgroundColor(SIDEBAR_RAISED) - .borderRadius(24) - .accessibilityText(RemoteI18n.t('settings.title')) - .stateEffect(true) - .onClick(() => this.onOpenSettings()) - } - .width('100%') - .height(56) - .padding({ left: 12 }) - .alignItems(VerticalAlign.Center) - .zIndex(2) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspacePicker.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspacePicker.ets deleted file mode 100644 index 89f843bb37..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspacePicker.ets +++ /dev/null @@ -1,385 +0,0 @@ -import { WorkspaceToolsState, WorkspaceToolsIntent, WorkspaceFileEntry } from '../state/WorkspaceToolsState'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { SavedRuntimeConnection, RecentWorkspaceEntry, RemoteWorkspaceIdentity } from '../../model/RemoteModels'; -import { remoteWorkspaceIdentityMatches, remoteWorkspaceKey } from '../../services/RemoteSessionIdentity'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CARD, CONTENT_ON_ACTION, CONTENT_ON_INK, INK, LINE, MUTED, PAGE_BG, PRIMARY_ACTION, SOFT, TRANSPARENT } from './Theme'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; - -@ComponentV2 -export struct SidebarWorkspacePicker { - @Local browsing: boolean = false; - @Param tools: WorkspaceToolsState = new WorkspaceToolsState(); - @Param canBrowse: boolean = false; - @Event onBrowse: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - @Local targetPath: string = ''; - @Local connectionId: string = ''; - @Param savedConnections: SavedRuntimeConnection[] = []; - @Param deviceName: string = ''; - @Param workspaces: RecentWorkspaceEntry[] = []; - @Param selectedWorkspacePath: string = ''; - /** Identity of the active workspace; the ID wins over the path when present. */ - @Param selectedWorkspaceId: string = ''; - @Param selectedWorkspaceConnectionId: string = ''; - @Param selectedWorkspaceSshHost: string = ''; - @Param loading: boolean = false; - @Event onClose: () => void = () => {}; - /** - * The sheet's own bottom edge, in vp. The picker is a full-height sheet and - * its confirm button is the fixed control at that edge, so the button keeps - * the navigation bar clear itself. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - /** - * Catalog rows report their stable `workspaceId`; the manual path entry has - * none, which is the only case where the host may resolve by path. - */ - @Event onSelectWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = - (_path: string, _connectionId?: string) => {}; - - // Keyed rows keep their identity; resolve their content from the latest snapshot. - @Computed - get workspaceIndex(): Map { - const index = new Map(); - this.workspaces.forEach((item: RecentWorkspaceEntry) => { index.set(remoteWorkspaceKey(item), item); }); - return index; - } - - private currentWorkspace(item: RecentWorkspaceEntry): RecentWorkspaceEntry { - return this.workspaceIndex.get(remoteWorkspaceKey(item)) || item; - } - - private isSelected(workspace: RecentWorkspaceEntry): boolean { - if (this.selectedWorkspacePath.length === 0 && this.selectedWorkspaceId.length === 0) { - return false; - } - const selected: RemoteWorkspaceIdentity = { - workspaceId: this.selectedWorkspaceId.length > 0 ? this.selectedWorkspaceId : undefined, - path: this.selectedWorkspacePath, - remoteConnectionId: this.selectedWorkspaceConnectionId.length > 0 ? this.selectedWorkspaceConnectionId : undefined, - remoteSshHost: this.selectedWorkspaceSshHost.length > 0 ? this.selectedWorkspaceSshHost : undefined - }; - return remoteWorkspaceIdentityMatches(workspace, selected, this.workspaces); - } - - private connectionOptions(): SelectOption[] { - const options: SelectOption[] = [{ value: this.deviceName }]; - this.savedConnections.forEach((connection: SavedRuntimeConnection) => { options.push({ value: connection.name }); }); - return options; - } - - private selectedConnectionIndex(): number { - if (this.connectionId.length === 0) return 0; - const index = this.savedConnections.findIndex((connection: SavedRuntimeConnection): boolean => connection.id === this.connectionId); - return index >= 0 ? index + 1 : 0; - } - - private visibleWorkspaces(): RecentWorkspaceEntry[] { - if (this.connectionId.length === 0) { - return this.workspaces.filter((item: RecentWorkspaceEntry): boolean => !this.isRemoteRoot(item)) - .concat(this.workspaces.filter((item: RecentWorkspaceEntry): boolean => this.isRemoteRoot(item))); - } - // A saved SSH profile is not a live connection. Do not keep showing the - // host catalog while the selected profile is still probing or unavailable. - if (this.tools.browseBusy || this.tools.browseError.length > 0 || - this.tools.browsePath.length === 0 || this.tools.browseEntries.length === 0) return []; - const connection = this.savedConnections.find((item: SavedRuntimeConnection): boolean => item.id === this.connectionId); - const rows = this.workspaces.filter((item: RecentWorkspaceEntry): boolean => - item.remoteConnectionId === this.connectionId || - (connection !== undefined && connection.host.length > 0 && item.remoteSshHost === connection.host) - ); - // Keep a persisted remote root available for browsing, but put concrete - // project folders first so the root cannot masquerade as the project. - return rows.filter((item: RecentWorkspaceEntry): boolean => !this.isRemoteRoot(item)) - .concat(rows.filter((item: RecentWorkspaceEntry): boolean => this.isRemoteRoot(item))); - } - - private isRemoteRoot(workspace: RecentWorkspaceEntry): boolean { - const path = (workspace.path || '').trim(); - return path === '/' && (workspace.workspaceKind || '').toLowerCase() === 'remote'; - } - - private canOpenTargetPath(): boolean { - const path = this.targetPath.trim(); - return !this.loading && path.length > 0 && !(this.connectionId.length > 0 && path === '/'); - } - - private openRemoteRootForBrowsing(workspace: RecentWorkspaceEntry): void { - const connection = workspace.remoteConnectionId || this.connectionId; - if (connection.length === 0) return; - this.connectionId = connection; - this.targetPath = '/'; - this.browsing = true; - this.onBrowse({ type: 'browse-workspace', path: '/', text: connection }); - } - - private workspaceTitle(workspace: RecentWorkspaceEntry): string { - if (this.isRemoteRoot(workspace)) return RemoteI18n.t('sidebar.browseRemoteRoot'); - return workspace.name || this.basename(workspace.path); - } - - private workspaceSubtitle(workspace: RecentWorkspaceEntry): string { - const connectionId = workspace.remoteConnectionId?.trim() || ''; - const savedConnection = connectionId.length > 0 ? - this.savedConnections.find((connection: SavedRuntimeConnection): boolean => connection.id === connectionId) : undefined; - const remoteLabel = savedConnection?.name?.trim() || workspace.remoteSshHost?.trim() || ''; - return remoteLabel.length > 0 ? `${remoteLabel} · ${workspace.path}` : workspace.path; - } - - private selectConnection(index: number): void { - this.connectionId = index > 0 ? this.savedConnections[index - 1].id : ''; - this.browsing = this.connectionId.length > 0; - if (this.connectionId.length > 0) { - this.targetPath = '/'; - this.onBrowse({ type: 'browse-workspace', path: '/', text: this.connectionId }); - } - } - - build() { - Column({ space: 0 }) { - this.Header() - Divider().color(LINE) - if (this.savedConnections.length > 0 || this.deviceName.length > 0) { - Column({ space: 7 }) { - Text(RemoteI18n.t('sidebar.controlledDevice')).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - Select(this.connectionOptions()) - .selected(this.selectedConnectionIndex()) - .value(this.connectionId.length > 0 ? this.savedConnections.find((connection: SavedRuntimeConnection): boolean => connection.id === this.connectionId)?.name || this.deviceName : this.deviceName) - .fontColor(INK).width('100%').height(54).enabled(!this.loading) - .backgroundColor(CARD).border({ width: 1, color: LINE }).borderRadius(16) - .onSelect((index: number) => this.selectConnection(index)) - }.width('100%').padding({ top: 14, bottom: 12 }) - } - Column({ space: 7 }) { - Text(RemoteI18n.t('sidebar.currentPath')).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.folder')).fontSize(19).fontColor([INK]) - }.width(38).height(38).borderRadius(11).backgroundColor(CARD) - TextInput({ text: this.targetPath, placeholder: RemoteI18n.t('sidebar.targetWorkspacePath') }) - .fontColor(INK).fontSize(MobileDesignTypography.bodySmall.size).layoutWeight(1) - .height(38).padding({ left: 0, right: 0 }).backgroundColor(TRANSPARENT).border({ width: 0, color: TRANSPARENT }) - .onChange((value: string) => { this.targetPath = value; }) - .enabled(!this.loading) - SymbolGlyph($r('sys.symbol.chevron_right')).fontSize(16).fontColor([MUTED]) - }.width('100%').height(64).padding({ left: 12, right: 12 }).backgroundColor(SOFT).borderRadius(16) - }.width('100%').padding({ bottom: 12 }) - Button(RemoteI18n.t('workspaceTools.browse')) - .fontColor(INK).fontSize(MobileDesignTypography.bodySmall.size).height(44).width('100%') - .backgroundColor(SOFT).borderRadius(13).enabled(this.canBrowse && !this.tools.browseBusy && !this.loading) - .onClick(() => { this.browsing = true; this.onBrowse({ type: 'browse-workspace', path: this.targetPath || (this.connectionId.length === 0 ? this.selectedWorkspacePath : '') || '/', text: this.connectionId }); }) - if (this.browsing) { this.FolderBrowser() } - if (this.connectionId.length > 0 && this.targetPath.trim() === '/') { - Text(RemoteI18n.t('sidebar.remoteRootBrowseOnly')) - .fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - .maxLines(2).width('100%').padding({ top: 2 }) - } - Row({ space: 8 }) { - Text(RemoteI18n.t('sidebar.recentWorkspaces')).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size).fontWeight(FontWeight.Medium).layoutWeight(1) - Text(RemoteI18n.t('sidebar.tapToSwitch')).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - }.width('100%').padding({ top: 14, bottom: 7 }) - if ((this.loading || this.tools.browseBusy) && this.visibleWorkspaces().length === 0) { - this.LoadingState() - } else if (this.visibleWorkspaces().length === 0) { - this.EmptyState() - } else { - Scroll() { - Column({ space: 4 }) { - ForEach(this.visibleWorkspaces(), (row: RecentWorkspaceEntry) => { - this.WorkspaceRow(row) - }, (workspace: RecentWorkspaceEntry): string => remoteWorkspaceKey(workspace)) - } - .width('100%') - .padding({ top: 10, bottom: 18 }) - } - .width('100%') - .layoutWeight(1) - .scrollBar(BarState.Off) - } - Row() { - Button(RemoteI18n.t('sidebar.openWorkspacePath')) - .fontColor(CONTENT_ON_ACTION).fontSize(MobileDesignTypography.bodyMedium.size).fontWeight(FontWeight.Medium) - .backgroundColor(PRIMARY_ACTION).height(48).width('100%').borderRadius(14) - .enabled(this.canOpenTargetPath()) - .onClick(() => this.onSelectWorkspace(this.targetPath.trim(), this.connectionId.length > 0 ? this.connectionId : undefined)) - // The sheet's fixed confirm button: the strip, or the design's own - // spacing where the strip is already clear, so it never sits in it. - }.width('100%').padding({ top: 12, bottom: this.insets.bottomPadding(16) }).backgroundColor(PAGE_BG) - } - .width('100%') - .height('100%') - .padding({ left: 18, right: 18, top: 10 }) - .backgroundColor(PAGE_BG) - } - - @Builder - private FolderBrowser() { - Column({ space: 8 }) { - if (this.tools.browseBusy) { - Row({ space: 8 }) { - LoadingProgress().width(18).height(18).color(MUTED) - Text(RemoteI18n.t('common.loading')).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size) - }.width('100%') - } else if (this.tools.browseError.length > 0) { - Text(this.tools.browseError).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size).maxLines(3) - } else { - Text(this.tools.browsePath).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size).maxLines(2) - } - Row({ space: 8 }) { - Button(RemoteI18n.t('workspaceTools.up')) - .fontColor(INK).fontSize(MobileDesignTypography.labelSmall.size).height(40).layoutWeight(1) - .backgroundColor(CARD).border({ width: 1, color: LINE }).borderRadius(12) - .onClick(() => { - const current = this.tools.browsePath.replace(/\/+$/, ''); - this.onBrowse({ type: 'browse-workspace', path: current.slice(0, current.lastIndexOf('/')) || '/', text: this.connectionId }); - }) - Button(RemoteI18n.t('workspaceTools.selectFolder')) - .fontColor(CONTENT_ON_INK).fontSize(MobileDesignTypography.labelSmall.size).height(40).layoutWeight(1) - .backgroundColor(INK).borderRadius(12) - .onClick(() => { this.targetPath = this.tools.browsePath; this.browsing = false; }) - }.enabled(!this.tools.browseBusy && this.tools.browseError.length === 0 && this.tools.browsePath.length > 0) - List() { - ForEach(this.tools.browseEntries, (entry: WorkspaceFileEntry) => { - if (entry.isDirectory) { - ListItem() { Text(entry.name).fontColor(INK).padding(10).width('100%') - .onClick(() => this.onBrowse({ type: 'browse-workspace', path: entry.path, text: this.connectionId })) } - } - }, (entry: WorkspaceFileEntry): string => entry.path) - if (this.tools.browseHasMore) { ListItem() { Button(RemoteI18n.t('workspaceTools.more')).onClick(() => this.onBrowse({ type: 'browse-more', path: this.tools.browsePath, text: this.connectionId })) } } - }.height(200).enabled(!this.tools.browseBusy) - }.width('100%') - } - - @Builder - private Header() { - Row({ space: 12 }) { - Column({ space: 2 }) { - Text(RemoteI18n.t('sidebar.selectWorkspace')) - .width('100%') - .fontSize(MobileDesignTypography.headlineMedium.size) - .fontWeight(FontWeight.Bold) - .fontColor(INK) - Text(this.deviceName) - .width('100%') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.xmark')) - .fontSize(17) - .fontColor([MUTED]) - } - .width(40) - .height(40) - .borderRadius(20) - .backgroundColor(SOFT) - .accessibilityText(RemoteI18n.t('common.close')) - .onClick(() => this.onClose()) - } - .width('100%') - .height(66) - .alignItems(VerticalAlign.Center) - } - - @Builder - private WorkspaceRow(row: RecentWorkspaceEntry) { - Row({ space: 12 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.folder')) - .fontSize(20) - .fontColor([INK]) - } - .width(34) - .height(34) - .borderRadius(10) - .backgroundColor(CARD) - Column({ space: 3 }) { - Text(this.workspaceTitle(this.currentWorkspace(row))) - .width('100%') - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontWeight(this.isSelected(this.currentWorkspace(row)) ? FontWeight.Medium : FontWeight.Regular) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.workspaceSubtitle(this.currentWorkspace(row))) - .width('100%') - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.isRemoteRoot(this.currentWorkspace(row)) ? - $r('sys.symbol.questionmark_circle') : this.isSelected(this.currentWorkspace(row)) ? - $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.chevron_right')) - .fontSize(this.isRemoteRoot(this.currentWorkspace(row)) ? 17 : this.isSelected(this.currentWorkspace(row)) ? 19 : 15) - .fontColor([this.isRemoteRoot(this.currentWorkspace(row)) ? MUTED : this.isSelected(this.currentWorkspace(row)) ? PRIMARY_ACTION : MUTED]) - } - .width(40) - .height(40) - } - .width('100%') - .height(68) - .padding({ left: 10, right: 8 }) - .borderRadius(14) - .backgroundColor(this.isSelected(this.currentWorkspace(row)) ? SOFT : PAGE_BG) - .onClick(() => { - const workspace = this.currentWorkspace(row); - if (this.isRemoteRoot(workspace)) { - this.openRemoteRootForBrowsing(workspace); - } else { - this.onSelectWorkspace(workspace.path, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId); - } - }) - } - - @Builder - private LoadingState() { - Column({ space: 12 }) { - LoadingProgress().width(22).height(22).color(MUTED) - Text(RemoteI18n.t('common.loading')).fontSize(MobileDesignTypography.bodyMedium.size).fontColor(MUTED) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - } - - @Builder - private EmptyState() { - Column({ space: 8 }) { - SymbolGlyph($r('sys.symbol.folder')).fontSize(30).fontColor([MUTED]) - Text(this.connectionId.length > 0 ? RemoteI18n.t('status.remoteUnavailable') : RemoteI18n.t('sidebar.emptyWorkspaces')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) - } - - private basename(path: string): string { - const normalized = path.replace(/\/+$/, ''); - const index = normalized.lastIndexOf('/'); - return index >= 0 ? normalized.substring(index + 1) : normalized; - } -} 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 deleted file mode 100644 index 0145880263..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspaceSection.ets +++ /dev/null @@ -1,479 +0,0 @@ -import { WorkspaceToolsPanel } from './WorkspaceToolsPanel'; -import { WorkspaceToolsState, WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { SavedRuntimeConnection, RecentWorkspaceEntry, RemoteSession } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - DeviceDirectoryEntry, - DeviceDirectoryState, - emptyDeviceDirectoryEntry -} from '../state/DeviceDirectoryState'; -import { SidebarDirectoryPreviewPolicy } from '../policy/SidebarDirectoryPreviewPolicy'; -import { SidebarDeviceProjectionPolicy } from '../policy/SidebarDeviceProjectionPolicy'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { AdaptiveSheetOptions } from './AdaptiveSheetOptions'; -import { - SIDEBAR_INK, - SIDEBAR_MUTED, - SIDEBAR_SELECTION, - SIDEBAR_SUBTLE, - STATUS_DANGER, - STATUS_SUCCESS, - TRANSPARENT, -} from './Theme'; -import { SidebarDeviceGroup } from './SidebarDeviceGroup'; -import { SidebarDeviceIcon } from './SidebarNavigationIcons'; -import { SidebarWorkspacePicker } from './SidebarWorkspacePicker'; -import { ConnectionStatusPresenter } from '../../services/ConnectionStatusPresenter'; - -/** - * Flat device selector followed by the selected device's workspace tree. - * - * Device rows choose the remote context; they no longer each own a nested - * directory. This keeps one visible workspace hierarchy and makes its owner - * explicit without repeating the same tree under every account desktop. - */ -@ComponentV2 -export struct SidebarWorkspaceSection { - @Param workspaceTools: WorkspaceToolsState = new WorkspaceToolsState(); - @Event onWorkspaceTools: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param sessions: RemoteSession[] = []; - @Param savedConnections: SavedRuntimeConnection[] = []; - @Param savedConnectionsTargetId: string = ''; - @Param recentWorkspaces: RecentWorkspaceEntry[] = []; - @Param workspaceName: string = ''; - @Param workspacePath: string = ''; - @Param workspaceConnectionId: string = ''; - @Param workspaceSshHost: string = ''; - /** Stable record ID of the active workspace; empty for pre-ID hosts. */ - @Param workspaceId: string = ''; - @Param workspaceKind: string = 'normal'; - @Param connectionState: string = 'idle'; - @Param controlTargetType: string = 'none'; - @Param controlTargetDeviceId: string = ''; - @Param controlTargetDeviceName: string = ''; - @Param selectedSessionId: string = ''; - @Param runningSessionId: string = ''; - @Param query: string = ''; - @Param supportsHarnessProfiles: boolean = false; - @Param workspacePickerPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SessionDetails); - @Event onOpenSession: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onSessionActions: (session: RemoteSession) => void = (_session: RemoteSession) => {}; - @Event onCreateInWorkspace: (deviceId: string, path: string, agentType: string, connectionId?: string, sshHost?: string, - workspaceId?: string) => void = (_deviceId: string, _path: string, _agentType: string) => {}; - @Event onOpenWorkspace: (deviceId: string, path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => void = - (_deviceId: string, _path: string) => {}; - @Event onExpandWorkspace: (deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, - workspaceId?: string) => Promise = async (_deviceId: string, _path: string) => {}; - @Event onSelectDevice: (deviceId: string) => void = (_deviceId: string) => {}; - @Event onReconnect: () => void = () => {}; - @Event onRetryDevice: (deviceId: string) => void = (_deviceId: string) => {}; - @Event onAddWorkspace: (deviceId: string) => void = (_deviceId: string) => {}; - @Event onRefreshDevices: () => Promise = async () => {}; - @Event onAddDevice: () => void = () => {}; - @Local visibleDeviceCount: number = SidebarDirectoryPreviewPolicy.PREVIEW_COUNT; - @Local showWorkspacePicker: boolean = false; - @Local workspacePickerDeviceId: string = ''; - private readonly transientEntry: DeviceDirectoryEntry = emptyDeviceDirectoryEntry('', '', false); - - build() { - Column() { - this.DeviceSectionHeader() - if (this.directoryState.refreshError.length > 0) { - Text(this.directoryState.refreshError) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(STATUS_DANGER) - .width('100%') - .padding({ top: 4, bottom: 8 }) - .onClick(() => { void this.onRefreshDevices(); }) - } - Row() {}.height(0) - .bindSheet($$this.workspaceTools.visible, this.WorkspaceTools(), { height: SheetSize.LARGE, showClose: false, onWillDismiss: (action: DismissSheetAction): void => { - if (this.workspaceTools.dirty) this.onWorkspaceTools({ type: 'close' }); - else { this.onWorkspaceTools({ type: 'close' }); action.dismiss(); } - }, onDisappear: () => this.onWorkspaceTools({ type: 'close' }) }) - if (this.deviceEntries().length > 0) { - ForEach(this.visibleDeviceEntries(), (entry: DeviceDirectoryEntry) => { - this.DeviceRow(entry) - }, (entry: DeviceDirectoryEntry): string => this.deviceKey(entry)) - if (this.visibleDeviceCount < this.deviceEntries().length) { - this.MoreDevicesRow() - } - // The workspace tree owns projection caches and local disclosure state. - // Include the projection source: a transient control target and its - // account directory entry are different observed objects, even when - // they identify the same device. - ForEach(this.selectedEntries(), (entry: DeviceDirectoryEntry) => { - this.WorkspaceSection(entry) - }, (entry: DeviceDirectoryEntry): string => this.deviceKey(entry)) - } - } - .width('100%') - .alignItems(HorizontalAlign.Start) - .margin({ top: 10 }) - .bindSheet($$this.showWorkspacePicker, this.WorkspacePicker(), this.workspacePickerSheetOptions()) - } - - @Builder - private WorkspaceTools() { - WorkspaceToolsPanel({ state: this.workspaceTools, onIntent: this.onWorkspaceTools }) - } - - @Builder - private DeviceSectionHeader() { - Row() { - Text(RemoteI18n.t('sidebar.devices')) - .id('sidebar-workspace-section') - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(SIDEBAR_MUTED) - Blank() - Stack({ alignContent: Alignment.Center }) { - if (this.directoryState.refreshing) { - LoadingProgress() - .width(18) - .height(18) - .color(SIDEBAR_MUTED) - } else { - SymbolGlyph($r('sys.symbol.arrow_clockwise')) - .fontSize(20) - .fontWeight(FontWeight.Medium) - .fontColor([SIDEBAR_MUTED]) - } - } - .width(34) - .height(38) - .enabled(!this.directoryState.refreshing) - .accessibilityText(RemoteI18n.t('common.refresh')) - .onClick(() => { - void this.onRefreshDevices(); - }) - - } - .width('100%') - .height(42) - .alignItems(VerticalAlign.Center) - } - - @Builder - private DeviceRow(entry: DeviceDirectoryEntry) { - Row({ space: 8 }) { - SidebarDeviceIcon({ - deviceName: entry.deviceName, - iconSize: 24, - tint: SIDEBAR_INK - }) - .hitTestBehavior(HitTestMode.None) - Text(entry.displayName) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(this.isSelected(entry) ? FontWeight.Bold : FontWeight.Regular) - .fontColor(SIDEBAR_INK) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .wordBreak(WordBreak.BREAK_ALL) - .hitTestBehavior(HitTestMode.None) - if (entry.status === 'loading') { - LoadingProgress() - .width(13) - .height(13) - .color(SIDEBAR_MUTED) - .hitTestBehavior(HitTestMode.None) - } else { - Text('') - .width(8) - .height(8) - .backgroundColor(this.deviceHealthColor(entry)) - .borderRadius(4) - .hitTestBehavior(HitTestMode.None) - } - } - .width('100%') - .height(52) - .padding({ left: 8, right: 4 }) - .alignItems(VerticalAlign.Center) - .backgroundColor(this.isSelected(entry) ? SIDEBAR_SELECTION : TRANSPARENT) - .borderRadius(10) - .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(() => { - if (this.canRetryDevice(entry)) { - this.onReconnect(); - } else if (this.canUseDevice(entry)) { - this.onSelectDevice(entry.deviceId); - } - }) - } - - private canRetryDevice(entry: DeviceDirectoryEntry): boolean { - return this.isActiveDevice(entry.deviceId) && - (this.connectionState === 'failed' || this.connectionState === 'disconnected'); - } - - private deviceHealthColor(entry: DeviceDirectoryEntry): ResourceColor { - if (!this.isActiveDevice(entry.deviceId)) return entry.online ? STATUS_SUCCESS : SIDEBAR_SUBTLE; - if (this.connectionState === 'connected') return STATUS_SUCCESS; - if (this.connectionState === 'failed' || this.connectionState === 'disconnected') return STATUS_DANGER; - return SIDEBAR_MUTED; - } - - @Builder - private WorkspaceSection(entry: DeviceDirectoryEntry) { - Column() { - Row() { - Text(RemoteI18n.t('sidebar.workspaces')) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(SIDEBAR_MUTED) - Blank() - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.plus')) - .fontSize(18) - .fontColor([this.canUseDevice(entry) ? SIDEBAR_INK : SIDEBAR_SUBTLE]) - } - .width(34) - .height(34) - .opacity(this.canUseDevice(entry) ? 1 : 0.38) - .accessibilityText(RemoteI18n.t('sidebar.addWorkspace')) - .onClick(() => { - if (this.canUseDevice(entry)) { - this.openWorkspacePicker(entry); - } - }) - } - .width('100%') - .height(48) - .margin({ top: 16 }) - .alignItems(VerticalAlign.Center) - - if (entry.catalogSource === 'recent') { - Text(RemoteI18n.t('sidebar.legacyWorkspaceCatalog')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - .padding({ left: 10, right: 10, bottom: 4 }) - } - SidebarDeviceGroup({ - onWorkspaceTools: this.onWorkspaceTools, - device: entry, - directoryState: this.directoryState, - sessions: this.usesLiveDirectory(entry) ? this.sessions : [], - workspaceName: this.liveWorkspaceName(entry), - workspacePath: this.liveWorkspacePath(entry), - workspaceConnectionId: this.isActiveDevice(entry.deviceId) ? this.workspaceConnectionId : '', - workspaceSshHost: this.isActiveDevice(entry.deviceId) ? this.workspaceSshHost : '', - workspaceId: this.isActiveDevice(entry.deviceId) ? this.workspaceId : '', - workspaceKind: this.liveWorkspaceKind(entry), - selectedSessionId: this.selectedSessionIdFor(entry), - runningSessionId: this.isActiveDevice(entry.deviceId) ? this.runningSessionId : '', - query: this.query, - isActive: this.isActiveDevice(entry.deviceId), - supportsHarnessProfiles: this.supportsHarnessProfiles, - onRetry: () => { - if (this.isDirectoryEntry(entry)) { - this.onRetryDevice(entry.deviceId); - } - }, - onOpenSession: this.onOpenSession, - onSessionActions: this.onSessionActions, - onCreateInWorkspace: (path: string, agentType: string, connectionId?: string, sshHost?: string, workspaceId?: string) => { - this.onCreateInWorkspace(entry.deviceId, path, agentType, connectionId, sshHost, workspaceId); - }, - onOpenWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => { - this.onOpenWorkspace(entry.deviceId, path, connectionId, sshHost, workspaceId); - }, - onExpandWorkspace: async (path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): Promise => { - await this.onExpandWorkspace(entry.deviceId, path, remoteConnectionId, remoteSshHost, workspaceId); - }, - onWorkspaceExpandedChange: (path: string, expanded: boolean, remoteConnectionId?: string, remoteSshHost?: string, - workspaceId?: string): void => { - this.directoryState.setWorkspaceExpanded(entry.deviceId, path, expanded, remoteConnectionId, remoteSshHost, workspaceId); - } - }) - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - - @Builder - private MoreDevicesRow() { - Row({ space: 8 }) { - Text('···') - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - Text(RemoteI18n.f('sidebar.moreDevices', - String(this.deviceEntries().length - this.visibleDeviceCount))) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(SIDEBAR_MUTED) - } - .width('100%') - .height(40) - .padding({ left: 10 }) - .alignItems(VerticalAlign.Center) - .onClick(() => { - this.visibleDeviceCount += SidebarDirectoryPreviewPolicy.PREVIEW_COUNT; - }) - } - - private deviceEntries(): DeviceDirectoryEntry[] { - const directoryEntries = this.directoryState.devices; - if (!SidebarDeviceProjectionPolicy.shouldPrependControlTarget( - directoryEntries.map((entry: DeviceDirectoryEntry): string => entry.deviceId), - this.controlTargetType, - this.controlTargetDeviceId, - this.isConnected(), - this.recentWorkspaces.length > 0 || this.sessions.length > 0 - )) { - return directoryEntries; - } - this.updateTransientEntry(); - return [this.transientEntry].concat(directoryEntries); - } - - @Builder - private WorkspacePicker() { - SidebarWorkspacePicker({ - tools: this.workspaceTools, - canBrowse: this.isActiveDevice(this.workspacePickerDevice().deviceId), - onBrowse: this.onWorkspaceTools, - 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()), - selectedWorkspacePath: this.isActiveDevice(this.workspacePickerDevice().deviceId) ? - this.workspacePath : '', - selectedWorkspaceId: this.isActiveDevice(this.workspacePickerDevice().deviceId) ? this.workspaceId : '', - selectedWorkspaceConnectionId: this.isActiveDevice(this.workspacePickerDevice().deviceId) ? - this.workspaceConnectionId : '', - selectedWorkspaceSshHost: this.isActiveDevice(this.workspacePickerDevice().deviceId) ? this.workspaceSshHost : '', - loading: this.workspacePickerDevice().status === 'loading', - onClose: () => { - this.showWorkspacePicker = false; - }, - onSelectWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => { - const deviceId = this.workspacePickerDeviceId; - this.showWorkspacePicker = false; - this.onOpenWorkspace(deviceId, path, connectionId, sshHost, workspaceId); - } - }) - } - - private openWorkspacePicker(entry: DeviceDirectoryEntry): void { - this.workspacePickerDeviceId = entry.deviceId; - this.showWorkspacePicker = true; - this.onAddWorkspace(entry.deviceId); - } - - private workspacePickerDevice(): DeviceDirectoryEntry { - const entry = this.deviceEntries().find((item: DeviceDirectoryEntry): boolean => - item.deviceId === this.workspacePickerDeviceId - ); - return entry || this.transientEntry; - } - - private workspacePickerSheetOptions(): SheetOptions { - return AdaptiveSheetOptions.fromPlacement(this.workspacePickerPlacement, true); - } - - private visibleDeviceEntries(): DeviceDirectoryEntry[] { - const entries = this.deviceEntries(); - return entries.length <= this.visibleDeviceCount ? entries : entries.slice(0, this.visibleDeviceCount); - } - - private selectedEntry(): DeviceDirectoryEntry | undefined { - const entries = this.deviceEntries(); - const selectedId = this.directoryState.selectedDeviceId.trim(); - if (selectedId.length === 0) { - return undefined; - } - return entries.find((entry: DeviceDirectoryEntry): boolean => entry.deviceId === selectedId); - } - - private selectedEntries(): DeviceDirectoryEntry[] { - const selected = this.selectedEntry(); - return selected ? [selected] : []; - } - - private isSelected(entry: DeviceDirectoryEntry): boolean { - const selected = this.selectedEntry(); - return !!selected && selected.deviceId === entry.deviceId; - } - - private deviceKey(entry: DeviceDirectoryEntry): string { - return this.isDirectoryEntry(entry) ? entry.deviceId : `transient:${entry.deviceId}`; - } - - private updateTransientEntry(): void { - const targetId = this.controlTargetDeviceId.trim(); - this.transientEntry.deviceId = targetId; - this.transientEntry.deviceName = this.controlTargetDeviceName.trim() || targetId; - this.transientEntry.online = this.isConnected(); - this.transientEntry.status = 'ready'; - this.transientEntry.workspaces = this.recentWorkspaces; - this.transientEntry.sessions = this.sessions; - } - - private isDirectoryEntry(entry: DeviceDirectoryEntry): boolean { - return this.directoryState.find(entry.deviceId) === entry; - } - - private usesLiveDirectory(entry: DeviceDirectoryEntry): boolean { - return this.isActiveDevice(entry.deviceId) && this.isConnected(); - } - - private liveWorkspacePath(entry: DeviceDirectoryEntry): string { - return this.usesLiveDirectory(entry) ? this.workspacePath : ''; - } - - private liveWorkspaceName(entry: DeviceDirectoryEntry): string { - if (this.liveWorkspacePath(entry).length === 0) return ''; - if (this.workspaceKind === 'remote' && this.workspaceConnectionId.length > 0) { - const connection = this.savedConnections.find((item: SavedRuntimeConnection): boolean => { - return item.id === this.workspaceConnectionId && item.name.trim().length > 0; - }); - if (connection) return connection.name; - } - return this.workspaceName; - } - - private liveWorkspaceKind(entry: DeviceDirectoryEntry): string { - return this.usesLiveDirectory(entry) ? this.workspaceKind : 'normal'; - } - private workspacesForDevice(entry: DeviceDirectoryEntry): RecentWorkspaceEntry[] { - return entry.workspaces; - } - - private selectedSessionIdFor(entry: DeviceDirectoryEntry): string { - if (this.selectedSessionId.length === 0) { - return ''; - } - if (this.isActiveDevice(entry.deviceId)) { - return this.selectedSessionId; - } - return entry.sessions.some((item: RemoteSession): boolean => item.id === this.selectedSessionId) ? - this.selectedSessionId : ''; - } - - private isActiveDevice(deviceId: string): boolean { - const activeId = this.controlTargetDeviceId; - if (activeId.length === 0) { - return this.directoryState.devices.length === 0; - } - return deviceId === activeId; - } - - private canUseDevice(entry: DeviceDirectoryEntry): boolean { - return entry.online || (this.isActiveDevice(entry.deviceId) && this.isConnected()); - } - - - private isConnected(): boolean { - return this.connectionState === 'connected' || this.connectionState === 'reconnecting'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SkillPickerSheet.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SkillPickerSheet.ets deleted file mode 100644 index cfb8e1bbcf..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SkillPickerSheet.ets +++ /dev/null @@ -1,464 +0,0 @@ -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { - CommandCatalogProjection, - COMMAND_CATALOG_FILTER_ALL, - SkillCatalogFilter, - SkillCatalogPresentation, - SkillCatalogRow, - SkillCatalogSection -} from '../../services/CommandCatalogProjection'; -import { - CommandPaletteCatalogStatus, - CommandPalettePolicy, - CommandPaletteProbeFailure -} from '../../services/CommandPalettePolicy'; -import { CommandPalettePresentation } from '../state/CommandPaletteState'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { AppActionButton, AppActionStyle } from './AppActionButton'; -import { SheetCloseHeader } from './SheetCloseHeader'; -import { - SHEET_ACTION_HEIGHT, - SHEET_FOOTER_BOTTOM_PADDING, - SHEET_FOOTER_TOP_PADDING, - SHEET_HORIZONTAL_PADDING, - SHEET_TOP_RADIUS -} from './SheetLayout'; -import { CARD, CONTENT_ON_INK, INK, LINE, MUTED, PAGE_BG, SOFT, SUBTLE, TRANSPARENT } from './Theme'; - -// The picker's own geometry, matching the approved design's half-sheet. -const SKILL_SEARCH_HEIGHT: number = 42; -const SKILL_SEARCH_RADIUS: number = 14; -const FILTER_CHIP_HEIGHT: number = 28; -const SKILL_ICON_SURFACE: number = 36; -const SKILL_ICON_RADIUS: number = 10; -const SKILL_SECTION_HEIGHT: number = 28; -const SKILL_TAG_HEIGHT: number = 16; -const SKILL_UNAVAILABLE_OPACITY: number = 0.4; - -/** - * The skill picker, opened from the composer's 技能 chip. - * - * It is the row's other half: the chips run commands, and this chooses the one - * skill token a message may carry. Selecting inserts; it never sends. The sheet - * is also where an unsupported desktop is explained, because a dead chip would - * say less than an empty catalog with a reason and a way to re-check it. - */ -@ComponentV2 -export struct SkillPickerSheet { - @Param palette: CommandPalettePresentation = CommandPalettePresentation.hidden(); - @Event onSelect: (skillId: string, skillLabel: string) => void = (_skillId: string, _skillLabel: string) => {}; - @Event onRefresh: () => void = () => {}; - @Event onClose: () => void = () => {}; - @Local query: string = ''; - @Local filterId: string = COMMAND_CATALOG_FILTER_ALL; - // The sheet is a bottom sheet under the immersive shell, so it reads the - // navigation-bar strip itself and ends in a tail that rests above it. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - // The next open starts from the whole catalog rather than from whatever the - // previous visit was filtering. - this.query = ''; - this.filterId = COMMAND_CATALOG_FILTER_ALL; - } - - build() { - Column() { - SheetCloseHeader({ - title: RemoteI18n.t('commands.skills.title'), - showDivider: true, - onClose: this.onClose - }) - this.SearchBox() - this.Filters() - if (this.isLoading()) { - this.LoadingState() - } else if (this.isUnavailable()) { - this.UnavailableState() - } else if (this.presentation().isEmpty) { - this.EmptyState() - } else if (this.presentation().hasNoMatches) { - this.NoMatchState() - } else { - this.SkillList() - } - this.Footer() - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .borderRadius({ topLeft: SHEET_TOP_RADIUS, topRight: SHEET_TOP_RADIUS }) - } - - @Builder - SearchBox() { - Row() { - Row({ space: 8 }) { - SymbolGlyph($r('sys.symbol.magnifyingglass')) - .fontSize(16) - .fontColor([MUTED]) - TextInput({ placeholder: RemoteI18n.t('commands.skills.searchPlaceholder'), text: this.query }) - .layoutWeight(1) - .height(SKILL_SEARCH_HEIGHT) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(INK) - .placeholderColor(MUTED) - .backgroundColor(TRANSPARENT) - .padding(0) - .maxLines(1) - .enabled(!this.isUnavailable()) - .onChange((value: string) => { - this.query = value; - }) - } - .width('100%') - .height(SKILL_SEARCH_HEIGHT) - .padding({ left: 12, right: 12 }) - .backgroundColor(CARD) - .border({ width: 1, color: LINE }) - .borderRadius(SKILL_SEARCH_RADIUS) - .opacity(this.isUnavailable() ? SKILL_UNAVAILABLE_OPACITY : 1) - } - // A 100%-width child cannot inset itself with margin (margin lands outside - // the border and overflows the parent), so the wrapper owns the inset and - // the bordered box fills what remains. - .width('100%') - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING, top: 12 }) - } - - @Builder - Filters() { - Scroll() { - Row({ space: 4 }) { - ForEach(this.presentation().filters, (filter: SkillCatalogFilter) => { - Text(`${RemoteI18n.t(filter.labelKey)} ${filter.count}`) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(this.filterId === filter.id ? CONTENT_ON_INK : MUTED) - .backgroundColor(this.filterId === filter.id ? INK : SOFT) - .height(FILTER_CHIP_HEIGHT) - .padding({ left: 12, right: 12 }) - .borderRadius(FILTER_CHIP_HEIGHT / 2) - .accessibilityText(RemoteI18n.t(filter.labelKey)) - .onClick(() => { - if (!this.isUnavailable()) { - this.filterId = filter.id; - } - }) - }, (filter: SkillCatalogFilter) => filter.id) - } - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING }) - } - .scrollable(ScrollDirection.Horizontal) - .scrollBar(BarState.Off) - .align(Alignment.Start) - .width('100%') - .height(FILTER_CHIP_HEIGHT) - .margin({ top: 12 }) - .opacity(this.isUnavailable() ? SKILL_UNAVAILABLE_OPACITY : 1) - } - - @Builder - SkillList() { - Scroll() { - Column({ space: 2 }) { - ForEach(this.presentation().sections, (section: SkillCatalogSection) => { - this.SectionHeader(section) - ForEach(section.rows, (row: SkillCatalogRow) => { - this.SkillRow(row) - }, (row: SkillCatalogRow) => row.id) - }, (section: SkillCatalogSection) => section.id) - } - .width('100%') - .padding({ bottom: this.insets.tailSpacing(12) }) - } - .width('100%') - .layoutWeight(1) - .align(Alignment.TopStart) - .scrollBar(BarState.Off) - .margin({ top: 6 }) - } - - @Builder - SectionHeader(section: SkillCatalogSection) { - Row({ space: 6 }) { - Text(RemoteI18n.t(section.titleKey)) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - Text(`${section.count}`) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - Blank() - } - .width('100%') - .height(SKILL_SECTION_HEIGHT) - .padding({ left: SHEET_HORIZONTAL_PADDING + 2, right: SHEET_HORIZONTAL_PADDING + 2 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - SkillRow(row: SkillCatalogRow) { - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(row.isBuiltin ? - $r('sys.symbol.wrench_and_screwdriver') : $r('sys.symbol.doc_text')) - .fontSize(20) - .fontColor([MUTED]) - } - .width(SKILL_ICON_SURFACE) - .height(SKILL_ICON_SURFACE) - .backgroundColor(this.isSelected(row) ? CARD : SOFT) - .borderRadius(SKILL_ICON_RADIUS) - - Column({ space: 1 }) { - Row({ space: 6 }) { - Text(row.name) - .fontSize(MobileDesignTypography.titleSmall.size) - .lineHeight(MobileDesignTypography.titleSmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - if (this.rowTag(row).length > 0) { - Text(this.rowTag(row)) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(SKILL_TAG_HEIGHT) - .fontColor(MUTED) - .padding({ left: 4, right: 4 }) - .backgroundColor(this.isSelected(row) ? CARD : SOFT) - .borderRadius(4) - } - Blank() - } - .width('100%') - .alignItems(VerticalAlign.Center) - - Text(row.description) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .width('100%') - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - - Column({ space: 2 }) { - Text(row.insertHint) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - if (this.isSelected(row)) { - SymbolGlyph($r('sys.symbol.checkmark_circle')) - .fontSize(16) - .fontColor([INK]) - } - } - .alignItems(HorizontalAlign.End) - } - .width('100%') - .constraintSize({ minHeight: MobileDesignGeometry.selectionRowHeight }) - .padding({ left: SHEET_HORIZONTAL_PADDING + 4, right: SHEET_HORIZONTAL_PADDING + 4, top: 8, bottom: 8 }) - .backgroundColor(this.isSelected(row) ? SOFT : TRANSPARENT) - .borderRadius(12) - .accessibilityText(`${row.name} · ${row.insertHint}`) - .onClick(() => { - this.onSelect(row.id, row.name); - }) - } - - @Builder - LoadingState() { - Column() { - LoadingProgress() - .width(24) - .height(24) - .color(MUTED) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - } - - /** - * The read did not answer, so the sheet explains and offers the re-check. - * - * What it claims follows from how the read failed: a host that reported the - * version gap is an upgrade, a host that refused for its own reasons is quoted, - * and a read that never reached a host is a connection to look at. Claiming a - * version gap for a timeout would send the user to update a desktop that is - * already current. - */ - @Builder - UnavailableState() { - Column({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.info_circle')) - .fontSize(26) - .fontColor([MUTED]) - } - .width(64) - .height(64) - .backgroundColor(SOFT) - .borderRadius(32) - - Text(RemoteI18n.t(this.unavailableTitleKey())) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .textAlign(TextAlign.Center) - - Text(RemoteI18n.t(this.unavailableBodyKey())) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .constraintSize({ maxWidth: 260 }) - - // The desktop's own words for the refusal. A version gap reads as one, and - // so does the other common cause — a workspace or session the host cannot - // find — which this app would otherwise have to guess at. - if (this.palette.catalogErrorText.length > 0) { - Text(this.palette.catalogErrorText) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - .textAlign(TextAlign.Center) - .constraintSize({ maxWidth: 280 }) - .maxLines(4) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - - AppActionButton({ - label: RemoteI18n.t('commands.skills.recheck'), - style: AppActionStyle.Secondary, - actionHeight: SHEET_ACTION_HEIGHT, - elevated: false, - onAction: this.onRefresh - }) - .width(176) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .padding({ left: 10, right: 10, bottom: 12 }) - } - - @Builder - NoMatchState() { - Column() { - Text(RemoteI18n.t('commands.skills.noMatch')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING }) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - } - - /** - * The host answered, and this mode has nothing to invoke. - * - * Distinct from a failed probe: the read worked, so there is nothing to - * re-check, and the sentence says which of the two happened. - */ - @Builder - EmptyState() { - Column() { - Text(RemoteI18n.t('commands.skills.empty')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .constraintSize({ maxWidth: 260 }) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING }) - } - - @Builder - Footer() { - Text(RemoteI18n.t(this.isUnavailable() ? - 'commands.skills.footerUnavailable' : 'commands.skills.footer')) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .width('100%') - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: SHEET_FOOTER_TOP_PADDING, - bottom: SHEET_FOOTER_BOTTOM_PADDING - }) - } - - private presentation(): SkillCatalogPresentation { - return CommandCatalogProjection.present(this.palette.catalog, this.query, this.filterId); - } - - private isLoading(): boolean { - return this.palette.catalogStatus === CommandPaletteCatalogStatus.Loading; - } - - /** - * The read did not answer, so there is no list to show. - * - * The row's own explanation counts too, because a chip can reach this sheet - * while the read that would fill it is still outstanding. - */ - private isUnavailable(): boolean { - if (this.palette.catalogStatus === CommandPaletteCatalogStatus.Failed) { - return true; - } - return !this.isLoading() && this.palette.rowReasonKey.length > 0; - } - - private unavailableTitleKey(): string { - return CommandPalettePolicy.probeTitleKey(this.failure()); - } - - private unavailableBodyKey(): string { - return CommandPalettePolicy.probeBodyKey(this.failure()); - } - - /** - * How the read failed, as this sheet tells it. - * - * A read that never failed — the row is explaining something else — is not a - * version claim either, so it takes the same wording as an unreachable host. - */ - private failure(): string { - if (this.palette.catalogStatus !== CommandPaletteCatalogStatus.Failed) { - return CommandPaletteProbeFailure.Unreachable; - } - return this.palette.catalogFailure; - } - - private rowTag(row: SkillCatalogRow): string { - return row.group.length > 0 ? row.group : row.source; - } - - private isSelected(row: SkillCatalogRow): boolean { - return this.palette.skillId.length > 0 && this.palette.skillId === row.id; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StartupBrandReveal.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StartupBrandReveal.ets deleted file mode 100644 index 930ade278f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StartupBrandReveal.ets +++ /dev/null @@ -1,108 +0,0 @@ -import { MotionPreference } from '../../services/MotionPreference'; -import { WelcomeBrandFlow } from './WelcomeBrandFlow'; -import { MobileDesignMotion, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { PAGE_BG, INK } from './Theme'; - -/** Native rendering of the mobile startup_brand_reveal motion contract. */ -@ComponentV2 -export struct StartupBrandReveal { - @Event onFinished: () => void = () => {}; - @Local progress: number = 0; - @Local stageScale: number = 1; - private readonly letters: string[] = ['O', 'p', 'e', 'n', 'B', 'ı', 't', 'F', 'u', 'n']; - private readonly widths: number[] = [30, 25, 24, 25, 28, 10, 16, 24, 25, 25]; - private timer: number = -1; - private started: number = 0; - - aboutToAppear(): void { - if (MotionPreference.reduceMotion()) { this.onFinished(); return; } - this.started = Date.now(); - this.timer = setInterval(() => { - this.progress = Math.min(1, (Date.now() - this.started) / MobileDesignMotion.startupBrand); - if (this.progress >= 1) { clearInterval(this.timer); this.onFinished(); } - }, 16); - } - aboutToDisappear(): void { clearInterval(this.timer); } - private clamp(x: number): number { return Math.max(0, Math.min(1, x)); } - private smooth(x: number): number { const v = this.clamp(x); return v * v * (3 - 2 * v); } - private ease(x: number): number { return 1 - Math.pow(1 - this.clamp(x), 3); } - private time(): number { return Math.min(this.progress / 0.65 * 0.9, 0.9); } - private settle(): number { return this.smooth((this.progress - 0.66) / 0.19); } - private start(index: number): number { return 0.19 + index * 0.048; } - private x(index: number): number { - let x = 24; - for (let i = 0; i < index; i++) x += this.widths[i]; - return x; - } - private reveal(index: number): number { return this.ease((this.time() - this.start(index)) / 0.05); } - private bounce(index: number): number { - const p = this.clamp((this.time() - this.start(index)) / 0.085); - return Math.sin(p * Math.PI) * Math.pow(1 - p, 0.65); - } - private dot(): number[] { - const t = this.time(); - let x = 9; - let y = 110; - let sx = 1; - let sy = 1; - for (let i = 0; i < 10; i++) { - const end = this.start(i); - const begin = i === 0 ? end - 0.065 : this.start(i - 1); - const from = i === 0 ? 9 : this.x(i) + 10; - const to = this.x(i + 1) + 10; - if (t >= end) { x = to; continue; } - if (t >= begin) { - const step = this.clamp((t - begin) / (end - begin)); - const hop = this.clamp((step - 0.16) / 0.84); - const squash = Math.sin(this.clamp(step / 0.16) * Math.PI); - x = from + (to - from) * this.smooth(hop); - y -= 4 * hop * (1 - hop) * (i === 0 ? 20 : 15); - sx = 1 + 0.2 * squash; sy = 1 - 0.18 * squash; - } - break; - } - if (t >= 0.70) { - const flight = this.clamp((t - 0.70) / 0.16); - const travel = this.smooth(flight); - x += (this.x(5) + 5 - x) * travel; - y = 110 - 15 * travel - Math.sin(Math.PI * flight) * 44; - sx = 1 + (7.35 / 9 - 1) * travel; sy = sx; - if (t > 0.86 && t < 0.9) y -= Math.sin((t - 0.86) / 0.04 * Math.PI) * 2; - } - return [x, y + 42 * this.settle(), sx, sy]; - } - private markScale(): number { - const p = this.clamp((this.progress - 0.66) / 0.19) - 1; - return 0.65 + 0.35 * (1 + 2.2 * p * p * p + 1.2 * p * p); - } - private halo(): number { return Math.sin(this.clamp((this.time() - 0.86) / 0.04) * Math.PI); } - - build() { - Stack({ alignContent: Alignment.Center }) { - Stack({ alignContent: Alignment.TopStart }) { - WelcomeBrandFlow({ markSize: 156, sweep: true }) - .position({ x: 62, y: -34 }).scale({ x: this.markScale(), y: this.markScale() }) - .opacity(this.ease((this.progress - 0.66) / 0.19)) - ForEach(this.letters, (letter: string, index: number) => { - Text(letter).fontSize(MobileDesignTypography.brandWordmark.size).fontWeight(FontWeight.Medium).fontColor(INK) - .width(this.widths[index]).height(56).textAlign(TextAlign.Center) - .position({ x: this.x(index), y: 82 + 42 * this.settle() }) - .opacity(this.reveal(index)) - .translate({ y: 7 * (1 - this.reveal(index)) - 8 * this.bounce(index) }) - .rotate({ angle: (index % 2 === 0 ? -1 : 1) * this.bounce(index) * 6 }) - }, (_letter: string, index: number) => `${index}`) - Circle().width(22).height(22).fill($r('app.color.brand_dot')) - .position({ x: this.dot()[0] - 11, y: this.dot()[1] - 11 }).opacity(this.halo() * 0.16) - Circle().width(9).height(9).fill($r('app.color.brand_dot')) - .position({ x: this.dot()[0] - 4.5, y: this.dot()[1] - 4.5 }) - .scale({ x: this.dot()[2], y: this.dot()[3] }).opacity(this.ease(this.time() / 0.12)) - }.width(280).height(240).scale({ x: this.stageScale, y: this.stageScale }) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - .onSizeChange((_oldSize: SizeOptions, size: SizeOptions) => { - this.stageScale = Math.min(1, Math.max(0.1, (Number(size.width) - 32) / 280)); - }) - .opacity(1 - this.smooth((this.progress - 0.97) / 0.03)) - .hitTestBehavior(HitTestMode.Block).accessibilityLevel('no-hide-descendants') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StreamingMarkdownContent.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StreamingMarkdownContent.ets deleted file mode 100644 index 9d0401ee03..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/StreamingMarkdownContent.ets +++ /dev/null @@ -1,179 +0,0 @@ -import { MarkdownContent } from './MarkdownContent'; -import { RemoteLogger } from '../../services/RemoteLogger'; - -const STREAMING_MARKDOWN_CACHE: Map = new Map(); - -@ComponentV2 -export struct StreamingMarkdownContent { - @Param text: string = ''; - @Param active: boolean = false; - @Param streamKey: string = ''; - @Param renderRevision: number = 0; - @Event onCopyText: (text: string) => void = (_text: string) => {}; - @Event onOpenLink: (reference: string, label: string) => void = (_reference: string, _label: string) => {}; - @Local renderedText: string = ''; - @Local renderedRevision: number = 0; - private targetText: string = ''; - private timerId: number = 0; - private frameIntervalMs: number = 40; - private revealDurationMs: number = 1400; - private cacheWriteInterval: number = 4; - private frameCount: number = 0; - private lastLoggedTargetBucket: number = -1; - private lastLoggedRenderedBucket: number = -1; - - aboutToAppear(): void { - this.targetText = this.text; - this.renderedText = this.initialRenderedText(); - this.logTargetProgress('appear', true); - this.logRenderedProgress(true); - if (this.active && this.text.length > 0) { - this.startTimer(); - } - } - - aboutToDisappear(): void { - this.logTargetProgress('disappear', true); - this.logRenderedProgress(true); - this.saveRenderedText(); - this.clearTimer(); - } - - build() { - MarkdownContent({ - text: this.renderedText, - renderRevision: this.renderedRevision, - onCopyText: (_body: string) => { - this.onCopyText(this.text); - }, - onOpenLink: (reference: string, label: string) => { - this.onOpenLink(reference, label); - } - }) - } - - @Monitor('text', 'active', 'streamKey', 'renderRevision') - private handleTextChanged(): void { - this.logTargetProgress(this.active ? 'target' : 'settled', !this.active); - if (!this.active) { - this.clearTimer(); - this.targetText = this.text; - this.renderedText = this.text; - this.renderedRevision += 1; - this.logRenderedProgress(true); - this.saveRenderedText(); - return; - } - const cached = this.cachedRenderedText(); - if (cached.length > this.renderedText.length && this.text.startsWith(cached)) { - this.renderedText = cached; - this.renderedRevision += 1; - this.logRenderedProgress(false); - } - if (this.text === this.renderedText) { - this.clearTimer(); - this.targetText = this.text; - this.saveRenderedText(); - return; - } - // The input is already revision-reconciled by the transcript owner. A - // rewrite or deletion is authoritative, not a stale streaming chunk. - // Only append-only growth may continue the previous reveal animation. - if (!this.text.startsWith(this.targetText) || !this.text.startsWith(this.renderedText)) { - this.clearTimer(); - this.targetText = this.text; - this.renderedText = this.text; - this.renderedRevision += 1; - this.saveRenderedText(); - return; - } - this.targetText = this.text; - this.startTimer(); - } - - private startTimer(): void { - if (this.timerId !== 0) { - return; - } - this.frameCount = 0; - this.timerId = setInterval(() => { - if (this.renderedText.length >= this.targetText.length) { - this.clearTimer(); - return; - } - const remaining = this.targetText.length - this.renderedText.length; - const totalFrames = Math.max(1, Math.floor(this.revealDurationMs / this.frameIntervalMs)); - const step = Math.max(1, Math.ceil(remaining / totalFrames)); - this.renderedText = this.targetText.slice(0, Math.min(this.targetText.length, this.renderedText.length + step)); - this.renderedRevision += 1; - this.frameCount += 1; - this.logRenderedProgress(false); - if (this.frameCount % this.cacheWriteInterval === 0 || this.renderedText.length >= this.targetText.length) { - this.saveRenderedText(); - } - }, this.frameIntervalMs); - } - - private clearTimer(): void { - if (this.timerId !== 0) { - clearInterval(this.timerId); - this.timerId = 0; - } - } - - private initialRenderedText(): string { - if (!this.active) { - return this.text; - } - const cached = this.cachedRenderedText(); - if (cached.length > 0 && this.text.startsWith(cached)) { - return cached; - } - return ''; - } - - private cachedRenderedText(): string { - const key = this.normalizedStreamKey(); - if (key.length === 0) { - return ''; - } - return STREAMING_MARKDOWN_CACHE.get(key) || ''; - } - - private saveRenderedText(): void { - const key = this.normalizedStreamKey(); - if (key.length === 0) { - return; - } - STREAMING_MARKDOWN_CACHE.set(key, this.renderedText); - } - - private normalizedStreamKey(): string { - return this.streamKey.trim(); - } - - private logTargetProgress(reason: string, force: boolean): void { - const bucket = Math.floor(this.text.length / 256); - if (!force && bucket === this.lastLoggedTargetBucket) { - return; - } - this.lastLoggedTargetBucket = bucket; - RemoteLogger.info( - `stream markdown ${reason} key=${this.normalizedStreamKey()} target=${this.text.length} ` + - `rendered=${this.renderedText.length} revision=${this.renderRevision} active=${this.active ? 1 : 0}` - ); - } - - private logRenderedProgress(force: boolean): void { - const bucket = Math.floor(this.renderedText.length / 256); - if (!force && bucket === this.lastLoggedRenderedBucket) { - return; - } - this.lastLoggedRenderedBucket = bucket; - RemoteLogger.info( - `stream markdown frame key=${this.normalizedStreamKey()} target=${this.targetText.length} ` + - `rendered=${this.renderedText.length} frame=${this.frameCount}` - ); - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SubagentTaskCard.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SubagentTaskCard.ets deleted file mode 100644 index 46c380706b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SubagentTaskCard.ets +++ /dev/null @@ -1,279 +0,0 @@ -import { InteractionMailboxState } from '../../model/InteractionMailbox'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConversationUiMessageItem, ConversationUiQuestionAnswer } from '../state/ConversationUiModels'; -import { SubagentBranchExpansionState } from '../state/SubagentBranchExpansionState'; -import { ChatMessageStructurePolicy } from '../policy/ChatMessageStructurePolicy'; -import { - CARD, - INK, - LINE, - MUTED, - SOFT, - STATUS_DANGER, - TRANSPARENT, -} from './Theme'; -import { ThinkingBlock } from './ThinkingBlock'; -import { ToolStatusList } from './ToolStatusList'; -import { ToolGlyph } from './ToolGlyphs'; - -@ComponentV2 -export struct SubagentTaskCard { - @Param interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - @Param title: string = ''; - @Param path: string = ''; - @Param status: string = 'completed'; - /** - * Process items of this branch, as re-read by the bubble on every render. - * - * A snapshot array would freeze the first empty branch: the ForEach that draws - * this card is keyed by the branch view key, which deliberately does not change - * while the subagent publishes steps, so its item builder never re-runs. - */ - @Param items: ConversationUiMessageItem[] = []; - @Param renderRevision: number = 0; - /** - * The tool call that launched this worker; the key its disclosure is kept under. - * - * A branch is identified by what launched it. The render path is only a - * fallback for a host that sent no tool call id, and it is stable for as long - * as the branch is, which is all a key has to be. - */ - @Param branchId: string = ''; - /** - * Disclosure owned by the conversation, not by this card. - * - * The row this card sits in is rebuilt whenever the turn is republished, and - * with it every component below the row's keyed subtree. State kept here would - * be what the reader loses at that moment — which is what happened when a - * launch settled under an open card — so the boolean lives in owner state that - * outlives the row and this card only reads and writes it. - */ - @Param expansion: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - @Event onApproveTool: (toolId: string, updatedInput?: Object) => void = - (_toolId: string, _updatedInput?: Object) => {}; - @Event onRejectTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onCancelTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => void = - (_toolId: string, _answers: ConversationUiQuestionAnswer) => {}; - @Event onOpenFilePreview: (path: string, label: string) => void = - (_path: string, _label: string) => {}; - @Event onBuildPlan: (path: string, name: string) => void = (_path: string, _name: string) => {}; - /** - * Raised when the reader opens this branch, so the owner of its records can - * make sure the worker is actually being followed. - */ - @Event onBranchExpanded: (branchId: string) => void = (_branchId: string) => {}; - - build() { - Column() { - Row({ space: 8 }) { - Stack({ alignContent: Alignment.BottomEnd }) { - Stack({ alignContent: Alignment.Center }) { - ToolGlyph({ kind: 'task', color: this.isError() ? STATUS_DANGER : MUTED }) - } - .width(18) - .height(18) - .backgroundColor(SOFT) - .borderRadius(5) - .border({ width: 1, color: this.isError() ? STATUS_DANGER : LINE }) - if (this.isRunning() || this.isError()) { - Text(this.isError() ? '!' : '•') - .width(10) - .height(10) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Bold) - .fontColor(CARD) - .textAlign(TextAlign.Center) - .backgroundColor(this.isError() ? STATUS_DANGER : MUTED) - .borderRadius(5) - .border({ width: 1, color: CARD }) - } - } - .width(20) - .height(20) - Text(this.title) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.isError() ? STATUS_DANGER : MUTED) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.statusText()) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(this.isError() ? STATUS_DANGER : MUTED) - .maxLines(1) - if (this.hasProcessItems()) { - SymbolGlyph(this.isExpanded() ? $r('sys.symbol.chevron_up') : $r('sys.symbol.chevron_down')) - .fontSize(13) - .fontColor([MUTED]) - .width(16) - .height(16) - } - } - .width('100%') - .height(28) - .alignItems(VerticalAlign.Center) - .onClick(() => { - this.toggleExpanded(); - }) - if (this.isExpanded() && this.hasProcessItems()) { - this.ProcessItems() - } - } - .width('100%') - .padding({ - left: this.isEmphasized() ? 10 : 0, - right: this.isEmphasized() ? 10 : 0, - top: this.isEmphasized() ? 6 : 0, - bottom: this.isEmphasized() ? 6 : 0 - }) - .backgroundColor(this.isEmphasized() || this.isExpanded() ? SOFT : TRANSPARENT) - .borderRadius(this.isEmphasized() ? 14 : 8) - .border({ width: this.isEmphasized() || this.isExpanded() ? 1 : 0, color: LINE }) - .accessibilityText(`${this.title}, ${this.statusText()}`) - } - - @Builder - private ProcessItems() { - Column({ space: 6 }) { - ForEach(this.visibleProcessItems(), (entry: ConversationUiMessageItem, index: number) => { - if (ChatMessageStructurePolicy.isThinkingEntry(entry)) { - ThinkingBlock({ - text: entry.content || '', - status: this.childStatus(index), - keepExpandedWhenDone: false, - streaming: this.childStatus(index) === 'running', - streamKey: `${this.processItemKey(index)}-thinking` - }) - } else if (entry.tool) { - ToolStatusList({ - interactionMailbox: this.interactionMailbox, - tools: [entry.tool], - renderRevision: this.renderRevision, - isBusy: this.isRunning(), - onApproveTool: this.onApproveTool, - onRejectTool: this.onRejectTool, - onCancelTool: this.onCancelTool, - onAnswerQuestion: this.onAnswerQuestion, - onOpenFilePreview: this.onOpenFilePreview, - onBuildPlan: this.onBuildPlan - }) - } else if ((entry.content || '').trim().length > 0) { - Column({ space: 3 }) { - Text(RemoteI18n.t('chat.subagentOutput')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - Text(this.processTextPreview(entry.content || '')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(INK) - .width('100%') - .maxLines(4) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .alignItems(HorizontalAlign.Start) - } - }, (_entry: ConversationUiMessageItem, index: number) => this.processItemKey(index)) - } - .width('100%') - .padding({ left: 14, top: 6, bottom: 4 }) - .border({ width: { left: 1 }, color: LINE }) - } - - /** - * View key for one process entry, anchored to the Task that owns it. - * - * Counting each kind separately keeps a child's key while siblings of other - * kinds arrive, so a running Task cannot renumber what is already drawn. - */ - /** - * The reader's disclosure of this branch, read from the conversation that owns it. - * - * Reading it in `build` is what subscribes this card to it: the disclosure is - * `@Trace`, so opening or closing the branch repaints exactly this card. - */ - private isExpanded(): boolean { - return this.expansion.isExpanded(this.branchKey()); - } - - /** - * Opens or closes the branch, and tells the owner of its records when it opened. - * - * An open branch is a request to see the worker: its stream may have been - * released (the cap releases a settled child, and a wide delegation holds only - * so many at once), so the same gesture both flips the disclosure and asks for - * the worker to be followed again. Re-attaching is idempotent, and does nothing - * for a branch that is already being followed. - */ - private toggleExpanded(): void { - if (!this.hasProcessItems()) return; - if (this.expansion.toggle(this.branchKey())) { - this.onBranchExpanded(this.branchId); - } - } - - /** What this branch's disclosure is remembered under. */ - private branchKey(): string { - return this.branchId.length > 0 ? this.branchId : this.path; - } - - private processItemKey(index: number): string { - const items = this.visibleProcessItems(); - const ordinals: Map = new Map(); - for (let cursor = 0; cursor <= index && cursor < items.length; cursor++) { - const kind = this.processItemKind(items[cursor]); - const ordinal = ordinals.get(kind) || 0; - if (cursor === index) return `${this.path}-process-${kind}-${ordinal}`; - ordinals.set(kind, ordinal + 1); - } - return `${this.path}-process-item-${index}`; - } - - private processItemKind(entry: ConversationUiMessageItem): string { - if (ChatMessageStructurePolicy.isThinkingEntry(entry)) return 'thinking'; - return entry.tool ? 'tool' : 'text'; - } - - private isRunning(): boolean { - const normalized = this.status.toLowerCase(); - return normalized === 'running' || normalized === 'active' || normalized === 'preparing' || - normalized === 'pending' || normalized === 'queued'; - } - - private isError(): boolean { - const normalized = this.status.toLowerCase(); - return normalized === 'failed' || normalized === 'error' || normalized === 'timeout' || - normalized === 'cancelled' || normalized === 'canceled' || normalized === 'rejected'; - } - - private statusText(): string { - if (this.isRunning()) return RemoteI18n.t('common.running'); - return RemoteI18n.t(this.isError() ? 'common.failed' : 'common.done'); - } - - private isEmphasized(): boolean { - return this.isRunning() || this.isError(); - } - - private visibleProcessItems(): ConversationUiMessageItem[] { - return this.items.filter((entry: ConversationUiMessageItem) => - !!entry.tool || (entry.content || '').trim().length > 0 || - (!!entry.subItems && entry.subItems.length > 0)); - } - - private hasProcessItems(): boolean { - return this.visibleProcessItems().length > 0; - } - - private childStatus(index: number): string { - return this.isRunning() && index === this.visibleProcessItems().length - 1 ? 'running' : 'done'; - } - - private processTextPreview(raw: string): string { - const text = raw.trim(); - if (text.length <= 320) return text; - return `${text.slice(0, 320).trim()}…`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/TemplateIcon.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/TemplateIcon.ets deleted file mode 100644 index 86d16c223d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/TemplateIcon.ets +++ /dev/null @@ -1,36 +0,0 @@ -import { INK } from './Theme'; - -// Monochrome bitmap glyph tinted with a semantic theme color. -// -// The reference assets are black-pixel PNGs with an alpha mask, and ArkUI -// cannot tint those the way iOS template images work: `fillColor` only applies -// to SVG sources, and `renderMode(ImageRenderMode.Template)` is a monochrome -// render that keeps the original luminance, so the black pixels stayed black on -// dark surfaces. Painting the tint over the glyph in an offscreen layer and -// clipping it to the alpha mask with `SRC_IN` keeps the color a plain -// `ResourceColor`, so it still resolves per theme. -@ComponentV2 -export struct TemplateIcon { - @Require @Param src: Resource; - @Param iconWidth: number = 24; - @Param iconHeight: number = 24; - @Param tint: ResourceColor = INK; - - build() { - Stack() { - Image(this.src) - .width(this.iconWidth) - .height(this.iconHeight) - .objectFit(ImageFit.Contain) - .draggable(false) - Text('') - .width(this.iconWidth) - .height(this.iconHeight) - .backgroundColor(this.tint) - .blendMode(BlendMode.SRC_IN) - } - .width(this.iconWidth) - .height(this.iconHeight) - .blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/Theme.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/Theme.ets deleted file mode 100644 index 14376ca7d3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/Theme.ets +++ /dev/null @@ -1,86 +0,0 @@ -export const PAGE_BG: ResourceColor = $r('app.color.page_bg'); -export const WELCOME_PAGE_BG: ResourceColor = $r('app.color.welcome_page_bg'); -/** PAGE_BG at zero alpha, per theme — the transparent end of a fade-out. */ -export const PAGE_BG_FADE: ResourceColor = $r('app.color.page_bg_fade'); -/** - * PAGE_BG at partial alpha, for a surface the transcript scrolls underneath. - * It is the floor under `backgroundBlurStyle`, not a replacement for it: the - * blur carries the effect, this keeps the text on top readable on a build or a - * device where the blur does not land. - */ -export const PAGE_BG_OVERLAY: ResourceColor = $r('app.color.page_bg_overlay'); -export const TRANSPARENT: ResourceColor = $r('app.color.transparent'); -export const INK: ResourceColor = $r('app.color.ink'); -export const MUTED: ResourceColor = $r('app.color.muted'); -export const SUBTLE: ResourceColor = $r('app.color.subtle'); -export const LINE: ResourceColor = $r('app.color.line'); -export const CARD: ResourceColor = $r('app.color.card'); -/** CARD at partial alpha, for a card that floats over scrolling content. */ -export const CARD_OVERLAY: ResourceColor = $r('app.color.card_overlay'); -export const ACCENT: ResourceColor = $r('app.color.accent'); -export const FILE_LINK: ResourceColor = $r('app.color.file_link'); -export const PRIMARY_ACTION: ResourceColor = $r('app.color.primary_action'); -export const CONTENT_ON_ACTION: ResourceColor = $r('app.color.content_on_action'); -/** - * Content that sits on an INK-filled surface. INK inverts per theme while - * content_on_action is pinned to the action color, so an ink chip must not - * borrow CONTENT_ON_ACTION — page_bg is the theme-correct inverse of INK. - */ -export const CONTENT_ON_INK: ResourceColor = $r('app.color.page_bg'); -export const CONNECT_HERO_BG: ResourceColor = $r('app.color.connect_hero_bg'); -export const CONNECT_HERO_ACCENT: ResourceColor = $r('app.color.connect_hero_accent'); -export const CONNECT_HERO_SECONDARY: ResourceColor = $r('app.color.connect_hero_secondary'); -export const CONNECT_HERO_SURFACE: ResourceColor = $r('app.color.connect_hero_surface'); -export const SCRIM: ResourceColor = $r('app.color.scrim'); -export const SHELL_SCRIM: ResourceColor = $r('app.color.shell_scrim'); -export const MEDIA_BACKGROUND: ResourceColor = $r('app.color.media_background'); -export const MEDIA_SCRIM: ResourceColor = $r('app.color.media_scrim'); -export const MEDIA_CONTROL_BACKGROUND: ResourceColor = $r('app.color.media_control_background'); -export const TOAST_BACKGROUND: ResourceColor = $r('app.color.toast_background'); -export const SHADOW_FAINT: ResourceColor = $r('app.color.shadow_faint'); -export const SHADOW_SUBTLE: ResourceColor = $r('app.color.shadow_subtle'); -export const SHADOW_MEDIUM: ResourceColor = $r('app.color.shadow_medium'); -export const SHADOW_STRONG: ResourceColor = $r('app.color.shadow_strong'); -export const FLOATING_BORDER: ResourceColor = $r('app.color.floating_border'); -export const SOFT: ResourceColor = $r('app.color.soft'); -export const FLOATING_PANEL_BG: ResourceColor = $r('app.color.floating_panel_bg'); -/** - * Sidebar chrome, mirroring the desktop client's structural navigation surface. - * - * The conversation keeps the paper-and-ink page tokens; the sidebar is a - * different structural layer there and here, so it reads one step away from the - * content surface instead of sharing PAGE_BG with it. Each constant below is - * one desktop semantic role, and the alpha ones are meant to composite over - * SIDEBAR_BG rather than be flattened. - */ -/** Desktop `color.surface.chrome`. */ -export const SIDEBAR_BG: ResourceColor = $r('app.color.sidebar_bg'); -/** SIDEBAR_BG at zero alpha, per theme — the transparent end of a fade-out. */ -export const SIDEBAR_BG_FADE: ResourceColor = $r('app.color.sidebar_bg_fade'); -/** Desktop `color.surface.raised` — a control lifted off the chrome. */ -export const SIDEBAR_RAISED: ResourceColor = $r('app.color.sidebar_raised'); -/** Desktop `color.border.subtle`. */ -export const SIDEBAR_LINE: ResourceColor = $r('app.color.sidebar_line'); -/** Desktop `color.action.quiet.hover` — quiet fills such as the search field. */ -export const SIDEBAR_HOVER: ResourceColor = $r('app.color.sidebar_hover'); -/** Desktop `color.selection.surface` — the selected device, workspace or session. */ -export const SIDEBAR_SELECTION: ResourceColor = $r('app.color.sidebar_selection'); -/** Desktop `color.content.primary`. */ -export const SIDEBAR_INK: ResourceColor = $r('app.color.sidebar_ink'); -/** Desktop `color.content.secondary`. */ -export const SIDEBAR_MUTED: ResourceColor = $r('app.color.sidebar_muted'); -/** Desktop `color.content.caption`. */ -export const SIDEBAR_SUBTLE: ResourceColor = $r('app.color.sidebar_subtle'); -export const STATUS_SUCCESS: ResourceColor = $r('app.color.status_success'); -export const STATUS_DANGER: ResourceColor = $r('app.color.status_danger'); -export const STATUS_WARNING: ResourceColor = $r('app.color.status_warning'); -export const CODE_LINE_NUMBER: ResourceColor = $r('app.color.code_line_number'); -export const CODE_KEYWORD: ResourceColor = $r('app.color.code_keyword'); -export const CODE_STRING: ResourceColor = $r('app.color.code_string'); -export const CODE_NUMBER: ResourceColor = $r('app.color.code_number'); -export const CODE_COMMENT: ResourceColor = $r('app.color.code_comment'); -export const CODE_FUNCTION: ResourceColor = $r('app.color.code_function'); -export const CODE_TYPE: ResourceColor = $r('app.color.code_type'); -export const CODE_CONSTANT: ResourceColor = $r('app.color.code_constant'); -export const CODE_PROPERTY: ResourceColor = $r('app.color.code_property'); -export const CODE_TARGET_BG: ResourceColor = $r('app.color.code_target_bg'); diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ThinkingBlock.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ThinkingBlock.ets deleted file mode 100644 index 7fe6b67953..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ThinkingBlock.ets +++ /dev/null @@ -1,165 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ThinkingPresentationPolicy } from '../policy/ThinkingPresentationPolicy'; -import { MUTED } from './Theme'; - -@ComponentV2 -export struct ThinkingBlock { - @Param text: string = ''; - @Param status: string = ''; - @Param keepExpandedWhenDone: boolean = false; - @Param streaming: boolean = false; - @Param streamKey: string = ''; - @Local dotPhase: number = 0; - @Local expanded: boolean = false; - @Local userToggled: boolean = false; - private dotTimerId: number = 0; - - aboutToAppear(): void { - this.userToggled = false; - this.expanded = ThinkingPresentationPolicy.defaultExpanded(this.isRunning(), this.keepExpandedWhenDone); - this.syncDotTimer(); - } - - aboutToDisappear(): void { - this.stopDotTimer(); - } - - @Monitor('status') - onStatusChanged(): void { - this.expanded = ThinkingPresentationPolicy.expandedForStatus( - this.isRunning(), - this.keepExpandedWhenDone, - this.userToggled, - this.expanded - ); - if (!this.isRunning()) { - this.userToggled = false; - } - this.syncDotTimer(); - } - - build() { - if (ThinkingPresentationPolicy.shouldRender(this.status, this.text)) { - Column({ space: 8 }) { - this.HeaderRow() - if (this.expanded && this.hasBody()) { - Text(this.text) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(MUTED) - .width('100%') - } - } - .width('100%') - .padding({ left: 2, right: 2, top: 2, bottom: this.expanded && this.hasBody() ? 8 : 2 }) - } - } - - @Builder - HeaderRow() { - Row({ space: 8 }) { - Row({ space: 8 }) { - if (this.isRunning()) { - this.RunningDots() - } else { - // The Stack holds the 16vp slot so the label does not shift between - // the running and collapsed states. The glyph itself stays unsized: - // a chevron's natural advance box is only half as wide as it is - // tall, and SymbolGlyph draws the glyph against the left edge of a - // box forced wider than that. - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph(this.expanded ? $r('sys.symbol.chevron_down') : $r('sys.symbol.chevron_right')) - .fontSize(14) - .fontColor([MUTED]) - } - .width(16) - .height(16) - } - Text(this.isRunning() ? RemoteI18n.t('chat.thinkingInProgress') : RemoteI18n.t('chat.thinkingComplete')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .layoutWeight(1) - } - .layoutWeight(1) - .height(32) - .alignItems(VerticalAlign.Center) - .onClick(() => { - if (!ThinkingPresentationPolicy.allowsToggle(this.hasBody())) { - return; - } - this.userToggled = this.isRunning(); - this.expanded = !this.expanded; - }) - .accessibilityText(this.isRunning() ? - RemoteI18n.t('chat.thinkingInProgress') : - RemoteI18n.t('chat.thinkingComplete')) - } - .width('100%') - .height(32) - .alignItems(VerticalAlign.Center) - } - - @Builder - RunningDots() { - Row({ space: ThinkingPresentationPolicy.RUNNING_DOT_GAP }) { - Text('•') - .width(ThinkingPresentationPolicy.RUNNING_DOT_WIDTH) - .height(18) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(MUTED) - .opacity(this.dotOpacity(0)) - .animation({ duration: 180, curve: Curve.EaseInOut }) - Text('•') - .width(ThinkingPresentationPolicy.RUNNING_DOT_WIDTH) - .height(18) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(MUTED) - .opacity(this.dotOpacity(1)) - .animation({ duration: 180, curve: Curve.EaseInOut }) - Text('•') - .width(ThinkingPresentationPolicy.RUNNING_DOT_WIDTH) - .height(18) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(MUTED) - .opacity(this.dotOpacity(2)) - .animation({ duration: 180, curve: Curve.EaseInOut }) - } - // Reserve the full intrinsic strip width. A narrower fixed width lets the - // last dots paint into the following "Thinking" label in ArkUI Rows. - .width(ThinkingPresentationPolicy.runningDotsWidth()) - .height(18) - } - - private dotOpacity(index: number): number { - return this.dotPhase === index ? 1.0 : 0.34; - } - - private isRunning(): boolean { - return ThinkingPresentationPolicy.isRunning(this.status); - } - - private hasBody(): boolean { - return this.text.trim().length > 0; - } - - private syncDotTimer(): void { - if (this.isRunning()) { - if (this.dotTimerId === 0) { - this.dotTimerId = setInterval(() => { - this.dotPhase = (this.dotPhase + 1) % 3; - }, 360); - } - return; - } - this.stopDotTimer(); - } - - private stopDotTimer(): void { - if (this.dotTimerId !== 0) { - clearInterval(this.dotTimerId); - this.dotTimerId = 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolGlyphs.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolGlyphs.ets deleted file mode 100644 index e3b85f683f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolGlyphs.ets +++ /dev/null @@ -1,40 +0,0 @@ -import { MUTED } from './Theme'; - -@ComponentV2 -export struct ToolGlyph { - @Param kind: string = 'tool'; - @Param color: ResourceColor = MUTED; - - build() { - SymbolGlyph(this.symbol()) - .fontSize(this.isChevron() ? 18 : 14) - .fontColor([this.color]) - .width(this.isChevron() ? 14 : 15) - .height(this.isChevron() ? 14 : 15) - } - - private isChevron(): boolean { - return this.kind.indexOf('chevron_') === 0; - } - - private symbol(): Resource { - if (this.kind === 'search') return $r('sys.symbol.magnifyingglass'); - if (this.kind === 'document') return $r('sys.symbol.doc_text'); - if (this.kind === 'stack') return $r('sys.symbol.rectangle_stack'); - if (this.kind === 'question') return $r('sys.symbol.questionmark_circle'); - if (this.kind === 'todo') return $r('sys.symbol.list_checkmark'); - if (this.kind === 'task') return $r('sys.symbol.person'); - if (this.kind === 'git') return $r('sys.symbol.arrow_triangle_merge'); - if (this.kind === 'delete') return $r('sys.symbol.trash'); - if (this.kind === 'diff') return $r('sys.symbol.doc_text_badge_magnifyingglass'); - if (this.kind === 'patch' || this.kind === 'command') return $r('sys.symbol.code_square'); - if (this.kind === 'create') return $r('sys.symbol.doc_text_badge_arrow_up'); - if (this.kind === 'mutate') return $r('sys.symbol.square_and_pencil'); - if (this.kind === 'folder') return $r('sys.symbol.folder'); - if (this.kind === 'web') return $r('sys.symbol.link'); - if (this.kind === 'chevron_right') return $r('sys.symbol.chevron_right'); - if (this.kind === 'chevron_up') return $r('sys.symbol.chevron_up'); - if (this.kind === 'chevron_down') return $r('sys.symbol.chevron_down'); - return $r('sys.symbol.wrench_and_screwdriver'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolInteractionPanels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolInteractionPanels.ets deleted file mode 100644 index fee8e65101..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolInteractionPanels.ets +++ /dev/null @@ -1,336 +0,0 @@ -import { MobileDesignTypography, MobileDesignGeometry } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConversationUiQuestionAnswer } from '../state/ConversationUiModels'; -import { ACCENT, PRIMARY_ACTION, CARD, INK, LINE, MUTED, CONTENT_ON_ACTION, STATUS_DANGER, SOFT } from './Theme'; - -interface QuestionOption { - label: string; - description?: string; -} - -interface QuestionInput { - question: string; - header: string; - options: QuestionOption[]; - multiSelect?: boolean; -} - -interface QuestionPayload { - questions?: QuestionInput[]; -} - -@ComponentV2 -export struct ToolConfirmationPanel { - @Param toolId: string = ''; - @Param defaultInputText: string = ''; - @Param hasEditableInput: boolean = false; - @Param leadingInset: number = 30; - @Param compactActions: boolean = true; - @Param isBusy: boolean = false; - @Event onApproveTool: (toolId: string, updatedInput?: Object) => void = - (_toolId: string, _updatedInput?: Object) => {}; - @Event onRejectTool: (toolId: string) => void = (_toolId: string) => {}; - @Local inputText: string = ''; - @Local inputError: string = ''; - - aboutToAppear(): void { - this.inputText = this.defaultInputText; - } - - build() { - Column({ space: 8 }) { - if (this.hasEditableInput) { - this.InputEditor() - } - if (this.compactActions) { - Row({ space: MobileDesignGeometry.approvalCardGap }) { - Blank() - Button(RemoteI18n.t('chat.reject')) - .fontSize(MobileDesignTypography.labelMedium.size).fontColor(INK) - .height(MobileDesignGeometry.approvalActionHeight).padding({ left: 16, right: 16 }) - .backgroundColor(SOFT).borderRadius(MobileDesignGeometry.approvalActionRadius) - .enabled(!this.isBusy) - .onClick(() => this.onRejectTool(this.toolId)) - Button(RemoteI18n.t('chat.approve')) - .fontSize(MobileDesignTypography.labelMedium.size).fontColor(CONTENT_ON_ACTION) - .height(MobileDesignGeometry.approvalActionHeight).padding({ left: 16, right: 16 }) - .backgroundColor(PRIMARY_ACTION).borderRadius(MobileDesignGeometry.approvalActionRadius) - .enabled(!this.isBusy).onClick(() => this.approve()) - }.width('100%') - } else { - Row({ space: 8 }) { - Text(RemoteI18n.t('chat.approve')) - .fontSize(MobileDesignTypography.labelMedium.size) - .fontColor(CONTENT_ON_ACTION) - .textAlign(TextAlign.Center) - .height(32) - .layoutWeight(1) - .backgroundColor(ACCENT) - .borderRadius(16) - .enabled(!this.isBusy) - .onClick(() => this.approve()) - Text(RemoteI18n.t('chat.reject')) - .fontSize(MobileDesignTypography.labelMedium.size) - .fontColor(INK) - .textAlign(TextAlign.Center) - .height(32) - .layoutWeight(1) - .backgroundColor(SOFT) - .borderRadius(16) - .border({ width: 1, color: LINE }) - .enabled(!this.isBusy) - .onClick(() => this.onRejectTool(this.toolId)) - } - .width('100%') - } - } - .width('100%') - .padding({ left: this.leadingInset }) - } - - @Builder - private InputEditor() { - Column({ space: 6 }) { - Row() { - Text(RemoteI18n.t('chat.toolInput')).fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED) - Blank() - Text(RemoteI18n.t('chat.reset')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .onClick(() => { - this.inputText = this.defaultInputText; - this.inputError = ''; - }) - } - .width('100%') - TextArea({ placeholder: RemoteI18n.t('chat.editJsonInput'), text: this.inputText }) - .height(96) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(INK) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .backgroundColor(SOFT) - .borderRadius(14) - .padding(10) - .border({ width: 1, color: this.inputError.length > 0 ? STATUS_DANGER : LINE }) - .defaultFocus(false) - .enabled(!this.isBusy) - .onChange((value: string) => { - this.inputText = value; - this.inputError = ''; - }) - if (this.inputError.length > 0) { - Text(this.inputError).fontSize(MobileDesignTypography.labelSmall.size).fontColor(STATUS_DANGER) - } - } - .width('100%') - } - - private approve(): void { - if (this.toolId.length === 0 || this.isBusy) { - return; - } - if (!this.hasEditableInput) { - this.onApproveTool(this.toolId); - return; - } - const rawInput = this.inputText.trim(); - if (rawInput.length === 0) { - this.inputError = RemoteI18n.t('chat.jsonObjectRequired'); - return; - } - try { - const parsed = JSON.parse(rawInput) as Object; - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { - this.inputError = RemoteI18n.t('chat.jsonObjectRequired'); - return; - } - this.inputError = ''; - this.onApproveTool(this.toolId, parsed); - } catch (_err) { - this.inputError = RemoteI18n.t('chat.jsonInvalid'); - } - } -} - -@ComponentV2 -export struct ToolQuestionAnswerPanel { - @Param toolId: string = ''; - @Param questionsJson: string = ''; - @Param isBusy: boolean = false; - @Event onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => void = - (_toolId: string, _answers: ConversationUiQuestionAnswer) => {}; - @Local questions: QuestionInput[] = []; - @Local selectedAnswers: Map = new Map(); - @Local customAnswers: Map = new Map(); - - aboutToAppear(): void { - this.questions = this.parseQuestions(this.questionsJson); - } - - @Monitor('questionsJson') - onQuestionsChanged(): void { - this.questions = this.parseQuestions(this.questionsJson); - this.selectedAnswers = new Map(); - this.customAnswers = new Map(); - } - - build() { - Column({ space: 8 }) { - ForEach(this.questions, (question: QuestionInput, index: number) => { - this.Question(question, index); - }, (question: QuestionInput, index: number) => `${index}:${question.header}:${question.question}`) - Row() { - Text(RemoteI18n.t('chat.submitAnswer')) - .fontSize(MobileDesignTypography.labelMedium.size) - .fontColor(this.canSubmit() ? CONTENT_ON_ACTION : MUTED) - .textAlign(TextAlign.Center) - .height(32) - .layoutWeight(1) - .backgroundColor(this.canSubmit() ? ACCENT : SOFT) - .opacity(this.isBusy ? 0.5 : 1) - .borderRadius(16) - .onClick(() => this.submit()) - } - .width('100%') - } - .width('100%') - .padding({ left: 30 }) - } - - @Builder - private Question(question: QuestionInput, index: number) { - Column({ space: 6 }) { - Text(question.header.length > 0 ? `${question.header} ${question.question}` : question.question) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(INK) - .width('100%') - ForEach(question.options, (option: QuestionOption) => { - this.OptionRow(option, index, question.multiSelect === true) - }, (option: QuestionOption) => option.label) - if (this.isOtherSelected(index)) { - TextArea({ placeholder: RemoteI18n.t('chat.answerPlaceholder'), text: this.customAnswers.get(index) || '' }) - .height(64).fontSize(MobileDesignTypography.labelSmall.size).backgroundColor(CARD).borderRadius(10).padding(10) - .border({ width: 1, color: LINE }).defaultFocus(false).enabled(!this.isBusy) - .onChange((value: string) => { - const next = new Map(this.customAnswers); - next.set(index, value); - this.customAnswers = next; - }) - } - } - .width('100%') - } - - // The label is the thing being chosen, so it wraps rather than truncates: an - // option the user cannot read in full is one they cannot pick with any - // confidence. That rules out a fixed row height and a side-by-side - // description, which on a phone leaves the label a sliver of the row. - @Builder - private OptionRow(option: QuestionOption, index: number, multiSelect: boolean) { - Row({ space: 8 }) { - SymbolGlyph(this.isSelected(index, option.label) ? - $r('sys.symbol.checkmark_circle_fill') : $r('sys.symbol.circle')) - .fontSize(18) - .fontColor([this.isSelected(index, option.label) ? INK : MUTED]) - .width(20) - Column({ space: 3 }) { - Text(option.label) - .fontSize(MobileDesignTypography.bodyMedium.size) - .lineHeight(MobileDesignTypography.bodyMedium.lineHeight) - .fontColor(INK) - .width('100%') - if (option.description && option.description.length > 0) { - Text(option.description) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .maxLines(3) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .width('100%') - } - } - .layoutWeight(1) - .alignItems(HorizontalAlign.Start) - } - .width('100%') - .alignItems(VerticalAlign.Top) - .padding({ left: 10, right: 10, top: 9, bottom: 9 }) - .backgroundColor(this.isSelected(index, option.label) ? SOFT : CARD).borderRadius(10) - .onClick(() => this.toggleOption(index, option.label, multiSelect)) - } - - private canSubmit(): boolean { - if (this.isBusy || this.toolId.length === 0 || this.questions.length === 0) { - return false; - } - return this.questions.every((_question: QuestionInput, index: number) => { - const selected = this.selectedAnswers.get(index) || []; - if (selected.length === 0) return false; - return !this.isOtherSelected(index) || (this.customAnswers.get(index) || '').trim().length > 0; - }); - } - - private isSelected(index: number, label: string): boolean { - return (this.selectedAnswers.get(index) || []).indexOf(label) >= 0; - } - - private isOtherSelected(index: number): boolean { - return this.isSelected(index, RemoteI18n.t('common.other')); - } - - private toggleOption(index: number, label: string, multiSelect: boolean): void { - if (this.isBusy) return; - const current = (this.selectedAnswers.get(index) || []).slice(); - if (multiSelect) { - const position = current.indexOf(label); - if (position >= 0) current.splice(position, 1); - else current.push(label); - } else { - current.splice(0, current.length, label); - } - const next = new Map(this.selectedAnswers); - next.set(index, current); - this.selectedAnswers = next; - } - - private submit(): void { - if (!this.canSubmit()) { - return; - } - const answers: ConversationUiQuestionAnswer = {}; - this.questions.forEach((question: QuestionInput, index: number) => { - const selected = (this.selectedAnswers.get(index) || []).map((value: string) => { - return value === RemoteI18n.t('common.other') ? (this.customAnswers.get(index) || '').trim() : value; - }); - const value: string | string[] = question.multiSelect === true ? selected : selected[0]; - (answers as Record)[`${index}`] = value as Object; - }); - this.onAnswerQuestion(this.toolId, answers); - } - - private parseQuestions(value: string): QuestionInput[] { - try { - const payload = JSON.parse(value) as QuestionPayload; - return (payload.questions || []).map((question: QuestionInput) => this.normalizeQuestion(question)) - .filter((question: QuestionInput) => question.question.length > 0); - } catch (_err) { - return []; - } - } - - private normalizeQuestion(question: QuestionInput): QuestionInput { - const normalized: QuestionInput = { - question: question.question || '', - header: question.header || '', - options: (question.options || []).slice(), - multiSelect: question.multiSelect === true - }; - const otherLabel = RemoteI18n.t('common.other'); - if (!normalized.options.some((option: QuestionOption) => option.label.trim().toLowerCase() === 'other' || - option.label === otherLabel)) { - normalized.options.push({ label: otherLabel, description: '' }); - } - return normalized; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets deleted file mode 100644 index e02a3f5436..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ToolStatusList.ets +++ /dev/null @@ -1,1014 +0,0 @@ -import { InteractionMailboxState } from '../../model/InteractionMailbox'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { - ConversationUiPlanTool, - ConversationUiQuestionAnswer, - ConversationUiToolStatus -} from '../state/ConversationUiModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ToolFileReference, ToolFileReferenceResolver } from '../policy/ToolFileReferenceResolver'; -import { ActivityGroupPolicy, ActivityRowPlan, ActivityThinkingPart } from '../policy/ActivityGroupPolicy'; -import { ToolCollapseGroup, ToolCollapsePolicy } from '../policy/ToolCollapsePolicy'; -import { ToolStatusPresentationPolicy } from '../policy/ToolStatusPresentationPolicy'; -import { PlanToolPolicy } from '../policy/PlanToolPolicy'; -import { - CARD, - FILE_LINK, - INK, - LINE, - MUTED, - SHADOW_SUBTLE, - SOFT, - STATUS_DANGER, - STATUS_SUCCESS, - TRANSPARENT, -} from './Theme'; -import { ThinkingBlock } from './ThinkingBlock'; -import { ToolGlyph } from './ToolGlyphs'; -import { ToolConfirmationPanel, ToolQuestionAnswerPanel } from './ToolInteractionPanels'; - -interface TodoPreviewItem { - content?: string; - status?: string; -} - -interface ToolInputSummaryPayload { - todos?: TodoPreviewItem[]; - content?: string; - command?: string; - cmd?: string; - pattern?: string; - regex?: string; - query?: string; - search_term?: string; - needle?: string; - path?: string; - file_path?: string; - filePath?: string; - url?: string; - prompt?: string; - question?: string; - description?: string; - title?: string; - task?: string; -} - -interface ToolRenderEntry { - type: string; - key: string; - tool?: ConversationUiToolStatus; - thinking?: ActivityThinkingPart; - tools: ConversationUiToolStatus[]; - readCount: number; - searchCount: number; - commandCount: number; - otherCount: number; -} - -@ComponentV2 -export struct ToolStatusList { - @Param interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - @Param tools: ConversationUiToolStatus[] = []; - /** Reasoning that ran between these tools; folded away with them. */ - @Param thinkingParts: ActivityThinkingPart[] = []; - /** Explicit invalidation signal for replacement snapshots from the relay. */ - @Param renderRevision: number = 0; - @Param isBusy: boolean = false; - @Event onApproveTool: (toolId: string, updatedInput?: Object) => void = - (_toolId: string, _updatedInput?: Object) => {}; - @Event onRejectTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onCancelTool: (toolId: string) => void = (_toolId: string) => {}; - @Event onAnswerQuestion: (toolId: string, answers: ConversationUiQuestionAnswer) => void = - (_toolId: string, _answers: ConversationUiQuestionAnswer) => {}; - @Event onOpenFilePreview: (path: string, label: string) => void = - (_path: string, _label: string) => {}; - @Event onBuildPlan: (path: string, name: string) => void = (_path: string, _name: string) => {}; - @Local expanded: boolean = false; - @Local expandedToolKey: string = ''; - @Local editingApprovalKey: string = ''; - - build() { - Column({ space: 4 }) { - ForEach(this.toolRenderEntries(this.renderRevision), (entry: ToolRenderEntry, index: number) => { - if (entry.type === 'summary') { - this.CollapsedToolSummary(entry) - } else if (entry.thinking) { - this.ThinkingRow(entry.thinking) - } else if (entry.tool) { - if (PlanToolPolicy.isPlanTool(entry.tool)) { - this.PlanCard(entry.tool) - } else { - this.ToolRow(entry.tool, index) - } - } - }, (entry: ToolRenderEntry) => entry.key) - } - .width('100%') - } - - @Builder - PlanCard(tool: ConversationUiToolStatus) { - Column({ space: 12 }) { - Row({ space: 10 }) { - Stack({ alignContent: Alignment.Center }) { - ToolGlyph({ kind: 'document', color: INK }) - } - .width(32) - .height(32) - .backgroundColor(SOFT) - .borderRadius(9) - Column({ space: 2 }) { - Text(this.planDescriptor(tool).name) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(this.planSubtitle(tool)) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .alignItems(HorizontalAlign.Start) - .layoutWeight(1) - } - .width('100%') - .alignItems(VerticalAlign.Center) - - Row({ space: 8 }) { - Text(RemoteI18n.t('chat.planView')) - .fontSize(MobileDesignTypography.labelMedium.size) - .fontColor(this.planDescriptor(tool).file_path.length > 0 ? INK : MUTED) - .textAlign(TextAlign.Center) - .height(36) - .layoutWeight(1) - .padding({ left: 12, right: 12 }) - .backgroundColor(SOFT) - .borderRadius(18) - .border({ width: 1, color: LINE }) - .enabled(this.planDescriptor(tool).file_path.length > 0) - .onClick(() => { - const plan = this.planDescriptor(tool); - if (plan.file_path.length > 0) { - this.onOpenFilePreview(plan.file_path, plan.name); - } - }) - Text(RemoteI18n.t('chat.planBuild')) - .fontSize(MobileDesignTypography.labelMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(this.canStartPlanBuild(tool) ? CARD : MUTED) - .textAlign(TextAlign.Center) - .height(36) - .layoutWeight(1) - .padding({ left: 12, right: 12 }) - .backgroundColor(this.canStartPlanBuild(tool) ? INK : SOFT) - .borderRadius(18) - .border({ width: 1, color: this.canStartPlanBuild(tool) ? INK : LINE }) - .enabled(this.canStartPlanBuild(tool)) - .onClick(() => { - const plan = this.planDescriptor(tool); - if (this.canStartPlanBuild(tool)) { - this.onBuildPlan(plan.file_path, plan.name); - } - }) - } - .width('100%') - } - .width('100%') - .padding(14) - .backgroundColor(CARD) - .borderRadius(18) - .border({ width: 1, color: LINE }) - .shadow({ radius: 12, color: SHADOW_SUBTLE, offsetY: 4 }) - } - - @Builder - CollapsedToolSummary(entry: ToolRenderEntry) { - Row({ space: 8 }) { - this.SummaryTypeBadge(entry) - Text(this.collapsedSummaryTitle(entry)) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(MUTED) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - this.ChevronIcon(this.expanded ? 'up' : 'down') - } - .width('100%') - .height(28) - .alignItems(VerticalAlign.Center) - .padding({ left: 0, right: 0 }) - .onClick(() => { - this.expanded = !this.expanded; - }) - } - - @Builder - ThinkingRow(part: ActivityThinkingPart) { - ThinkingBlock({ - text: part.text, - status: part.status, - keepExpandedWhenDone: false, - streaming: part.streaming, - streamKey: part.streamKey - }) - } - - @Builder - ToolRow(tool: ConversationUiToolStatus, index: number) { - if (this.isTodoTool(tool)) { - this.TodoCard(tool, index) - } else { - Column({ space: 4 }) { - Row({ space: 8 }) { - this.ToolStatusIcon(tool) - Text(this.toolLineLabel(tool)) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontColor(this.toolFilePath(tool).length > 0 ? FILE_LINK : MUTED) - .layoutWeight(1) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .onClick(() => { - if (this.toolFilePath(tool).length > 0) { - this.openToolFile(tool); - } else { - this.toggleToolExpanded(tool, index); - } - }) - this.TrailingChevron(tool, index) - } - .width('100%') - .height(28) - .alignItems(VerticalAlign.Center) - - if (this.canExpandTool(tool) && this.expandedToolKey === this.toolKey(tool, index)) { - if (this.toolInputPreview(tool).length > 0) { - this.ToolDetail(this.operationLabel(tool), this.toolInputPreview(tool), false) - } - if (this.toolResultPreview(tool).length > 0) { - this.ToolDetail(this.hasToolError(tool) ? RemoteI18n.t('chat.error') : RemoteI18n.t('chat.output'), this.toolResultPreview(tool), this.hasToolError(tool)) - } - } - - if (this.isPendingConfirmation(tool) && !this.interactionMailbox.ownsToolInteraction(tool.id || '')) { - if (this.hasEditableToolInput(tool)) { - Row() { - Blank() - Button(RemoteI18n.t(this.editingApprovalKey === this.toolKey(tool, index) ? 'chat.hideApprovalInput' : 'chat.editApprovalInput')) - .fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED) - .backgroundColor(SOFT).height(32).padding({ left: 8, right: 8 }) - .enabled(!this.isBusy) - .onClick(() => { this.editingApprovalKey = this.editingApprovalKey === this.toolKey(tool, index) ? '' : this.toolKey(tool, index); }) - }.width('100%') - } - ToolConfirmationPanel({ - toolId: tool.permission_request_id ? `permission:${tool.permission_request_id}` : tool.id || '', - defaultInputText: this.defaultToolInputText(tool), - hasEditableInput: this.hasEditableToolInput(tool) && this.editingApprovalKey === this.toolKey(tool, index), - isBusy: this.isBusy, - onApproveTool: this.onApproveTool, - onRejectTool: this.onRejectTool - }) - } - if (this.isQuestionTool(tool) && !this.interactionMailbox.ownsToolInteraction(tool.id || '')) { - ToolQuestionAnswerPanel({ - toolId: tool.id || '', - questionsJson: this.questionInputJson(tool), - isBusy: this.isBusy, - onAnswerQuestion: this.onAnswerQuestion - }) - } - if ((this.isRunningTool(tool) || this.isQuestionTool(tool)) && - !(this.isQuestionTool(tool) && this.interactionMailbox.ownsToolInteraction(tool.id || ''))) { - Row() { - Blank() - Text(RemoteI18n.t('chat.cancelTool')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(INK) - .textAlign(TextAlign.Center) - .height(32) - .padding({ left: 14, right: 14 }) - .backgroundColor(SOFT) - .borderRadius(16) - .border({ width: 1, color: LINE }) - .onClick(() => { - this.onCancelTool(tool.id || ''); - }) - } - .width('100%') - .padding({ left: 30 }) - } - } - .width('100%') - .padding({ - left: this.toolRowHorizontalPadding(tool, index), - right: this.toolRowHorizontalPadding(tool, index), - top: this.toolRowVerticalPadding(tool, index), - bottom: this.toolRowVerticalPadding(tool, index) - }) - .backgroundColor(this.toolRowBg(tool, index)) - .borderRadius(this.toolRowRadius(tool, index)) - .border({ width: this.toolRowBorderWidth(tool, index), color: LINE }) - } - } - - @Builder - TodoCard(tool: ConversationUiToolStatus, index: number) { - Column({ space: 8 }) { - Row({ space: 9 }) { - Stack({ alignContent: Alignment.Center }) { - ToolGlyph({ kind: 'todo', color: STATUS_SUCCESS }) - }.width(22).height(22).backgroundColor(STATUS_SUCCESS).opacity(0.14).borderRadius(6) - Column({ space: 2 }) { - Text(this.operationLabel(tool)).fontSize(MobileDesignTypography.bodySmall.size).fontWeight(FontWeight.Medium).fontColor(INK) - Text(this.todoSummary(tool)).fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED).maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) - }.layoutWeight(1).alignItems(HorizontalAlign.Start) - if (this.todoItems(tool).length > 0) { Text(`${this.todoDone(tool)}/${this.todoItems(tool).length}`).fontSize(MobileDesignTypography.labelSmall.size).fontColor(MUTED) } - this.ChevronIcon(this.expandedToolKey === this.toolKey(tool, index) ? 'down' : 'right') - }.width('100%').height(32).onClick(() => { this.expandedToolKey = this.expandedToolKey === this.toolKey(tool, index) ? '' : this.toolKey(tool, index); }) - if (this.expandedToolKey === this.toolKey(tool, index) && this.todoItems(tool).length > 0) { - Column({ space: 8 }) { - Row() { - Blank().width(`${this.todoItems(tool).length > 0 ? this.todoDone(tool) * 100 / this.todoItems(tool).length : 0}%`).height(2).backgroundColor(MUTED) - }.width('100%').height(2).backgroundColor(LINE).borderRadius(2) - - ForEach(this.todoItems(tool), (item: TodoPreviewItem, itemIndex: number) => { - Row({ space: 8 }) { - Text((item.status || '').toLowerCase() === 'completed' ? '✓' : (item.status || '').toLowerCase() === 'in_progress' ? '•' : '○') - .fontSize(MobileDesignTypography.bodySmall.size).fontColor((item.status || '').toLowerCase() === 'completed' ? STATUS_SUCCESS : MUTED) - Text(item.content || '').fontSize(MobileDesignTypography.bodySmall.size).fontColor(INK).layoutWeight(1).maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - }, (item: TodoPreviewItem, itemIndex: number) => `${this.toolKey(tool, index)}-${itemIndex}`) - }.width('100%').padding({ left: 31 }) - } - if (this.expandedToolKey === this.toolKey(tool, index) && this.todoItems(tool).length === 0 && this.toolResultPreview(tool).length > 0) { - this.ToolDetail(RemoteI18n.t('chat.output'), this.toolResultPreview(tool), this.hasToolError(tool)) - } - }.width('100%').padding({ left: 10, right: 10, top: 10, bottom: 10 }).backgroundColor(SOFT).borderRadius(14).border({ width: 1, color: LINE }) - } - - private todoSummary(tool: ConversationUiToolStatus): string { - let items = this.todoItems(tool); - let active = items.find((item: TodoPreviewItem) => (item.status || '').toLowerCase() === 'in_progress') || - items.find((item: TodoPreviewItem) => (item.status || '').toLowerCase() === 'pending'); - if (items.length === 0) return this.summaryLabel(tool); - if (this.todoDone(tool) === items.length) return RemoteI18n.t('chat.thinkingDone'); - return active?.content || items[0].content || RemoteI18n.t('chat.toolTodoFallback'); - } - - private todoDone(tool: ConversationUiToolStatus): number { - return this.todoItems(tool).filter((item: TodoPreviewItem) => (item.status || '').toLowerCase() === 'completed').length; - } - - private todoItems(tool: ConversationUiToolStatus): TodoPreviewItem[] { - let values: string[] = []; - if (tool.tool_input) values.push(JSON.stringify(tool.tool_input)); - if (tool.input_preview) values.push(tool.input_preview); - if (tool.tool_output) values.push(JSON.stringify(tool.tool_output)); - if (tool.result_preview) values.push(tool.result_preview); - for (let value of values) { - try { - let parsed = JSON.parse(value) as ToolInputSummaryPayload; - if (parsed.todos && parsed.todos.length > 0) return parsed.todos; - } catch (_error) {} - } - return []; - } - - @Builder - ToolStatusIcon(tool: ConversationUiToolStatus) { - Stack({ alignContent: Alignment.BottomEnd }) { - this.ToolTypeBadge(tool) - if (this.shouldShowStatusBadge(tool)) { - this.ToolStatusBadge(tool) - } - } - .width(20) - .height(20) - } - - @Builder - TrailingChevron(tool: ConversationUiToolStatus, index: number) { - if (this.canExpandTool(tool)) { - Stack({ alignContent: Alignment.Center }) { - this.ChevronIcon(this.expandedToolKey === this.toolKey(tool, index) ? 'down' : 'right') - } - .width(32) - .height(28) - .onClick(() => { - this.toggleToolExpanded(tool, index); - }) - } else { - Text('') - .width(14) - .height(14) - } - } - - @Builder - SummaryTypeBadge(entry: ToolRenderEntry) { - Stack({ alignContent: Alignment.Center }) { - this.SummaryTypeSymbol(entry) - } - .width(18) - .height(18) - .backgroundColor(this.summaryTypeBg(entry)) - .borderRadius(5) - .border({ width: 1, color: TRANSPARENT }) - } - - @Builder - ToolTypeBadge(tool: ConversationUiToolStatus) { - Stack({ alignContent: Alignment.Center }) { - this.ToolTypeSymbol(tool) - } - .width(18) - .height(18) - .backgroundColor(this.toolTypeBg(tool)) - .borderRadius(5) - .border({ width: 1, color: this.toolTypeBorderColor(tool) }) - } - - @Builder - SummaryTypeSymbol(entry: ToolRenderEntry) { - ToolGlyph({ kind: this.summaryGlyphKind(entry), color: this.summaryTypeColor(entry) }) - } - - @Builder - ToolTypeSymbol(tool: ConversationUiToolStatus) { - ToolGlyph({ kind: this.toolGlyphKind(tool), color: this.toolTypeColor(tool) }) - } - - @Builder - ToolStatusBadge(tool: ConversationUiToolStatus) { - Text(this.toolStatusIcon(tool)) - .width(10) - .height(10) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontWeight(FontWeight.Bold) - .fontColor(CARD) - .textAlign(TextAlign.Center) - .backgroundColor(this.toolStatusColor(tool)) - .borderRadius(5) - .border({ width: 1, color: CARD }) - } - - @Builder - ChevronIcon(direction: string) { - ToolGlyph({ kind: `chevron_${direction}`, color: MUTED }) - } - - @Builder - ToolDetail(label: string, value: string, isError: boolean) { - Column({ space: 4 }) { - Text(label) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - Text(value) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(isError ? STATUS_DANGER : MUTED) - .width('100%') - .maxLines(5) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .width('100%') - .padding({ left: 30, top: 2 }) - } - - private displayStatus(status: string): string { - const normalized = (status || '').toLowerCase(); - if (normalized === 'running' || normalized === 'active') { - return RemoteI18n.t('common.running'); - } - if (normalized === 'pending_confirmation' || normalized === 'needs_confirmation') { - return RemoteI18n.t('chat.pendingConfirmation'); - } - if (normalized === 'completed' || normalized === 'done' || normalized === 'sent') { - return RemoteI18n.t('common.done'); - } - if (normalized === 'failed' || normalized === 'error') { - return RemoteI18n.t('common.failed'); - } - if (normalized === 'cancelled' || normalized === 'canceled') { - return RemoteI18n.t('chat.cancelled'); - } - return status || RemoteI18n.t('common.waiting'); - } - - private isEmphasizedToolRow(tool: ConversationUiToolStatus, index: number): boolean { - return this.expandedToolKey === this.toolKey(tool, index) || - this.isPendingConfirmation(tool) || - this.isQuestionTool(tool) || - this.isRunningTool(tool); - } - - private toolRowBg(tool: ConversationUiToolStatus, index: number): ResourceColor { - if (this.isEmphasizedToolRow(tool, index)) { - return SOFT; - } - return TRANSPARENT; - } - - private toolRowBorderWidth(tool: ConversationUiToolStatus, index: number): number { - return this.isEmphasizedToolRow(tool, index) ? 1 : 0; - } - - private toolRowRadius(tool: ConversationUiToolStatus, index: number): number { - return this.isEmphasizedToolRow(tool, index) ? 14 : 8; - } - - private toolRowVerticalPadding(tool: ConversationUiToolStatus, index: number): number { - return this.isEmphasizedToolRow(tool, index) ? 6 : 0; - } - - private toolRowHorizontalPadding(tool: ConversationUiToolStatus, index: number): number { - return this.isEmphasizedToolRow(tool, index) ? 10 : 0; - } - - private toolRenderEntries(_renderRevision: number): ToolRenderEntry[] { - const groups = this.expanded ? - ToolCollapsePolicy.expandedGroups(this.tools) : - ToolCollapsePolicy.collapsedGroups(this.tools); - const parts = ActivityGroupPolicy.mergeThinkingParts(this.thinkingParts); - // Without a summary row there is nothing to expand, so the reasoning has to - // stay on screen or it would be lost. - const showThinking = this.expanded || !ActivityGroupPolicy.hasSummaryRow(groups); - const entries: ToolRenderEntry[] = []; - ActivityGroupPolicy.weaveRows(groups, parts, showThinking).forEach((row: ActivityRowPlan) => { - if (row.kind === 'thinking') { - entries.push(this.thinkingEntry(parts[row.index])); - return; - } - entries.push(this.entryFromGroup(groups[row.index])); - }); - return entries; - } - - private thinkingEntry(part: ActivityThinkingPart): ToolRenderEntry { - return { - type: 'thinking', - key: part.streamKey, - thinking: part, - tools: [], - readCount: 0, - searchCount: 0, - commandCount: 0, - otherCount: 0 - }; - } - - private entryFromGroup(group: ToolCollapseGroup): ToolRenderEntry { - if (group.type === 'summary') { - const stats = this.collapsedToolStats(group.tools); - return { - type: 'summary', - key: `summary-${group.startIndex}-${group.tools.length}-${stats.readCount}-${stats.searchCount}-${stats.commandCount}-${stats.otherCount}`, - tools: group.tools, - readCount: stats.readCount, - searchCount: stats.searchCount, - commandCount: stats.commandCount, - otherCount: stats.otherCount - }; - } - const tool = group.tools[0]; - return this.toolEntry(tool, group.startIndex); - } - - private toolEntry(tool: ConversationUiToolStatus, index: number): ToolRenderEntry { - return { - type: 'tool', - key: this.toolKey(tool, index), - tool, - tools: [], - readCount: 0, - searchCount: 0, - commandCount: 0, - otherCount: 0 - }; - } - - private collapsedToolStats(tools: ConversationUiToolStatus[]): ToolRenderEntry { - let readCount = 0; - let searchCount = 0; - let commandCount = 0; - let otherCount = 0; - tools.forEach((tool: ConversationUiToolStatus) => { - const kind = this.exploreToolKind(tool); - if (kind === 'read') { - readCount += 1; - } else if (kind === 'search') { - searchCount += 1; - } else if (this.isCommandTool(tool)) { - commandCount += 1; - } else { - otherCount += 1; - } - }); - return { - type: 'summary', - key: '', - tools, - readCount, - searchCount, - commandCount, - otherCount - }; - } - - private exploreToolKind(tool: ConversationUiToolStatus): string { - const raw = tool.name || ''; - const normalized = this.normalizedToolName(tool); - if (raw === 'Read' || normalized === 'read' || normalized === 'read_file' || - raw === 'LS' || normalized === 'ls' || normalized === 'list_directory') { - return 'read'; - } - if (raw === 'Grep' || raw === 'Glob' || raw === 'WebSearch' || - normalized === 'grep' || normalized === 'glob' || normalized === 'websearch' || - normalized === 'web_search' || normalized === 'semanticsearch' || normalized === 'semantic_search') { - return 'search'; - } - return ''; - } - - private collapsedSummaryTitle(entry: ToolRenderEntry): string { - return RemoteI18n.f('chat.toolsRan', `${entry.tools.length}`); - } - - private normalizedToolName(tool: ConversationUiToolStatus): string { - return ToolStatusPresentationPolicy.normalizedName(tool); - } - - private summaryGlyphKind(entry: ToolRenderEntry): string { - if (entry.searchCount > 0 && entry.readCount === 0) return 'search'; - if (entry.readCount > 0 && entry.searchCount === 0) return 'document'; - return 'stack'; - } - - private toolGlyphKind(tool: ConversationUiToolStatus): string { - if (this.isQuestionLikeTool(tool)) return 'question'; - if (this.isTodoTool(tool)) return 'todo'; - if (this.isTaskTool(tool)) return 'task'; - if (this.isGitTool(tool)) return 'git'; - if (this.isDeleteTool(tool)) return 'delete'; - if (this.isDiffTool(tool)) return 'diff'; - if (this.isPatchTool(tool)) return 'patch'; - if (this.isFileCreateTool(tool)) return 'create'; - if (this.isFileMutationTool(tool)) return 'mutate'; - if (this.isFileReadTool(tool)) return this.isDirectoryListTool(tool) ? 'folder' : 'document'; - if (this.isSearchTool(tool)) return 'search'; - if (this.isWebTool(tool)) return 'web'; - if (this.isCommandTool(tool)) return 'command'; - return 'tool'; - } - - private isQuestionLikeTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isQuestionLike(tool); - } - - private isTodoTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isTodo(tool); - } - - private isTaskTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isTask(tool); - } - - private isDirectoryListTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isDirectoryList(tool); - } - - private isFileReadTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isFileRead(tool); - } - - private isFileMutationTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isFileMutation(tool); - } - - private isCommandTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isCommand(tool); - } - - private isGitTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isGit(tool); - } - - private isWebTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isWeb(tool); - } - - private isDiffTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isDiff(tool); - } - - private isDeleteTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isDelete(tool); - } - - private isFileCreateTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isFileCreate(tool); - } - - private isPatchTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isPatch(tool); - } - - private isSearchTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isSearch(tool); - } - - private operationLabel(tool: ConversationUiToolStatus): string { - const raw = tool.name || 'Tool'; - const normalized = this.normalizedToolName(tool); - if (raw === 'TodoWrite' || normalized === 'todo_write' || normalized === 'todowrite') { - return RemoteI18n.t('chat.toolOpTodoWrite'); - } - if (raw === 'Task' || normalized === 'task') { - return RemoteI18n.t('chat.toolOpTask'); - } - if (this.isFileReadTool(tool)) { - return RemoteI18n.t('chat.toolOpRead'); - } - if (raw === 'Write' || raw === 'Create' || normalized === 'write' || normalized === 'write_file' || - normalized === 'create_file') { - return RemoteI18n.t('chat.toolOpWrite'); - } - if (raw === 'Delete' || normalized === 'delete' || normalized === 'delete_file') { - return RemoteI18n.t('chat.toolOpDelete'); - } - if (raw === 'GetFileDiff' || normalized === 'get_file_diff' || normalized === 'getfilediff') { - return RemoteI18n.t('chat.toolOpDiff'); - } - if (this.isFileMutationTool(tool)) { - return RemoteI18n.t('chat.toolOpEdit'); - } - if (this.isCommandTool(tool)) { - return RemoteI18n.t('chat.toolOpCommand'); - } - if (raw === 'WebSearch' || normalized === 'websearch' || normalized === 'web_search') { - return RemoteI18n.t('chat.toolOpWebSearch'); - } - if (this.isWebTool(tool)) { - return RemoteI18n.t('chat.toolOpWebFetch'); - } - if (this.isSearchTool(tool)) { - return RemoteI18n.t('chat.toolOpSearch'); - } - if (raw === 'AskUserQuestion') { - return RemoteI18n.t('chat.toolOpAskUser'); - } - return raw; - } - - private summaryLabel(tool: ConversationUiToolStatus): string { - const parsed = this.toolInputPayload(tool); - const fromPayload = this.summaryFromPayload(tool, parsed); - if (fromPayload.length > 0) { - return this.compactText(fromPayload, 46); - } - - const preview = this.toolInputPreview(tool); - if (preview.length > 0 && !this.looksLikeJson(preview)) { - return this.compactText(preview, 46); - } - return tool.name || 'Tool'; - } - - private toolInputPayload(tool: ConversationUiToolStatus): ToolInputSummaryPayload { - if (tool.tool_input) { - try { - return JSON.parse(JSON.stringify(tool.tool_input)) as ToolInputSummaryPayload; - } catch (_err) { - } - } - const preview = tool.input_preview || ''; - if (preview.trim().length > 0) { - try { - return JSON.parse(preview) as ToolInputSummaryPayload; - } catch (_err) { - } - } - return {}; - } - - private summaryFromPayload(tool: ConversationUiToolStatus, payload: ToolInputSummaryPayload): string { - const name = tool.name || ''; - if ((name === 'TodoWrite' || this.normalizedToolName(tool) === 'todowrite') && - payload.todos && payload.todos.length > 0) { - return payload.todos[0].content || RemoteI18n.t('chat.toolTodoFallback'); - } - - if (name === 'Task') { - return ToolStatusPresentationPolicy.taskTitle(tool) || RemoteI18n.t('chat.toolTaskFallback'); - } - - const path = payload.file_path || payload.filePath || payload.path || ''; - if (path.length > 0) { - return this.lastPathSegment(path); - } - - return payload.description || - payload.command || - payload.cmd || - payload.pattern || - payload.regex || - payload.query || - payload.search_term || - payload.needle || - payload.title || - payload.question || - payload.prompt || - payload.content || - payload.url || - ''; - } - - private lastPathSegment(path: string): string { - const normalized = path.replace(/\\/g, '/'); - const parts = normalized.split('/'); - return parts[parts.length - 1] || normalized; - } - - private looksLikeJson(value: string): boolean { - const text = value.trim(); - return text.indexOf('{') === 0 || text.indexOf('[') === 0; - } - - private compactText(value: string, limit: number): string { - const text = value.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim(); - if (text.length <= limit) { - return text; - } - return `${text.slice(0, limit)}...`; - } - - private toolLineLabel(tool: ConversationUiToolStatus): string { - if (this.isRunningTool(tool)) { - return `${RemoteI18n.t('chat.toolRunning')} “${this.compactText(this.operationTarget(tool), 24)}”`; - } - if (this.isPendingConfirmation(tool) || this.isQuestionTool(tool)) { - return `${this.displayStatus(tool.status || 'pending')} · ${this.operationLabel(tool)}`; - } - if (this.isCompletedTool(tool) || this.isCancelledTool(tool) || this.hasToolError(tool)) { - return `${this.operationLabel(tool)} · ${this.compactText(this.operationTarget(tool), 28)}`; - } - return `${this.displayStatus(tool.status || 'pending')} · ${this.operationLabel(tool)}`; - } - - private operationTarget(tool: ConversationUiToolStatus): string { - const summary = this.summaryLabel(tool); - if (summary.length > 0 && summary !== tool.name) { - return summary; - } - return this.operationLabel(tool); - } - - private toolFileReference(tool: ConversationUiToolStatus): ToolFileReference | undefined { - return ToolFileReferenceResolver.resolve(tool.name || '', tool.tool_input, tool.input_preview || ''); - } - - private toolFilePath(tool: ConversationUiToolStatus): string { - return this.toolFileReference(tool)?.path || ''; - } - - private openToolFile(tool: ConversationUiToolStatus): void { - const reference = this.toolFileReference(tool); - if (reference) { - this.onOpenFilePreview(reference.path, reference.label); - } - } - - private toggleToolExpanded(tool: ConversationUiToolStatus, index: number): void { - if (!this.canExpandTool(tool)) { - return; - } - const key = this.toolKey(tool, index); - this.expandedToolKey = this.expandedToolKey === key ? '' : key; - } - - private canExpandTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.canExpand(tool); - } - - private toolTypeColor(tool: ConversationUiToolStatus): ResourceColor { - if (this.isDeleteTool(tool)) { - return STATUS_DANGER; - } - if (this.isTodoTool(tool) || this.isFileCreateTool(tool)) { - return STATUS_SUCCESS; - } - return MUTED; - } - - private toolTypeBg(_tool: ConversationUiToolStatus): ResourceColor { - return SOFT; - } - - private toolTypeBorderColor(tool: ConversationUiToolStatus): ResourceColor { - return LINE; - } - - private toolStatusIcon(tool: ConversationUiToolStatus): string { - const normalized = (tool.status || '').toLowerCase(); - if (normalized === 'running' || normalized === 'active') { - return '•'; - } - if (normalized === 'pending_confirmation' || normalized === 'needs_confirmation') { - return '?'; - } - if (normalized === 'cancelled' || normalized === 'canceled' || normalized === 'rejected') { - return '×'; - } - return '•'; - } - - private toolStatusColor(tool: ConversationUiToolStatus): ResourceColor { - return MUTED; - } - - private shouldShowStatusBadge(tool: ConversationUiToolStatus): boolean { - return this.isPendingConfirmation(tool) || - this.isQuestionTool(tool) || - this.isRunningTool(tool) || - this.isCancelledTool(tool); - } - - private summaryTypeColor(_entry: ToolRenderEntry): ResourceColor { - return MUTED; - } - - private summaryTypeBg(_entry: ToolRenderEntry): ResourceColor { - return SOFT; - } - - private toolInputPreview(tool: ConversationUiToolStatus): string { - return ToolStatusPresentationPolicy.inputPreview(tool); - } - - private toolResultPreview(tool: ConversationUiToolStatus): string { - return ToolStatusPresentationPolicy.resultPreview(tool); - } - - private hasToolError(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.hasError(tool); - } - - private isPendingConfirmation(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isPendingConfirmation(tool); - } - - private hasEditableToolInput(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.hasEditableInput(tool); - } - - private defaultToolInputText(tool: ConversationUiToolStatus): string { - return ToolStatusPresentationPolicy.defaultInputText(tool); - } - - private isRunningTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isRunning(tool); - } - - private isCompletedTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isCompleted(tool); - } - - private isCancelledTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isCancelled(tool); - } - - private isQuestionTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.isQuestion(tool); - } - - private questionInputJson(tool: ConversationUiToolStatus): string { - return ToolStatusPresentationPolicy.questionInputJson(tool); - } - - private planDescriptor(tool: ConversationUiToolStatus): ConversationUiPlanTool { - return PlanToolPolicy.descriptor(tool) || { file_path: '', name: 'Plan' }; - } - - private planSubtitle(tool: ConversationUiToolStatus): string { - const plan = this.planDescriptor(tool); - if ((plan.overview || '').trim().length > 0) { - return plan.overview || ''; - } - if (plan.file_path.length > 0) { - return this.compactText(plan.file_path, 54); - } - return this.displayStatus(tool.status || 'pending'); - } - - private canStartPlanBuild(tool: ConversationUiToolStatus): boolean { - return !this.isBusy && PlanToolPolicy.canBuild(tool); - } - - private toolKey(tool: ConversationUiToolStatus, index: number): string { - return ToolStatusPresentationPolicy.key(tool, index); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UsageReportSheet.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UsageReportSheet.ets deleted file mode 100644 index e76baa2cae..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UsageReportSheet.ets +++ /dev/null @@ -1,206 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CommandPaletteUsageStatus, CommandPalettePresentation } from '../state/CommandPaletteState'; -import { UsageReportRow, UsageReportSection } from '../policy/UsageReportPresentationPolicy'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { AppActionButton, AppActionStyle } from './AppActionButton'; -import { SheetCloseHeader } from './SheetCloseHeader'; -import { SHEET_ACTION_HEIGHT, SHEET_FOOTER_BOTTOM_PADDING, SHEET_FOOTER_TOP_PADDING, SHEET_HORIZONTAL_PADDING, SHEET_TOP_RADIUS } from './SheetLayout'; -import { INK, MUTED, PAGE_BG, SUBTLE } from './Theme'; - -const USAGE_SECTION_HEIGHT: number = 30; -const USAGE_ROW_MIN_HEIGHT: number = 30; - -/** - * The session's usage, opened from the 用量 chip. - * - * Every row comes from the report the host actually sent: the desktop report is - * mirrored field by field and all of it is optional, so this sheet renders what - * is present and never fills a missing metric with a zero. A report that - * arrived with gaps says so at the end instead of pretending to be complete. - */ -@ComponentV2 -export struct UsageReportSheet { - @Param palette: CommandPalettePresentation = CommandPalettePresentation.hidden(); - @Event onRetry: () => void = () => {}; - @Event onClose: () => void = () => {}; - // The sheet is a bottom sheet under the immersive shell, so it reads the - // navigation-bar strip itself and ends in a tail that rests above it. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column() { - SheetCloseHeader({ - title: RemoteI18n.t('usage.title'), - showDivider: true, - onClose: this.onClose - }) - if (this.isLoading()) { - this.LoadingState() - } else if (this.isFailed()) { - this.FailedState() - } else if (this.palette.usageSections.length === 0) { - this.EmptyState() - } else { - this.Report() - } - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .borderRadius({ topLeft: SHEET_TOP_RADIUS, topRight: SHEET_TOP_RADIUS }) - } - - @Builder - Report() { - Scroll() { - Column({ space: 4 }) { - ForEach(this.palette.usageSections, (section: UsageReportSection) => { - this.SectionHeader(section) - ForEach(section.rows, (row: UsageReportRow) => { - this.ReportRow(row) - }, (row: UsageReportRow, index: number) => `${section.id}-${index}-${row.labelKey}`) - }, (section: UsageReportSection) => section.id) - if (this.palette.usagePartial) { - Text(RemoteI18n.t('usage.partialNote')) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - .width('100%') - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING, top: 10 }) - } - } - .width('100%') - .padding({ top: 8, bottom: this.insets.tailSpacing(SHEET_FOOTER_BOTTOM_PADDING) }) - } - .width('100%') - .layoutWeight(1) - .align(Alignment.TopStart) - .scrollBar(BarState.Off) - } - - @Builder - SectionHeader(section: UsageReportSection) { - Row() { - Text(RemoteI18n.t(section.titleKey)) - .fontSize(MobileDesignTypography.labelSmall.size) - .lineHeight(MobileDesignTypography.labelSmall.lineHeight) - .fontColor(SUBTLE) - Blank() - } - .width('100%') - .height(USAGE_SECTION_HEIGHT) - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING }) - .alignItems(VerticalAlign.Bottom) - } - - @Builder - ReportRow(row: UsageReportRow) { - Row() { - Text(RemoteI18n.t(row.labelKey)) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .layoutWeight(1) - Blank() - Text(row.valueKey.length > 0 ? RemoteI18n.t(row.valueKey) : row.value) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .textAlign(TextAlign.End) - } - .width('100%') - .constraintSize({ minHeight: USAGE_ROW_MIN_HEIGHT }) - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING, top: 4, bottom: 4 }) - .alignItems(VerticalAlign.Top) - } - - @Builder - LoadingState() { - Column() { - LoadingProgress() - .width(24) - .height(24) - .color(MUTED) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - } - - /** - * The read failed. The host's own text is shown when it sent one — a usage - * failure is usually about the target session, not about this app. - */ - @Builder - FailedState() { - Column({ space: 10 }) { - Text(RemoteI18n.t('usage.loadFailed')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(INK) - .textAlign(TextAlign.Center) - if (this.palette.usageErrorText.length > 0) { - Text(this.palette.usageErrorText) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .constraintSize({ maxWidth: 280 }) - } - AppActionButton({ - label: RemoteI18n.t('common.retry'), - style: AppActionStyle.Secondary, - actionHeight: SHEET_ACTION_HEIGHT, - elevated: false, - onAction: this.onRetry - }) - .width(176) - .margin({ top: 4 }) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .padding({ left: 10, right: 10, bottom: 12 }) - } - - @Builder - EmptyState() { - Column() { - Text(RemoteI18n.t('usage.empty')) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(MUTED) - .textAlign(TextAlign.Center) - .padding({ left: SHEET_HORIZONTAL_PADDING, right: SHEET_HORIZONTAL_PADDING }) - } - .width('100%') - .layoutWeight(1) - .justifyContent(FlexAlign.Center) - .padding({ bottom: SHEET_FOOTER_TOP_PADDING }) - } - - private isLoading(): boolean { - return this.palette.usageStatus === CommandPaletteUsageStatus.Loading; - } - - private isFailed(): boolean { - return this.palette.usageStatus === CommandPaletteUsageStatus.Failed; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UserMessageFullTextSheet.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UserMessageFullTextSheet.ets deleted file mode 100644 index 1477744264..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/UserMessageFullTextSheet.ets +++ /dev/null @@ -1,86 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { RollbackSelectionMenu } from './RollbackSelectionMenu'; -import { SheetCloseHeader } from './SheetCloseHeader'; -import { SHEET_HORIZONTAL_PADDING, SHEET_TOP_RADIUS } from './SheetLayout'; -import { INK, PAGE_BG } from './Theme'; - -/** - * One user message in full, opened from the truncated bubble's inline "full - * text" affordance. - * - * The body is a plain selectable Text on purpose: this is the surface where a - * long message is read and selected with the system selection menu and its - * handles, so it carries `CopyOptions.LocalDevice` while the truncated bubble - * it was opened from deliberately does not. Nothing else lives here — the - * sheet's placement, scrim and drag bar belong to the adaptive sheet contract - * the conversation binds it with. - * - * The panel also carries the rollback entry, on the same system selection menu - * the short bubble uses and through the same shared item: a message too long to - * read in its bubble is exactly the one a reader goes looking for that entry on. - * The panel closes as staging begins — the pane that owns the staging state is - * the conversation behind this sheet, and the preview belongs to it. - */ -@ComponentV2 -export struct UserMessageFullTextSheet { - @Param text: string = ''; - @Event onClose: () => void = () => {}; - @Event onRollback: () => void = () => {}; - /** - * The panel's own text controller, so the rollback item dismisses the system - * selection menu it was tapped in instead of leaving it over the conversation the - * staging belongs to (see `RollbackSelectionMenu`). - */ - private readonly selectionController: TextController = new TextController(); - // The sheet is a bottom sheet under the immersive shell, so it reads the - // navigation-bar strip itself and ends in a tail that rests the text above it. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column() { - SheetCloseHeader({ - title: RemoteI18n.t('chat.fullText'), - showDivider: true, - onClose: this.onClose - }) - Scroll() { - Text(this.text, { controller: this.selectionController }) - .width('100%') - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(INK) - .copyOption(CopyOptions.LocalDevice) - .editMenuOptions(RollbackSelectionMenu.options(this.selectionController, () => { - this.onRollback(); - })) - .padding({ - left: SHEET_HORIZONTAL_PADDING, - right: SHEET_HORIZONTAL_PADDING, - top: 18, - bottom: this.insets.tailSpacing(24) - }) - } - .width('100%') - .layoutWeight(1) - .align(Alignment.TopStart) - .scrollBar(BarState.Off) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .borderRadius({ topLeft: SHEET_TOP_RADIUS, topRight: SHEET_TOP_RADIUS }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WatchProvisionCard.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WatchProvisionCard.ets deleted file mode 100644 index 35fe15f1e4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WatchProvisionCard.ets +++ /dev/null @@ -1,193 +0,0 @@ -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { WatchProvisionPhase, WatchProvisionState } from '../state/WatchProvisionState'; -import { CARD, STATUS_SUCCESS, INK, LINE, SCRIM, MUTED, PRIMARY_ACTION, CONTENT_ON_ACTION, STATUS_DANGER, SOFT, - SUBTLE } from './Theme'; - -/** - * The one place a watch can be added to the account. It is deliberately modal: - * granting a device a 30-day credential should interrupt, not sit in a corner - * waiting to be noticed. - */ -@ComponentV2 -export struct WatchProvisionCard { - @Param state: WatchProvisionState = new WatchProvisionState(); - @Event onApprove: (password: string) => void = (_password: string) => {}; - @Event onReject: () => void = () => {}; - @Event onDismiss: () => void = () => {}; - @Local password: string = ''; - - build() { - if (this.state.visible()) { - Stack() { - Text('') - .width('100%') - .height('100%') - .backgroundColor(SCRIM) - .onClick(() => { - // Tapping away while the desktop is minting would leave the watch - // with no answer and no card to explain it. - if (this.state.dismissible()) { - this.onDismiss(); - } - }) - - Column({ space: 18 }) { - Text(RemoteI18n.t('watchProvision.title')) - .fontSize(MobileDesignTypography.headlineLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(INK) - .width('100%') - - Column({ space: 6 }) { - Text(this.state.deviceName) - .fontSize(MobileDesignTypography.headlineSmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - .width('100%') - .maxLines(2) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - Text(RemoteI18n.f('watchProvision.deviceId', this.state.deviceIdLabel)) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontColor(MUTED) - .width('100%') - } - .width('100%') - .padding({ left: 16, right: 16, top: 14, bottom: 14 }) - .backgroundColor(SOFT) - .borderRadius(20) - - if (this.state.phase === WatchProvisionPhase.Asking) { - Text(RemoteI18n.t('watchProvision.body')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(MUTED) - .width('100%') - } else if (this.state.phase === WatchProvisionPhase.Password) { - Column({ space: 12 }) { - Text(RemoteI18n.t('watchProvision.passwordBody')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(MUTED) - .width('100%') - TextInput({ - placeholder: RemoteI18n.t('watchProvision.passwordPlaceholder'), - text: this.password - }) - .height(54) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(INK) - .placeholderColor(SUBTLE) - .backgroundColor(SOFT) - .borderRadius(18) - .padding({ left: 18, right: 18 }) - .type(InputType.Password) - .showPasswordIcon(true) - .onChange((value: string) => { this.password = value; }) - if (this.state.message.length > 0) { - Text(this.state.message) - .fontSize(MobileDesignTypography.bodySmall.size) - .lineHeight(MobileDesignTypography.bodySmall.lineHeight) - .fontColor(STATUS_DANGER) - .width('100%') - } - } - .width('100%') - } else if (this.state.phase === WatchProvisionPhase.Working) { - Row({ space: 10 }) { - LoadingProgress() - .width(20) - .height(20) - .color(MUTED) - Text(RemoteI18n.t('watchProvision.working')) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(MUTED) - .layoutWeight(1) - } - .width('100%') - } else { - Text(this.state.message) - .fontSize(MobileDesignTypography.bodyLarge.size) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .fontColor(this.state.phase === WatchProvisionPhase.Done ? STATUS_SUCCESS : STATUS_DANGER) - .width('100%') - } - - if (this.state.phase === WatchProvisionPhase.Asking) { - Row({ space: 12 }) { - Button(RemoteI18n.t('watchProvision.reject')) - .layoutWeight(1) - .height(56) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(INK) - .backgroundColor(SOFT) - .borderRadius(28) - .onClick(this.onReject) - Button(RemoteI18n.t('watchProvision.approve')) - .layoutWeight(1) - .height(56) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(CONTENT_ON_ACTION) - .backgroundColor(PRIMARY_ACTION) - .borderRadius(28) - .onClick(() => { this.onApprove(''); }) - } - .width('100%') - } else if (this.state.phase === WatchProvisionPhase.Password) { - Row({ space: 12 }) { - Button(RemoteI18n.t('watchProvision.reject')) - .layoutWeight(1) - .height(56) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(INK) - .backgroundColor(SOFT) - .borderRadius(28) - .onClick(() => { - this.password = ''; - this.onReject(); - }) - Button(RemoteI18n.t('watchProvision.passwordConfirm')) - .layoutWeight(1) - .height(56) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(CONTENT_ON_ACTION) - .backgroundColor(PRIMARY_ACTION) - .borderRadius(28) - .enabled(this.password.length > 0) - .opacity(this.password.length > 0 ? 1 : 0.45) - .onClick(() => { - const password = this.password; - this.password = ''; - this.onApprove(password); - }) - } - .width('100%') - } else if (this.state.phase !== WatchProvisionPhase.Working) { - Button(RemoteI18n.t('watchProvision.gotIt')) - .width('100%') - .height(56) - .fontSize(MobileDesignTypography.labelLarge.size) - .fontWeight(FontWeight.Bold) - .fontColor(CONTENT_ON_ACTION) - .backgroundColor(PRIMARY_ACTION) - .borderRadius(28) - .onClick(this.onDismiss) - } - } - .width('82%') - .constraintSize({ maxWidth: 520 }) - .padding({ left: 26, right: 26, top: 28, bottom: 26 }) - .backgroundColor(CARD) - .borderRadius(34) - .border({ width: 1, color: LINE }) - } - .width('100%') - .height('100%') - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeBrandFlow.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeBrandFlow.ets deleted file mode 100644 index 607c05187d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeBrandFlow.ets +++ /dev/null @@ -1,81 +0,0 @@ -import { LengthMetricsUnit } from '@kit.ArkUI'; -import { MotionPreference } from '../../services/MotionPreference'; -import { INK, TRANSPARENT } from './Theme'; -const CONTOURS: string[] = [ - "M154.860 59.584 Q167.500 59.584 173.820 70.531 L200.680 117.053 Q207.000 128.000 200.680 138.947 L173.820 185.469 Q167.500 196.416 154.860 196.416 L101.140 196.416 Q88.500 196.416 82.180 185.469 L55.320 138.947 Q49.000 128.000 55.320 117.053 L82.180 70.531 Q88.500 59.584 101.140 59.584 Z", - "M152.788 57.185 Q165.682 56.702 172.547 67.628 L201.722 114.060 Q208.586 124.985 202.557 136.392 L176.934 184.875 Q170.905 196.282 158.011 196.765 L103.212 198.815 Q90.318 199.298 83.453 188.372 L54.278 141.940 Q47.414 131.015 53.443 119.608 L79.066 71.125 Q85.095 59.718 97.989 59.235 Z", - "M150.574 54.847 Q163.702 53.863 171.119 64.741 L202.639 110.973 Q210.056 121.851 204.343 133.713 L180.066 184.126 Q174.353 195.988 161.224 196.972 L105.426 201.153 Q92.298 202.137 84.881 191.259 L53.361 145.027 Q45.944 134.149 51.657 122.287 L75.934 71.874 Q81.647 60.012 94.776 59.028 Z", - "M148.218 52.578 Q161.562 51.074 169.537 61.879 L203.427 107.798 Q211.401 118.603 206.031 130.911 L183.208 183.221 Q177.838 195.529 164.494 197.032 L107.782 203.422 Q94.438 204.926 86.463 194.121 L52.573 148.202 Q44.599 137.397 49.969 125.089 L72.792 72.779 Q78.162 60.471 91.506 58.968 Z", - "M145.724 50.384 Q159.263 48.344 167.799 59.048 L204.079 104.542 Q212.616 115.246 207.614 127.991 L186.355 182.157 Q181.353 194.902 167.814 196.943 L110.276 205.616 Q96.737 207.656 88.201 196.952 L51.921 151.458 Q43.384 140.754 48.386 128.009 L69.645 73.843 Q74.647 61.098 88.186 59.057 Z", - "M143.094 48.274 Q156.805 45.680 165.907 56.257 L204.592 101.209 Q213.694 111.786 209.085 124.957 L189.498 180.935 Q184.889 194.106 171.178 196.700 L112.906 207.726 Q99.195 210.320 90.093 199.743 L51.408 154.791 Q42.306 144.214 46.915 131.043 L66.502 75.065 Q71.111 61.894 84.822 59.300 Z", - "M140.330 46.254 Q154.191 43.091 163.861 53.512 L204.959 97.806 Q214.629 108.227 210.439 121.813 L192.629 179.551 Q188.438 193.137 174.578 196.301 L115.670 209.746 Q101.809 212.909 92.139 202.488 L51.041 158.194 Q41.371 147.773 45.561 134.187 L63.371 76.449 Q67.562 62.863 81.422 59.699 Z", - "M137.437 44.331 Q151.423 40.584 161.662 50.823 L205.177 94.338 Q215.416 104.577 211.669 118.563 L195.741 178.007 Q191.993 191.993 178.007 195.741 L118.563 211.669 Q104.577 215.416 94.338 205.177 L50.823 161.662 Q40.584 151.423 44.331 137.437 L60.259 77.993 Q64.007 64.007 77.993 60.259 Z", - "M134.416 42.513 Q148.504 38.167 159.311 48.195 L205.242 90.813 Q216.049 100.840 212.769 115.214 L198.826 176.300 Q195.545 190.673 181.458 195.019 L121.584 213.487 Q107.496 217.833 96.689 207.805 L50.758 165.187 Q39.951 155.160 43.231 140.786 L57.174 79.700 Q60.455 65.327 74.542 60.981 Z", - "M131.272 40.805 Q145.436 35.849 156.810 45.637 L205.149 87.237 Q216.523 97.025 213.733 111.769 L201.877 174.431 Q199.087 189.175 184.923 194.131 L124.728 215.195 Q110.564 220.151 99.190 210.363 L50.851 168.763 Q39.477 158.975 42.267 144.231 L54.123 81.569 Q56.913 66.825 71.077 61.869 Z", - "M128.010 39.216 Q142.223 33.637 154.160 43.157 L204.895 83.616 Q216.832 93.136 214.556 108.234 L204.885 172.401 Q202.609 187.499 188.396 193.077 L127.990 216.784 Q113.777 222.363 101.840 212.843 L51.105 172.384 Q39.168 162.864 41.444 147.766 L51.115 83.599 Q53.391 68.501 67.604 62.923 Z", - "M124.633 37.750 Q138.869 31.539 151.365 40.762 L204.475 79.959 Q216.972 89.182 215.233 104.616 L207.842 170.209 Q206.103 185.643 191.868 191.854 L131.367 218.250 Q117.131 224.461 104.635 215.238 L51.525 176.041 Q39.028 166.818 40.767 151.384 L48.158 85.791 Q49.897 70.357 64.132 64.146 Z", - "M121.147 36.415 Q135.377 29.562 148.427 38.459 L203.889 76.272 Q216.938 85.169 215.758 100.920 L210.742 167.858 Q209.562 183.608 195.331 190.461 L134.853 219.585 Q120.623 226.438 107.573 217.541 L52.111 179.728 Q39.062 170.831 40.242 155.080 L45.258 88.142 Q46.438 72.392 60.669 65.539 Z", - "M117.556 35.216 Q131.752 27.713 145.348 36.256 L203.131 72.563 Q216.727 81.106 216.127 97.152 L213.575 165.347 Q212.975 181.393 198.778 188.896 L138.444 220.784 Q124.248 228.287 110.652 219.744 L52.869 183.437 Q39.273 174.894 39.873 158.848 L42.425 90.653 Q43.025 74.607 57.222 67.104 Z", - "M113.866 34.160 Q128.000 26.000 142.134 34.160 L202.201 68.840 Q216.335 77.000 216.335 93.320 L216.335 162.680 Q216.335 179.000 202.201 187.160 L142.134 221.840 Q128.000 230.000 113.866 221.840 L53.799 187.160 Q39.665 179.000 39.665 162.680 L39.665 93.320 Q39.665 77.000 53.799 68.840 Z" -]; -const LENGTHS: number[] = [460.633, 470.212, 479.792, 489.371, 498.95, 508.529, 518.108, 527.687, 537.267, 546.846, 556.425, 566.004, 575.583, 585.163, 594.742]; - -/** Desktop contour-flow effect; only highlights move, never the brand silhouette. */ -@ComponentV2 -export struct WelcomeBrandFlow { - @Param markSize: number = 92; - @Param sweep: boolean = false; - private canvas: CanvasRenderingContext2D = new CanvasRenderingContext2D(new RenderingContextSettings(true), LengthMetricsUnit.PX); - private paintSweep(): void { - const color = this.getUIContext().getHostContext()?.resourceManager.getColorSync($r('app.color.ink').id) || 0; - const r = (color >>> 16) & 255; const g = (color >>> 8) & 255; const b = color & 255; - const ctx = this.canvas; - const pixels = this.getUIContext().vp2px(this.markSize); - ctx.clearRect(0, 0, pixels, pixels); - ctx.save();ctx.scale(pixels / 256, pixels / 256); - const shift = this.moving ? (Math.min(1, this.phase / 0.75) * 2 - 1) * 256 : 0; - const gradient = ctx.createLinearGradient(shift, shift, 256 + shift, 256 + shift); - gradient.addColorStop(0, `rgba(${r},${g},${b},0.16)`); - gradient.addColorStop(0.46, `rgba(${r},${g},${b},0.25)`); - gradient.addColorStop(0.55, `rgba(${r},${g},${b},1)`); - gradient.addColorStop(0.65, `rgba(${r},${g},${b},0.25)`); - gradient.addColorStop(1, `rgba(${r},${g},${b},0.16)`); - ctx.strokeStyle = this.moving ? gradient : `rgb(${r},${g},${b})`; - ctx.lineWidth = 1.45; - CONTOURS.forEach((contour: string) => { ctx.stroke(new Path2D(contour)); }); - ctx.restore(); - } - @Local phase: number = 0; - @Local moving: boolean = false; - private timer: number = -1; - aboutToDisappear(): void { this.stop(); } - private stop(): void { if(this.timer>=0) clearInterval(this.timer);this.timer=-1; } - private play(): void { - this.stop();this.moving=!MotionPreference.reduceMotion(); - if(this.moving) this.timer=setInterval(()=>{const cycle=this.sweep?5000:18000;this.phase=(Date.now()%cycle)/cycle;if(this.sweep)this.paintSweep();},33); - if(this.sweep)this.paintSweep(); - } - build() { - Stack({ alignContent: Alignment.Center }) { - if (this.sweep) { - Canvas(this.canvas).width(this.markSize).height(this.markSize).onReady(() => this.paintSweep()) - } else { - Shape() { - ForEach(CONTOURS, (contour: string,index: number)=>{ - Path().commands(contour).fill(TRANSPARENT).stroke(INK).strokeWidth(px2vp(1)).opacity(0.25) - if(this.moving) { - ForEach([0.34,0.26,0.18],(length: number,layer: number)=>{ - Path().commands(contour).fill(TRANSPARENT).stroke(INK).strokeWidth(px2vp(1)) - .strokeDashArray([px2vp(LENGTHS[index]*length/2),px2vp(LENGTHS[index]*(1-length)),px2vp(LENGTHS[index]*length/2),0]) - .strokeDashOffset(px2vp(-LENGTHS[index]*(this.phase+index*0.03))) - .opacity(layer===2?0.36:layer===1?0.14:0.12) - }) - } - }) - }.viewPort({ x: 0, y: 0, width: 256, height: 256 }) - .width(this.markSize).height(this.markSize) - } - }.width(this.markSize).height(this.markSize).accessibilityLevel('no-hide-descendants') - .onVisibleAreaChange([0],(visible: boolean)=>{if(visible)this.play();else this.stop();}) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeHome.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeHome.ets deleted file mode 100644 index 7013483ff3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WelcomeHome.ets +++ /dev/null @@ -1,204 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MobileDesignTypography, MobileDesignGeometry as G } from '../../generated/MobileDesignTokens'; -import { MotionPreference } from '../../services/MotionPreference'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { WelcomeBrandFlow } from './WelcomeBrandFlow'; -import { INK, PAGE_BG, WELCOME_PAGE_BG, MUTED, TRANSPARENT } from './Theme'; - -/** - * A welcome composition with the C staggered-slide phrase timeline. - * - * The window layout mode is not this page's business any more: it used to switch - * the whole shell in and out of full-screen as the compact welcome page came and - * went, which left every other page — the chat page above all — laid out without - * it. The shell runs immersive for every page now, and this page only reserves - * the status bar for its own header. - */ -@ComponentV2 -export struct WelcomeHome { - @Param signedIn: boolean = false; - @Event onLogin: () => void = () => {}; - @Event onMiniApps: () => void = () => {}; - @Local elapsed: number = 0; - @Local pageHeight: number = 700; - @Local pageWidth: number = 390; - // The dock paints into the strip (expandSafeArea carries its background to - // the screen edge), so its buttons read the strip: the design's own clearance - // where it is already taller than the indicator, the indicator's height - // where it is not. - // - // The page's top strip comes from the same binding rather than a read of its - // own. It used to ask the service for the status bar height once, at mount, - // which left the header reserving the strip a landscape rotation had already - // moved the camera cutout onto, and left the value stale after the rotation. - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - private timer: number = -1; - private started: number = 0; - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.stop(); - this.insets.unbind(); - } - - private stop(): void { if (this.timer >= 0) clearInterval(this.timer); this.timer = -1; } - private play(): void { - this.stop(); - if (MotionPreference.reduceMotion()) { this.elapsed = 2700; return; } - this.started = Date.now(); - this.timer = setInterval(() => { this.elapsed = Date.now() - this.started; }, 16); - } - private phrases(): string[] { - return ['OpenBitFun', RemoteI18n.t('home.welcome_work'), RemoteI18n.t('home.welcome_play'), RemoteI18n.t('home.welcome_yours')]; - } - private duration(word: string): number { return 250 + word.length * 185 + (word === 'OpenBitFun' ? 600 : 0) + 1800 + 650; } - private phraseIndex(): number { - const words = this.phrases(); - let total = 0; - for (const word of words) total += this.duration(word); - let time = this.elapsed % total; - for (let i = 0; i < words.length; i++) { if (time < this.duration(words[i])) return i; time -= this.duration(words[i]); } - return 0; - } - private word(): string { return this.phrases()[this.phraseIndex()]; } - private time(): number { - const words = this.phrases(); - let total = 0; - for (const word of words) total += this.duration(word); - let time = this.elapsed % total; - for (let i = 0; i < this.phraseIndex(); i++) time -= this.duration(words[i]); - return time; - } - private clamp(value: number): number { return Math.max(0, Math.min(1, value)); } - private progress(index: number): number { return this.clamp((this.time() - 180 - index * 55) / 800); } - private exitProgress(): number { return this.clamp((this.time() - this.duration(this.word()) + 650) / 650); } - private bump(index: number): number { const p = this.progress(index); return Math.sin(p * Math.PI) * (1-p); } - private glyphOffset(index: number): number { - return Math.pow(1-this.progress(index), 3) * 38 - this.bump(index) * 5 - Math.pow(this.exitProgress(), 2) * 30; - } - - private wide(): boolean { return this.pageWidth >= 600; } - private landscape(): boolean { - return this.pageWidth >= 840 && this.pageWidth / Math.max(1, this.pageHeight) >= 1.2; - } - build() { - Scroll() { - Column() { - Row() { - ForEach('OpenBitFun'.split(''), (letter: string) => { this.Glyph(letter, G.welcomeHeaderWordSize); }) - }.width('100%').height(G.welcomeHeaderHeight) - .padding({ left: this.wide() ? 40 : G.welcomeGutter, right: G.welcomeGutter }) - if (this.landscape()) { - Row({ space: 48 }) { - Column() { this.Hero() }.layoutWeight(1) - Column() { this.Actions() }.layoutWeight(1) - }.width('100%').constraintSize({ maxWidth: 1000, - minHeight: Math.max(400, this.pageHeight - G.welcomeHeaderHeight) }) - .padding({ left: 40, right: 40, bottom: 48 }) - .alignItems(VerticalAlign.Center) - } else if (this.wide()) { - Column() { - this.Hero() - this.Actions() - }.width('100%').constraintSize({ minHeight: Math.max(540, this.pageHeight - G.welcomeHeaderHeight) }) - .justifyContent(FlexAlign.Center).padding({ bottom: 64 }) - } else { - Column() { - Column() { this.Hero() } - .justifyContent(FlexAlign.Center).width('100%') - .layoutWeight(1) - .constraintSize({ minHeight: 300 }) - .padding({ bottom: 24 }) - this.Actions() - }.width('100%').height(Math.max(0, - this.pageHeight - this.insets.top - G.welcomeHeaderHeight)) - } - }.width('100%') - }.width('100%').height('100%').scrollBar(BarState.Off).backgroundColor(WELCOME_PAGE_BG) - .padding({ top: this.insets.top }) - .onSizeChange((_old: SizeOptions, size: SizeOptions) => { - this.pageHeight = Number(size.height); - this.pageWidth = Number(size.width); - }) - .onVisibleAreaChange([0], (visible: boolean) => { if (visible) this.play(); else this.stop(); }) - } - - @Builder - private Hero() { - Column({ space: this.wide() ? 16 : 20 }) { - WelcomeBrandFlow({ markSize: this.landscape() ? 216 : this.wide() ? 184 : 156, sweep: true }) - Row() { - ForEach(this.word().split(''), (letter: string, index: number) => { - Stack() { this.Glyph(letter, this.word().length > 12 ? 25 : 30); } - .opacity(this.clamp(this.progress(index)*3)*(1-this.exitProgress())) - .translate({ x: this.glyphOffset(index) }) - .scale({ x: 1+this.bump(index)*0.045, y: 1+this.bump(index)*0.045 }) - }, (letter: string, index: number) => `${this.phraseIndex()}-${index}-${letter}`) - }.height(48).accessibilityLevel('no-hide-descendants') - }.width('100%').margin({ bottom: this.wide() ? 32 : 0 }) - } - - @Builder - private Actions() { - Column({ space: G.welcomeButtonGap }) { - this.Action() - Button({ type: ButtonType.Normal }) { - Row({ space: 5 }) { - Text(RemoteI18n.t('home.exploreMiniApps')).fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(this.wide() ? MUTED : $r('app.color.welcome_secondary')) - SymbolGlyph($r('sys.symbol.chevron_right')).fontSize(MobileDesignTypography.labelSmall.size) - .fontColor([this.wide() ? MUTED : $r('app.color.welcome_secondary')]) - } - }.height(44).width('100%').backgroundColor(TRANSPARENT).onClick(this.onMiniApps) - }.width('100%').constraintSize({ maxWidth: this.wide() ? 400 : G.welcomeMaxWidth }) - .padding({ left: G.welcomeGutter, right: G.welcomeGutter, top: this.wide() ? 0 : G.welcomeGutter, - bottom: this.wide() ? 0 : this.insets.bottomPadding(G.welcomeDockBottom) }) - .backgroundColor(this.wide() ? TRANSPARENT : $r('app.color.welcome_dock')) - // The dock's fill reaches the bottom edge of the screen. The cutout is a - // separate avoid area from the system bars, so it is claimed here too. - // - // The sides are named as well, and the claim is only ever load-bearing in - // one combination. The dock only has a fill of its own in the compact - // composition — `wide()` swaps it for a centred column capped at 400vp - // whose background is TRANSPARENT — but `wide()` is a logical-width test - // (`pageWidth >= 600`) and a side cutout is not: a landscape window below - // 600vp still puts the camera on a side edge, and split screen, a free - // window and a hover posture all produce one. In that combination this - // column does sit on the window's left and right edges, so leaving the - // sides unnamed is the same page-colour sliver beside the fill that the - // shell's other three full-bleed backgrounds would show. Naming them in - // the wide composition costs nothing, because there the dock paints - // TRANSPARENT and an edge claim against a transparent fill draws nothing. - .expandSafeArea([SafeAreaType.SYSTEM, SafeAreaType.CUTOUT], - [SafeAreaEdge.START, SafeAreaEdge.END, SafeAreaEdge.BOTTOM]) - .borderRadius({ topLeft: G.welcomeDockRadius, topRight: G.welcomeDockRadius }) - } - @Builder - private Glyph(letter: string, size: number) { - if (letter === 'i') { - Stack({ alignContent: Alignment.Top }) { - Text('ı').fontSize(size).fontWeight(FontWeight.Medium).fontColor(INK) - Circle().width(size*0.14).height(size*0.14).fill($r('app.color.brand_dot')).translate({ y: size*0.25 }) - } - } else { - Text(letter).fontSize(size).fontWeight(FontWeight.Medium).fontColor(INK) - } - } - - @Builder - private Action() { - Button({ type: ButtonType.Normal }) { - Row({ space: 10 }) { - Text(RemoteI18n.t(this.signedIn ? 'home.connectComputer' : 'home.welcome_login')) - .fontSize(MobileDesignTypography.labelMedium.size).fontWeight(FontWeight.Medium).fontColor(this.wide() ? PAGE_BG : $r('app.color.welcome_button_label')) - }.justifyContent(FlexAlign.Center) - }.width('100%').height(G.welcomeButtonHeight).borderRadius(28) - .backgroundColor(this.wide() ? INK : $r('app.color.welcome_button')).onClick(this.onLogin) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WideConversationHost.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WideConversationHost.ets deleted file mode 100644 index 23666cd23e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WideConversationHost.ets +++ /dev/null @@ -1,434 +0,0 @@ -import { RemoteUiState } from '../../services/RemoteUiState'; -import { REMOTE_CAPABILITY_HARNESS_PROFILES_V1 } from '../../model/RemoteModels'; -import { - AppRootPresentationActions, - emptyAppRootPresentationActions -} from '../actions/AppRootPresentationActions'; -import { WideLayoutGeometry } from '../layout/WideLayoutGeometry'; -import { AppRoute, AppRouteContract } from '../navigation/AppRouteContract'; -import { FilePreviewLayout, FilePreviewPlacement } from '../policy/FilePreviewPlacementPolicy'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { AppShellState } from '../state/AppShellState'; -import { FilePreviewState } from '../state/FilePreviewState'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { DeviceDirectoryState } from '../state/DeviceDirectoryState'; -import { RemotePageState } from '../state/RemotePageState'; -import { AppSidebar } from './AppSidebar'; -import { ConversationRouteSurface } from './ConversationRouteSurface'; -import { FilePreviewSurface } from './FilePreviewSurface'; -import { - RemoteSurfaceHost, - RemoteSurfaceMode, - RemoteSurfaceState -} from './remote/RemoteSurfaceHost'; -import { SidebarToggleButton } from './SidebarToggleButton'; -import { SidebarWorkspaceSection } from './SidebarWorkspaceSection'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; -import { - LINE, - PAGE_BG, - SHADOW_SUBTLE, - SIDEBAR_BG, -} from './Theme'; - -const WIDE_DETAIL_CONTENT_MAX_WIDTH: number = 920; - -@ComponentV2 -export struct WideConversationHost { - @Param route: AppRoute = AppRoute.RemoteHome; - @Param shellState: AppShellState = new AppShellState(); - @Param remotePageState: RemotePageState = new RemotePageState(); - @Param deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Param generalPageState: GeneralChatPageState = new GeneralChatPageState(); - @Param filePreviewState: FilePreviewState = new FilePreviewState(); - @Param remoteSurfaceState: RemoteSurfaceState = new RemoteSurfaceState(); - @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - @Param filePreviewLayout: FilePreviewLayout = new FilePreviewLayout(FilePreviewPlacement.Hidden); - @Param sessionDetailsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SessionDetails); - @Param fullTextSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - @Param skillPickerSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SkillPicker); - @Param usageReportSheetPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UsageReport); - @Param wideMasterPaneWidth: number = 0; - @Param wideMasterDetailGap: number = 0; - @Param wideDetailContentOffset: number = 0; - @Param wideDetailContentWidth: number = 0; - @Param wideCollapsedDetailContentOffset: number = 0; - @Param wideCollapsedDetailContentWidth: number = 0; - @Param wideMasterPaneCollapsed: boolean = false; - @Param wideMasterPaneMotionActive: boolean = false; - @Param filePreviewExpanded: boolean = false; - @Param canToggleFilePreviewExpanded: boolean = false; - @Event onCollapseMasterPane: () => void = () => {}; - @Event onRestoreMasterPane: () => void = () => {}; - @Event onToggleFilePreviewExpanded: () => void = () => {}; - @Event onOpenRemoteViewSettings: () => void = () => {}; - /** - * The window's own insets, in vp. Every pane in this host is pinned to the - * window's edges, so the floating controls that are not part of a page's own - * header band keep the status bar strip clear themselves. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - if (this.showsRemoteConversation() && - this.filePreviewLayout.placement === FilePreviewPlacement.WideMasterPreviewFocus) { - this.RemoteMasterPreviewFocusContent(); - } else if (this.showsRemoteConversation() && - this.filePreviewLayout.placement === FilePreviewPlacement.WideFocusSplit) { - this.RemotePreviewFocusContent(); - } else if (this.showsRemoteDetail()) { - this.RemoteChatContent(); - } else if (this.route === AppRoute.RemoteHome) { - this.RemoteHomeContent(); - } - } - - @Builder - private RemoteHomeContent() { - Row() { - if (!this.wideMasterPaneCollapsed) { - this.MasterPane() - this.MasterDetailGap() - } - this.RemoteHomeDetail() - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private RemoteHomeDetail() { - Stack({ alignContent: Alignment.TopStart }) { - Row() { - if (this.currentDetailOffset() > 0) { - Row() {}.width(this.currentDetailOffset()).height('100%') - } - Column() { - RemoteSurfaceHost({ - mode: RemoteSurfaceMode.Placeholder, - remotePageState: this.remotePageState, - presentationState: this.remoteSurfaceState, - actions: this.actions, - wideMasterPaneCollapsed: false, - sessionDetailsPlacement: this.sessionDetailsPlacement, - onRestoreSidebar: this.onRestoreMasterPane - }) - } - .width(this.currentDetailWidth() > 0 ? this.currentDetailWidth() : '100%') - .height('100%').backgroundColor(PAGE_BG) - if (this.currentDetailOffset() > 0) { - Row() {}.layoutWeight(1).height('100%') - } - } - .width('100%').height('100%').justifyContent(FlexAlign.Start).backgroundColor(PAGE_BG) - - if (this.wideMasterPaneCollapsed) { - // The detail pane's top edge is the window's, so the floating control - // keeps the status bar strip above it instead of sitting under it — and - // its left edge is the window's too, which is the edge a rotated device - // moves the camera cutout onto. - SidebarToggleButton({ restore: true, controlSize: 44, onToggle: this.onRestoreMasterPane }) - .position({ x: this.insets.leftPadding(12), y: 12 + this.insets.top }).zIndex(2) - .hitTestBehavior(HitTestMode.Default) - } - } - .layoutWeight(1).height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private MasterPane() { - Column() { - Column() { - AppSidebar({ - toolLocations: this.remotePageState.savedConnectionsTargetId === this.remotePageState.controlTargetDeviceId ? this.remotePageState.savedConnections : [], - onWorkspaceTools: this.actions.onWorkspaceTools, - controlTargetDeviceId: this.remotePageState.controlTargetDeviceId, - connectionState: this.remotePageState.connectionState, - accountUserId: this.remotePageState.accountUserId, - showCollapseButton: true, - showViewSettingsButton: false, - showWorkspaceSection: true, - contentSlot: () => { - this.WorkspaceMasterContent() - }, - onClose: this.actions.onSidebar.close, - onNewChat: this.actions.onSidebar.newChat, - onEnterCode: this.actions.onSidebar.enterCode, - onOpenMiniApps: this.actions.onRemoteHome.openMiniApps, - onCollapse: this.onCollapseMasterPane, - onOpenViewSettings: this.onOpenRemoteViewSettings, - onSearchQueryChange: (query: string) => { - this.actions.onRemoteHome.queryChanged(query); - }, - onOpenSettings: this.actions.onSidebar.settings, - onOpenAccount: this.actions.onSidebar.openAccount, - }) - } - .width('100%').height('100%').backgroundColor(SIDEBAR_BG) - .borderRadius(18).clip(true) - .shadow({ radius: 24, color: SHADOW_SUBTLE, offsetX: 4, offsetY: 8 }) - } - .width(WideLayoutGeometry.masterPaneWidth(this.filePreviewLayout, this.wideMasterPaneWidth)) - .height('100%').padding({ left: 10, right: 6, top: 10, bottom: 10 }).backgroundColor(PAGE_BG) - .transition(this.wideMasterPaneMotionActive ? - TransitionEffect.translate({ x: -28, y: 0 }).combine(TransitionEffect.opacity(0)) - .animation({ duration: 220, curve: Curve.EaseInOut }) : TransitionEffect.opacity(1)) - } - - @Builder - private WorkspaceMasterContent() { - SidebarWorkspaceSection({ - workspaceTools: this.remotePageState.workspaceTools, - onWorkspaceTools: this.actions.onWorkspaceTools, - directoryState: this.deviceDirectoryState, - sessions: this.remotePageState.visibleSessions(), - recentWorkspaces: this.remotePageState.recentWorkspaces, - savedConnections: this.remotePageState.savedConnections, - savedConnectionsTargetId: this.remotePageState.savedConnectionsTargetId, - workspaceName: this.remotePageState.workspaceName, - workspacePath: this.remotePageState.workspacePath, - workspaceConnectionId: this.remotePageState.workspaceConnectionId, - workspaceSshHost: this.remotePageState.workspaceSshHost, - workspaceId: this.remotePageState.workspaceId, - workspaceKind: this.remotePageState.workspaceKind, - connectionState: this.remotePageState.connectionState, - controlTargetType: this.remotePageState.controlTargetType, - controlTargetDeviceId: this.remotePageState.controlTargetDeviceId, - controlTargetDeviceName: this.remotePageState.controlTargetDeviceName || - this.remotePageState.desktopName, - selectedSessionId: this.wideSelectedSessionId(), - runningSessionId: this.remotePageState.hasRunningActiveTurn() ? - this.remotePageState.activeSession.sessionId : '', - supportsHarnessProfiles: this.remotePageState.supportsHostCapability( - REMOTE_CAPABILITY_HARNESS_PROFILES_V1), - workspacePickerPlacement: this.sessionDetailsPlacement, - onOpenSession: this.actions.onRemoteHome.openSessionInPlace, - onCreateInWorkspace: (deviceId: string, path: string, agentType: string, connectionId?: string, sshHost?: string, - workspaceId?: string) => { - this.actions.onRemoteHome.createInWorkspaceInPlace(path, agentType, deviceId, connectionId, sshHost, workspaceId); - }, - onOpenWorkspace: (deviceId: string, path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => { - this.actions.onRemoteHome.selectWorkspace(path, deviceId, connectionId, sshHost, workspaceId); - }, - onExpandWorkspace: async (deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, - workspaceId?: string): Promise => { - await this.actions.onRemoteHome.loadWorkspaceSessions(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId); - }, - onSelectDevice: this.actions.onRemoteHome.selectDirectoryDevice, - onRetryDevice: this.actions.onRemoteHome.retryDirectoryDevice, - onReconnect: this.actions.onRemoteHome.reconnect, - onAddWorkspace: this.actions.onRemoteHome.addDirectoryWorkspace, - onRefreshDevices: this.actions.onSidebar.refreshDevices, - onAddDevice: this.actions.onSidebar.openAccountDevices - }) - } - - @Builder - private RemoteChatContent() { - if (this.filePreviewLayout.placement === FilePreviewPlacement.WideTriplePane) { - Row() { - if (!this.wideMasterPaneCollapsed) { - this.MasterPane() - this.PaneGap( - this.filePreviewLayout.masterConversationGap, - this.filePreviewLayout.masterConversationGapIsCrease - ) - } - this.ConversationDetail( - false, - this.wideMasterPaneCollapsed ? this.collapsedTripleConversationWidth() : - this.filePreviewLayout.conversationPaneWidth - ) - this.PaneGap( - this.filePreviewLayout.conversationPreviewGap, - this.filePreviewLayout.conversationPreviewGapIsCrease - ) - this.FilePreviewPane(this.filePreviewLayout.previewPaneWidth) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } else { - Row() { - if (!this.wideMasterPaneCollapsed) { - this.MasterPane() - this.MasterDetailGap() - } - this.ConversationDetail(false) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - } - - @Builder - private RemotePreviewFocusContent() { - Row() { - this.ConversationDetail(false, this.filePreviewLayout.conversationPaneWidth) - this.PaneGap( - this.filePreviewLayout.conversationPreviewGap, - this.filePreviewLayout.conversationPreviewGapIsCrease - ) - this.FilePreviewPane(this.filePreviewLayout.previewPaneWidth) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private RemoteMasterPreviewFocusContent() { - Row() { - this.MasterPane() - this.PaneGap( - this.filePreviewLayout.masterConversationGap, - this.filePreviewLayout.masterConversationGapIsCrease - ) - this.FilePreviewPane(this.filePreviewLayout.previewPaneWidth) - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private FilePreviewPane(paneWidth: number) { - Column() { - FilePreviewSurface({ - state: this.filePreviewState, - remoteAvailable: RemoteUiState.canUseRemote(this.remotePageState.connectionState), - downloadPath: this.remotePageState.downloadingFilePath, - downloadedPath: this.remotePageState.downloadedFilePath, - downloadStatus: this.remotePageState.fileDownloadStatus, - previewExpanded: this.filePreviewExpanded, - canToggleExpanded: this.canToggleFilePreviewExpanded, - onClose: this.actions.onFilePreview.close, - onRefresh: this.actions.onFilePreview.refresh, - onDownload: this.actions.onFilePreview.download, - onOpenLink: this.actions.onFilePreview.openLink, - onToggleExpanded: this.onToggleFilePreviewExpanded - }) - } - .width(paneWidth).height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private ConversationDetail(showBackButton: boolean, paneWidth: number = 0) { - if (paneWidth > 0) { - Column() { - this.RouteSurface(showBackButton) - } - .width(paneWidth).height('100%').constraintSize({ maxWidth: WIDE_DETAIL_CONTENT_MAX_WIDTH }) - .backgroundColor(PAGE_BG) - } else { - Stack({ alignContent: Alignment.TopStart }) { - Row() { - if (this.currentDetailOffset() > 0) { - Row() {}.width(this.currentDetailOffset()).height('100%') - } - Row() { - Column() { this.RouteSurface(showBackButton) } - .width('100%').height('100%') - .backgroundColor(PAGE_BG) - } - .width(this.currentDetailWidth() > 0 ? this.currentDetailWidth() : '100%') - .height('100%').justifyContent(FlexAlign.Center) - if (this.currentDetailOffset() > 0) { - Row() {}.layoutWeight(1).height('100%') - } - } - .width('100%').height('100%').justifyContent(FlexAlign.Start).backgroundColor(PAGE_BG) - } - .layoutWeight(1).height('100%').backgroundColor(PAGE_BG) - } - } - - @Builder - private RouteSurface(showBackButton: boolean) { - ConversationRouteSurface({ - route: this.route, - remotePageState: this.remotePageState, - generalPageState: this.generalPageState, - filePreviewState: this.filePreviewState, - remoteSurfaceState: this.remoteSurfaceState, - actions: this.actions, - showSidebarButton: false, - showBackButton, - showSidebarRestoreButton: WideLayoutGeometry.showsMasterRestoreButton( - this.wideMasterPaneCollapsed, - this.filePreviewLayout - ), - useWidePresentation: true, - fullTextSheetPlacement: this.fullTextSheetPlacement, - skillPickerSheetPlacement: this.skillPickerSheetPlacement, - usageReportSheetPlacement: this.usageReportSheetPlacement, - onRestoreSidebar: this.onRestoreMasterPane - }) - } - - @Builder - private MasterDetailGap() { - if (this.wideMasterDetailGap > 0) { - // Reserve the physical crease so rows do not sit on the hinge, but do - // not paint it as a divider. The device already has that hinge. - Row() {}.width(this.wideMasterDetailGap).height('100%').backgroundColor(PAGE_BG) - } - } - - @Builder - private PaneGap(width: number, isPhysicalCrease: boolean) { - if (width > 0) { - Row() {}.width(width).height('100%').backgroundColor(isPhysicalCrease ? PAGE_BG : LINE) - } - } - - private wideSelectedSessionId(): string { - if (this.remotePageState.pendingSessionId.length > 0) { - return this.remotePageState.pendingSessionId; - } - return AppRouteContract.isRemoteRoute(this.route) ? - this.remotePageState.activeSession.sessionId : ''; - } - - private showsRemoteConversation(): boolean { - return this.route === AppRoute.RemoteChat; - } - - private showsRemoteDetail(): boolean { - return this.route === AppRoute.RemoteChat; - } - - private currentDetailOffset(): number { - return WideLayoutGeometry.detailOffset( - this.wideMasterPaneCollapsed, - this.wideDetailContentOffset, - this.wideCollapsedDetailContentOffset - ); - } - - private currentDetailWidth(): number { - return WideLayoutGeometry.detailWidth( - this.wideMasterPaneCollapsed, - this.wideDetailContentWidth, - this.wideCollapsedDetailContentWidth - ); - } - - private collapsedTripleConversationWidth(): number { - return this.filePreviewLayout.masterPaneWidth + - this.filePreviewLayout.masterConversationGap + - this.filePreviewLayout.conversationPaneWidth; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceFileEditorView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceFileEditorView.ets deleted file mode 100644 index af0e0ac49c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceFileEditorView.ets +++ /dev/null @@ -1,60 +0,0 @@ -import { webview } from '@kit.ArkWeb'; -import { WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; -interface EditorFrame { content: string; editing: boolean; lineNumbers: boolean; ink: string; muted: string; } -interface EditorEvent { type: string; text?: string; } -class EditorNativeBridge { - private receive: (raw: string) => void; - constructor(receive: (raw: string) => void) { this.receive = receive; } - postMessage(raw: string): void { this.receive(raw); } -} -@ComponentV2 -export struct WorkspaceFileEditorView { - @Param content: string = ''; - @Param editing: boolean = false; - @Param lineNumbers: boolean = true; - @Event onIntent: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - private controller: webview.WebviewController = new webview.WebviewController(); - private ready: boolean = false; - private active: boolean = true; - private running: boolean = false; - private dirty: boolean = true; - private bridge: EditorNativeBridge = new EditorNativeBridge((raw: string): void => { - if (!this.active) return; - try { - const event = JSON.parse(raw) as EditorEvent; - if (event.type === 'ready') { this.ready = true; this.changed(); } - else if (event.type === 'edit' && this.editing && typeof event.text === 'string') this.onIntent({ type: 'edit', text: event.text }); - } catch (_error) { /* Only typed editor input can leave the renderer. */ } - }); - @Monitor('content', 'editing', 'lineNumbers') - private changed(): void { this.dirty = true; void this.flush(); } - private color(id: number): string { - const value = this.getUIContext().getHostContext()?.resourceManager.getColorSync(id) || 0; - return `#${(value & 0xffffff).toString(16).padStart(6, '0')}`; - } - private async flush(): Promise { - if (!this.ready || !this.active || this.running) return; - this.running = true; - try { - while (this.dirty && this.active) { - this.dirty = false; - const frame: EditorFrame = { content: this.content, editing: this.editing, lineNumbers: this.lineNumbers, - ink: this.color($r('app.color.ink').id), muted: this.color($r('app.color.muted').id) }; - await this.controller.runJavaScript(`window.OpenBitFunEditor.accept(${JSON.stringify(frame)})`); - } - } catch (error) { this.onIntent({ type: 'file-renderer-error', text: String(error) }); } - finally { this.running = false; } - } - aboutToDisappear(): void { this.active = false; this.ready = false; } - build() { - Web({ src: $rawfile('editor/index.html'), controller: this.controller }) - .javaScriptAccess(true).domStorageAccess(false).fileAccess(false) - .darkMode(WebDarkMode.Auto).forceDarkAccess(false) - .javaScriptProxy({ object: this.bridge, name: 'OpenBitFunEditorHost', methodList: ['postMessage'], controller: this.controller }) - .onControllerAttached(() => { this.active = true; }) - .onPageEnd(() => { void this.controller.runJavaScript('window.OpenBitFunEditor.connect()').catch((error: Error) => this.onIntent({ type: 'file-renderer-error', text: error.message })); }) - .onErrorReceive((event: OnErrorReceiveEvent) => this.onIntent({ type: 'file-renderer-error', text: event.error.getErrorInfo() })) - .onOverrideUrlLoading((request: WebResourceRequest): boolean => !request.getRequestUrl().startsWith('resource://rawfile/editor/')) - .width('100%').height('100%') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceTerminalView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceTerminalView.ets deleted file mode 100644 index 257020d8b7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceTerminalView.ets +++ /dev/null @@ -1,84 +0,0 @@ -import { webview } from '@kit.ArkWeb'; -import { WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; - -interface TerminalBridgeEvent { type: string; data?: string; cols?: number; rows?: number; } -interface TerminalTheme { background: string; foreground: string; cursor: string; } -interface TerminalFrame { epoch: string; revision: number; reset: boolean; data: string; theme: TerminalTheme; } -class TerminalNativeBridge { - private dispatch: (raw: string) => void; - constructor(dispatch: (raw: string) => void) { this.dispatch = dispatch; } - postMessage(raw: string): void { this.dispatch(raw); } -} - -/** Platform renderer only: authenticated transport and PTY ownership remain in the ViewModel. */ -@ComponentV2 -export struct WorkspaceTerminalView { - @Param terminalId: string = ''; - @Param output: string = ''; - @Event onIntent: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - private controller: webview.WebviewController = new webview.WebviewController(); - private ready: boolean = false; - private active: boolean = true; - private sending: boolean = false; - private dirty: boolean = false; - private reset: boolean = true; - private sentEpoch: string = ''; - private sentOutput: string = ''; - private revision: number = 0; - private bridge: TerminalNativeBridge = new TerminalNativeBridge((raw: string): void => this.receive(raw)); - - @Monitor('terminalId', 'output') - private changed(): void { this.dirty = true; void this.flush(); } - private receive(raw: string): void { - if (!this.active) return; - try { - const event = JSON.parse(raw) as TerminalBridgeEvent; - if (event.type === 'ready' || event.type === 'resync') { - this.ready = true; this.reset = true; this.dirty = true; void this.flush(); - } else if (event.type === 'input' && typeof event.data === 'string') { - this.onIntent({ type: 'terminal-write', text: event.data }); - } else if (event.type === 'resize' && event.cols && event.rows) { - this.onIntent({ type: 'terminal-resize', text: `${event.cols}x${event.rows}` }); - } - } catch (_error) { /* Invalid renderer messages cannot invoke host operations. */ } - } - private color(id: number): string { - const value = this.getUIContext().getHostContext()?.resourceManager.getColorSync(id) || 0; - return `#${(value & 0xffffff).toString(16).padStart(6, '0')}`; - } - private async flush(): Promise { - if (!this.ready || !this.active || this.sending) return; - this.sending = true; - try { - while (this.dirty && this.ready && this.active) { - this.dirty = false; - const epoch = this.terminalId; const output = this.output; - const reset = this.reset || epoch !== this.sentEpoch || !output.startsWith(this.sentOutput); - this.reset = false; - const foreground = this.color($r('app.color.ink').id); - const frame: TerminalFrame = { epoch: epoch, revision: ++this.revision, reset: reset, - data: reset ? output : output.slice(this.sentOutput.length), - theme: { background: this.color($r('app.color.media_background').id), foreground: foreground, cursor: foreground } }; - await this.controller.runJavaScript(`window.OpenBitFunTerminal.accept(${JSON.stringify(frame)})`); - this.sentEpoch = epoch; this.sentOutput = output; - } - } catch (_error) { this.reset = true; this.dirty = true; } - finally { this.sending = false; } - } - onWillApplyTheme(_theme: Theme): void { - this.dirty = true; - void this.flush(); - } - aboutToDisappear(): void { this.active = false; this.ready = false; } - build() { - Web({ src: $rawfile('terminal/index.html'), controller: this.controller }) - .javaScriptAccess(true).domStorageAccess(false).fileAccess(false) - .darkMode(WebDarkMode.Auto).forceDarkAccess(false) - .javaScriptProxy({ object: this.bridge, name: 'OpenBitFunTerminalHost', methodList: ['postMessage'], controller: this.controller }) - .onControllerAttached(() => { this.active = true; }) - .onPageEnd(() => { void this.controller.runJavaScript('window.OpenBitFunTerminal.connect()').catch((error: Error) => this.onIntent({ type: 'terminal-renderer-error', text: error.message })); }) - .onErrorReceive((event: OnErrorReceiveEvent) => this.onIntent({ type: 'terminal-renderer-error', text: event.error.getErrorInfo() })) - .onOverrideUrlLoading((request: WebResourceRequest): boolean => !request.getRequestUrl().startsWith('resource://rawfile/terminal/')) - .width('100%').height('100%') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceToolsPanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceToolsPanel.ets deleted file mode 100644 index 534434ed4b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/WorkspaceToolsPanel.ets +++ /dev/null @@ -1,309 +0,0 @@ -import { RuntimeLocationPolicy } from '../policy/RuntimeLocationPolicy'; -import { WorkspaceFileEditorView } from './WorkspaceFileEditorView'; -import { WorkspaceTerminalView } from './WorkspaceTerminalView'; -import { WorkspaceToolsState, WorkspaceToolsIntent, WorkspaceFileEntry, WorkspaceTerminalEntry, WorkspaceToolLocation } from '../state/WorkspaceToolsState'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CARD, CONTENT_ON_INK, INK, MEDIA_BACKGROUND, MUTED, PAGE_BG, LINE, SOFT, TRANSPARENT } from './Theme'; -import { SheetCloseButton } from './SheetCloseButton'; -import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; - -@ComponentV2 -export struct WorkspaceToolsPanel { - @Param state: WorkspaceToolsState = new WorkspaceToolsState(); - @Event onIntent: (intent: WorkspaceToolsIntent) => void = (_intent: WorkspaceToolsIntent) => {}; - private filesScroller: Scroller = new Scroller(); - /** - * The sheet's own bottom edge, in vp. The panel is a full-height sheet, so - * its scrolling viewport runs to the screen edge and its rows roll under the - * navigation indicator; the tail spacer and the fixed bottom controls are - * what keep the bar clear. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - @Monitor('state.directory', 'state.connectionId', 'state.sort') - private onFileLocationChanged(): void { - this.filesScroller.scrollEdge(Edge.Top); - } - - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - Column({ space: 0 }) { - Row({ space: 12 }) { - Blank().layoutWeight(1) - SheetCloseButton({ uniformGlyph: true, onClose: () => this.onIntent({ type: 'close' }) }) - } - .width('100%') - .height(56) - .alignItems(VerticalAlign.Center) - if (this.state.deviceScope) { - Select([{ value: RemoteI18n.t('workspaceTools.runtimeLocal') }, ...this.state.locations.map((item: WorkspaceToolLocation): SelectOption => ({ value: item.name }))]) - .value(this.state.locations.find((item: WorkspaceToolLocation): boolean => item.id === this.state.connectionId)?.name || RemoteI18n.t('workspaceTools.runtimeLocal')) - .fontColor(INK).width('100%').height(54).enabled(!this.state.busy) - .backgroundColor(CARD).border({ width: 1, color: LINE }).borderRadius(16) - .onSelect((index: number) => this.onIntent({ type: 'open-device', connectionId: index === 0 ? '' : this.state.locations[index - 1]?.id, tab: this.state.initialTab })) - } - if (this.state.error.length > 0) { Text(this.state.saveConflict ? RemoteI18n.t('workspaceTools.fileConflict') : this.state.error).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size) } - if (this.state.confirmDiscard) { - Text(RemoteI18n.t('workspaceTools.unsaved')).fontColor(INK) - Row({ space: 8 }) { - Button(RemoteI18n.t('common.cancel')).onClick(() => this.onIntent({ type: 'discard-cancel' })) - Button(RemoteI18n.t('workspaceTools.discard')).onClick(() => this.onIntent({ type: 'discard-confirm' })) - } - } - Tabs({ index: this.state.initialTab }) { - TabContent() { this.Files() }.tabBar(new SubTabBarStyle(RemoteI18n.t('workspaceTools.files')).labelStyle({ selectedColor: INK, unselectedColor: MUTED }).indicator({ color: INK })) - TabContent() { this.Terminal() }.tabBar(new SubTabBarStyle(RemoteI18n.t('workspaceTools.terminal')).labelStyle({ selectedColor: INK, unselectedColor: MUTED }).indicator({ color: INK })) - }.barHeight(50).onChange((index: number) => this.onIntent({ type: 'panel', tab: index })).layoutWeight(1) - }.padding({ left: 16, right: 16 }).width('100%').height('100%').backgroundColor(PAGE_BG) - } - @Builder - private Files() { - if (this.state.editorVisible) { this.Editor() } else { this.FileDirectory() } - } - private sortTitle(): string { - if (this.state.sort === 1) return RemoteI18n.t('workspaceTools.nameDesc'); - if (this.state.sort === 2) return RemoteI18n.t('workspaceTools.modifiedAsc'); - if (this.state.sort === 3) return RemoteI18n.t('workspaceTools.modifiedDesc'); - return RemoteI18n.t('workspaceTools.nameAsc'); - } - private fileActionTitle(): string { - if (this.state.fileAction === 'file') return RemoteI18n.t('workspaceTools.newFile'); - if (this.state.fileAction === 'folder') return RemoteI18n.t('workspaceTools.mkdir'); - if (this.state.fileAction === 'rename') return RemoteI18n.t('workspaceTools.rename'); - if (this.state.fileAction === 'upload') return RemoteI18n.t('workspaceTools.upload'); - return RemoteI18n.t('workspaceTools.confirmDelete'); - } - @Builder - private FileActionForm() { - Column({ space: 16 }) { - Row({ space: 12 }) { - Button(RemoteI18n.t('common.cancel')) - .fontColor(MUTED).backgroundColor(TRANSPARENT).height(40).borderRadius(8) - .onClick(() => this.onIntent({ type: 'file-action-cancel' })) - Text(this.fileActionTitle()).fontColor(INK).fontSize(MobileDesignTypography.titleMedium.size).fontWeight(FontWeight.Medium).layoutWeight(1).maxLines(2) - Button(this.fileActionTitle()) - .fontColor(CONTENT_ON_INK).backgroundColor(INK).height(40).borderRadius(8) - .enabled(this.state.fileAction === 'delete' || this.state.fileActionName.trim().length > 0) - .onClick(() => this.onIntent({ type: 'file-action-submit' })) - }.enabled(!this.state.busy).width('100%') - if (this.state.fileAction === 'delete') { - Text(this.state.fileActionPath).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size).maxLines(3) - } - else { - TextInput({ text: this.state.fileActionName, placeholder: RemoteI18n.t('workspaceTools.fileName') }) - .fontColor(INK).backgroundColor(SOFT).borderRadius(8).height(48).enabled(!this.state.busy) - .onChange((value: string) => this.onIntent({ type: 'file-action-name', text: value })) - .onSubmit(() => { if (!this.state.busy && this.state.fileActionName.trim()) this.onIntent({ type: 'file-action-submit' }); }) - } - if (this.state.error) { Text(this.state.error).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size) } - if (this.state.busy) { LoadingProgress().width(24).height(24).color(MUTED) } - }.padding({ left: 20, right: 20, top: 20, bottom: this.insets.bottomPadding(24) }).width('100%').backgroundColor(CARD) - } - @Builder - private FileDirectory() { - Column({ space: 12 }) { - Row({ space: 8 }) { - Button() { SymbolGlyph($r('sys.symbol.arrow_up')).fontColor([INK]).fontSize(18) } - .width(40).height(40).padding(0).backgroundColor(TRANSPARENT).borderRadius(8).accessibilityText(RemoteI18n.t('workspaceTools.up')) - .onClick(() => this.onIntent({ type: 'directory', path: RuntimeLocationPolicy.parent(this.state.directory) })) - Text(this.state.directory).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size).maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }).layoutWeight(1) - Button() { SymbolGlyph($r('sys.symbol.arrow_clockwise')).fontColor([MUTED]).fontSize(18) } - .width(40).height(40).padding(0).backgroundColor(TRANSPARENT).borderRadius(8).accessibilityText(RemoteI18n.t('workspaceTools.refresh')) - .onClick(() => this.onIntent({ type: 'directory' })) - }.width('100%').height(48).padding({ left: 4, right: 4 }).backgroundColor(CARD).border({ width: 1, color: LINE }).borderRadius(8) - Row({ space: 8 }) { - Button() { - Row({ space: 6 }) { - SymbolGlyph($r('sys.symbol.doc_text')).fontColor([INK]).fontSize(16) - Text(RemoteI18n.t('workspaceTools.newFile')).fontColor(INK).fontSize(MobileDesignTypography.labelSmall.size) - } - }.layoutWeight(1).height(44).padding({ left: 4, right: 4 }).backgroundColor(CARD).border({ width: 1, color: LINE }).borderRadius(13) - .onClick(() => this.onIntent({ type: 'file-action', text: 'file' })) - Button() { - Row({ space: 6 }) { - SymbolGlyph($r('sys.symbol.folder')).fontColor([INK]).fontSize(16) - Text(RemoteI18n.t('workspaceTools.mkdir')).fontColor(INK).fontSize(MobileDesignTypography.labelSmall.size) - } - }.layoutWeight(1).height(44).padding({ left: 4, right: 4 }).backgroundColor(SOFT).borderRadius(13) - .onClick(() => this.onIntent({ type: 'file-action', text: 'folder' })) - Button() { - Row({ space: 6 }) { - SymbolGlyph($r('sys.symbol.doc_text_badge_arrow_up')).fontColor([INK]).fontSize(16) - Text(RemoteI18n.t('workspaceTools.upload')).fontColor(INK).fontSize(MobileDesignTypography.labelSmall.size) - } - }.layoutWeight(1).height(44).padding({ left: 4, right: 4 }).backgroundColor(SOFT).borderRadius(13) - .onClick(() => this.onIntent({ type: 'file-action', text: 'upload' })) - }.width('100%').height(44) - Row({ space: 8 }) { - Row({ space: 6 }) { - Text(RemoteI18n.t('workspaceTools.files')).fontColor(INK).fontSize(MobileDesignTypography.bodySmall.size).fontWeight(FontWeight.Medium) - Text(String(this.state.entries.length)).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - }.layoutWeight(1).alignItems(VerticalAlign.Center) - Select([ - { value: RemoteI18n.t('workspaceTools.nameAsc') }, { value: RemoteI18n.t('workspaceTools.nameDesc') }, - { value: RemoteI18n.t('workspaceTools.modifiedAsc') }, { value: RemoteI18n.t('workspaceTools.modifiedDesc') } - ]).selected(this.state.sort).value(this.sortTitle()).fontColor(MUTED).height(34).width(132).enabled(!this.state.busy) - .backgroundColor(SOFT).borderRadius(17) - .onSelect((index: number) => this.onIntent({ type: 'sort', text: String(index) })) - }.enabled(!this.state.busy).width('100%') - if (this.state.busy) { LoadingProgress().width(24).height(24).color(MUTED) } - List({ scroller: this.filesScroller }) { - ForEach(this.state.entries, (entry: WorkspaceFileEntry) => { - ListItem() { - Row({ space: 8 }) { - Row({ space: 12 }) { - SymbolGlyph(entry.isDirectory ? $r('sys.symbol.folder') : $r('sys.symbol.doc_text')).fontColor([MUTED]).fontSize(20) - Text(entry.name).fontColor(INK).fontSize(MobileDesignTypography.bodyMedium.size).maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }).layoutWeight(1) - }.layoutWeight(1).constraintSize({ minHeight: 56 }).onClick(() => this.onIntent({ type: entry.isDirectory ? 'directory' : 'read', path: entry.path })) - Button() { this.MoreGlyph() } - .width(40).height(40).padding(0).backgroundColor(TRANSPARENT).borderRadius(8).accessibilityText(entry.name) - .bindMenu([ - { value: RemoteI18n.t('workspaceTools.rename'), action: () => this.onIntent({ type: 'file-action', text: 'rename', path: entry.path }) }, - { value: RemoteI18n.t('workspaceTools.delete'), action: () => this.onIntent({ type: 'file-action', text: 'delete', path: entry.path }) }, - { value: RemoteI18n.t('workspaceTools.download'), enabled: !entry.isDirectory, action: () => this.onIntent({ type: 'download', path: entry.path }) } - ]) - }.width('100%').padding({ left: 12, right: 8 }).backgroundColor(CARD) - } - }, (entry: WorkspaceFileEntry) => entry.path) - if (this.state.hasMore) { ListItem() { Button(RemoteI18n.t('workspaceTools.more')).fontColor(INK).backgroundColor(TRANSPARENT).height(44).onClick(() => this.onIntent({ type: 'more' })) } } - // The list's tail spacer: the strip plus the panel's own breathing, so - // the viewport can run to the screen edge — rows roll under the - // navigation indicator while they are moving — while the last row - // still rests above the bar. - ListItem() { - Column().width('100%').height(this.insets.tailSpacing(16)) - } - }.divider({ strokeWidth: 1, color: LINE }).border({ width: 1, color: LINE }).borderRadius(8).layoutWeight(1).enabled(!this.state.busy) - if (this.state.downloadStatus || this.state.uploadPending) { - Column({ space: 8 }) { - if (this.state.downloadStatus) { Text(this.state.downloadStatus).fontColor(MUTED).fontSize(MobileDesignTypography.bodySmall.size) } - if (this.state.uploadPending) { - Progress({ value: this.state.uploadProgress, total: 100, type: ProgressType.Linear }) - Row({ space: 8 }) { - Button(RemoteI18n.t('workspaceTools.resumeUpload')).fontColor(INK).backgroundColor(PAGE_BG).onClick(() => this.onIntent({ type: 'upload-resume' })) - Button(RemoteI18n.t('workspaceTools.cancelUpload')).fontColor(INK).backgroundColor(PAGE_BG).onClick(() => this.onIntent({ type: 'upload-cancel' })) - }.enabled(!this.state.busy) - } - }.width('100%').margin({ bottom: this.insets.bottomPadding(16) }) - } - }.padding({ top: 12 }).width('100%').height('100%') - .bindSheet(this.state.fileAction.length > 0, this.FileActionForm(), { height: SheetSize.FIT_CONTENT, showClose: false, backgroundColor: PAGE_BG, keyboardAvoidMode: SheetKeyboardAvoidMode.TRANSLATE_AND_RESIZE, - onWillDismiss: (action: DismissSheetAction): void => { if (!this.state.busy) { this.onIntent({ type: 'file-action-cancel' }); action.dismiss(); } } }) - } - @Builder - private MoreGlyph() { - Row({ space: 3 }) { - Circle().width(3).height(3).fill(MUTED) - Circle().width(3).height(3).fill(MUTED) - Circle().width(3).height(3).fill(MUTED) - } - } - @Builder - private Editor() { - Column({ space: 12 }) { - Row({ space: 8 }) { - Button() { SymbolGlyph($r('sys.symbol.chevron_left')).fontColor([INK]).fontSize(18) } - .width(40).height(40).padding(0).backgroundColor(TRANSPARENT).borderRadius(8) - .accessibilityText(RemoteI18n.t('workspaceTools.back')) - .onClick(() => this.onIntent({ type: 'editor-back' })) - Column({ space: 2 }) { - Text(this.state.selectedFile.split('/').pop() || this.state.selectedFile) - .fontColor(INK).fontSize(MobileDesignTypography.titleSmall.size).fontWeight(FontWeight.Medium) - .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }).width('100%') - Text(this.state.selectedFile).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }).width('100%') - }.layoutWeight(1).alignItems(HorizontalAlign.Start) - if (this.state.dirty) { Text('•').fontColor(MUTED).fontSize(MobileDesignTypography.bodyLarge.size) } - }.width('100%').height(48) - Row({ space: 8 }) { - Button() { SymbolGlyph($r('sys.symbol.arrow_down_to_line')).fontColor([MUTED]).fontSize(16) } - .width(40).height(36).padding(0).backgroundColor(SOFT).borderRadius(8) - .accessibilityText(RemoteI18n.t('workspaceTools.download')).enabled(!this.state.busy) - .onClick(() => this.onIntent({ type: 'download' })) - Button(RemoteI18n.t('workspaceTools.lineNumbers')).fontColor(MUTED).fontSize(MobileDesignTypography.labelSmall.size) - .height(36).backgroundColor(SOFT).borderRadius(8).onClick(() => this.onIntent({ type: 'line-numbers' })) - if (this.state.editing) { - Button(RemoteI18n.t('workspaceTools.save')).fontColor(CONTENT_ON_INK).backgroundColor(INK).height(36).borderRadius(8) - .enabled(!this.state.busy).onClick(() => this.onIntent({ type: 'save' })) - } else { - Button(RemoteI18n.t('workspaceTools.edit')).fontColor(INK).backgroundColor(SOFT).height(36).borderRadius(8) - .onClick(() => this.onIntent({ type: 'editor-edit' })) - } - }.width('100%').justifyContent(FlexAlign.End) - // The editor is a WebView: its scrolling and its padding live inside the - // web renderer, so the panel cannot end it in an ArkUI tail spacer the - // way the file list does. The card is therefore fixed content, like the - // terminal key row: its bottom edge stops at the navigation bar's top, - // while the sheet's own fill still reaches the screen edge below it. - WorkspaceFileEditorView({ content: this.state.content, editing: this.state.editing, - lineNumbers: this.state.lineNumbers, onIntent: this.onIntent }).layoutWeight(1) - .border({ width: 1, color: LINE }).borderRadius(8).backgroundColor(CARD) - .margin({ bottom: this.insets.bottomPadding(16) }) - }.padding({ top: 12 }).width('100%').height('100%') - } - private terminalOptions(): SelectOption[] { - return this.state.terminals.map((entry: WorkspaceTerminalEntry): SelectOption => ({ value: entry.name || entry.id })); - } - @Builder - private Terminal() { - Column({ space: 12 }) { - if (this.state.terminalId.length === 0) { - Column({ space: 16 }) { - Stack({ alignContent: Alignment.Center }) { - SymbolGlyph($r('sys.symbol.rectangle_stack')).fontColor([MUTED]).fontSize(32) - }.width(72).height(72).backgroundColor(SOFT).borderRadius(20) - Button(RemoteI18n.t('workspaceTools.createTerminal')) - .fontColor(CONTENT_ON_INK).backgroundColor(INK) - .borderRadius(8).height(44).padding({ left: 18, right: 18 }) - .enabled(!this.state.busy) - .onClick(() => this.onIntent({ type: 'terminal-create' })) - if (this.state.terminals.length > 0) { - Select(this.terminalOptions()).value(RemoteI18n.t('workspaceTools.selectTerminal')).fontColor(INK).height(44) - .backgroundColor(SOFT).borderRadius(8) - .onSelect((index: number) => this.onIntent({ type: 'terminal-attach', path: this.state.terminals[index]?.id })) - } - }.width('100%').layoutWeight(1).justifyContent(FlexAlign.Center).border({ width: 1, color: LINE }).borderRadius(12) - } else { - Row({ space: 8 }) { - Button() { SymbolGlyph($r('sys.symbol.plus')).fontColor([INK]).fontSize(17) } - .width(40).height(40).padding(0).backgroundColor(SOFT).borderRadius(8) - .accessibilityText(RemoteI18n.t('workspaceTools.createTerminal')) - .onClick(() => this.onIntent({ type: 'terminal-create' })) - Select(this.terminalOptions()).value(this.state.terminals.find((entry: WorkspaceTerminalEntry): boolean => entry.id === this.state.terminalId)?.name || this.state.terminalId) - .fontColor(INK).height(40).layoutWeight(1).backgroundColor(SOFT).borderRadius(8) - .onSelect((index: number) => this.onIntent({ type: 'terminal-attach', path: this.state.terminals[index]?.id })) - }.enabled(!this.state.busy).width('100%') - Row() { - WorkspaceTerminalView({ terminalId: this.state.terminalId, output: this.state.output, onIntent: this.onIntent }) - }.layoutWeight(1).width('100%').padding(10).backgroundColor(MEDIA_BACKGROUND).borderRadius(12) - Row({ space: 8 }) { - Scroll() { - Row({ space: 8 }) { - Button('Esc').fontColor(INK).backgroundColor(SOFT).borderRadius(8).height(36).onClick(() => this.onIntent({ type: 'terminal-write', text: '\u001b' })) - Button('Tab').fontColor(INK).backgroundColor(SOFT).borderRadius(8).height(36).onClick(() => this.onIntent({ type: 'terminal-write', text: '\t' })) - Button('Enter').fontColor(INK).backgroundColor(SOFT).borderRadius(8).height(36).onClick(() => this.onIntent({ type: 'terminal-write', text: '\r' })) - Button('Ctrl-C').fontColor(INK).backgroundColor(SOFT).borderRadius(8).height(36).onClick(() => this.onIntent({ type: 'terminal-write', text: '\u0003' })) - } - }.layoutWeight(1).height(40).scrollable(ScrollDirection.Horizontal).scrollBar(BarState.Off) - Button() { SymbolGlyph($r('sys.symbol.xmark')).fontColor([MUTED]).fontSize(16) } - .width(40).height(36).padding(0).backgroundColor(SOFT).borderRadius(8) - .accessibilityText(RemoteI18n.t('workspaceTools.closeTerminal')) - .onClick(() => this.onIntent({ type: 'terminal-close' })) - }.width('100%').enabled(this.state.terminalId.length > 0) - // The key row is the tab's fixed bottom control; it keeps the strip - // clear so the terminal above it ends above the navigation bar. - .margin({ bottom: this.insets.bottomPadding(16) }) - } - }.padding({ top: 8 }).width('100%').height('100%') - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/remote/RemoteSurfaceHost.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/remote/RemoteSurfaceHost.ets deleted file mode 100644 index 6ab4000728..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/remote/RemoteSurfaceHost.ets +++ /dev/null @@ -1,474 +0,0 @@ -import { RecentRemoteHome } from '../RecentRemoteHome'; -import { WelcomeHome } from '../WelcomeHome'; -import { MobileDesignTypography } from '../../../generated/MobileDesignTokens'; -import { RemoteI18n } from '../../../i18n/RemoteI18n'; -import { REMOTE_CAPABILITY_HARNESS_PROFILES_V1, RemoteSession } from '../../../model/RemoteModels'; -import { RemoteLogger } from '../../../services/RemoteLogger'; -import { RemoteUiState } from '../../../services/RemoteUiState'; -import { RemotePageState } from '../../state/RemotePageState'; -import { - AppRootPresentationActions, - emptyAppRootPresentationActions -} from '../../actions/AppRootPresentationActions'; -import { ConversationViewSettings } from '../ConversationViewSettings'; -import { ConversationHeader } from '../ConversationHeader'; -import { RemoteCompactHomePolicy } from '../../policy/RemoteCompactHomePolicy'; -import { RemoteSessionList } from '../RemoteSessionList'; -import { RemoteSessionLoadingView } from '../RemoteSessionLoadingView'; -import { SidebarToggleButton } from '../SidebarToggleButton'; -import { SessionActionPresentation } from '../SessionActionSurface'; -import { WindowInsetsBinding } from '../../../services/WindowSystemBarService'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../../policy/SettingsPlacementPolicy'; -import { CARD, STATUS_SUCCESS, INK, MUTED, PAGE_BG, PRIMARY_ACTION, CONTENT_ON_ACTION, STATUS_DANGER } from '../Theme'; - -export enum RemoteSurfaceMode { - Master = 'master', - CompactHome = 'compact_home', - Placeholder = 'placeholder', - Settings = 'settings' -} - -/** Shared presentation state for compact and wide Remote surfaces. */ -@ObservedV2 -export class RemoteSurfaceState { - @Trace sortMode: string = 'project'; - @Trace workspaceFilter: string = ''; - @Trace agentFilter: string = ''; - @Trace statusFilter: string = ''; - @Trace showWorkspaceMetadata: boolean = false; - @Trace showUpdatedMetadata: boolean = false; - @Trace showStatusMetadata: boolean = false; - - setSortMode(value: string): void { this.sortMode = value; } - setWorkspaceFilter(value: string): void { this.workspaceFilter = value; } - setAgentFilter(value: string): void { this.agentFilter = value; } - setStatusFilter(value: string): void { this.statusFilter = value; } - setWorkspaceMetadata(value: boolean): void { this.showWorkspaceMetadata = value; } - setUpdatedMetadata(value: boolean): void { this.showUpdatedMetadata = value; } - setStatusMetadata(value: boolean): void { this.showStatusMetadata = value; } -} - -@ComponentV2 -export struct RemoteSurfaceHost { - @Param mode: RemoteSurfaceMode = RemoteSurfaceMode.Master; - @Param remotePageState: RemotePageState = new RemotePageState(); - @Param presentationState: RemoteSurfaceState = new RemoteSurfaceState(); - @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - @Param showSelectedSession: boolean = false; - @Param compact: boolean = false; - @Param wideMasterPaneCollapsed: boolean = false; - @Param sessionDetailsPlacement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.SessionDetails); - /** - * The window's own insets, in vp. The home surfaces are full-screen pages — - * the compact header and the wide placeholder are both the page's top edge — - * so their header bands reserve the status bar themselves rather than being - * handed a page that already ends below it. - */ - @Local insets: WindowInsetsBinding = new WindowInsetsBinding(); - @Event onOpenSidebar: () => void = () => {}; - @Event onRestoreSidebar: () => void = () => {}; - @Event onCloseSettings: () => void = () => {}; - - // The wide layout keeps the master pane inside a routed destination, so a - // mount here while switching sessions means the navigation stack was torn - // down for a change that is only page state — the sidebar rebuild this used - // to pay for. See AppShellViewModel.replaceRouteWithoutAnimation. - aboutToAppear(): void { - const context = this.getUIContext().getHostContext(); - if (context) { - this.insets.bind(this.getUIContext(), context); - } - RemoteLogger.info( - `remote surface mounted mode=${this.mode} connection=${this.remotePageState.connectionState} sessions=${this.remotePageState.visibleSessions().length}` - ); - } - - aboutToDisappear(): void { - this.insets.unbind(); - } - - build() { - if (this.mode !== RemoteSurfaceMode.Settings && - RemoteCompactHomePolicy.shouldShowWelcomeHome(this.remotePageState.controlTargetType, - this.remotePageState.connectionState, this.remotePageState.accountUserId.trim().length > 0)) { - this.WelcomeEntry() - } else if (this.mode === RemoteSurfaceMode.Master) { - this.MasterContent(); - } else if (this.mode === RemoteSurfaceMode.CompactHome) { - this.CompactHomeContent(); - } else if (this.mode === RemoteSurfaceMode.Placeholder) { - this.FlowPlaceholder(); - } else { - this.SettingsContent(); - } - } - - @Builder - private MasterContent() { - Column() { - this.StatusRow() - if (this.isInitialLoading()) { - RemoteSessionLoadingView() - } else if (this.canShowSessionList()) { - RemoteSessionList({ - sessions: this.remotePageState.visibleSessions(), - query: this.remotePageState.sessionQuery, - sortMode: this.presentationState.sortMode, - workspaceFilter: this.presentationState.workspaceFilter, - agentFilter: this.presentationState.agentFilter, - statusFilter: this.presentationState.statusFilter, - workspaceName: this.remotePageState.workspaceName, - workspacePath: this.remotePageState.workspacePath, - workspaceId: this.remotePageState.workspaceId, - workspaceConnectionId: this.remotePageState.workspaceConnectionId, - workspaceSshHost: this.remotePageState.workspaceSshHost, - workspaceKind: this.remotePageState.workspaceKind, - recentWorkspaces: this.remotePageState.recentWorkspaces, - actionPresentation: SessionActionPresentation.Popover, - sessionDetailsPlacement: this.sessionDetailsPlacement, - showWorkspaceMetadata: this.presentationState.showWorkspaceMetadata, - showUpdatedMetadata: this.presentationState.showUpdatedMetadata, - showStatusMetadata: this.presentationState.showStatusMetadata, - supportsHarnessProfiles: this.supportsHarnessProfiles(), - hasMoreSessions: this.remotePageState.hasMoreSessions, - // Opening a transcript is supersedable; keep rows tappable while that - // request hydrates so a second choice is not silently swallowed. - isBusy: this.remotePageState.isLoadingSessions, - // A pending id means a row was tapped, whether or not the open is slow - // enough to have raised a skeleton. Keying the highlight off the - // loading flag instead used to tie selection to how long the load took. - selectedSessionId: this.remotePageState.pendingSessionId.length > 0 ? - this.remotePageState.pendingSessionId : - (this.showSelectedSession ? this.remotePageState.conversation.activeSession.sessionId : ''), - onCreate: () => this.createSession('code'), - onCreateAssistantSession: () => this.createAssistantSession(), - onCreateInWorkspace: (path: string, agentType: string, connectionId?: string, sshHost?: string, workspaceId?: string) => - this.createSessionInWorkspace(path, agentType, connectionId, sshHost, workspaceId), - onSelectWorkspace: (path: string, connectionId?: string, sshHost?: string, workspaceId?: string) => - this.actions.onRemoteHome.selectWorkspace(path, undefined, connectionId, sshHost, workspaceId), - onOpenSession: (session: RemoteSession) => this.openSession(session), - onDeleteSession: (session: RemoteSession) => this.actions.onRemoteHome.deleteSession(session), - onLoadMore: () => this.actions.onRemoteHome.loadMore() - }) - } else { - this.ConnectionEntry() - } - } - .width('100%') - .height('100%') - .alignItems(HorizontalAlign.Start) - .padding({ bottom: 84 }) - } - - @Builder - private StatusRow() { - Row({ space: 6 }) { - this.StatusIndicator() - Text(this.statusText()) - .fontSize(MobileDesignTypography.bodyMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(MUTED) - .maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - .layoutWeight(1) - if (this.canReconnect()) { - Text(RemoteI18n.t('remote.settings.reconnect')) - .fontSize(MobileDesignTypography.bodySmall.size) - .fontWeight(FontWeight.Medium) - .fontColor(CONTENT_ON_ACTION) - .height(28) - .padding({ left: 12, right: 12 }) - .backgroundColor(PRIMARY_ACTION) - .borderRadius(14) - .onClick(() => this.actions.onRemoteHome.reconnect()) - } - } - .width('100%') - .margin({ top: 16, bottom: 6 }) - .alignItems(VerticalAlign.Center) - } - - @Builder - private StatusIndicator() { - if (this.isSyncing()) { - LoadingProgress().width(14).height(14).color(MUTED) - } else { - Stack() { - Text('') - } - .width(7) - .height(7) - .backgroundColor(this.statusColor()) - .borderRadius(4) - } - } - - @Builder - private WelcomeEntry() { - WelcomeHome({ - signedIn: this.remotePageState.accountUserId.trim().length > 0, - onLogin: () => { - if (this.remotePageState.accountUserId.trim().length > 0) { - this.actions.onRemoteHome.connectWorkspace(); - } else { - this.actions.onSettings.openAccount(); - } - }, - onMiniApps: this.actions.onRemoteHome.openMiniApps - }) - } - - @Builder - private ConnectionEntry() { - if (this.isInitialLoading()) { - RemoteSessionLoadingView() - } else { - this.CompactEmptyState() - } - } - - @Builder - private CompactHomeContent() { - Column() { - // The compact home is a page, not a sheet: its header band is the top edge - // of the window, so the band reserves the status bar and the drawer - // control and title start below the clock and the indicators. The band is - // the window's full width, so it reserves the side strips as well — the - // drawer control is the control a landscape cutout would land on. - ConversationHeader({ - title: RemoteI18n.t('app.title'), - subtitle: this.compactHeaderContext(), - titleFallback: RemoteI18n.t('app.title'), - showSidebarButton: true, - onOpenSidebar: this.onOpenSidebar - }) - .padding({ - left: this.insets.leftPadding(0), - right: this.insets.rightPadding(0), - top: this.insets.top - }) - if (RemoteCompactHomePolicy.shouldShowConnectHome(this.remotePageState.connectionState)) { - this.ConnectionEntry() - } else { - this.CompactEmptyState() - } - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - @Builder - private CompactEmptyState() { - RecentRemoteHome({ - sessions: this.remotePageState.recentHomeSessions(), - desktopName: this.desktopName(), - onOpen: (session: RemoteSession) => this.openSession(session), - connected: this.remotePageState.connectionState === 'connected', - busy: this.isInitialLoading(), - onBrowse: () => { if (this.compact) this.onOpenSidebar(); else this.onRestoreSidebar(); }, - onConnect: () => this.actions.onRemoteHome.connectWorkspace() - }).layoutWeight(1) - } - - @Builder - private FlowPlaceholder() { - Column() { - Row({ space: 8 }) { - if (this.wideMasterPaneCollapsed) { - SidebarToggleButton({ restore: true, controlSize: 48, onToggle: this.onRestoreSidebar }) - } else { - Blank().width(48).height(48) - } - Column({ space: 4 }) { - Text(RemoteI18n.t('app.title')).fontSize(MobileDesignTypography.headlineMedium.size).fontWeight(FontWeight.Bold).fontColor(INK) - Text(this.desktopName()).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).maxLines(1) - .textOverflow({ overflow: TextOverflow.Ellipsis }) - } - .layoutWeight(1).alignItems(HorizontalAlign.Center) - Blank().width(48).height(48) - } - // No hairline under the welcome header. The compact header does not draw - // one and neither does the desktop client; the wide surface is the same - // page, not a sheet, so it should not grow a divider just because it is - // wider. The band's box grows by the status bar strip for the same reason - // the compact header's does: the wide detail pane's top edge is the - // window's top edge too. - // - // The sides are not stated the same way, because the wide surface has two - // parents and only one of them is the window. Mounted by `WideRouteContent` - // the band is the whole wide page and both of its side edges are the - // window's; mounted by `WideConversationHost.RemoteHomeDetail` it is the - // detail pane, and then only its right edge is the window's — its left one - // is the master pane's, so the left strip only indents the restore control - // instead of clearing a cutout. A layout dump of the master/detail posture - // reads exactly that: the band's own box sits at the pane's left edge - // (x=980 on a 789vp landscape window) while its content starts 72px further - // in, and the same band collapsed flush against the window's left edge does - // need that strip. Padding cannot be claimed per edge the way - // `expandSafeArea` can, so the strip is reserved on both sides and the - // over-reservation is a bounded indent rather than a missing clearance; - // reverting both sides would put the compact header and the flush-left wide - // composition back under the cutout this strip exists for. - .width('100%').height(76 + this.insets.top) - .padding({ - left: this.insets.leftPadding(16), - right: this.insets.rightPadding(16), - top: 14 + this.insets.top, - bottom: 12 - }) - // Named so a layout dump can be read against the pixels: this band is the - // one whose box-vs-content offset is the whole question above. - .id('remote-wide-home-band') - - this.CompactEmptyState() - - } - .width('100%').height('100%').backgroundColor(PAGE_BG) - } - - @Builder - private SettingsContent() { - ConversationViewSettings({ - sessions: this.remotePageState.visibleSessions(), - workspaceName: this.remotePageState.workspaceName, - workspacePath: this.remotePageState.workspacePath, - workspaceKind: this.remotePageState.workspaceKind, - recentWorkspaces: this.remotePageState.recentWorkspaces, - sortMode: this.presentationState.sortMode, - workspaceFilter: this.presentationState.workspaceFilter, - agentFilter: this.presentationState.agentFilter, - statusFilter: this.presentationState.statusFilter, - showWorkspaceMetadata: this.presentationState.showWorkspaceMetadata, - showUpdatedMetadata: this.presentationState.showUpdatedMetadata, - showStatusMetadata: this.presentationState.showStatusMetadata, - onSortModeChange: (value: string) => this.presentationState.setSortMode(value), - onWorkspaceFilterChange: (value: string) => this.presentationState.setWorkspaceFilter(value), - onAgentFilterChange: (value: string) => this.presentationState.setAgentFilter(value), - onStatusFilterChange: (value: string) => this.presentationState.setStatusFilter(value), - onWorkspaceMetadataChange: (value: boolean) => this.presentationState.setWorkspaceMetadata(value), - onUpdatedMetadataChange: (value: boolean) => this.presentationState.setUpdatedMetadata(value), - onStatusMetadataChange: (value: boolean) => this.presentationState.setStatusMetadata(value), - onClose: this.onCloseSettings - }) - } - - private openSession(session: RemoteSession): void { - if (this.compact) { - this.actions.onSidebar.openSession(session); - } else { - this.actions.onRemoteHome.openSessionInPlace(session); - } - } - - private createSession(agentType: string): void { - if (this.compact) { - this.actions.onSidebar.close(); - this.actions.onRemoteHome.create(agentType); - } else { - this.actions.onRemoteHome.createInPlace(agentType); - } - } - - private createSessionInWorkspace( - path: string, agentType: string, connectionId?: string, sshHost?: string, workspaceId?: string - ): void { - if (this.compact) { - this.actions.onSidebar.close(); - this.actions.onRemoteHome.createInWorkspace(path, agentType, undefined, connectionId, sshHost, workspaceId); - } else { - this.actions.onRemoteHome.createInWorkspaceInPlace(path, agentType, undefined, connectionId, sshHost, workspaceId); - } - } - - private createAssistantSession(): void { - this.createSession('code'); - } - - private supportsHarnessProfiles(): boolean { - return this.remotePageState.supportsHostCapability(REMOTE_CAPABILITY_HARNESS_PROFILES_V1); - } - - /** - * Whether the surface still owes the user a way back onto a desktop. - * - * The connect button used to live only on the disconnected placeholder, so - * the moment a restored session list took that placeholder's place there was - * no entry point left anywhere on the surface — a list from the cache reads - * as "connected" while nothing is. Offering it from the status row instead - * keeps the two independent: the list says what the phone knows, this says - * whether the desktop is answering. - */ - private canReconnect(): boolean { - return !RemoteUiState.canUseRemote(this.remotePageState.connectionState) && !this.isSyncing(); - } - - private canShowSessionList(): boolean { - return this.remotePageState.connectionState === 'connected' || - this.remotePageState.visibleSessions().length > 0 || - this.remotePageState.isLoadingHome || this.remotePageState.isLoadingSessions; - } - - /** - * Only the first load gets a skeleton. Once there are sessions to show — from - * this connection or from the cache a launch restored — connecting is a - * refresh happening behind a usable list, and replacing that list with - * placeholder rows would be a step backwards. - */ - private isInitialLoading(): boolean { - return RemoteCompactHomePolicy.shouldShowInitialLoading( - this.remotePageState.connectionState, - this.remotePageState.sessions.length, - this.remotePageState.isLoadingHome - ); - } - - /** Work in progress, whether or not there is already a list behind it. */ - private isSyncing(): boolean { - return this.remotePageState.isLoadingHome || this.isConnecting(); - } - - private isConnecting(): boolean { - return this.remotePageState.connectionState === 'parsing' || - this.remotePageState.connectionState === 'pairing' || - this.remotePageState.connectionState === 'reconnecting'; - } - - private statusText(): string { - if (this.remotePageState.conversation.statusText.length > 0) { - return this.remotePageState.conversation.statusText; - } - return this.desktopName(); - } - - private statusColor(): ResourceColor { - if (this.remotePageState.connectionState === 'connected') return STATUS_SUCCESS; - if (this.remotePageState.connectionState === 'failed' || this.remotePageState.connectionState === 'disconnected') { - return STATUS_DANGER; - } - return MUTED; - } - - /** - * Compact Remote Home names the bound desktop under the title, the same - * context the conversation header carries. Keep it stable during recovery so - * the content does not shift when the sidebar health state changes. - */ - private compactHeaderContext(): string { - return RemoteCompactHomePolicy.headerSubtitle( - this.remotePageState.connectionState, - this.remotePageState.desktopName - ); - } - - private desktopName(): string { - return this.remotePageState.desktopName.length > 0 ? this.remotePageState.desktopName : - RemoteI18n.t('remote.settings.noDesktop'); - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/host/AppRootHostAdapter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/host/AppRootHostAdapter.ets deleted file mode 100644 index 3521d6b6fa..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/host/AppRootHostAdapter.ets +++ /dev/null @@ -1,68 +0,0 @@ -import { common } from '@kit.AbilityKit'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { INK } from '../components/Theme'; - -export interface AppRootHostPort { - attach(context: Context, uiContext: UIContext): void; - context(): Context; - animate(duration: number, callback: () => void): void; - showToast(message: string, duration: number): boolean; - openExternalLink?(link: string): Promise; - offerTaskNotifications?(): Promise; -} - -export class ArkUiAppRootHostAdapter implements AppRootHostPort { - private hostContext: Context = {} as Context; - private uiContext: UIContext = {} as UIContext; - - attach(context: Context, uiContext: UIContext): void { - this.hostContext = context; - this.uiContext = uiContext; - } - - context(): Context { - return this.hostContext; - } - - animate(duration: number, callback: () => void): void { - try { - this.uiContext.animateTo({ duration, curve: Curve.EaseOut }, callback); - } catch (_err) { - callback(); - } - } - - showToast(message: string, duration: number): boolean { - try { - this.uiContext.getPromptAction().showToast({ message, duration }); - return true; - } catch (_err) { - return false; - } - } - - async offerTaskNotifications(): Promise { - const result = await this.uiContext.getPromptAction().showDialog({ - title: RemoteI18n.t('notification.onboardingTitle'), - message: RemoteI18n.t('notification.onboardingBody'), - buttons: [ - { text: RemoteI18n.t('notification.onboardingLater'), color: INK as Resource }, - { text: RemoteI18n.t('notification.onboardingEnable'), color: INK as Resource } - ] - }); - return result.index === 1; - } - - async openExternalLink(link: string): Promise { - const value = link.trim(); - if (!/^https?:\/\//i.test(value)) { - return false; - } - try { - await (this.hostContext as common.UIAbilityContext).openLink(value); - return true; - } catch (_err) { - return false; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/layout/WideLayoutGeometry.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/layout/WideLayoutGeometry.ets deleted file mode 100644 index 9bc7af78b8..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/layout/WideLayoutGeometry.ets +++ /dev/null @@ -1,30 +0,0 @@ -import { FilePreviewLayout, FilePreviewPlacement } from '../policy/FilePreviewPlacementPolicy'; - -/** Pure geometry helpers shared by wide conversation presentation paths. */ -export class WideLayoutGeometry { - static masterPaneWidth(layout: FilePreviewLayout, fallback: number): number { - return layout.placement === FilePreviewPlacement.WideTriplePane || - layout.placement === FilePreviewPlacement.WideMasterPreviewFocus ? layout.masterPaneWidth : fallback; - } - - static detailOffset(collapsed: boolean, expandedOffset: number, collapsedOffset: number): number { - return collapsed ? collapsedOffset : expandedOffset; - } - - static detailWidth(collapsed: boolean, expandedWidth: number, collapsedWidth: number): number { - return collapsed ? collapsedWidth : expandedWidth; - } - - static showsMasterRestoreButton(collapsed: boolean, layout: FilePreviewLayout): boolean { - return collapsed || layout.placement === FilePreviewPlacement.WideFocusSplit; - } - - static restoreMasterClosesPreview(layout: FilePreviewLayout): boolean { - return layout.placement === FilePreviewPlacement.WideFocusSplit; - } - - static areaLength(value: Object): number { - const parsed = Number.parseFloat(`${value}`); - return Number.isNaN(parsed) ? 0 : parsed; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRootRouteState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRootRouteState.ets deleted file mode 100644 index 58ca1bf03e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRootRouteState.ets +++ /dev/null @@ -1,91 +0,0 @@ -import { SelectedImageAttachment } from '../../model/RemoteModels'; -import { VoiceInputRouteSnapshot } from '../../services/VoiceInputLifecycleController'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { RemotePageState } from '../state/RemotePageState'; -import { AppRoute, AppRouteContract } from './AppRouteContract'; - -/** Keeps route-dependent composer state mapping out of the root component. */ -export class AppRootRouteState { - static isGeneralComposerRoute(route: AppRoute): boolean { - return AppRouteContract.isGeneralComposerRoute(route); - } - - static chatInput(route: AppRoute, general: GeneralChatPageState, remote: RemotePageState): string { - return AppRootRouteState.isGeneralComposerRoute(route) ? - general.conversation.chatInput : remote.conversation.chatInput; - } - - static selectedImages(route: AppRoute, general: GeneralChatPageState, - remote: RemotePageState): SelectedImageAttachment[] { - return AppRootRouteState.isGeneralComposerRoute(route) ? - general.conversation.selectedImages : remote.conversation.selectedImages; - } - - static voiceListening(route: AppRoute, general: GeneralChatPageState, remote: RemotePageState): boolean { - return AppRootRouteState.isGeneralComposerRoute(route) ? - general.conversation.isVoiceListening : remote.conversation.isVoiceListening; - } - - static setChatInput(route: AppRoute, value: string, general: GeneralChatPageState, remote: RemotePageState): void { - if (AppRootRouteState.isGeneralComposerRoute(route)) { - general.setChatInput(value); - return; - } - remote.setChatInput(value); - } - - static setSelectedImages(route: AppRoute, images: SelectedImageAttachment[], general: GeneralChatPageState, - remote: RemotePageState): void { - if (AppRootRouteState.isGeneralComposerRoute(route)) { - general.setSelectedImages(images); - return; - } - remote.setSelectedImages(images); - } - - static addSelectedImages(route: AppRoute, images: SelectedImageAttachment[], general: GeneralChatPageState, - remote: RemotePageState): void { - if (AppRootRouteState.isGeneralComposerRoute(route)) { - general.addSelectedImages(images); - return; - } - remote.addSelectedImages(images); - } - - static removeSelectedImage(route: AppRoute, imageId: string, general: GeneralChatPageState, - remote: RemotePageState): void { - if (AppRootRouteState.isGeneralComposerRoute(route)) { - general.removeSelectedImage(imageId); - return; - } - remote.removeSelectedImage(imageId); - } - - static clearComposer(route: AppRoute, general: GeneralChatPageState, remote: RemotePageState): void { - if (AppRootRouteState.isGeneralComposerRoute(route)) { - general.clearComposer(); - return; - } - remote.clearComposer(); - } - - static setVoiceListening(route: AppRoute, isListening: boolean, general: GeneralChatPageState, - remote: RemotePageState): void { - if (AppRootRouteState.isGeneralComposerRoute(route)) { - general.setVoiceListening(isListening); - return; - } - remote.setVoiceListening(isListening); - } - - static snapshot(route: AppRoute, isBusy: boolean, general: GeneralChatPageState, - remote: RemotePageState): VoiceInputRouteSnapshot { - return { - routeId: `${route}`, - isListening: AppRootRouteState.voiceListening(route, general, remote), - isBusy, - inputText: AppRootRouteState.chatInput(route, general, remote), - selectedImageCount: AppRootRouteState.selectedImages(route, general, remote).length - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRouteContract.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRouteContract.ets deleted file mode 100644 index ab625f238a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/navigation/AppRouteContract.ets +++ /dev/null @@ -1,114 +0,0 @@ -export enum AppRoute { - ChatHome = 'ChatHome', - GeneralChat = 'GeneralChat', - RemoteHome = 'RemoteHome', - RemoteChat = 'RemoteChat' -} - -export class ChatRouteParam { - sessionId: string; - - constructor(sessionId: string) { - this.sessionId = sessionId; - } -} - -export enum AppNavigationBackAction { - CloseSidebar = 'close_sidebar', - CloseActiveChat = 'close_active_chat', - PopRemoteHome = 'pop_remote_home', - AllowSystem = 'allow_system' -} - -export class AppNavigationPathSpec { - name: AppRoute; - private readonly sessionId: string; - - constructor(name: AppRoute, sessionId: string = '') { - this.name = name; - this.sessionId = sessionId; - } - - hasSessionParam(): boolean { - return this.sessionId.length > 0; - } - - routeParam(): ChatRouteParam { - return new ChatRouteParam(this.sessionId); - } -} - -export class AppRouteContract { - // Read legacy navigation names without reopening the retired local runtime. - static controllerRoute(route: AppRoute): AppRoute { - return route === AppRoute.RemoteChat ? AppRoute.RemoteChat : AppRoute.RemoteHome; - } - - static currentRoute(pathNames: string[]): AppRoute { - if (pathNames.length === 0) { - return AppRoute.RemoteHome; - } - return AppRouteContract.controllerRoute(pathNames[pathNames.length - 1] as AppRoute); - } - - static isGeneralComposerRoute(route: AppRoute): boolean { - return false; - } - - static isSessionRoute(route: AppRoute): boolean { - return route === AppRoute.RemoteChat; - } - - /** - * Whether a route belongs to the remote surfaces. - * - * Stated as the complement of the general composer routes so the two - * predicates cannot drift apart: a route is one or the other, never both. - */ - static isRemoteRoute(route: AppRoute): boolean { - return !AppRouteContract.isGeneralComposerRoute(route); - } - - /** - * Where "connect a desktop" lands. - * - * Resuming beats landing: if there is a remote session already in flight, go - * back to it rather than dropping the user on a picker they did not ask for. - */ - static remoteSurfaceDestination( - remoteAvailable: boolean, - activeRemoteSessionId: string - ): AppNavigationPathSpec { - if (remoteAvailable && activeRemoteSessionId.length > 0) { - return new AppNavigationPathSpec(AppRoute.RemoteChat, activeRemoteSessionId); - } - return new AppNavigationPathSpec(AppRoute.RemoteHome); - } - - static routeParam(sessionId: string): ChatRouteParam { - return new ChatRouteParam(sessionId); - } - - static remoteSessionDestination(sessionId: string): AppNavigationPathSpec { - return new AppNavigationPathSpec(AppRoute.RemoteChat, sessionId); - } - - static pathSpec(currentRoute: AppRoute, route: AppRoute, sessionId: string = ''): AppNavigationPathSpec | undefined { - route = AppRouteContract.controllerRoute(route); - currentRoute = AppRouteContract.controllerRoute(currentRoute); - if (currentRoute === route) { - return undefined; - } - return new AppNavigationPathSpec(route, sessionId); - } - - static backAction(route: AppRoute, isSidebarOpen: boolean): AppNavigationBackAction { - if (isSidebarOpen) { - return AppNavigationBackAction.CloseSidebar; - } - if (route === AppRoute.RemoteChat) { - return AppNavigationBackAction.CloseActiveChat; - } - return AppNavigationBackAction.AllowSystem; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountDeviceSelectionPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountDeviceSelectionPolicy.ets deleted file mode 100644 index 2a85a48f80..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountDeviceSelectionPolicy.ets +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Shared selection rules for the account-device list on Connect and Settings. - * Online desktops can be selected. The last control target can still be tapped - * to reconnect after the live link drops, even if presence already reads offline. - */ -export class AccountDeviceSelectionPolicy { - static canSelectOnline( - online: boolean, - deviceId: string, - phoneDeviceId: string, - switchingDeviceId: string - ): boolean { - return online && deviceId !== phoneDeviceId && switchingDeviceId.length === 0; - } - - static shouldReconnectLastTarget( - deviceId: string, - controlTargetDeviceId: string, - connectionState: string - ): boolean { - return deviceId.length > 0 && - deviceId === controlTargetDeviceId && - connectionState !== 'connected'; - } - - static canActivate( - online: boolean, - deviceId: string, - phoneDeviceId: string, - controlTargetDeviceId: string, - connectionState: string, - switchingDeviceId: string - ): boolean { - if (switchingDeviceId.length > 0) { - return false; - } - return AccountDeviceSelectionPolicy.canSelectOnline(online, deviceId, phoneDeviceId, switchingDeviceId) || - AccountDeviceSelectionPolicy.shouldReconnectLastTarget(deviceId, controlTargetDeviceId, connectionState); - } - - static shouldShowConnectAction( - online: boolean, - deviceId: string, - phoneDeviceId: string, - controlTargetDeviceId: string, - connectionState: string - ): boolean { - return AccountDeviceSelectionPolicy.canActivate( - online, deviceId, phoneDeviceId, controlTargetDeviceId, connectionState, '' - ) && !(deviceId === controlTargetDeviceId && connectionState === 'connected'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountLoginErrorPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountLoginErrorPolicy.ets deleted file mode 100644 index f539df32a7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AccountLoginErrorPolicy.ets +++ /dev/null @@ -1,13 +0,0 @@ -interface AccountLoginFailure { code?: number; statusCode?: number; } - -/** Present structured failures without exposing SDK messages or response bodies. */ -export class AccountLoginErrorPolicy { - static messageKey(error: Object): string { - const failure = error as AccountLoginFailure; - if (failure.code === 2300028) return 'account.errorTimeout'; - if (failure.code === 2300060 || failure.code === 2300035) return 'account.errorSecureConnection'; - if (failure.code !== undefined) return 'account.errorNetwork'; - if (failure.statusCode === 429) return 'account.errorRateLimited'; - return 'remote.settings.accountLoginFailed'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ActivityGroupPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ActivityGroupPolicy.ets deleted file mode 100644 index 848715e7f1..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ActivityGroupPolicy.ets +++ /dev/null @@ -1,130 +0,0 @@ -import { ConversationUiToolStatus } from '../state/ConversationUiModels'; -import { ThinkingPresentationPolicy } from './ThinkingPresentationPolicy'; -import { ToolCollapseGroup, ToolCollapsePolicy } from './ToolCollapsePolicy'; - -/** - * One thinking block inside an activity group, pinned to the position it - * occupied in the transcript. `beforeToolIndex` is the number of tools in the - * group that had already run when the model wrote it, so it is also the index - * of the tool row this block belongs above. - */ -export interface ActivityThinkingPart { - beforeToolIndex: number; - text: string; - status: string; - streaming: boolean; - streamKey: string; -} - -/** - * One row of a folded activity group. `kind` is `'thinking'` or `'group'`, and - * `index` points into the thinking parts or the tool groups accordingly. - */ -export class ActivityRowPlan { - readonly kind: string; - readonly index: number; - - constructor(kind: string, index: number) { - this.kind = kind; - this.index = index; - } -} - -export class ActivityGroupPolicy { - static shouldFoldEntry( - isThinking: boolean, - isSubagent: boolean, - tool?: ConversationUiToolStatus - ): boolean { - if (isThinking) { - return true; - } - if (isSubagent || !tool) { - return false; - } - return ToolCollapsePolicy.shouldFoldIntoSummary(tool); - } - - /** - * Collapse thinking parts that sit at the same point in the run into one - * block, so an uninterrupted stretch of reasoning keeps a single header - * while reasoning on either side of a tool call stays where it happened. - */ - static mergeThinkingParts(parts: ActivityThinkingPart[]): ActivityThinkingPart[] { - const merged: ActivityThinkingPart[] = []; - let index = 0; - while (index < parts.length) { - const head = parts[index]; - const texts: string[] = []; - const statuses: string[] = []; - const streamings: boolean[] = []; - let cursor = index; - while (cursor < parts.length && parts[cursor].beforeToolIndex === head.beforeToolIndex) { - texts.push(parts[cursor].text); - statuses.push(parts[cursor].status); - streamings.push(parts[cursor].streaming); - cursor += 1; - } - merged.push({ - beforeToolIndex: head.beforeToolIndex, - text: ThinkingPresentationPolicy.mergedText(texts), - status: ThinkingPresentationPolicy.mergedStatusValue(statuses, streamings), - streaming: ThinkingPresentationPolicy.mergedStreaming(streamings), - streamKey: head.streamKey - }); - index = cursor; - } - return merged; - } - - /** - * A summary row stands for the whole fold, so the reasoning behind it belongs - * inside the expansion rather than above the header. - */ - static hasSummaryRow(groups: ToolCollapseGroup[]): boolean { - return groups.some((group: ToolCollapseGroup) => group.type === 'summary'); - } - - /** - * Lay thinking blocks out among tool rows in transcript order: each block sits - * above the tool that ran after it was written, and blocks written after the - * last tool trail the group. Thinking is never placed above a summary row, - * which is the fold's own header. - */ - static weaveRows( - groups: ToolCollapseGroup[], - parts: ActivityThinkingPart[], - showThinking: boolean - ): ActivityRowPlan[] { - const rows: ActivityRowPlan[] = []; - if (!showThinking) { - for (let index = 0; index < groups.length; index++) { - rows.push(new ActivityRowPlan('group', index)); - } - return rows; - } - let next = 0; - for (let index = 0; index < groups.length; index++) { - const group = groups[index]; - if (group.type === 'tool') { - while (next < parts.length && parts[next].beforeToolIndex <= group.startIndex) { - rows.push(new ActivityRowPlan('thinking', next)); - next += 1; - } - } - rows.push(new ActivityRowPlan('group', index)); - } - while (next < parts.length) { - rows.push(new ActivityRowPlan('thinking', next)); - next += 1; - } - return rows; - } - - static thinkingHeaderCount(thinkingPartCount: number): number { - if (thinkingPartCount <= 0) { - return 0; - } - return 1; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AdaptiveLayoutInput.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AdaptiveLayoutInput.ets deleted file mode 100644 index e4783f0878..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AdaptiveLayoutInput.ets +++ /dev/null @@ -1,49 +0,0 @@ -import { - ConversationLayoutCrease, - ConversationLayoutHorizontalCrease -} from './ConversationLayoutPolicy'; - -/** - * Device geometry for placement policies. Presentation constructs this once - * and never injects it into components. - */ -export class AdaptiveLayoutInput { - readonly viewportWidth: number; - readonly viewportHeight: number; - readonly foldStatus: number; - readonly isFolded: boolean; - readonly isExpandedFoldable: boolean; - readonly isHoverOperate: boolean; - readonly wideLayoutMatched: boolean; - readonly verticalCreases: ConversationLayoutCrease[]; - readonly horizontalCreases: ConversationLayoutHorizontalCrease[]; - readonly isRtl: boolean; - - constructor( - viewportWidth: number, - viewportHeight: number, - foldStatus: number, - isFolded: boolean, - isExpandedFoldable: boolean, - isHoverOperate: boolean, - wideLayoutMatched: boolean, - verticalCreases: ConversationLayoutCrease[], - horizontalCreases: ConversationLayoutHorizontalCrease[], - isRtl: boolean = false - ) { - this.viewportWidth = viewportWidth; - this.viewportHeight = viewportHeight; - this.foldStatus = foldStatus; - this.isFolded = isFolded; - this.isExpandedFoldable = isExpandedFoldable; - this.isHoverOperate = isHoverOperate; - this.wideLayoutMatched = wideLayoutMatched; - this.verticalCreases = verticalCreases; - this.horizontalCreases = horizontalCreases; - this.isRtl = isRtl; - } - - static empty(): AdaptiveLayoutInput { - return new AdaptiveLayoutInput(0, 0, 0, false, false, false, false, [], [], false); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantMessageCopyMenuPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantMessageCopyMenuPolicy.ets deleted file mode 100644 index 43aeec8247..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantMessageCopyMenuPolicy.ets +++ /dev/null @@ -1,60 +0,0 @@ -import { MessageCopyScope } from '../actions/ConversationIntent'; - -/** - * What one assistant copy entry writes. - * - * Separate from the clipboard scope because the action names the entry and the - * scope names the payload the clipboard owner receives: today the three entries - * map one to one, and this list is the only place that pairs them. - */ -export enum AssistantMessageCopyAction { - RichText = 'copy_rich_text', - Markdown = 'copy_markdown', - PlainText = 'copy_plain_text' -} - -export class AssistantMessageCopyMenuItem { - readonly action: AssistantMessageCopyAction; - /** The clipboard scope this entry copies with. */ - readonly scope: MessageCopyScope; - /** Dotted i18n key, resolved by the action row at render time. */ - readonly labelKey: string; - - constructor(action: AssistantMessageCopyAction, scope: MessageCopyScope, labelKey: string) { - this.action = action; - this.scope = scope; - this.labelKey = labelKey; - } -} - -/** - * The lightweight menu an assistant message's copy affordance opens. - * - * Items are resolved as data rather than drawn inline, so the menu's contents - * stay assertable without a device and a further export scope can arrive as one - * more entry. Every entry copies the same message body through a different - * clipboard scope: the row that renders it derives the plain rendering for - * `Plain` and passes the Markdown source unchanged for the other two. Labels - * stay as keys so this policy owns no copy and no locale. - */ -export class AssistantMessageCopyMenuPolicy { - static items(): AssistantMessageCopyMenuItem[] { - return [ - new AssistantMessageCopyMenuItem( - AssistantMessageCopyAction.RichText, - MessageCopyScope.Rich, - 'chat.copyRich' - ), - new AssistantMessageCopyMenuItem( - AssistantMessageCopyAction.Markdown, - MessageCopyScope.Markdown, - 'chat.copyMarkdown' - ), - new AssistantMessageCopyMenuItem( - AssistantMessageCopyAction.PlainText, - MessageCopyScope.Plain, - 'chat.copyPlain' - ) - ]; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantProcessLayoutPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantProcessLayoutPolicy.ets deleted file mode 100644 index 703986caab..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/AssistantProcessLayoutPolicy.ets +++ /dev/null @@ -1,53 +0,0 @@ -export class AssistantProcessLayoutPolicy { - /** - * Streaming used to pin the current thinking block after tools so the - * viewport could chase it. That inverts chronology: a Task card appears - * above the thought that produced it. Keep thinking in document order. - */ - static pinsThinkingAfterTools(): boolean { - return false; - } - - static omitsInFlowThinkingWhileStreaming(): boolean { - return false; - } - - static shouldRenderActivityThinking(hasContent: boolean): boolean { - return hasContent; - } - - static processBlockOrder( - thinkingText: string, - hasStructuredThinking: boolean, - visibleText: string, - showTyping: boolean, - toolCount: number - ): string[] { - const order: string[] = []; - const hasLeadingThinking = thinkingText.trim().length > 0 && !hasStructuredThinking; - if (hasLeadingThinking || hasStructuredThinking) { - order.push('thinking'); - } - if (toolCount > 0) { - order.push('tools'); - } - if (showTyping) { - order.push('typing'); - } - if (visibleText.trim().length > 0 && visibleText.trim() !== thinkingText.trim()) { - order.push('text'); - } - return order; - } - - static activityGroupBlockOrder(hasThinking: boolean, toolCount: number): string[] { - const order: string[] = []; - if (hasThinking) { - order.push('thinking'); - } - if (toolCount > 0) { - order.push('tools'); - } - return order; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets deleted file mode 100644 index 4bae245e58..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets +++ /dev/null @@ -1,803 +0,0 @@ -import { ConversationUiMessageItem, ConversationUiToolStatus } from '../state/ConversationUiModels'; -import { ActivityGroupPolicy, ActivityThinkingPart } from './ActivityGroupPolicy'; -import { ThinkingPresentationPolicy } from './ThinkingPresentationPolicy'; -import { ToolStatusPresentationPolicy } from './ToolStatusPresentationPolicy'; - -export interface StructuredRenderGroup { - type: string; - items: ConversationUiMessageItem[]; - itemStatuses: string[]; - itemStreaming: boolean[]; - itemChildActiveScopes: boolean[]; - tools: ConversationUiToolStatus[]; - key: string; - path: string; -} - -/** Pure projection of structured model output into renderable message groups. */ -export class ChatMessageStructurePolicy { - /** - * A single top-level text item is the transport's structured form of an - * ordinary assistant reply. Rendering it through the nested group pipeline - * adds no information and makes a recycled empty row change its entire - * subtree when the first token arrives. Keep that common case on the stable - * Markdown leaf; reserve structured rendering for genuinely composite work. - */ - static requiresStructuredRendering(items: ConversationUiMessageItem[]): boolean { - const renderable = items.filter((entry: ConversationUiMessageItem) => - ChatMessageStructurePolicy.isRenderableStructuredEntry(entry)); - if (renderable.length !== 1) { - return renderable.length > 0; - } - const entry = renderable[0]; - const hasSubItems = !!entry.subItems && entry.subItems.length > 0; - return !ChatMessageStructurePolicy.isTextEntry(entry) || hasSubItems || !!entry.tool; - } - - /** - * A composite turn commonly ends with one growing top-level text item after - * its reasoning and tools. Keep that volatile item out of the keyed - * structured ForEach so its Markdown leaf can be retained while text grows. - * Only peel it when it is the final renderable entry, preserving transcript - * order for turns that continue with another tool or nested activity. - */ - static trailingTopLevelText(items: ConversationUiMessageItem[]): string { - const index = ChatMessageStructurePolicy.trailingTopLevelTextIndex(items); - return index >= 0 ? (items[index].content || '') : ''; - } - - static withoutTrailingTopLevelText(items: ConversationUiMessageItem[]): ConversationUiMessageItem[] { - const index = ChatMessageStructurePolicy.trailingTopLevelTextIndex(items); - if (index < 0) return items; - return items.slice(0, index).concat(items.slice(index + 1)); - } - - static structuredGroups( - items: ConversationUiMessageItem[], - prefix: string, - activeScope: boolean, - messageStatus: string - ): StructuredRenderGroup[] { - const scopedItems = ChatMessageStructurePolicy.scopeSubagentItems(items); - const groups: StructuredRenderGroup[] = []; - let toolBuffer: ConversationUiToolStatus[] = []; - let activityItems: ConversationUiMessageItem[] = []; - let activityStatuses: string[] = []; - let activityStreaming: boolean[] = []; - let activityChildScopes: boolean[] = []; - let activityHasThinking = false; - const activeItemIndex = activeScope ? ChatMessageStructurePolicy.lastRenderableItemIndex(scopedItems) : -1; - - // A key is view identity in ArkUI: changing it discards the node together - // with its expansion state. Counting each kind separately keeps a key while - // siblings of other kinds arrive, so appended output cannot renumber the - // transcript that is already on screen. - const ordinals: Map = new Map(); - const nextPath = (kind: string): string => { - const ordinal = ordinals.get(kind) || 0; - ordinals.set(kind, ordinal + 1); - return `${prefix}-${kind}-${ordinal}`; - }; - - const flushTools = (): void => { - if (toolBuffer.length === 0) return; - const groupPath = nextPath('tools'); - groups.push({ - type: 'tool_group', items: [], itemStatuses: [], itemStreaming: [], itemChildActiveScopes: [], - tools: toolBuffer, - key: `${groupPath}-${ChatMessageStructurePolicy.stableToolHash(toolBuffer)}`, - path: groupPath - }); - toolBuffer = []; - }; - - const flushActivity = (): void => { - if (activityItems.length === 0) return; - if (!activityHasThinking) { - activityItems.forEach((entry: ConversationUiMessageItem) => { - if (entry.tool) toolBuffer.push(entry.tool); - }); - } else if (activityItems.length === 1) { - const entry = activityItems[0]; - flushTools(); - const itemPath = nextPath('thinking'); - groups.push({ - type: 'item', items: [entry], itemStatuses: [activityStatuses[0] || ''], - itemStreaming: [activityStreaming[0] || false], - itemChildActiveScopes: [activityChildScopes[0] || false], tools: [], - key: ChatMessageStructurePolicy.structuredItemKey(entry, itemPath), - path: itemPath - }); - } else { - flushTools(); - const groupPath = nextPath('activity'); - groups.push({ - type: 'activity_group', items: activityItems, itemStatuses: activityStatuses, - itemStreaming: activityStreaming, itemChildActiveScopes: activityChildScopes, tools: [], - key: ChatMessageStructurePolicy.activityGroupKey(activityItems, groupPath), - path: groupPath - }); - } - activityItems = []; - activityStatuses = []; - activityStreaming = []; - activityChildScopes = []; - activityHasThinking = false; - }; - - scopedItems.forEach((entry: ConversationUiMessageItem, index: number) => { - // Remote snapshots also mark tools executed inside a subagent. Those - // are Task details, not sibling subagent cards in the parent timeline. - if (ChatMessageStructurePolicy.isSubagentInternalTool(entry)) return; - // Task tool entries are subagent branches, not ordinary tool rows, and a - // subagent branch is never parent activity. Both checks run before the - // activity fold so a child's reasoning is never summarised as the - // parent's own, and so the branch keeps its title, children, and - // lifecycle presentation. - if (ChatMessageStructurePolicy.isSubagentEntry(entry)) { - flushActivity(); - flushTools(); - const subagentPath = nextPath('subagent'); - groups.push({ - type: 'item', items: [entry], - itemStatuses: [ChatMessageStructurePolicy.itemStatus(entry, index, activeItemIndex, - activeScope, messageStatus)], - itemStreaming: [ChatMessageStructurePolicy.itemShouldStream(entry, index, activeItemIndex, activeScope)], - itemChildActiveScopes: [ChatMessageStructurePolicy.itemChildActiveScope(entry, index, - activeItemIndex, activeScope)], - tools: [], key: ChatMessageStructurePolicy.structuredItemKey(entry, subagentPath), - path: subagentPath - }); - return; - } - if (ChatMessageStructurePolicy.shouldFoldIntoActivityGroup(entry)) { - activityItems.push(entry); - activityStatuses.push(ChatMessageStructurePolicy.itemStatus(entry, index, activeItemIndex, - activeScope, messageStatus)); - activityStreaming.push(ChatMessageStructurePolicy.itemShouldStream(entry, index, activeItemIndex, activeScope)); - activityChildScopes.push(ChatMessageStructurePolicy.itemChildActiveScope(entry, index, - activeItemIndex, activeScope)); - activityHasThinking = activityHasThinking || ChatMessageStructurePolicy.isThinkingEntry(entry); - return; - } - - flushActivity(); - if (entry.tool) { - toolBuffer.push(entry.tool); - return; - } - flushTools(); - const itemPath = nextPath('item'); - groups.push({ - type: 'item', items: [entry], - itemStatuses: [ChatMessageStructurePolicy.itemStatus(entry, index, activeItemIndex, - activeScope, messageStatus)], - itemStreaming: [ChatMessageStructurePolicy.itemShouldStream(entry, index, activeItemIndex, activeScope)], - itemChildActiveScopes: [ChatMessageStructurePolicy.itemChildActiveScope(entry, index, - activeItemIndex, activeScope)], - tools: [], key: ChatMessageStructurePolicy.structuredItemKey(entry, itemPath), - path: itemPath - }); - }); - flushActivity(); - flushTools(); - return groups; - } - - /** - * Rebuilds the branch hierarchy carried by the remote wire format. - * - * Live snapshots are intentionally flat and mark child-agent records with - * `is_subagent`. The parent UI must attach those records to the tool entry - * that launched the child before grouping ordinary transcript activity. - * Older desktop builds did not emit the marker, so while a legacy `Task` is - * running we use the same conservative fallback as mobile web and scope its - * following process items. - * - * A branch owner can arrive with its children nested in its own items — - * which is how this client hands a child stream's records to the card — and - * the same child can be restated flat behind it, so folding the restatement - * would draw every child twice. A counted restatement is skipped, and a child - * that legitimately repeats survives. - * - * A marked record with no owning owner entry in this list — a partial - * snapshot, or a child that arrived before its launch — keeps its own - * collapsed branch rather than being dropped, because the process it carries - * is exactly what the reader opened the branch to see. - */ - static scopeSubagentItems(items: ConversationUiMessageItem[]): ConversationUiMessageItem[] { - const result: ConversationUiMessageItem[] = []; - const hasSubagentMarkers = items.some((entry: ConversationUiMessageItem) => entry.is_subagent === true); - let currentTask: ConversationUiMessageItem | undefined = undefined; - let carried: number[] = []; - - items.forEach((entry: ConversationUiMessageItem) => { - if (ChatMessageStructurePolicy.isParentTaskEntry(entry)) { - const task = ChatMessageStructurePolicy.copyItem(entry); - result.push(task); - currentTask = task; - carried = (task.subItems || []).map((_child: ConversationUiMessageItem, index: number) => index); - return; - } - if (entry.is_subagent === true) { - if (currentTask) { - ChatMessageStructurePolicy.appendScopedChild(currentTask, carried, entry); - } else { - result.push(ChatMessageStructurePolicy.orphanSubagentBranch(entry)); - } - return; - } - if (!hasSubagentMarkers && currentTask && - ChatMessageStructurePolicy.isLegacyUnmarkedTaskOwner(currentTask) && - ChatMessageStructurePolicy.isRunningTaskEntry(currentTask) && - ChatMessageStructurePolicy.isLegacySubagentProcessEntry(entry)) { - ChatMessageStructurePolicy.appendScopedChild(currentTask, carried, entry); - return; - } - result.push(entry); - }); - return result; - } - - /** - * A marked record whose Task is not in this list still owns process the reader - * must be able to open, so it becomes its own collapsed branch. The outer copy - * keeps the marker and the tool identity that title and status come from; the - * inner copy drops the marker so the same record renders as branch content - * instead of nesting a second branch inside the first. - * - * A non-tool record's text is that content: leaving it on the outer copy would - * print it twice, once as the branch label and once as the step it labels, so - * the label falls back to the generic Task name and the body comes only from - * the child. A tool record keeps its text, because its label already resolves - * through the tool identity and its child draws a tool row rather than text. - */ - private static orphanSubagentBranch(entry: ConversationUiMessageItem): ConversationUiMessageItem { - const branch = ChatMessageStructurePolicy.copyItem(entry); - if (branch.subItems && branch.subItems.length > 0) { - return branch; - } - const child = ChatMessageStructurePolicy.copyItem(entry); - child.is_subagent = false; - child.subItems = []; - if (!entry.tool) { - branch.content = ''; - } - branch.subItems = [child]; - return branch; - } - - /** Only original nested occurrences are matched; new flat entries consume no quota. */ - private static appendScopedChild( - task: ConversationUiMessageItem, carried: number[], entry: ConversationUiMessageItem - ): void { - const children = (task.subItems || []).slice(); - const match = carried.findIndex((index: number) => - ChatMessageStructurePolicy.sameChildIdentity(children[index], entry)); - if (match < 0) { - children.push(entry); - } else { - const index = carried.splice(match, 1)[0]; - if (entry.tool) { - // Flat records may carry newer status/output for the same nested tool. - const updated = ChatMessageStructurePolicy.copyItem(entry); - if (entry.subItems === undefined) updated.subItems = children[index].subItems; - if (entry.content === undefined) updated.content = children[index].content; - updated.tool = ChatMessageStructurePolicy.mergeChildTool(children[index].tool, entry.tool); - children[index] = updated; - } - } - task.subItems = children; - } - - /** - * What makes two subagent children the same piece of work. - * - * Children arrive without an id, so the kind, its content, and the tool it - * names are all there is to tell one from the other. - */ - private static childFingerprint(entry: ConversationUiMessageItem): string { - return [ - (entry.type || '').toLowerCase(), - entry.content || '', - entry.tool ? ChatMessageStructurePolicy.toolIdentity(entry.tool) : '' - ].join('\u0000'); - } - - private static mergeChildTool( - previous: ConversationUiToolStatus | undefined, incoming: ConversationUiToolStatus - ): ConversationUiToolStatus { - return { - id: incoming.id ?? previous?.id, - name: incoming.name ?? previous?.name, - status: incoming.status ?? previous?.status, - duration_ms: incoming.duration_ms ?? previous?.duration_ms, - start_ms: incoming.start_ms ?? previous?.start_ms, - input_preview: incoming.input_preview ?? previous?.input_preview, - tool_input: incoming.tool_input ?? previous?.tool_input, - stdout: incoming.stdout ?? previous?.stdout, - stderr: incoming.stderr ?? previous?.stderr, - tool_output: incoming.tool_output ?? previous?.tool_output, - result_preview: incoming.result_preview ?? previous?.result_preview, - error_preview: incoming.error_preview ?? previous?.error_preview, - exit_code: incoming.exit_code ?? previous?.exit_code, - plan: incoming.plan ?? previous?.plan, - permission_request_id: incoming.permission_request_id ?? previous?.permission_request_id, - }; - } - - private static sameChildIdentity(a: ConversationUiMessageItem, b: ConversationUiMessageItem): boolean { - const aId = a.tool?.id || ''; - const bId = b.tool?.id || ''; - if (aId || bId) return aId.length > 0 && aId === bId; - return ChatMessageStructurePolicy.childFingerprint(a) === ChatMessageStructurePolicy.childFingerprint(b); - } - - /** - * The tool a child names, identified by its id when the agent gave one. - * - * Status is left out: a restatement often carries a newer status for the same - * piece of work, and treating that as identity would draw the child twice. - */ - private static toolIdentity(tool: ConversationUiToolStatus): string { - if (tool.id) return `id:${tool.id}`; - return ChatMessageStructurePolicy.toolFingerprint(tool, false); - } - - static structuredRenderKey( - items: ConversationUiMessageItem[], - prefix: string, - activeScope: boolean, - messageStatus: string - ): string { - const groupKeys = ChatMessageStructurePolicy.structuredGroups( - items, - prefix, - activeScope, - messageStatus - ).map((group: StructuredRenderGroup) => group.key); - return `${prefix}-structured-${ChatMessageStructurePolicy.stableTextHash(groupKeys.join('|'))}`; - } - - static activityGroupTools(group: StructuredRenderGroup): ConversationUiToolStatus[] { - const tools: ConversationUiToolStatus[] = []; - group.items.forEach((entry: ConversationUiMessageItem) => { - if (entry.tool) tools.push(entry.tool); - }); - return tools; - } - - static activityThinkingParts(group: StructuredRenderGroup, messageId: string): ActivityThinkingPart[] { - const raw: ActivityThinkingPart[] = []; - let toolsSeen = 0; - let thinkingSeen = 0; - group.items.forEach((entry: ConversationUiMessageItem, index: number) => { - if (ChatMessageStructurePolicy.isThinkingEntry(entry)) { - raw.push({ - beforeToolIndex: toolsSeen, text: entry.content || '', status: group.itemStatuses[index] || '', - streaming: group.itemStreaming[index] || false, - streamKey: `${messageId}-${group.path}-thinking-${thinkingSeen}` - }); - thinkingSeen += 1; - } else if (entry.tool) { - toolsSeen += 1; - } - }); - return ActivityGroupPolicy.mergeThinkingParts(raw); - } - - static activityThinkingCount(group: StructuredRenderGroup): number { - return group.items.filter((entry: ConversationUiMessageItem) => - ChatMessageStructurePolicy.isThinkingEntry(entry)).length; - } - - static activityThinkingText(group: StructuredRenderGroup): string { - const parts = group.items.filter((entry: ConversationUiMessageItem) => - ChatMessageStructurePolicy.isThinkingEntry(entry)).map((entry: ConversationUiMessageItem) => entry.content || ''); - return ThinkingPresentationPolicy.mergedText(parts); - } - - static activityThinkingStatus(group: StructuredRenderGroup): string { - const statuses: string[] = []; - const streamings: boolean[] = []; - group.items.forEach((entry: ConversationUiMessageItem, index: number) => { - if (ChatMessageStructurePolicy.isThinkingEntry(entry)) { - statuses.push(group.itemStatuses[index] || ''); - streamings.push(group.itemStreaming[index] || false); - } - }); - return ThinkingPresentationPolicy.mergedStatusValue(statuses, streamings); - } - - static activityThinkingStreaming(group: StructuredRenderGroup): boolean { - const streamings: boolean[] = []; - group.items.forEach((entry: ConversationUiMessageItem, index: number) => { - if (ChatMessageStructurePolicy.isThinkingEntry(entry)) streamings.push(group.itemStreaming[index] || false); - }); - return ThinkingPresentationPolicy.mergedStreaming(streamings); - } - - static toolsNotCoveredByItems( - tools: ConversationUiToolStatus[], - items: ConversationUiMessageItem[] - ): ConversationUiToolStatus[] { - const coveredTools = ChatMessageStructurePolicy.itemToolCoverageGroups(items); - const matched: boolean[] = coveredTools.map((_keys: string[]) => false); - return tools.filter((tool: ConversationUiToolStatus) => { - const matchIndex = ChatMessageStructurePolicy.matchCoveredToolIndex( - ChatMessageStructurePolicy.toolCoverageKeys(tool), coveredTools, matched); - if (matchIndex >= 0) { - matched[matchIndex] = true; - return false; - } - return true; - }); - } - - static isRenderableStructuredEntry(entry: ConversationUiMessageItem): boolean { - if (ChatMessageStructurePolicy.isSubagentInternalTool(entry)) return false; - if (ChatMessageStructurePolicy.isUserSteeringEntry(entry) || - ChatMessageStructurePolicy.isThinkingEntry(entry) || ChatMessageStructurePolicy.isTextEntry(entry) || - ChatMessageStructurePolicy.isSubagentEntry(entry) || !!entry.tool) return true; - return !!entry.subItems && entry.subItems.some((child: ConversationUiMessageItem) => - ChatMessageStructurePolicy.isRenderableStructuredEntry(child)); - } - - static isThinkingEntry(entry: ConversationUiMessageItem): boolean { - return (entry.type || '').toLowerCase() === 'thinking' && (entry.content || '').trim().length > 0; - } - - static isUserSteeringEntry(entry: ConversationUiMessageItem): boolean { - return (entry.type || '').toLowerCase() === 'user-steering' && - ((entry.content || '').trim().length > 0 || (entry.images || []).length > 0); - } - - static isTextEntry(entry: ConversationUiMessageItem): boolean { - const type = (entry.type || '').toLowerCase(); - if ((entry.content || '').trim().length === 0 || entry.tool || - ChatMessageStructurePolicy.isThinkingEntry(entry) || ChatMessageStructurePolicy.isSubagentEntry(entry)) { - return false; - } - return type === 'text' || type === 'message' || type.length === 0; - } - - static isSubagentEntry(entry: ConversationUiMessageItem): boolean { - const type = (entry.type || '').toLowerCase(); - return entry.is_subagent === true || type === 'subagent' || type === 'agent' || - (!!entry.tool && ToolStatusPresentationPolicy.normalizedName(entry.tool) === 'task'); - } - - /** - * Normalized names of the tool calls that launch a child agent. - * - * `Task` is the delegation tool older desktops used; the current delegation - * tool is `AgentSpawn`. Both own a branch, and mobile web accepts both names - * for the same reason. A plain tool row must never be mistaken for one of - * these, so the list stays explicit instead of matching a prefix or a - * contains-rule. - */ - private static isOwnerTool(tool: ConversationUiToolStatus): boolean { - const name = ToolStatusPresentationPolicy.normalizedName(tool); - return name === 'task' || name === 'agentspawn'; - } - - /** - * The tool entry that owns a subagent branch. - * - * An owner entry may carry the subagent marker as well: the host records the - * child Session id on the launching tool item, and the remote wire maps that - * field onto `is_subagent`. The marker therefore means "this item owns a - * subagent", not "this entry is subagent output", so it must not disqualify - * the owner — otherwise no launch ever opens a branch and every record of its - * child is lost or drawn as an orphan branch beside it. - */ - private static isParentTaskEntry(entry: ConversationUiMessageItem): boolean { - return !!entry.tool && ChatMessageStructurePolicy.isOwnerTool(entry.tool); - } - - /** - * Whether an unmarked owner may claim the process records that follow it. - * - * This is the compatibility path for older desktops, which ran a `Task` - * subagent inside the parent's own stream and published its process records - * flat and unmarked. Only `Task` ever used it. `AgentSpawn` was introduced - * with hidden child sessions, so the records that follow a launch are the - * parent's own work; folding them into the launch item would indent the - * parent's transcript under it. - */ - private static isLegacyUnmarkedTaskOwner(entry: ConversationUiMessageItem): boolean { - return !!entry.tool && ToolStatusPresentationPolicy.normalizedName(entry.tool) === 'task'; - } - - private static isRunningTaskEntry(entry: ConversationUiMessageItem): boolean { - if (!entry.tool) return false; - const status = (entry.tool.status || '').toLowerCase(); - return status === 'running' || status === 'active' || status === 'preparing' || - status === 'pending' || status === 'queued'; - } - - /** - * The branch entry a Task card is drawing, read from the transcript as it is - * now. - * - * The structured ForEach is keyed by the branch view key, which deliberately - * does not change while a subagent publishes steps, so its item builder keeps - * the entry it first captured — including the empty child list of a Task whose - * subagent had not started yet. Param expressions are re-evaluated on every - * render, so the card re-reads its branch through here instead of trusting that - * snapshot, and a step published later reaches a card that is already open. - * - * Branches are identified by the Task's tool call when the host sent one, and - * by the ordinal the render path numbered them with otherwise. - */ - static subagentBranchAt( - items: ConversationUiMessageItem[], - ordinal: number, - ownerToolId: string - ): ConversationUiMessageItem | undefined { - const branches = ChatMessageStructurePolicy.scopeSubagentItems(items) - .filter((entry: ConversationUiMessageItem) => ChatMessageStructurePolicy.isSubagentEntry(entry)); - if (ownerToolId.length > 0) { - const owned = branches.find((entry: ConversationUiMessageItem) => - !!entry.tool && entry.tool.id === ownerToolId); - if (owned) return owned; - } - return ordinal >= 0 && ordinal < branches.length ? branches[ordinal] : undefined; - } - - /** The ordinal a branch path was numbered with, e.g. `item-subagent-2` is 2. */ - static subagentOrdinal(path: string): number { - const marker = path.lastIndexOf('-subagent-'); - if (marker < 0) return 0; - const ordinal = Number(path.slice(marker + '-subagent-'.length)); - return Number.isFinite(ordinal) && ordinal >= 0 ? ordinal : 0; - } - - private static isLegacySubagentProcessEntry(entry: ConversationUiMessageItem): boolean { - return ChatMessageStructurePolicy.isThinkingEntry(entry) || - ChatMessageStructurePolicy.isTextEntry(entry) || !!entry.tool; - } - - private static copyItem(entry: ConversationUiMessageItem): ConversationUiMessageItem { - return { - type: entry.type, - steering_id: entry.steering_id, - round_index: entry.round_index, - content: entry.content, - tool: entry.tool, - is_subagent: entry.is_subagent, - subItems: entry.subItems ? entry.subItems.slice() : [], - images: entry.images ? entry.images.slice() : undefined - }; - } - - private static isSubagentInternalTool(entry: ConversationUiMessageItem): boolean { - // A marked record that already carries children is a branch of its own, not - // an internal tool of some other branch. - if (!!entry.subItems && entry.subItems.length > 0) return false; - // A launch item is a branch too, even before its child has published - // anything. Dropping it while its branch is empty would make the card the - // reader just opened disappear and reappear as the child's first step lands. - if (!!entry.tool && ChatMessageStructurePolicy.isOwnerTool(entry.tool)) return false; - return entry.is_subagent === true && !!entry.tool; - } - - static subagentTitle(entry: ConversationUiMessageItem): string { - const taskTool = !!entry.tool && ChatMessageStructurePolicy.isOwnerTool(entry.tool); - if (entry.tool && taskTool) { - const title = ChatMessageStructurePolicy.subagentTaskTitle(entry.tool); - if (title.length > 0) return title; - } - const content = ChatMessageStructurePolicy.plainSubagentLabel(entry.content || ''); - if (content.length > 0 && content.length <= 80) return content; - if (entry.tool && entry.tool.name && !taskTool) { - return ChatMessageStructurePolicy.plainSubagentLabel(entry.tool.name); - } - return ''; - } - - static subagentBody(entry: ConversationUiMessageItem): string { - if (entry.tool && ChatMessageStructurePolicy.isOwnerTool(entry.tool)) return ''; - const content = ChatMessageStructurePolicy.plainSubagentLabel(entry.content || ''); - if (content.length === 0 || content === ChatMessageStructurePolicy.subagentTitle(entry)) return ''; - return content; - } - - static isAttentionTool(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.hasError(tool) || - ChatMessageStructurePolicy.isPendingTool(tool) || - ChatMessageStructurePolicy.isRunningTool(tool) || ToolStatusPresentationPolicy.isQuestionLike(tool); - } - - static hasAttentionItems(items: ConversationUiMessageItem[]): boolean { - return items.some((entry: ConversationUiMessageItem) => { - if (entry.tool && ChatMessageStructurePolicy.isAttentionTool(entry.tool)) return true; - return !!entry.subItems && ChatMessageStructurePolicy.hasAttentionItems(entry.subItems); - }); - } - - static hasAttentionTools(tools: ConversationUiToolStatus[]): boolean { - return tools.some((tool: ConversationUiToolStatus) => ChatMessageStructurePolicy.isAttentionTool(tool)); - } - - private static lastRenderableItemIndex(items: ConversationUiMessageItem[]): number { - for (let index = items.length - 1; index >= 0; index--) { - if (ChatMessageStructurePolicy.isRenderableStructuredEntry(items[index])) return index; - } - return -1; - } - - private static trailingTopLevelTextIndex(items: ConversationUiMessageItem[]): number { - const index = ChatMessageStructurePolicy.lastRenderableItemIndex(items); - if (index < 0 || !ChatMessageStructurePolicy.isTextEntry(items[index])) return -1; - return index; - } - - private static itemStatus( - entry: ConversationUiMessageItem, - index: number, - activeItemIndex: number, - activeScope: boolean, - messageStatus: string - ): string { - if (ChatMessageStructurePolicy.isThinkingEntry(entry) && index === activeItemIndex && activeScope) { - return messageStatus || 'active'; - } - return ChatMessageStructurePolicy.isThinkingEntry(entry) ? 'done' : ''; - } - - private static itemShouldStream( - entry: ConversationUiMessageItem, - index: number, - activeItemIndex: number, - activeScope: boolean - ): boolean { - if (index !== activeItemIndex || !activeScope) return false; - return ChatMessageStructurePolicy.isThinkingEntry(entry) || ChatMessageStructurePolicy.isTextEntry(entry) || - (ChatMessageStructurePolicy.isSubagentEntry(entry) && (!entry.subItems || entry.subItems.length === 0)); - } - - private static itemChildActiveScope( - entry: ConversationUiMessageItem, - index: number, - activeItemIndex: number, - activeScope: boolean - ): boolean { - return index === activeItemIndex && activeScope && !!entry.subItems && entry.subItems.length > 0; - } - - private static shouldFoldIntoActivityGroup(entry: ConversationUiMessageItem): boolean { - return ActivityGroupPolicy.shouldFoldEntry( - ChatMessageStructurePolicy.isThinkingEntry(entry), - ChatMessageStructurePolicy.isSubagentEntry(entry), entry.tool); - } - - private static stableToolHash(tools: ConversationUiToolStatus[]): string { - return ChatMessageStructurePolicy.stableTextHash(tools.map((tool: ConversationUiToolStatus) => - `${tool.id || ''}:${tool.name || ''}:${tool.status || ''}`).join('|')); - } - - private static itemToolCoverageGroups(items: ConversationUiMessageItem[]): string[][] { - const groups: string[][] = []; - items.forEach((entry: ConversationUiMessageItem) => { - if (entry.tool) groups.push(ChatMessageStructurePolicy.toolCoverageKeys(entry.tool)); - if (entry.subItems) { - ChatMessageStructurePolicy.itemToolCoverageGroups(entry.subItems).forEach((keys: string[]) => groups.push(keys)); - } - }); - return groups; - } - - private static matchCoveredToolIndex(keys: string[], groups: string[][], matched: boolean[]): number { - for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) { - if (matched[groupIndex]) continue; - for (let keyIndex = 0; keyIndex < keys.length; keyIndex++) { - if (groups[groupIndex].indexOf(keys[keyIndex]) >= 0) return groupIndex; - } - } - return -1; - } - - private static toolCoverageKeys(tool: ConversationUiToolStatus): string[] { - const keys: string[] = []; - const toolId = tool.id || ''; - if (toolId.length > 0) keys.push(`id:${toolId}`); - keys.push(`full:${ChatMessageStructurePolicy.toolFingerprint(tool, true)}`); - if (toolId.length === 0 || ChatMessageStructurePolicy.hasToolFingerprintData(tool)) { - keys.push(`stable:${ChatMessageStructurePolicy.toolFingerprint(tool, false)}`); - } - return keys; - } - - private static toolFingerprint(tool: ConversationUiToolStatus, includeStatus: boolean): string { - return ChatMessageStructurePolicy.stableTextHash([ - ToolStatusPresentationPolicy.normalizedName(tool), includeStatus ? (tool.status || '') : '', - tool.input_preview || '', tool.result_preview || '', tool.error_preview || '', tool.stdout || '', - tool.stderr || '', `${tool.exit_code || 0}`, ChatMessageStructurePolicy.objectSignature(tool.tool_input), - ChatMessageStructurePolicy.objectSignature(tool.tool_output) - ].join('|')); - } - - private static hasToolFingerprintData(tool: ConversationUiToolStatus): boolean { - return (tool.input_preview || '').length > 0 || (tool.result_preview || '').length > 0 || - (tool.error_preview || '').length > 0 || (tool.stdout || '').length > 0 || - (tool.stderr || '').length > 0 || !!tool.tool_input || !!tool.tool_output; - } - - private static objectSignature(value?: Object): string { - if (!value) return ''; - try { - return JSON.stringify(value); - } catch (_err) { - return 'object'; - } - } - - private static subagentTaskTitle(tool: ConversationUiToolStatus): string { - return ChatMessageStructurePolicy.plainSubagentLabel(ToolStatusPresentationPolicy.taskTitle(tool)); - } - - private static plainSubagentLabel(raw: string): string { - let text = (raw || '').trim(); - const wrappers: string[] = ['**', '__', '`', '*', '_']; - for (let index = 0; index < wrappers.length; index++) { - const wrapper = wrappers[index]; - if (text.length > wrapper.length * 2 && text.startsWith(wrapper) && text.endsWith(wrapper)) { - text = text.slice(wrapper.length, text.length - wrapper.length).trim(); - break; - } - } - while (text.startsWith('#')) { - text = text.slice(1).trim(); - } - return text; - } - - static structuredItemKey(entry: ConversationUiMessageItem, path: string): string { - if (ChatMessageStructurePolicy.isThinkingEntry(entry)) return `${path}-thinking`; - if (ChatMessageStructurePolicy.isUserSteeringEntry(entry) && entry.steering_id) { - return `${path}-steering-${entry.steering_id}`; - } - if (entry.tool && entry.tool.id) return `${path}-tool-${entry.tool.id}`; - const content = entry.content || ''; - const childCount = entry.subItems ? entry.subItems.length : 0; - return `${path}-${entry.type || 'item'}-${entry.is_subagent === true ? 'subagent' : 'main'}-` + - `${content.length}-${ChatMessageStructurePolicy.stableTextHash(content)}-${childCount}`; - } - - private static activityGroupKey(items: ConversationUiMessageItem[], path: string): string { - const parts: string[] = []; - // Counting each kind separately keeps the key while siblings of other kinds - // arrive inside the group, the same way the group paths above do. - const ordinals: Map = new Map(); - items.forEach((entry: ConversationUiMessageItem) => { - const thinking = ChatMessageStructurePolicy.isThinkingEntry(entry); - const kind = thinking ? 'thinking' : entry.tool ? 'tool' : 'item'; - const ordinal = ordinals.get(kind) || 0; - ordinals.set(kind, ordinal + 1); - parts.push([ - `${kind}-${ordinal}`, entry.type || '', - thinking ? 'thinking' : `${(entry.content || '').length}:${ChatMessageStructurePolicy.stableTextHash(entry.content || '')}`, - entry.tool ? `${entry.tool.id || ''}:${entry.tool.name || ''}:${entry.tool.status || ''}` : '' - ].join(':')); - }); - return `${path}-${ChatMessageStructurePolicy.stableTextHash(parts.join('|'))}`; - } - - private static stableTextHash(text: string): string { - let hash = 0; - for (let index = 0; index < text.length; index++) hash = ((hash << 5) - hash + text.charCodeAt(index)) | 0; - return Math.abs(hash).toString(36); - } - - private static isRunningTool(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return status === 'running' || status === 'active'; - } - - private static isPendingTool(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return status === 'pending' || status === 'queued' || - status === 'pending_confirmation' || status === 'needs_confirmation'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConnectSheetLandingPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConnectSheetLandingPolicy.ets deleted file mode 100644 index cae4599b30..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConnectSheetLandingPolicy.ets +++ /dev/null @@ -1,59 +0,0 @@ -export class ConnectSheetStep { - static readonly Intro: string = 'intro'; - static readonly Account: string = 'account'; -} - -/** - * Which step the connect sheet shows. A signed-in phone picks from the - * account device directory; a signed-out phone is sent to account sign-in. - * The step follows authentication live, so signing in while the sheet is - * open moves it to the device list. - */ -export class ConnectSheetLandingPolicy { - static step(accountAuthenticated: boolean): string { - return accountAuthenticated ? ConnectSheetStep.Account : ConnectSheetStep.Intro; - } -} - -export class ConnectSheetStatusPolicy { - static isConnectError( - connectionState: string, - isBusy: boolean, - isConnected: boolean, - statusText: string, - failedLabel: string, - missingParams: string, - urlRequired: string - ): boolean { - if (connectionState === 'failed') { - return true; - } - if (isBusy || isConnected) { - return false; - } - const text = statusText.toLowerCase(); - return text.indexOf('http') >= 0 || - text.indexOf('error') >= 0 || - text.indexOf('failed') >= 0 || - text.indexOf(failedLabel.toLowerCase()) >= 0 || - statusText === missingParams || - statusText === urlRequired || - text.indexOf('rejected') >= 0; - } - - static failureHintKey(kind: string): string { - if (kind === 'expired_room') { - return 'connect.hintExpiredRoom'; - } - if (kind === 'network') { - return 'connect.hintNetwork'; - } - if (kind === 'protected_user') { - return 'connect.hintProtectedUser'; - } - if (kind === 'invalid_link') { - return 'connect.hintInvalidLink'; - } - return ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationHeaderPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationHeaderPolicy.ets deleted file mode 100644 index 99c9b327a4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationHeaderPolicy.ets +++ /dev/null @@ -1,65 +0,0 @@ -import { ChatSurface } from '../state/ChatSurface'; - -export class ConversationHeaderPresentation { - title: string = ''; - subtitle: string = ''; - fallbackKey: string = 'app.title'; - allowRename: boolean = false; - showActions: boolean = false; - - constructor( - title: string, - subtitle: string, - fallbackKey: string, - allowRename: boolean, - showActions: boolean - ) { - this.title = title; - this.subtitle = subtitle; - this.fallbackKey = fallbackKey; - this.allowRename = allowRename; - this.showActions = showActions; - } -} - -/** - * One header contract for local and remote chat. - * View supplies i18n for fallbackKey; this policy only decides structure. - */ -export class ConversationHeaderPolicy { - static readonly REMOTE_BRAND: string = 'OpenBitFun'; - - static present( - surface: ChatSurface, - sessionTitle: string, - desktopName: string, - workspaceBranch: string, - hasTimeline: boolean - ): ConversationHeaderPresentation { - if (surface === ChatSurface.Remote) { - return new ConversationHeaderPresentation( - sessionTitle, - ConversationHeaderPolicy.remoteSubtitle(desktopName, workspaceBranch), - 'chat.remoteSession', - true, - true - ); - } - return new ConversationHeaderPresentation( - sessionTitle, - '', - 'app.title', - false, - hasTimeline - ); - } - - static remoteSubtitle(desktopName: string, workspaceBranch: string): string { - if (desktopName.length > 0) { - return desktopName; - } - return workspaceBranch.length > 0 ? - `${ConversationHeaderPolicy.REMOTE_BRAND} · ${workspaceBranch}` : - ConversationHeaderPolicy.REMOTE_BRAND; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationLayoutPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationLayoutPolicy.ets deleted file mode 100644 index d3a686d225..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationLayoutPolicy.ets +++ /dev/null @@ -1,375 +0,0 @@ -import { MobileDesignBreakpoints } from '../../generated/MobileDesignTokens'; - -export class ConversationLayoutCrease { - readonly left: number; - readonly width: number; - - constructor(left: number, width: number) { - this.left = left; - this.width = width; - } -} - -export class ConversationLayoutHorizontalCrease { - readonly top: number; - readonly height: number; - - constructor(top: number, height: number) { - this.top = top; - this.height = height; - } -} - -export class ConversationLayoutRect { - readonly left: number; - readonly top: number; - readonly width: number; - readonly height: number; - - constructor(left: number, top: number, width: number, height: number) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - } -} - -export class ConversationLayoutCreases { - readonly vertical: ConversationLayoutCrease[]; - readonly horizontal: ConversationLayoutHorizontalCrease[]; - - constructor( - vertical: ConversationLayoutCrease[], - horizontal: ConversationLayoutHorizontalCrease[] - ) { - this.vertical = vertical; - this.horizontal = horizontal; - } -} - -export class ConversationLayoutGeometry { - readonly masterPaneWidth: number; - readonly masterDetailGap: number; - readonly isExtraWide: boolean; - readonly detailContentOffset: number; - readonly detailContentWidth: number; - readonly collapsedDetailContentOffset: number; - readonly collapsedDetailContentWidth: number; - - constructor( - masterPaneWidth: number, - masterDetailGap: number, - isExtraWide: boolean, - detailContentOffset: number, - detailContentWidth: number, - collapsedDetailContentOffset: number, - collapsedDetailContentWidth: number - ) { - this.masterPaneWidth = masterPaneWidth; - this.masterDetailGap = masterDetailGap; - this.isExtraWide = isExtraWide; - this.detailContentOffset = detailContentOffset; - this.detailContentWidth = detailContentWidth; - this.collapsedDetailContentOffset = collapsedDetailContentOffset; - this.collapsedDetailContentWidth = collapsedDetailContentWidth; - } -} - -export class ConversationLayoutPolicy { - /** Official GridRow sm|md boundary: 320 / 600 / 840 / 1440 vp. */ - static readonly MD_MIN_WIDTH: number = MobileDesignBreakpoints.wide; - static readonly LG_MIN_WIDTH: number = MobileDesignBreakpoints.extraWide; - static readonly XL_MIN_WIDTH: number = MobileDesignBreakpoints.xl; - static readonly WIDE_LAYOUT_MIN_WIDTH: number = 600; - static readonly EXTRA_WIDE_MIN_WIDTH: number = 840; - static readonly FALLBACK_MASTER_PANE_WIDTH: number = 344; - static readonly MIN_MASTER_PANE_WIDTH: number = 280; - static readonly MIN_DETAIL_PANE_WIDTH: number = 360; - static readonly SYNTHETIC_HINGE_WIDTH: number = 16; - static readonly FOLD_STATUS_UNKNOWN: number = 0; - static readonly FOLD_STATUS_EXPANDED: number = 1; - static readonly FOLD_STATUS_FOLDED: number = 2; - static readonly FOLD_STATUS_HALF_FOLDED: number = 3; - static readonly FOLD_STATUS_EXPANDED_WITH_SECOND_EXPANDED: number = 11; - static readonly FOLD_STATUS_FOLDED_WITH_SECOND_EXPANDED: number = 12; - static readonly FOLD_STATUS_HALF_FOLDED_WITH_SECOND_EXPANDED: number = 13; - static readonly FOLD_STATUS_EXPANDED_WITH_SECOND_HALF_FOLDED: number = 21; - static readonly FOLD_STATUS_FOLDED_WITH_SECOND_HALF_FOLDED: number = 22; - static readonly FOLD_STATUS_HALF_FOLDED_WITH_SECOND_HALF_FOLDED: number = 23; - - static isFoldedStatus(status: number): boolean { - return status === ConversationLayoutPolicy.FOLD_STATUS_FOLDED; - } - - static isExpandedFoldableStatus(status: number): boolean { - return status !== ConversationLayoutPolicy.FOLD_STATUS_UNKNOWN && - status !== ConversationLayoutPolicy.FOLD_STATUS_FOLDED; - } - - static isHoverStatus(status: number): boolean { - return status === ConversationLayoutPolicy.FOLD_STATUS_HALF_FOLDED || - status === ConversationLayoutPolicy.FOLD_STATUS_HALF_FOLDED_WITH_SECOND_HALF_FOLDED; - } - - static useHoverOperate( - status: number, - viewportWidth: number, - viewportHeight: number - ): boolean { - if (!ConversationLayoutPolicy.isHoverStatus(status)) { - return false; - } - if (viewportWidth >= ConversationLayoutPolicy.MD_MIN_WIDTH && - viewportWidth >= viewportHeight) { - return false; - } - return true; - } - - static isLandscapeRotation(rotation: number): boolean { - return rotation === 1 || rotation === 3 || rotation === 90 || rotation === 270; - } - - static resolveLayoutViewportWidth( - areaWidth: number, - areaHeight: number, - displayWidth: number, - displayHeight: number, - rotation: number = 0 - ): number { - const landscape = ConversationLayoutPolicy.isLandscapeRotation(rotation) || - (displayWidth > 0 && displayWidth >= displayHeight); - const layoutWidth = landscape ? Math.max(displayWidth, displayHeight) : displayWidth; - if (layoutWidth > 0 && areaWidth > 0 && areaWidth < layoutWidth * 0.8) { - return layoutWidth; - } - return areaWidth > 0 ? areaWidth : layoutWidth; - } - - static classifyCreaseRects( - viewportWidth: number, - viewportHeight: number, - rects: ConversationLayoutRect[] - ): ConversationLayoutCreases { - const vertical: ConversationLayoutCrease[] = []; - const horizontal: ConversationLayoutHorizontalCrease[] = []; - rects.forEach((rect: ConversationLayoutRect): void => { - if (rect.width < 0 || rect.height < 0) { - return; - } - const mappedVertical = ConversationLayoutPolicy.mapVerticalCrease( - viewportWidth, - viewportHeight, - rect - ); - if (mappedVertical) { - vertical.push(mappedVertical); - return; - } - const mappedHorizontal = ConversationLayoutPolicy.mapHorizontalCrease(viewportWidth, rect); - if (mappedHorizontal) { - horizontal.push(mappedHorizontal); - } - }); - return new ConversationLayoutCreases( - ConversationLayoutPolicy.visibleCreases(viewportWidth, vertical), - ConversationLayoutPolicy.visibleHorizontalCreases(viewportHeight, horizontal) - ); - } - - static verticalCreasesFromRects( - viewportWidth: number, - viewportHeight: number, - rects: ConversationLayoutRect[] - ): ConversationLayoutCrease[] { - return ConversationLayoutPolicy.classifyCreaseRects( - viewportWidth, - viewportHeight, - rects - ).vertical; - } - - static horizontalCreasesFromRects( - viewportWidth: number, - viewportHeight: number, - rects: ConversationLayoutRect[] - ): ConversationLayoutHorizontalCrease[] { - return ConversationLayoutPolicy.classifyCreaseRects( - viewportWidth, - viewportHeight, - rects - ).horizontal; - } - - private static mapVerticalCrease( - viewportWidth: number, - viewportHeight: number, - rect: ConversationLayoutRect - ): ConversationLayoutCrease | undefined { - if (rect.height > rect.width) { - return new ConversationLayoutCrease(rect.left, rect.width); - } - if (viewportWidth <= 0 || viewportHeight <= 0) { - return undefined; - } - const spansViewportHeight = rect.width >= viewportHeight * 0.8; - const rotatedRight = rect.top + rect.height; - if (spansViewportHeight && rect.top > 0 && rotatedRight < viewportWidth) { - return new ConversationLayoutCrease(rect.top, rect.height); - } - return undefined; - } - - private static mapHorizontalCrease( - viewportWidth: number, - rect: ConversationLayoutRect - ): ConversationLayoutHorizontalCrease | undefined { - if (rect.width <= rect.height) { - return undefined; - } - if (viewportWidth > 0 && rect.width < viewportWidth * 0.8) { - return undefined; - } - return new ConversationLayoutHorizontalCrease(rect.top, rect.height); - } - - static useMasterDetail( - viewportWidth: number, - mediaQueryMatched: boolean, - isFolded: boolean, - creases: ConversationLayoutCrease[], - isExpandedFoldable: boolean = false, - isHover: boolean = false - ): boolean { - if (isFolded || isHover) { - return false; - } - if (!ConversationLayoutPolicy.hasWideViewport(viewportWidth, mediaQueryMatched)) { - return false; - } - const visibleCreases = ConversationLayoutPolicy.effectiveVerticalCreases( - viewportWidth, - creases, - isExpandedFoldable - ); - if (visibleCreases.length > 0) { - return ConversationLayoutPolicy.canFitMasterDetail(viewportWidth, visibleCreases); - } - return ConversationLayoutPolicy.canFitMasterDetail(viewportWidth, []); - } - - static resolveWideGeometry( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): ConversationLayoutGeometry { - const visibleCreases = ConversationLayoutPolicy.visibleCreases(viewportWidth, creases); - const firstCrease = ConversationLayoutPolicy.firstUsableCrease(viewportWidth, visibleCreases); - const masterPaneWidth = firstCrease ? firstCrease.left : - ConversationLayoutPolicy.fallbackMasterPaneWidth(viewportWidth); - const masterDetailGap = firstCrease ? Math.max(0, firstCrease.width) : 0; - const detailStart = masterPaneWidth + masterDetailGap; - const detailWidth = Math.max(0, viewportWidth - detailStart); - return new ConversationLayoutGeometry( - masterPaneWidth, - masterDetailGap, - visibleCreases.length > 1 || viewportWidth >= ConversationLayoutPolicy.LG_MIN_WIDTH, - 0, - detailWidth, - 0, - Math.max(0, viewportWidth) - ); - } - - static effectiveVerticalCreases( - viewportWidth: number, - creases: ConversationLayoutCrease[], - synthesizeCenterHinge: boolean - ): ConversationLayoutCrease[] { - const visibleCreases = ConversationLayoutPolicy.visibleCreases(viewportWidth, creases); - if (visibleCreases.length > 0) { - return visibleCreases; - } - if (!synthesizeCenterHinge) { - return []; - } - const synthetic = ConversationLayoutPolicy.syntheticCenterCrease(viewportWidth); - return synthetic ? [synthetic] : []; - } - - static syntheticCenterCrease(viewportWidth: number): ConversationLayoutCrease | undefined { - const hinge = ConversationLayoutPolicy.SYNTHETIC_HINGE_WIDTH; - const minimum = ConversationLayoutPolicy.MIN_MASTER_PANE_WIDTH + - ConversationLayoutPolicy.MIN_DETAIL_PANE_WIDTH + hinge; - if (viewportWidth < minimum) { - return undefined; - } - const centered = Math.floor((viewportWidth - hinge) / 2); - const maximumMaster = viewportWidth - hinge - ConversationLayoutPolicy.MIN_DETAIL_PANE_WIDTH; - const masterPaneWidth = Math.max( - ConversationLayoutPolicy.MIN_MASTER_PANE_WIDTH, - Math.min(centered, maximumMaster) - ); - return new ConversationLayoutCrease(masterPaneWidth, hinge); - } - - private static canFitMasterDetail( - viewportWidth: number, - visibleCreases: ConversationLayoutCrease[] - ): boolean { - const firstCrease = ConversationLayoutPolicy.firstUsableCrease(viewportWidth, visibleCreases); - const masterPaneWidth = firstCrease ? firstCrease.left : - ConversationLayoutPolicy.fallbackMasterPaneWidth(viewportWidth); - const masterDetailGap = firstCrease ? Math.max(0, firstCrease.width) : 0; - return masterPaneWidth >= ConversationLayoutPolicy.MIN_MASTER_PANE_WIDTH && - viewportWidth - masterPaneWidth - masterDetailGap >= ConversationLayoutPolicy.MIN_DETAIL_PANE_WIDTH; - } - - private static fallbackMasterPaneWidth(viewportWidth: number): number { - const maximumMaster = viewportWidth - ConversationLayoutPolicy.MIN_DETAIL_PANE_WIDTH; - if (maximumMaster < ConversationLayoutPolicy.MIN_MASTER_PANE_WIDTH) { - return ConversationLayoutPolicy.FALLBACK_MASTER_PANE_WIDTH; - } - return Math.min(ConversationLayoutPolicy.FALLBACK_MASTER_PANE_WIDTH, maximumMaster); - } - - private static firstUsableCrease( - viewportWidth: number, - visibleCreases: ConversationLayoutCrease[] - ): ConversationLayoutCrease | undefined { - return visibleCreases.find((crease: ConversationLayoutCrease): boolean => { - return crease.left >= ConversationLayoutPolicy.MIN_MASTER_PANE_WIDTH && - crease.left + crease.width <= viewportWidth - ConversationLayoutPolicy.MIN_DETAIL_PANE_WIDTH; - }); - } - - private static hasWideViewport(viewportWidth: number, mediaQueryMatched: boolean): boolean { - return mediaQueryMatched || viewportWidth >= ConversationLayoutPolicy.MD_MIN_WIDTH; - } - - private static visibleCreases( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): ConversationLayoutCrease[] { - return creases - .filter((crease: ConversationLayoutCrease): boolean => { - return crease.left > 0 && crease.width >= 0 && crease.left + crease.width < viewportWidth; - }) - .sort((left: ConversationLayoutCrease, right: ConversationLayoutCrease): number => left.left - right.left); - } - - private static visibleHorizontalCreases( - viewportHeight: number, - creases: ConversationLayoutHorizontalCrease[] - ): ConversationLayoutHorizontalCrease[] { - return creases - .filter((crease: ConversationLayoutHorizontalCrease): boolean => { - return crease.top > 0 && - crease.height >= 0 && - crease.top + crease.height < viewportHeight; - }) - .sort(( - left: ConversationLayoutHorizontalCrease, - right: ConversationLayoutHorizontalCrease - ): number => left.top - right.top); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationMessageRenderPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationMessageRenderPolicy.ets deleted file mode 100644 index 57d79e5f21..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationMessageRenderPolicy.ets +++ /dev/null @@ -1,70 +0,0 @@ -import { ConversationUiImage, ConversationUiMessage, ConversationUiMessageItem } from '../state/ConversationUiModels'; - -export class ConversationMessageRenderPolicy { - /** - * Desktop attachments reach this device as pixels, never as a readable path, - * so an image the host could not inline has nothing to draw. - */ - static hasRenderableImagePixels(image: ConversationUiImage): boolean { - return (image.data_url || '').trim().length > 0; - } - - static visibleText(text?: string): string { - const value = (text || '').trim(); - if (value === '(空消息)' || value === '(empty message)') { - return ''; - } - return value; - } - - static shouldRender(item: ConversationUiMessage): boolean { - if ((item.role || '').toLowerCase() === 'user') { - return true; - } - if (ConversationMessageRenderPolicy.visibleText(item.text).length > 0) { - return true; - } - if ((item.thinking || '').trim().length > 0) { - return true; - } - if (item.tools && item.tools.length > 0) { - return true; - } - if (ConversationMessageRenderPolicy.hasRenderableItems(item.items || [])) { - return true; - } - if (item.images && item.images.length > 0) { - return true; - } - const status = (item.status || '').toLowerCase(); - return status === 'active' || status === 'failed'; - } - - /** - * Copy is available only for a settled assistant answer. Streamed text may - * already be non-empty while the turn is still changing. - */ - static canCopyAssistant( - item: ConversationUiMessage, - isStreaming: boolean, - isFinalizing: boolean, - sourceTextLength: number - ): boolean { - if ((item.role || '').toLowerCase() === 'user' || isStreaming || isFinalizing || sourceTextLength <= 0) { - return false; - } - const status = (item.status || '').toLowerCase(); - return status === '' || status === 'done' || status === 'completed' || - status === 'success' || status === 'sent'; - } - - static hasRenderableItems(items: ConversationUiMessageItem[]): boolean { - return items.some((entry: ConversationUiMessageItem) => { - if ((entry.content || '').trim().length > 0 || !!entry.tool) { - return true; - } - return !!entry.subItems && ConversationMessageRenderPolicy.hasRenderableItems(entry.subItems); - }); - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationModelPresentationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationModelPresentationPolicy.ets deleted file mode 100644 index 34d62ebf67..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationModelPresentationPolicy.ets +++ /dev/null @@ -1,279 +0,0 @@ -import { - ConversationUiModel, - ConversationUiModelCatalog -} from '../state/ConversationUiModels'; - -/** One role row of the composer selector's defaults section. */ -export interface ConversationUiModelRoleEntry { - /** Semantic model id sent to the host: `primary` or `fast`. */ - role: string; - labelKey: string; - /** Concrete model the role runs, or undefined when it has no target. */ - model: ConversationUiModel | undefined; - /** True when the role runs the primary model because it has none of its own. */ - fallsBackToPrimary: boolean; -} - -export class ConversationModelPresentationPolicy { - /** Semantic selectors the host accepts in place of a concrete model id. */ - static readonly ROLE_PRIMARY: string = 'primary'; - static readonly ROLE_FAST: string = 'fast'; - - static enabledModels(catalog: ConversationUiModelCatalog): ConversationUiModel[] { - return catalog.models.filter((model: ConversationUiModel) => model.enabled); - } - - /** - * Resolves a selector to an enabled concrete model. - * - * `primary` resolves the configured primary model; `fast` uses its own model - * and falls back to the primary model when none is configured, exactly like - * the host's own model selection. Empty, `auto`, `default` and unknown - * selectors resolve to nothing so callers keep their existing fallback chain. - */ - static resolveModel( - catalog: ConversationUiModelCatalog, - modelId: string - ): ConversationUiModel | undefined { - const value = (modelId || '').trim(); - if (value.length === 0) { - return undefined; - } - if (value === ConversationModelPresentationPolicy.ROLE_PRIMARY) { - return ConversationModelPresentationPolicy.enabledModel(catalog, catalog.default_models.primary || ''); - } - if (value === ConversationModelPresentationPolicy.ROLE_FAST) { - return ConversationModelPresentationPolicy.enabledModel(catalog, catalog.default_models.fast || '') || - ConversationModelPresentationPolicy.enabledModel(catalog, catalog.default_models.primary || ''); - } - return ConversationModelPresentationPolicy.enabledModel(catalog, value); - } - - static isSemanticModelId(modelId: string): boolean { - const value = (modelId || '').trim(); - return value === ConversationModelPresentationPolicy.ROLE_PRIMARY || - value === ConversationModelPresentationPolicy.ROLE_FAST; - } - - /** The selected role, or an empty string when the selection is not a role. */ - static selectedRole(selectedModelId: string): string { - const value = (selectedModelId || '').trim(); - return ConversationModelPresentationPolicy.isSemanticModelId(value) ? value : ''; - } - - /** - * The selected role only while it still resolves to an enabled concrete - * model. A role the catalog can no longer run is presented as no selection at - * all, so the trigger and the role rows agree. - */ - static resolvedSelectedRole(catalog: ConversationUiModelCatalog, selectedModelId: string): string { - const role = ConversationModelPresentationPolicy.selectedRole(selectedModelId); - if (role.length === 0) { - return ''; - } - return ConversationModelPresentationPolicy.resolveModel(catalog, role) ? role : ''; - } - - static roleLabelKey(role: string): string { - if (role === ConversationModelPresentationPolicy.ROLE_PRIMARY) { - return 'chat.modelPrimary'; - } - if (role === ConversationModelPresentationPolicy.ROLE_FAST) { - return 'chat.modelFast'; - } - return ''; - } - - static roleBadgeLabelKey(role: string): string { - if (role === ConversationModelPresentationPolicy.ROLE_PRIMARY) { - return 'chat.modelRolePrimary'; - } - if (role === ConversationModelPresentationPolicy.ROLE_FAST) { - return 'chat.modelRoleFast'; - } - return ''; - } - - /** Roles a concrete model id serves, in primary-then-fast order. */ - static modelRoles(catalog: ConversationUiModelCatalog, modelId: string): string[] { - const value = (modelId || '').trim(); - const roles: string[] = []; - if (value.length === 0) { - return roles; - } - if (value === (catalog.default_models.primary || '').trim()) { - roles.push(ConversationModelPresentationPolicy.ROLE_PRIMARY); - } - if (value === (catalog.default_models.fast || '').trim()) { - roles.push(ConversationModelPresentationPolicy.ROLE_FAST); - } - return roles; - } - - /** - * Defaults section rows. Empty when neither role resolves to an enabled - * model, so the selector stays a plain model list. - */ - static roleEntries(catalog: ConversationUiModelCatalog): ConversationUiModelRoleEntry[] { - const primary = ConversationModelPresentationPolicy.resolveModel( - catalog, ConversationModelPresentationPolicy.ROLE_PRIMARY); - const fast = ConversationModelPresentationPolicy.resolveModel( - catalog, ConversationModelPresentationPolicy.ROLE_FAST); - if (!primary && !fast) { - return []; - } - const ownFast = ConversationModelPresentationPolicy.enabledModel(catalog, catalog.default_models.fast || ''); - return [ - { - role: ConversationModelPresentationPolicy.ROLE_PRIMARY, - labelKey: ConversationModelPresentationPolicy.roleLabelKey(ConversationModelPresentationPolicy.ROLE_PRIMARY), - model: primary, - fallsBackToPrimary: false - }, - { - role: ConversationModelPresentationPolicy.ROLE_FAST, - labelKey: ConversationModelPresentationPolicy.roleLabelKey(ConversationModelPresentationPolicy.ROLE_FAST), - model: fast, - fallsBackToPrimary: !ownFast - } - ]; - } - - /** - * Trigger label key for a role selection, or an empty string when the - * selection names a concrete model or the role no longer resolves. - */ - static selectedModelLabelKey(catalog: ConversationUiModelCatalog, selectedModelId: string): string { - return ConversationModelPresentationPolicy.roleLabelKey( - ConversationModelPresentationPolicy.resolvedSelectedRole(catalog, selectedModelId)); - } - - /** - * Notice key that replaces a role row's resolved-model metadata, or an empty - * string when the row shows the resolved model instead. - */ - static roleMetaNoticeKey(entry: ConversationUiModelRoleEntry): string { - return entry.fallsBackToPrimary ? 'chat.modelFastNotConfigured' : ''; - } - - /** - * True when a concrete row owns the current selection. A role selection - * highlights its role row instead, so no concrete row is marked. - */ - static isConcreteModelSelected(selectedModelId: string, modelId: string): boolean { - const value = (selectedModelId || '').trim(); - return value.length > 0 && - !ConversationModelPresentationPolicy.isSemanticModelId(value) && - value === (modelId || '').trim(); - } - - static selectedModel( - catalog: ConversationUiModelCatalog, - selectedModelId: string - ): ConversationUiModel | undefined { - const candidates = [ - selectedModelId, - catalog.session_model_id || '', - catalog.default_models.primary || '' - ]; - for (let index = 0; index < candidates.length; index += 1) { - const model = ConversationModelPresentationPolicy.resolveModel(catalog, candidates[index]); - if (model) { - return model; - } - } - return undefined; - } - - static primaryLabel(model: ConversationUiModel, fallback: string): string { - const modelName = ConversationModelPresentationPolicy.cleanLabel(model.model_name || ''); - if (ConversationModelPresentationPolicy.isSpecificLabel(modelName)) { - return modelName; - } - const name = ConversationModelPresentationPolicy.cleanLabel(model.name || ''); - if (ConversationModelPresentationPolicy.isSpecificLabel(name)) { - return name; - } - const id = ConversationModelPresentationPolicy.cleanLabel(model.id || ''); - return id.length > 0 ? id : fallback; - } - - static secondaryLabel(model: ConversationUiModel, fallback: string): string { - const provider = ConversationModelPresentationPolicy.cleanLabel(model.provider || ''); - const name = ConversationModelPresentationPolicy.cleanLabel(model.name || ''); - const primary = ConversationModelPresentationPolicy.primaryLabel(model, fallback); - if (provider.length > 0 && name.length > 0 && name !== primary && name !== provider) { - return `${provider} · ${name}`; - } - if (provider.length > 0 && provider !== primary) { - return provider; - } - if (name.length > 0 && name !== primary) { - return name; - } - return model.id || primary; - } - - /** Provider and context-window metadata, e.g. `openai · 128k`. */ - static modelContextLabel(model: ConversationUiModel): string { - const parts: string[] = []; - const provider = ConversationModelPresentationPolicy.cleanLabel(model.provider || ''); - if (provider.length > 0) { - parts.push(provider); - } - const context = ConversationModelPresentationPolicy.contextWindowLabel(model.context_window); - if (context.length > 0) { - parts.push(context); - } - return parts.join(' · '); - } - - /** Resolved model name plus its provider/context metadata for a role row. */ - static roleMetaLabel(model: ConversationUiModel | undefined, fallback: string): string { - if (!model) { - return ''; - } - const name = ConversationModelPresentationPolicy.primaryLabel(model, fallback); - const context = ConversationModelPresentationPolicy.modelContextLabel(model); - return context.length > 0 ? `${name} · ${context}` : name; - } - - private static enabledModel( - catalog: ConversationUiModelCatalog, - modelId: string - ): ConversationUiModel | undefined { - const value = (modelId || '').trim(); - if (value.length === 0) { - return undefined; - } - return catalog.models.find((item: ConversationUiModel) => item.id === value && item.enabled); - } - - private static contextWindowLabel(contextWindow: number | undefined): string { - if (!contextWindow || contextWindow <= 0) { - return ''; - } - return `${Math.round(contextWindow / 1000)}k`; - } - - private static cleanLabel(value: string): string { - const trimmed = (value || '').trim(); - if (trimmed.length === 0) { - return ''; - } - const withoutScheme = trimmed.replace(/^openbitfun[:/_-]+/i, '').replace(/^anthropic[:/_-]+/i, ''); - const parts = withoutScheme.split(/[/:]/).filter((part: string) => part.length > 0); - return parts.length > 0 ? parts[parts.length - 1] : withoutScheme; - } - - private static isSpecificLabel(label: string): boolean { - const normalized = label.toLowerCase(); - return label.length > 0 && - normalized !== 'openbitfun' && - normalized !== 'anthropic' && - normalized !== 'openai' && - normalized !== 'google' && - normalized !== 'azure' && - normalized !== 'openbitfun'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationSessionFilterPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationSessionFilterPolicy.ets deleted file mode 100644 index 9ef633a22b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ConversationSessionFilterPolicy.ets +++ /dev/null @@ -1,52 +0,0 @@ -import { RemoteSession } from '../../model/RemoteModels'; - -export class ConversationSessionFilterPolicy { - static matches( - session: RemoteSession, - query: string, - fallbackWorkspacePath: string, - workspaceFilter: string, - agentFilter: string, - statusFilter: string, - assistantSession: boolean - ): boolean { - if (session.id.length === 0 || session.status === 'archived') { - return false; - } - const normalizedQuery = query.trim().toLowerCase(); - if (normalizedQuery.length > 0 && session.title.toLowerCase().indexOf(normalizedQuery) < 0) { - return false; - } - const workspacePath = session.workspacePath || (assistantSession ? '' : fallbackWorkspacePath); - if (workspaceFilter.length > 0 && - !ConversationSessionFilterPolicy.workspacePathsEqual(workspacePath, workspaceFilter)) { - return false; - } - if (agentFilter.length > 0 && ConversationSessionFilterPolicy.agentGroup(session, assistantSession) !== agentFilter) { - return false; - } - const status = (session.status || '').trim().toLowerCase(); - return statusFilter.length === 0 || status === statusFilter; - } - - static agentGroup(session: RemoteSession, assistantSession: boolean): string { - if (assistantSession) { - return 'chat'; - } - return (session.agentType || '').toLowerCase() === 'cowork' ? 'cowork' : 'code'; - } - - static workspacePathsEqual(left: string, right: string): boolean { - return ConversationSessionFilterPolicy.normalizeWorkspacePath(left) === - ConversationSessionFilterPolicy.normalizeWorkspacePath(right); - } - - /** Public so a caller can bucket by workspace instead of comparing pairwise. */ - static normalizeWorkspacePath(path: string): string { - let value = path.trim(); - while (value.length > 1 && (value.endsWith('/') || value.endsWith('\\'))) { - value = value.slice(0, value.length - 1); - } - return value; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/DeviceModelSettingsEntryPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/DeviceModelSettingsEntryPolicy.ets deleted file mode 100644 index 7a2ec93b0c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/DeviceModelSettingsEntryPolicy.ets +++ /dev/null @@ -1,66 +0,0 @@ -import { REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1 } from '../../model/RemoteModels'; - -/** - * Entry rules for the device model settings page. - * - * The page reads and writes the desktop the phone is driving right now, so the - * entry belongs to that row and to no other: an offline row has no link to - * answer with, and an online desktop this phone is not connected to would - * promise a read the client cannot perform. Capability, link and row identity - * are decided here together so the row, its badge and its reason line can never - * disagree. - */ -export class DeviceModelSettingsEntryPolicy { - /** One-line reason shown when the degraded entry is tapped. */ - static readonly DEGRADE_REASON_KEY: string = 'settings.model.unsupported'; - - /** The host advertises the device model defaults command. */ - static supportsDeviceModelDefaults(capabilities: string[]): boolean { - return (capabilities || []).indexOf(REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1) >= 0; - } - - /** Whether the device row carries the entry at all. */ - static showsEntry( - online: boolean, - deviceId: string, - phoneDeviceId: string, - controlTargetDeviceId: string, - connectionState: string - ): boolean { - return DeviceModelSettingsEntryPolicy.isDrivenTarget( - deviceId, phoneDeviceId, controlTargetDeviceId, connectionState - ) && online; - } - - /** Whether the entry opens the page. */ - static entryEnabled(supportsDeviceModelDefaults: boolean): boolean { - return supportsDeviceModelDefaults; - } - - /** - * The corner badge for an older desktop: the entry stays visible so the user - * learns why it is unavailable, and is greyed rather than silently missing. - */ - static showsUpgradeBadge(showsEntry: boolean, supportsDeviceModelDefaults: boolean): boolean { - return showsEntry && !supportsDeviceModelDefaults; - } - - /** The reason line to show, or an empty string when the entry is usable. */ - static degradeReasonKey(showsEntry: boolean, supportsDeviceModelDefaults: boolean): string { - return DeviceModelSettingsEntryPolicy.showsUpgradeBadge(showsEntry, supportsDeviceModelDefaults) ? - DeviceModelSettingsEntryPolicy.DEGRADE_REASON_KEY : ''; - } - - /** The desktop this phone is connected to and controlling, by row identity. */ - private static isDrivenTarget( - deviceId: string, - phoneDeviceId: string, - controlTargetDeviceId: string, - connectionState: string - ): boolean { - return deviceId.length > 0 && - deviceId !== phoneDeviceId && - deviceId === controlTargetDeviceId && - connectionState === 'connected'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FilePreviewPlacementPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FilePreviewPlacementPolicy.ets deleted file mode 100644 index 386c2f437f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FilePreviewPlacementPolicy.ets +++ /dev/null @@ -1,307 +0,0 @@ -import { ConversationLayoutCrease } from './ConversationLayoutPolicy'; - -export enum FilePreviewPlacement { - Hidden = 'hidden', - CompactFullPage = 'compact_full_page', - WideFocusSplit = 'wide_focus_split', - WideMasterPreviewFocus = 'wide_master_preview_focus', - WideTriplePane = 'wide_triple_pane' -} - -export class FilePreviewLayout { - readonly placement: FilePreviewPlacement; - readonly masterPaneWidth: number; - readonly masterConversationGap: number; - readonly conversationPaneWidth: number; - readonly conversationPreviewGap: number; - readonly previewPaneWidth: number; - readonly masterConversationGapIsCrease: boolean; - readonly conversationPreviewGapIsCrease: boolean; - - constructor( - placement: FilePreviewPlacement, - masterPaneWidth: number = 0, - masterConversationGap: number = 0, - conversationPaneWidth: number = 0, - conversationPreviewGap: number = 0, - previewPaneWidth: number = 0, - masterConversationGapIsCrease: boolean = false, - conversationPreviewGapIsCrease: boolean = false - ) { - this.placement = placement; - this.masterPaneWidth = masterPaneWidth; - this.masterConversationGap = masterConversationGap; - this.conversationPaneWidth = conversationPaneWidth; - this.conversationPreviewGap = conversationPreviewGap; - this.previewPaneWidth = previewPaneWidth; - this.masterConversationGapIsCrease = masterConversationGapIsCrease; - this.conversationPreviewGapIsCrease = conversationPreviewGapIsCrease; - } -} - -export class FilePreviewPlacementPolicy { - static readonly MIN_MASTER_WIDTH: number = 280; - static readonly MIN_CONVERSATION_WIDTH: number = 360; - static readonly MIN_PREVIEW_WIDTH: number = 360; - // A physical tri-fold panel is a stronger boundary than the generic tablet - // minimum. Current tri-fold right panels are about 290vp: that is still the - // complete screen and must not make preview hide the master pane. - static readonly MIN_CREASE_ALIGNED_PREVIEW_WIDTH: number = 280; - static readonly PANE_DIVIDER_WIDTH: number = 1; - - static resolve( - previewVisible: boolean, - largeScreenLayout: boolean, - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): FilePreviewPlacement { - return FilePreviewPlacementPolicy.resolveLayout( - previewVisible, - largeScreenLayout, - viewportWidth, - creases - ).placement; - } - - static resolveLayout( - previewVisible: boolean, - largeScreenLayout: boolean, - viewportWidth: number, - creases: ConversationLayoutCrease[], - preferredMasterWidth: number = FilePreviewPlacementPolicy.MIN_MASTER_WIDTH, - previewExpanded: boolean = false - ): FilePreviewLayout { - if (!previewVisible) { - return new FilePreviewLayout(FilePreviewPlacement.Hidden); - } - if (!largeScreenLayout) { - return new FilePreviewLayout( - FilePreviewPlacement.CompactFullPage, - 0, - 0, - Math.max(0, viewportWidth), - 0, - Math.max(0, viewportWidth) - ); - } - if (previewExpanded) { - const triFoldPreviewFocus = FilePreviewPlacementPolicy.creaseAlignedMasterPreviewFocus( - viewportWidth, - creases - ); - if (triFoldPreviewFocus) { - return triFoldPreviewFocus; - } - } - const creaseLayout = FilePreviewPlacementPolicy.creaseAlignedTriplePane(viewportWidth, creases); - if (creaseLayout) { - return creaseLayout; - } - const creaseFocusLayout = FilePreviewPlacementPolicy.creaseAlignedFocusSplit(viewportWidth, creases); - if (creaseFocusLayout) { - return creaseFocusLayout; - } - const lastCreaseFocusLayout = FilePreviewPlacementPolicy.lastCreaseFocusSplit(viewportWidth, creases); - if (lastCreaseFocusLayout) { - return lastCreaseFocusLayout; - } - const flatLayout = FilePreviewPlacementPolicy.flatTriplePane( - viewportWidth, - creases, - preferredMasterWidth - ); - if (flatLayout) { - return flatLayout; - } - const focusGap = FilePreviewPlacementPolicy.PANE_DIVIDER_WIDTH; - const minimumFocusWidth = FilePreviewPlacementPolicy.MIN_CONVERSATION_WIDTH + - FilePreviewPlacementPolicy.MIN_PREVIEW_WIDTH + focusGap; - if (viewportWidth < minimumFocusWidth) { - return new FilePreviewLayout( - FilePreviewPlacement.CompactFullPage, - 0, - 0, - Math.max(0, viewportWidth), - 0, - Math.max(0, viewportWidth) - ); - } - const focusContentWidth = Math.max(0, viewportWidth - focusGap); - const conversationWidth = Math.floor(focusContentWidth / 2); - return new FilePreviewLayout( - FilePreviewPlacement.WideFocusSplit, - 0, - 0, - conversationWidth, - focusGap, - focusContentWidth - conversationWidth - ); - } - - private static flatTriplePane( - viewportWidth: number, - creases: ConversationLayoutCrease[], - preferredMasterWidth: number - ): FilePreviewLayout | undefined { - if (FilePreviewPlacementPolicy.visibleCreases(viewportWidth, creases).length > 0) { - return undefined; - } - const minimum = FilePreviewPlacementPolicy.MIN_MASTER_WIDTH + - FilePreviewPlacementPolicy.MIN_CONVERSATION_WIDTH + - FilePreviewPlacementPolicy.MIN_PREVIEW_WIDTH + - FilePreviewPlacementPolicy.PANE_DIVIDER_WIDTH * 2; - if (viewportWidth < minimum) { - return undefined; - } - const dividerWidth = FilePreviewPlacementPolicy.PANE_DIVIDER_WIDTH; - const maximumMasterWidth = viewportWidth - dividerWidth * 2 - - FilePreviewPlacementPolicy.MIN_CONVERSATION_WIDTH - - FilePreviewPlacementPolicy.MIN_PREVIEW_WIDTH; - const masterWidth = Math.max( - FilePreviewPlacementPolicy.MIN_MASTER_WIDTH, - Math.min(preferredMasterWidth, maximumMasterWidth) - ); - const detailWidth = viewportWidth - masterWidth - dividerWidth * 2; - const conversationWidth = Math.floor(detailWidth / 2); - return new FilePreviewLayout( - FilePreviewPlacement.WideTriplePane, - masterWidth, - dividerWidth, - conversationWidth, - dividerWidth, - detailWidth - conversationWidth - ); - } - - private static creaseAlignedFocusSplit( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): FilePreviewLayout | undefined { - const visible = FilePreviewPlacementPolicy.visibleCreases(viewportWidth, creases); - if (visible.length !== 1) { - return undefined; - } - const crease = visible[0]; - const conversationWidth = crease.left; - const previewWidth = viewportWidth - crease.left - crease.width; - if (conversationWidth < FilePreviewPlacementPolicy.MIN_MASTER_WIDTH || - previewWidth < FilePreviewPlacementPolicy.MIN_PREVIEW_WIDTH) { - return undefined; - } - return new FilePreviewLayout( - FilePreviewPlacement.WideFocusSplit, - 0, - 0, - conversationWidth, - crease.width, - previewWidth, - false, - true - ); - } - - private static lastCreaseFocusSplit( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): FilePreviewLayout | undefined { - const visible = FilePreviewPlacementPolicy.visibleCreases(viewportWidth, creases); - if (visible.length < 2) { - return undefined; - } - const crease = visible[visible.length - 1]; - const conversationWidth = crease.left; - const previewWidth = viewportWidth - crease.left - crease.width; - if (conversationWidth < FilePreviewPlacementPolicy.MIN_CONVERSATION_WIDTH || - previewWidth < FilePreviewPlacementPolicy.MIN_MASTER_WIDTH) { - return undefined; - } - return new FilePreviewLayout( - FilePreviewPlacement.WideFocusSplit, - 0, - 0, - conversationWidth, - crease.width, - previewWidth, - false, - true - ); - } - - private static creaseAlignedTriplePane( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): FilePreviewLayout | undefined { - const visible = FilePreviewPlacementPolicy.visibleCreases(viewportWidth, creases); - if (visible.length < 2) { - return undefined; - } - const first = visible[0]; - const second = visible[1]; - const masterWidth = first.left; - const conversationWidth = second.left - first.left - first.width; - const previewWidth = viewportWidth - second.left - second.width; - if (masterWidth < FilePreviewPlacementPolicy.MIN_MASTER_WIDTH || - conversationWidth < FilePreviewPlacementPolicy.MIN_CONVERSATION_WIDTH || - previewWidth < FilePreviewPlacementPolicy.MIN_CREASE_ALIGNED_PREVIEW_WIDTH) { - return undefined; - } - return new FilePreviewLayout( - FilePreviewPlacement.WideTriplePane, - masterWidth, - first.width, - conversationWidth, - second.width, - previewWidth, - true, - true - ); - } - - /** - * When requested by the user, preserve navigation on the first panel and - * promote a narrow physical right-panel preview to the two-panel detail canvas. - * This is deliberately limited to geometry where the middle conversation - * panel was otherwise valid: malformed fold reports still use conservative - * focus fallbacks instead of being mistaken for a tri-fold device. - */ - private static creaseAlignedMasterPreviewFocus( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): FilePreviewLayout | undefined { - const visible = FilePreviewPlacementPolicy.visibleCreases(viewportWidth, creases); - if (visible.length < 2) return undefined; - const first = visible[0]; - const second = visible[1]; - const masterWidth = first.left; - const middleWidth = second.left - first.left - first.width; - const rightWidth = viewportWidth - second.left - second.width; - const previewWidth = viewportWidth - first.left - first.width; - if (masterWidth < FilePreviewPlacementPolicy.MIN_MASTER_WIDTH || - middleWidth < FilePreviewPlacementPolicy.MIN_CONVERSATION_WIDTH || - rightWidth < FilePreviewPlacementPolicy.MIN_CREASE_ALIGNED_PREVIEW_WIDTH || - rightWidth >= FilePreviewPlacementPolicy.MIN_PREVIEW_WIDTH) { - return undefined; - } - return new FilePreviewLayout( - FilePreviewPlacement.WideMasterPreviewFocus, - masterWidth, - first.width, - 0, - 0, - previewWidth, - true, - false - ); - } - - private static visibleCreases( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): ConversationLayoutCrease[] { - return creases - .filter((crease: ConversationLayoutCrease): boolean => { - return crease.left > 0 && crease.width >= 0 && crease.left + crease.width < viewportWidth; - }) - .sort((left: ConversationLayoutCrease, right: ConversationLayoutCrease): number => left.left - right.left); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FileTargetResolver.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FileTargetResolver.ets deleted file mode 100644 index c4c61e4f98..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/FileTargetResolver.ets +++ /dev/null @@ -1,156 +0,0 @@ -import { FilePreviewTarget, FilePreviewTargetContext } from '../../model/FilePreviewTarget'; -import { RemoteUiState } from '../../services/RemoteUiState'; - -export enum FileReferenceKind { - RemoteWorkspaceFile = 'remote_workspace_file', - HttpUrl = 'http_url', - Anchor = 'anchor', - UnsupportedScheme = 'unsupported_scheme', - Invalid = 'invalid' -} - -export class FileReferenceResolution { - readonly kind: FileReferenceKind; - readonly target?: FilePreviewTarget; - - constructor(kind: FileReferenceKind, target?: FilePreviewTarget) { - this.kind = kind; - this.target = target; - } -} - -export class FileTargetResolver { - static matchesRemotePath(reference: string, remotePath: string): boolean { - const raw = FileTargetResolver.cleanReference(reference); - if (raw.length === 0 || remotePath.length === 0 || raw.indexOf('#') === 0) { - return false; - } - const range = FileTargetResolver.extractLineRange(raw); - if (FileTargetResolver.hasUnsupportedScheme(range.path)) { - return false; - } - return RemoteUiState.normalizeRemoteFilePath(range.path) === remotePath; - } - - static resolve(reference: string, label: string, context: FilePreviewTargetContext): FileReferenceResolution { - const raw = FileTargetResolver.cleanReference(reference); - if (raw.length === 0) { - return new FileReferenceResolution(FileReferenceKind.Invalid); - } - const lower = raw.toLowerCase(); - if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) { - return new FileReferenceResolution(FileReferenceKind.HttpUrl); - } - if (raw.indexOf('#') === 0) { - return new FileReferenceResolution(FileReferenceKind.Anchor); - } - const range = FileTargetResolver.extractLineRange(raw); - if (FileTargetResolver.hasUnsupportedScheme(range.path)) { - return new FileReferenceResolution(FileReferenceKind.UnsupportedScheme); - } - - const remotePath: string = RemoteUiState.normalizeRemoteFilePath(range.path); - if (remotePath.length === 0 || remotePath === '/') { - return new FileReferenceResolution(FileReferenceKind.Invalid); - } - const displayName = label.trim().length > 0 ? label.trim() : FileTargetResolver.basename(remotePath); - return new FileReferenceResolution( - FileReferenceKind.RemoteWorkspaceFile, - new FilePreviewTarget( - raw, - remotePath, - displayName, - context.sessionId, - context.workspacePath, - context.controlTargetEpoch, - range.start, - range.end - ) - ); - } - - private static extractLineRange(reference: string): FileTargetLineRange { - const hashIndex = reference.lastIndexOf('#'); - if (hashIndex > 0) { - const parsed = FileTargetResolver.parseLineMarker(reference.slice(hashIndex + 1)); - if (parsed.start > 0) { - return new FileTargetLineRange(reference.slice(0, hashIndex), parsed.start, parsed.end); - } - } - const colon = reference.match(/^(.+):(\d+)(?:-(\d+))?$/); - if (colon && !FileTargetResolver.isWindowsDrivePrefix(colon[1])) { - return new FileTargetLineRange( - colon[1], - Number.parseInt(colon[2]), - colon[3] ? Number.parseInt(colon[3]) : 0 - ); - } - return new FileTargetLineRange(reference, 0, 0); - } - - private static parseLineMarker(marker: string): FileTargetLineRange { - const match = marker.match(/^L?(\d+)(?:-L?(\d+))?$/i); - if (!match) { - return new FileTargetLineRange('', 0, 0); - } - return new FileTargetLineRange( - '', - Number.parseInt(match[1]), - match[2] ? Number.parseInt(match[2]) : 0 - ); - } - - private static hasUnsupportedScheme(reference: string): boolean { - const scheme = reference.match(/^([A-Za-z][A-Za-z0-9+.-]*):/); - if (!scheme) { - return false; - } - if (scheme[1].length === 1 && reference.length >= 3 && - (reference.charAt(2) === '/' || reference.charAt(2) === '\\')) { - return false; - } - const lower = scheme[1].toLowerCase(); - if (reference.startsWith('openbitfun://runtime/') || reference.startsWith('openbitfun://current-session/')) return false; - return lower !== 'computer' && lower !== 'file'; - } - - private static isWindowsDrivePrefix(value: string): boolean { - return value.length === 1 && /[A-Za-z]/.test(value); - } - - private static cleanReference(reference: string): string { - let clean = reference.trim(); - while (clean.length > 0) { - const last = clean.charAt(clean.length - 1); - if (last === ',' || last === '.' || last === ';' || last === ':' || last === ')' || - last === ']' || last === '}' || last === '>' || last === ',' || last === '。' || - last === ';' || last === ':') { - clean = clean.slice(0, clean.length - 1); - } else { - break; - } - } - try { - return decodeURIComponent(clean); - } catch (_err) { - return clean; - } - } - - private static basename(path: string): string { - const parts = path.replace(/\\/g, '/').split('/'); - return parts[parts.length - 1] || path || 'file'; - } -} - -class FileTargetLineRange { - readonly path: string; - readonly start: number; - readonly end: number; - - constructor(path: string, start: number, end: number) { - this.path = path; - this.start = start; - this.end = end; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HarnessProfilePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HarnessProfilePolicy.ets deleted file mode 100644 index ec19ad7fcc..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HarnessProfilePolicy.ets +++ /dev/null @@ -1,11 +0,0 @@ -/** Maps the product execution levels onto the host's canonical Agents. */ -export class HarnessProfilePolicy { - static agentType(profileId: string): string { - switch (profileId.trim().toLowerCase()) { - case 'minimal': return 'minimal'; - case 'ultimate': return 'Ultra'; - case 'creative': return 'Creative'; - default: return 'agentic'; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HistoryPageArrivalTracker.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HistoryPageArrivalTracker.ets deleted file mode 100644 index ab81f6fdb5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/HistoryPageArrivalTracker.ets +++ /dev/null @@ -1,11 +0,0 @@ -/** One automatic page per deliberate drag; layout and bounce cannot re-arm it. */ -export class HistoryPageArrivalTracker { - private consumed: boolean = true; - beginGesture(): void { this.consumed = false; } - arrived(atStart: boolean): boolean { - if (!atStart || this.consumed) return false; - this.consumed = true; - return true; - } - cancelArrival(): void { this.consumed = true; } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/MessageFileReferenceProjector.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/MessageFileReferenceProjector.ets deleted file mode 100644 index 9e311d436a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/MessageFileReferenceProjector.ets +++ /dev/null @@ -1,112 +0,0 @@ -import { FilePreviewTargetContext } from '../../model/FilePreviewTarget'; -import { FileReferenceKind, FileTargetResolver } from './FileTargetResolver'; -import { - MarkdownParser, - ParsedMarkdownBlock, - ParsedMarkdownInline, - ParsedMarkdownListItem, - ParsedMarkdownTableCell, - ParsedMarkdownTableRow -} from '../../services/MarkdownParser'; - -export class MessageFileReference { - readonly id: string; - readonly path: string; - readonly remotePath: string; - readonly label: string; - - constructor(id: string, path: string, remotePath: string, label: string) { - this.id = id; - this.path = path; - this.remotePath = remotePath; - this.label = label; - } -} - -export class MessageFileReferenceProjectionCache { - private source: string = ''; - private references: MessageFileReference[] = []; - private initialized: boolean = false; - - referencesFor(source: string): MessageFileReference[] { - if (this.initialized && this.source === source) { - return this.references; - } - this.source = source; - this.references = MessageFileReferenceProjector.project(source); - this.initialized = true; - return this.references; - } -} - -export class MessageFileReferenceProjector { - private static readonly CONTEXT: FilePreviewTargetContext = - new FilePreviewTargetContext('_message_projection_', '', 0); - - static project(source: string, limit: number = 4): MessageFileReference[] { - const references: MessageFileReference[] = []; - const seenRemotePaths = new Set(); - MarkdownParser.parse(source).forEach((block: ParsedMarkdownBlock) => { - MessageFileReferenceProjector.collectInlines(block.inlines, references, seenRemotePaths, limit); - block.items.forEach((item: ParsedMarkdownListItem) => { - MessageFileReferenceProjector.collectInlines(item.inlines, references, seenRemotePaths, limit); - }); - block.tableRows.forEach((row: ParsedMarkdownTableRow) => { - row.cells.forEach((cell: ParsedMarkdownTableCell) => { - MessageFileReferenceProjector.collectInlines(cell.inlines, references, seenRemotePaths, limit); - }); - }); - }); - return references; - } - - private static collectInlines( - inlines: ParsedMarkdownInline[], - references: MessageFileReference[], - seenRemotePaths: Set, - limit: number - ): void { - inlines.forEach((inline: ParsedMarkdownInline) => { - if (references.length >= limit) { - return; - } - if (inline.type === 'link') { - MessageFileReferenceProjector.add(inline.url, references, seenRemotePaths); - return; - } - if (inline.type === 'code') { - return; - } - const found: string[] = inline.text.match(/(?:computer|file|openbitfun):\/\/[^\s)\]}>"']+/g) || []; - found.forEach((reference: string) => { - if (references.length < limit) { - MessageFileReferenceProjector.add(reference, references, seenRemotePaths); - } - }); - }); - } - - private static add( - reference: string, - references: MessageFileReference[], - seenRemotePaths: Set - ): void { - const lower = reference.trim().toLowerCase(); - const explicit = lower.startsWith('computer://') || lower.startsWith('file:') || - lower.startsWith('openbitfun://runtime/') || lower.startsWith('openbitfun://current-session/'); - const output = /\.(png|jpe?g|gif|webp|svg|bmp|avif|ico|html?|pdf|docx?|xlsx?|pptx?|csv|tsv|zip|mp4|webm|mp3|wav)(?:#.*)?$/i.test(lower); - if (!explicit && !output) return; - const resolution = FileTargetResolver.resolve(reference, '', MessageFileReferenceProjector.CONTEXT); - if (resolution.kind !== FileReferenceKind.RemoteWorkspaceFile || !resolution.target || - seenRemotePaths.has(resolution.target.remotePath)) { - return; - } - seenRemotePaths.add(resolution.target.remotePath); - references.push(new MessageFileReference( - `file-${references.length}-${resolution.target.remotePath}`, - resolution.target.rawReference, - resolution.target.remotePath, - resolution.target.displayName - )); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelRoleCandidatesPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelRoleCandidatesPolicy.ets deleted file mode 100644 index b3c3f25c55..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelRoleCandidatesPolicy.ets +++ /dev/null @@ -1,324 +0,0 @@ -import { RemoteModelCatalog, RemoteModelConfig } from '../../model/RemoteModels'; -import { - RemoteModelDefaultsRole, - RemoteModelDefaultsRoles, - RemoteModelDefaultsState -} from '../../services/RemoteModelDefaultsController'; - -/** - * The vocabulary the two device-model pages share. - * - * Which models a role may be set to, which of them the picker offers, and what a - * role row says are one reading of one catalog, so they are decided here as pure - * functions over it: no i18n lookup, no controller, no ArkUI. The pages resolve - * the keys this returns and own every pixel. - * - * The desktop is the authority. A role's value is whatever the last device read - * returned; a candidate is a model the desktop itself lists as enabled and - * capable, in the desktop's own order. Nothing here reorders, renames or repairs - * that list. - */ - -/** - * What the role picker shows for one device state. - * - * The picker is a list only while the device is actually answering. A snapshot - * that the gate replaced with "unavailable" still carries its last roles, and a - * role that is null there reads as a choice the user made — "fast follows the - * primary" on a desktop that was never asked, or on one the phone can no longer - * reach. So the marks, the list and the sentence about an empty list are decided - * here together with the reason, from the same state the reason comes from. - */ -export interface ModelPickerView { - /** The reason card: the device refused the page, or the last read failed. */ - reason: boolean; - /** The retry: the failure is a read this device can repeat. */ - retry: boolean; - /** The reading card: nothing has been read for this device yet. */ - reading: boolean; - /** The pinned row and the candidates are drawn. */ - list: boolean; - /** - * The rows on screen are the device's own answer, so a selected mark and an - * empty list may be read from them. A closed gate, a failed read or a page that - * has not been read yet all say no. - */ - answered: boolean; -} - -/** What one role row of the device model settings page shows. */ -export interface ModelRoleRowProjection { - /** The model the role points at; empty when the role has no model of its own. */ - modelId: string; - /** The catalog entry for `modelId`, when the desktop still lists it. */ - model: RemoteModelConfig | undefined; - /** The role has no model of its own: `fast` follows the primary, the rest are off. */ - unset: boolean; - /** The value line's placeholder key; empty while `modelId` names a model. */ - unsetKey: string; - /** The hint under the value; empty unless the role explicitly falls back. */ - hintKey: string; - /** - * The role resolves to an enabled model the desktop lists — its own, or for - * `fast` the primary it falls back to. This is what the row's leading mark - * states. - */ - resolved: boolean; -} - -export class ModelRoleCandidatesPolicy { - /** Model capabilities, as the desktop reports them. */ - static readonly CAPABILITY_TEXT_CHAT: string = 'text_chat'; - static readonly CAPABILITY_IMAGE_UNDERSTANDING: string = 'image_understanding'; - - /** The neutral "nothing is set here" value, shared with the model panels. */ - static readonly NOT_CONFIGURED_KEY: string = 'settings.modelService.notConfigured'; - - /** - * Models the picker may offer for a role: enabled, capable, in catalog order. - * - * A disabled model is not a candidate at all — the desktop would refuse the - * write, and offering it would turn a filter into an error message — and the - * capability is what makes the model usable for that role in the first place. - */ - static textChatCandidates(catalog: RemoteModelCatalog): RemoteModelConfig[] { - return ModelRoleCandidatesPolicy.capableModels( - catalog, ModelRoleCandidatesPolicy.CAPABILITY_TEXT_CHAT); - } - - static imageUnderstandingCandidates(catalog: RemoteModelCatalog): RemoteModelConfig[] { - return ModelRoleCandidatesPolicy.capableModels( - catalog, ModelRoleCandidatesPolicy.CAPABILITY_IMAGE_UNDERSTANDING); - } - - static candidatesForRole( - role: RemoteModelDefaultsRole, - catalog: RemoteModelCatalog - ): RemoteModelConfig[] { - return role === 'image_understanding' ? - ModelRoleCandidatesPolicy.imageUnderstandingCandidates(catalog) : - ModelRoleCandidatesPolicy.textChatCandidates(catalog); - } - - /** The desktop lists no model at all: the pickers have nothing to offer. */ - static isEmptyCatalog(catalog: RemoteModelCatalog): boolean { - return catalog.models.length === 0; - } - - /** - * The device cannot answer this page: it never advertised the command, or the - * phone is not connected to it, or the read itself failed. All three are the - * same fact to the picker — the list on screen is not an answer — and the - * controller has already resolved which sentence describes it into `error`. - */ - static isUnavailable(state: RemoteModelDefaultsState): boolean { - return !state.available || state.error.length > 0; - } - - /** - * Whether repeating the read is a way out. Only a device that can still answer - * can be asked again: a closed gate is the sheet's own business, and it re-arms - * by itself when the link or the desktop comes back. - */ - static canRepeatRead(state: RemoteModelDefaultsState): boolean { - return state.available && state.error.length > 0; - } - - /** The render decisions of one picker frame, all read from one state. */ - static pickerView(state: RemoteModelDefaultsState): ModelPickerView { - const reason = ModelRoleCandidatesPolicy.isUnavailable(state); - const reading = state.available && !reason && !state.loaded; - return { - reason, - retry: ModelRoleCandidatesPolicy.canRepeatRead(state), - reading, - // A device that can still answer keeps its list even after a failed read: - // those rows are the last thing it said, and they are not what failed. - list: state.available && !reading, - answered: !reason && !reading - }; - } - - /** - * Whether the picker offers the "no model" row. - * - * The primary model is required — the desktop always resolves one, and a phone - * that cleared it could leave the device with no model to run — so its picker - * has no such row. The other two are optional by contract: an empty `fast` is - * "follow the primary" and an empty `image_understanding` is "off". - */ - static allowsUnset(role: RemoteModelDefaultsRole): boolean { - return role !== 'primary'; - } - - /** The pinned row's label key. */ - static unsetLabelKey(role: RemoteModelDefaultsRole): string { - if (role === 'fast') { - return 'chat.modelFollowPrimary'; - } - return ModelRoleCandidatesPolicy.NOT_CONFIGURED_KEY; - } - - /** The pinned row's hint key. */ - static unsetHintKey(role: RemoteModelDefaultsRole): string { - if (role === 'fast') { - return 'chat.modelFastNotConfigured'; - } - if (role === 'image_understanding') { - return 'settings.model.imageUnderstandingUnset'; - } - return ''; - } - - /** The role's own label, shared by the rows, the picker title and the sent row. */ - static roleLabelKey(role: RemoteModelDefaultsRole): string { - if (role === 'primary') { - return 'chat.modelPrimary'; - } - if (role === 'fast') { - return 'chat.modelFast'; - } - if (role === 'image_understanding') { - return 'chat.modelImage'; - } - return ''; - } - - /** The filter sentence above the candidate list, templated with the device name. */ - static filterKey(role: RemoteModelDefaultsRole): string { - return role === 'image_understanding' ? - 'settings.model.filterImageUnderstanding' : 'settings.model.filterTextChat'; - } - - /** - * The capability badge belongs to the multimodal picker only: it explains why - * that list is short, and on any other page it would only widen every row. - */ - static showsCapabilityBadge(role: RemoteModelDefaultsRole): boolean { - return role === 'image_understanding'; - } - - /** The model id a role currently holds; empty when it holds none. */ - static selectedValue(roles: RemoteModelDefaultsRoles, role: RemoteModelDefaultsRole): string { - if (role === 'primary') { - return roles.primary || ''; - } - if (role === 'fast') { - return roles.fast || ''; - } - if (role === 'image_understanding') { - return roles.image_understanding || ''; - } - return ''; - } - - /** True while the role is set to "no model", i.e. the pinned row is the checked one. */ - static isUnsetSelected(roles: RemoteModelDefaultsRoles, role: RemoteModelDefaultsRole): boolean { - return ModelRoleCandidatesPolicy.allowsUnset(role) && - ModelRoleCandidatesPolicy.selectedValue(roles, role).length === 0; - } - - /** True when this candidate row is the role's current model. */ - static isCandidateSelected( - roles: RemoteModelDefaultsRoles, - role: RemoteModelDefaultsRole, - modelId: string - ): boolean { - return ModelRoleCandidatesPolicy.selectedValue(roles, role) === modelId; - } - - /** - * One role row of the settings page. - * - * An empty catalog is its own answer: with no model on the device there is - * nothing for any role to point at, so every row states the same unconfigured - * value and no row claims to resolve. Saying "follows the primary" there would - * promise a fallback the desktop cannot perform. - */ - static roleRow( - roles: RemoteModelDefaultsRoles, - role: RemoteModelDefaultsRole, - catalog: RemoteModelCatalog - ): ModelRoleRowProjection { - if (ModelRoleCandidatesPolicy.isEmptyCatalog(catalog)) { - return { - modelId: '', - model: undefined, - unset: true, - unsetKey: ModelRoleCandidatesPolicy.NOT_CONFIGURED_KEY, - hintKey: '', - resolved: false - }; - } - const modelId = ModelRoleCandidatesPolicy.selectedValue(roles, role); - const model = ModelRoleCandidatesPolicy.modelById(catalog, modelId); - const unset = modelId.length === 0; - return { - modelId, - model, - unset, - unsetKey: unset ? ModelRoleCandidatesPolicy.unsetLabelKey(role) : '', - hintKey: unset ? ModelRoleCandidatesPolicy.unsetHintKey(role) : '', - resolved: ModelRoleCandidatesPolicy.resolves(roles, role, catalog) - }; - } - - /** - * The model a role actually runs: its own, or for `fast` the primary model it - * falls back to. `image_understanding` has no fallback — an empty one means the - * capability is off rather than borrowed from another slot. - * - * A role only runs an enabled model, so a slot the desktop points at a disabled - * model resolves to nothing here even though the row still names it. This is - * the same reading of a catalog the composer's role rows use. - */ - static resolvedModel( - roles: RemoteModelDefaultsRoles, - role: RemoteModelDefaultsRole, - catalog: RemoteModelCatalog - ): RemoteModelConfig | undefined { - const own = ModelRoleCandidatesPolicy.enabledModelById( - catalog, ModelRoleCandidatesPolicy.selectedValue(roles, role)); - if (own) { - return own; - } - if (role === 'fast') { - return ModelRoleCandidatesPolicy.enabledModelById(catalog, roles.primary || ''); - } - return undefined; - } - - private static resolves( - roles: RemoteModelDefaultsRoles, - role: RemoteModelDefaultsRole, - catalog: RemoteModelCatalog - ): boolean { - return ModelRoleCandidatesPolicy.resolvedModel(roles, role, catalog) !== undefined; - } - - private static enabledModelById( - catalog: RemoteModelCatalog, - modelId: string - ): RemoteModelConfig | undefined { - const model = ModelRoleCandidatesPolicy.modelById(catalog, modelId); - return model && model.enabled ? model : undefined; - } - - private static modelById( - catalog: RemoteModelCatalog, - modelId: string - ): RemoteModelConfig | undefined { - if (modelId.length === 0) { - return undefined; - } - return catalog.models.find((model: RemoteModelConfig): boolean => model.id === modelId); - } - - private static capableModels( - catalog: RemoteModelCatalog, - capability: string - ): RemoteModelConfig[] { - return catalog.models.filter((model: RemoteModelConfig): boolean => - model.enabled && (model.capabilities || []).indexOf(capability) >= 0); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelServiceSettingsPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelServiceSettingsPolicy.ets deleted file mode 100644 index 69fc1a6193..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ModelServiceSettingsPolicy.ets +++ /dev/null @@ -1,169 +0,0 @@ -import { RemoteModelCatalog, RemoteModelConfig } from '../../model/RemoteModels'; -import { GENERAL_CHAT_LOCAL_MODEL_ID } from '../../services/general-chat/GeneralChatConfigStore'; - -export type ModelServicePage = 'overview' | 'account' | 'local'; - -/** - * Presentation rules for the general-chat model settings sheets. - * - * The settings row hosts system bindSheets (same contract as ComposerBar): - * adaptive height, no hand-rolled scrim, and a checkmark that only means - * "this is the selected model". - */ -export class ModelServiceSettingsPolicy { - static readonly HEADER_HEIGHT: number = 56; - static readonly CURRENT_ROW_HEIGHT: number = 64; - static readonly SOURCE_ROW_HEIGHT: number = 62; - static readonly ACCOUNT_MODEL_ROW_HEIGHT: number = 56; - static readonly ACCOUNT_MODEL_ROW_GAP: number = 6; - static readonly LANGUAGE_ROW_HEIGHT: number = 64; - static readonly SECTION_LABEL_HEIGHT: number = 20; - static readonly OVERVIEW_SECTION_GAP: number = 20; - static readonly OVERVIEW_TOP_PADDING: number = 16; - static readonly OVERVIEW_BOTTOM_PADDING: number = 24; - static readonly SOURCE_DIVIDER_HEIGHT: number = 1; - static readonly LIST_TOP_PADDING: number = 10; - static readonly LIST_BOTTOM_PADDING: number = 16; - static readonly EMPTY_ACCOUNT_HEIGHT: number = 80; - static readonly LOCAL_EDITOR_HEIGHT: number = 560; - static readonly MAX_ACCOUNT_VISIBLE_ROWS: number = 7; - static readonly MAX_SHEET_HEIGHT: number = 480; - static readonly LANGUAGE_LIST_TOP_PADDING: number = 8; - static readonly LANGUAGE_LIST_BOTTOM_PADDING: number = 28; - - static accountModels(catalog: RemoteModelCatalog): RemoteModelConfig[] { - return catalog.models.filter((model: RemoteModelConfig): boolean => { - return ModelServiceSettingsPolicy.isAccountModel(model) && model.enabled; - }); - } - - static currentModel(catalog: RemoteModelCatalog, selectedModelId: string): RemoteModelConfig | undefined { - const candidates = [ - selectedModelId, - catalog.session_model_id || '', - catalog.default_models.primary || '' - ]; - for (let index = 0; index < candidates.length; index += 1) { - const modelId = candidates[index]; - if (modelId.length === 0) { - continue; - } - const model = catalog.models.find((item: RemoteModelConfig): boolean => { - return item.id === modelId && item.enabled; - }); - if (model) { - return model; - } - } - return undefined; - } - - static modelLabel(model: RemoteModelConfig | undefined, fallback: string): string { - if (!model) { - return fallback; - } - return model.model_name || model.name || model.id || fallback; - } - - static isAccountModel(model: RemoteModelConfig): boolean { - return model.id.startsWith('cloud:'); - } - - static isLocalModel(model: RemoteModelConfig): boolean { - return model.id === GENERAL_CHAT_LOCAL_MODEL_ID; - } - - static isAccountModelSelected(catalog: RemoteModelCatalog, selectedModelId: string): boolean { - const current = ModelServiceSettingsPolicy.currentModel(catalog, selectedModelId); - return current !== undefined && ModelServiceSettingsPolicy.isAccountModel(current); - } - - static isLocalModelSelected(catalog: RemoteModelCatalog, selectedModelId: string): boolean { - const current = ModelServiceSettingsPolicy.currentModel(catalog, selectedModelId); - return current !== undefined && ModelServiceSettingsPolicy.isLocalModel(current); - } - - static hasCompleteLocalModel(apiUrl: string, modelName: string, hasApiKey: boolean): boolean { - return apiUrl.trim().length > 0 && modelName.trim().length > 0 && hasApiKey; - } - - /** - * A configured local row selects that model on the body tap. - * The trailing chevron always opens the editor. An incomplete row - * opens the editor from either target. - */ - static localRowSelectsOnBodyTap(apiUrl: string, modelName: string, hasApiKey: boolean): boolean { - return ModelServiceSettingsPolicy.hasCompleteLocalModel(apiUrl, modelName, hasApiKey); - } - - static sourceRowShowsSelectionCheck(): boolean { - return false; - } - - static overviewSheetHeight(): number { - return ModelServiceSettingsPolicy.HEADER_HEIGHT + - ModelServiceSettingsPolicy.OVERVIEW_TOP_PADDING + - ModelServiceSettingsPolicy.SECTION_LABEL_HEIGHT + - ModelServiceSettingsPolicy.CURRENT_ROW_HEIGHT + - ModelServiceSettingsPolicy.OVERVIEW_SECTION_GAP + - ModelServiceSettingsPolicy.SECTION_LABEL_HEIGHT + - ModelServiceSettingsPolicy.sourceGroupHeight() + - ModelServiceSettingsPolicy.OVERVIEW_BOTTOM_PADDING; - } - - static sourceGroupHeight(): number { - return ModelServiceSettingsPolicy.SOURCE_ROW_HEIGHT + - ModelServiceSettingsPolicy.SOURCE_DIVIDER_HEIGHT + - ModelServiceSettingsPolicy.SOURCE_ROW_HEIGHT; - } - - static accountListSheetHeight(modelCount: number): number { - const contentHeight = ModelServiceSettingsPolicy.accountListContentHeight(modelCount); - return Math.min( - ModelServiceSettingsPolicy.MAX_SHEET_HEIGHT, - ModelServiceSettingsPolicy.HEADER_HEIGHT + - ModelServiceSettingsPolicy.LIST_TOP_PADDING + - contentHeight + - ModelServiceSettingsPolicy.LIST_BOTTOM_PADDING - ); - } - - static accountListContentHeight(modelCount: number): number { - if (modelCount <= 0) { - return ModelServiceSettingsPolicy.EMPTY_ACCOUNT_HEIGHT; - } - const visibleRows = Math.min(modelCount, ModelServiceSettingsPolicy.MAX_ACCOUNT_VISIBLE_ROWS); - return visibleRows * ModelServiceSettingsPolicy.ACCOUNT_MODEL_ROW_HEIGHT + - Math.max(0, visibleRows - 1) * ModelServiceSettingsPolicy.ACCOUNT_MODEL_ROW_GAP; - } - - static localEditorSheetHeight(): number { - return ModelServiceSettingsPolicy.LOCAL_EDITOR_HEIGHT; - } - - static languageSheetHeight(languageCount: number): number { - const rows = Math.max(0, languageCount); - return ModelServiceSettingsPolicy.HEADER_HEIGHT + - ModelServiceSettingsPolicy.LANGUAGE_LIST_TOP_PADDING + - rows * ModelServiceSettingsPolicy.LANGUAGE_ROW_HEIGHT + - ModelServiceSettingsPolicy.LANGUAGE_LIST_BOTTOM_PADDING; - } - - static sheetPage(page: string): ModelServicePage { - if (page === 'account' || page === 'local') { - return page; - } - return 'overview'; - } - - /** - * Settings is already a bindSheet. Nested bindSheets on that content do not - * present, so child pages replace the settings list in place. - */ - static parentSettingsPage(page: string): string { - if (page === 'account' || page === 'local') { - return 'overview'; - } - return 'main'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/PlanToolPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/PlanToolPolicy.ets deleted file mode 100644 index 5a7bb58d51..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/PlanToolPolicy.ets +++ /dev/null @@ -1,83 +0,0 @@ -import { ConversationUiPlanTool, ConversationUiToolStatus } from '../state/ConversationUiModels'; - -interface PlanToolInput { - plan_file_path?: string; - file_path?: string; - filePath?: string; - path?: string; - name?: string; - title?: string; - overview?: string; -} - -/** Pure recognition/projection for legacy CreatePlan and modern .plan.md writes. */ -export class PlanToolPolicy { - static descriptor(tool: ConversationUiToolStatus): ConversationUiPlanTool | undefined { - if (tool.plan) { - return { - file_path: tool.plan.file_path || '', - name: PlanToolPolicy.planName(tool.plan.name, tool.plan.file_path), - overview: tool.plan.overview - }; - } - const input = PlanToolPolicy.input(tool); - const path = input.plan_file_path || input.file_path || input.filePath || input.path || ''; - const normalizedName = PlanToolPolicy.normalizedName(tool.name || ''); - const isCreatePlan = normalizedName === 'createplan'; - const isPlanWrite = (normalizedName === 'write' || normalizedName === 'writefile' || - normalizedName === 'createfile') && path.toLowerCase().endsWith('.plan.md'); - if (!isCreatePlan && !isPlanWrite) { - return undefined; - } - return { - file_path: path, - name: PlanToolPolicy.planName(input.name || input.title || '', path), - overview: input.overview - }; - } - - static isPlanTool(tool: ConversationUiToolStatus): boolean { - return PlanToolPolicy.descriptor(tool) !== undefined; - } - - static canBuild(tool: ConversationUiToolStatus): boolean { - const plan = PlanToolPolicy.descriptor(tool); - const status = (tool.status || '').toLowerCase(); - return !!plan && plan.file_path.length > 0 && - (status === 'completed' || status === 'done' || status === 'success'); - } - - private static normalizedName(name: string): string { - return name.replace(/[\s_-]/g, '').toLowerCase(); - } - - private static input(tool: ConversationUiToolStatus): PlanToolInput { - if (tool.tool_input) { - try { - return JSON.parse(JSON.stringify(tool.tool_input)) as PlanToolInput; - } catch (_err) { - } - } - const preview = tool.input_preview || ''; - if (preview.trim().length > 0) { - try { - return JSON.parse(preview) as PlanToolInput; - } catch (_err) { - } - } - return {}; - } - - private static planName(explicitName: string, path: string): string { - if (explicitName.trim().length > 0) { - return explicitName.trim(); - } - const normalizedPath = path.replace(/\\/g, '/'); - const parts = normalizedPath.split('/'); - const fileName = parts[parts.length - 1] || ''; - if (fileName.toLowerCase().endsWith('.plan.md')) { - return fileName.slice(0, fileName.length - '.plan.md'.length); - } - return fileName || 'Plan'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteCompactHomePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteCompactHomePolicy.ets deleted file mode 100644 index ec3a51ffce..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteCompactHomePolicy.ets +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Compact Remote Home is conversation chrome, not a session list. - * - * The sidebar may keep a cached list after the desktop drops so the user can - * still see what the phone already knows. Compact home must not treat that - * cache as a live link: "pick a session" only belongs on a connected desktop. - */ -export class RemoteCompactHomePolicy { - static shouldShowInitialLoading(connectionState: string, sessionCount: number, loadingHome: boolean): boolean { - // Recovery keeps the existing surface, including an already empty home. - if (sessionCount > 0 || connectionState === 'reconnecting') return false; - return loadingHome || connectionState === 'parsing' || connectionState === 'pairing'; - } - - static shouldShowRecentSessions(connected: boolean, sessionCount: number): boolean { - return connected || sessionCount > 0; - } - - static shouldShowWelcomeHome(controlTargetType: string, connectionState: string, signedIn: boolean = false): boolean { - return !signedIn && controlTargetType === 'none' && connectionState !== 'connected'; - } - - static shouldShowConnectHome(connectionState: string): boolean { - return connectionState !== 'connected'; - } - - static headerSubtitle(connectionState: string, desktopName: string): string { - // Recovery retains the selected device context; health belongs in the sidebar. - if (connectionState !== 'connected' && connectionState !== 'reconnecting') { - return ''; - } - return desktopName; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteSurfaceEntryPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteSurfaceEntryPolicy.ets deleted file mode 100644 index ecab9b45fa..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RemoteSurfaceEntryPolicy.ets +++ /dev/null @@ -1,14 +0,0 @@ -export class RemoteConnectEntryKind { - static readonly EnterSurface: string = 'enter_surface'; - static readonly OpenConnect: string = 'open_connect'; -} - -/** - * Switching to Remote is a change of context. Opening the connect sheet is a - * command to pick a desktop. Those two must not share an entry point. - */ -export class RemoteSurfaceEntryPolicy { - static shouldOpenConnectSheet(kind: string): boolean { - return kind === RemoteConnectEntryKind.OpenConnect; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RollbackPresentationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RollbackPresentationPolicy.ets deleted file mode 100644 index 454cf82e7a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RollbackPresentationPolicy.ets +++ /dev/null @@ -1,185 +0,0 @@ -import { - RollbackEntryDecision, - RollbackEntryDenyReason, - SessionRollbackPolicy, - SessionRollbackStage, - SessionRollbackState -} from './SessionRollbackPolicy'; - -/** - * What the staged rollback looks like, decided away from the pane that draws it. - * - * `SessionRollbackPolicy` owns the gating decision and the staging state machine; - * this module owns the three derivations the view would otherwise have to invent - * inline: which text a refusal is said with, which rows the local preview grays - * out, and what the bar above the composer shows. - * - * Nothing here reads a timeline, a composer or a locale catalog: the rows and the - * target text arrive as data, and every refusal answers with an i18n key rather - * than a sentence, so the same decisions are reachable from a host test. - */ - -/** - * One timeline row as the ghost preview addresses it. - * - * `key` is the row identity the virtual list renders with - * (`ChatTimelineRevisionTracker.itemKey`); `turnId` is the turn the row belongs - * to, which is what "the target and everything after it" is expressed in. - */ -export class RollbackGhostRow { - readonly key: string; - readonly turnId: string; - - constructor(key: string, turnId: string) { - this.key = key; - this.turnId = turnId; - } -} - -/** - * The facts a tap on the rollback entry is judged with. - * - * Projected once with the rest of the conversation, then resolved at tap time so - * a session that became busy between the render and the tap is judged as it is - * now, not as it was when the row was drawn. - */ -export class RollbackEntryFacts { - /** Capability strings the connected host advertised in its handshake. */ - readonly hostCapabilities: string[]; - /** True while a turn is running or a message is still queued. */ - readonly sessionBusy: boolean; - /** - * True for a session whose history belongs to another host. - * - * Always false on this controller: a detached dispatch projection is neither - * listed nor openable here (`RemoteResponseMapper.isVisibleSession` keeps child - * sessions out of the catalog), so the phone can never prove one and the host - * refusal stays the loud answer. The field exists because the gating policy - * asks for it and the phone must not silently answer "no" on its behalf. - */ - readonly isDispatchSession: boolean; - - constructor(hostCapabilities: string[], sessionBusy: boolean, isDispatchSession: boolean) { - this.hostCapabilities = hostCapabilities; - this.sessionBusy = sessionBusy; - this.isDispatchSession = isDispatchSession; - } - - /** A surface with no host behind it — the local General Chat pane. */ - static none(): RollbackEntryFacts { - return new RollbackEntryFacts([], false, false); - } - - /** - * Judge one tap. - * - * `isUserMessage` is constant here because the entry only ever exists on a user - * message: the two entry surfaces are the user bubble and its full-text panel, - * and the truncated bubble's menu is built from the same user-message policy. - */ - resolve(): RollbackEntryDecision { - return SessionRollbackPolicy.resolveRollbackEntry({ - isUserMessage: true, - hostCapabilities: this.hostCapabilities, - sessionBusy: this.sessionBusy, - isDispatchSession: this.isDispatchSession - }); - } -} - -/** What the bar above the composer shows for one staging state. */ -export class RollbackBarPresentation { - /** The bar exists only while a rollback is staged. */ - readonly visible: boolean; - /** Dotted i18n key for the bar's title. */ - readonly titleKey: string; - /** - * The withdrawn prompt, flattened to one line. - * - * Newlines become spaces rather than being cut here: the line that gets - * ellipsized is the layout's, so the only job left to this policy is making the - * preview a single line the layout can ellipsize. - */ - readonly preview: string; - - constructor(visible: boolean, titleKey: string, preview: string) { - this.visible = visible; - this.titleKey = titleKey; - this.preview = preview; - } -} - -export class RollbackPresentationPolicy { - /** Bar title: "roll back to". */ - static readonly ROLLBACK_TO_KEY: string = 'chat.rollbackTo'; - /** Selection-menu item on a user message. */ - static readonly ROLLBACK_ITEM_KEY: string = 'chat.rollbackItem'; - /** The system hint row a successful rollback leaves behind. */ - static readonly ROLLED_BACK_NOTICE_KEY: string = 'chat.rolledBackNotice'; - /** The connected host does not serve `session_rollback_v1`. */ - static readonly UNSUPPORTED_KEY: string = 'chat.rollbackUnsupported'; - /** A turn is running; history cannot change under it. */ - static readonly SESSION_BUSY_KEY: string = 'chat.rollbackSessionBusy'; - /** This kind of session is not a rollback target. */ - static readonly DISPATCH_DENIED_KEY: string = 'chat.rollbackDispatchDenied'; - /** A refused or stale rollback the client could not repair quietly. */ - static readonly FAILED_KEY: string = 'chat.rollbackFailed'; - - /** - * The key a refusal is said with. - * - * `None` and `NotUserMessage` never reach a surface: the first is an allowed - * entry, and the second cannot be produced by an entry that only exists on a - * user message. Both fall back to the loud failure copy so an unreachable - * combination still says something rather than nothing. - */ - static denyMessageKey(reason: RollbackEntryDenyReason): string { - if (reason === RollbackEntryDenyReason.DispatchSession) { - return RollbackPresentationPolicy.DISPATCH_DENIED_KEY; - } - if (reason === RollbackEntryDenyReason.SessionBusy) { - return RollbackPresentationPolicy.SESSION_BUSY_KEY; - } - if (reason === RollbackEntryDenyReason.HostUnsupported) { - return RollbackPresentationPolicy.UNSUPPORTED_KEY; - } - return RollbackPresentationPolicy.FAILED_KEY; - } - - /** The bar for one staging state; hidden unless the rollback is staged. */ - static bar(state: SessionRollbackState): RollbackBarPresentation { - if (state.stage !== SessionRollbackStage.Staging) { - return new RollbackBarPresentation(false, RollbackPresentationPolicy.ROLLBACK_TO_KEY, ''); - } - return new RollbackBarPresentation( - true, - RollbackPresentationPolicy.ROLLBACK_TO_KEY, - RollbackPresentationPolicy.singleLine(state.targetText) - ); - } - - /** - * The rows the staged preview grays out: the target turn and every row after it. - * - * A target this timeline does not contain — a transcript that already moved on — - * ghosts nothing. The preview is a local statement about rows that are on - * screen, and graying rows the target was never found among would be a guess - * about where the cut belongs. - */ - static ghostRowKeys(rows: RollbackGhostRow[], targetTurnId: string): string[] { - const target = targetTurnId.trim(); - if (target.length === 0) { - return []; - } - const start = rows.findIndex((row: RollbackGhostRow) => row.turnId === target); - if (start < 0) { - return []; - } - return rows.slice(start).map((row: RollbackGhostRow) => row.key); - } - - /** Whitespace runs collapse into one space so the preview is a single line. */ - private static singleLine(text: string): string { - return text.replace(/\s+/g, ' ').trim(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RuntimeLocationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RuntimeLocationPolicy.ets deleted file mode 100644 index be786910e9..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/RuntimeLocationPolicy.ets +++ /dev/null @@ -1,17 +0,0 @@ -/** Paths belong to the serving runtime; the phone OS does not determine syntax. */ -export class RuntimeLocationPolicy { - static parent(path: string): string { - if (/^[a-zA-Z]:[\\/]/.test(path)) { - const normalized = path.replace(/\\/g, '/').replace(/\/+$/, ''); - const parent = normalized.slice(0, normalized.lastIndexOf('/')); - return parent.length > 2 ? parent : `${normalized.slice(0, 2)}/`; - } - if (path.startsWith('\\\\')) { - const parts = path.replace(/\\/g, '/').split('/').filter((part: string): boolean => part.length > 0); - if (parts.length > 2) parts.pop(); - return `//${parts.join('/')}`; - } - const normalized = path.replace(/\/+$/, ''); - return normalized.slice(0, normalized.lastIndexOf('/')) || '/'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SelectionCapabilityPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SelectionCapabilityPolicy.ets deleted file mode 100644 index 738183ebb2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SelectionCapabilityPolicy.ets +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Which selection surface a device can offer over rendered markdown. - * - * `SelectionContainer` (API 26) is the only way to make a column of sibling - * `Text` components one continuous selection, so a handle can be dragged from a - * paragraph into the list item or code block underneath it. Below 26 the same - * subtree stays selectable one `Text` at a time through each child's own - * `copyOption`. - * - * The gate is given the device's reported API level instead of reading it, so - * the boundary stays host-testable and the platform read stays behind a service - * (see the mobile architecture rules for components). - */ -export class SelectionCapabilityPolicy { - /** First API level that ships `SelectionContainer`. */ - static readonly CROSS_BLOCK_SELECTION_API_LEVEL: number = 26; - - static supportsCrossBlockSelection(sdkApiVersion: number): boolean { - // Anything that is not a finite number is not evidence of API 26. A device - // whose level cannot be measured keeps the fallback path, which still copies - // the block the user pressed on, instead of risking an API-26 call that the - // platform would reject. - if (!Number.isFinite(sdkApiVersion)) { - return false; - } - return sdkApiVersion >= SelectionCapabilityPolicy.CROSS_BLOCK_SELECTION_API_LEVEL; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionActionPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionActionPolicy.ets deleted file mode 100644 index ddfeb71439..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionActionPolicy.ets +++ /dev/null @@ -1,31 +0,0 @@ -export enum SessionActionScope { - General = 'general', - Remote = 'remote' -} - -export class SessionActionCapabilities { - readonly canViewDetails: boolean; - readonly canArchive: boolean; - readonly canExport: boolean; - readonly canDelete: boolean; - - constructor(canViewDetails: boolean, canArchive: boolean, canExport: boolean, canDelete: boolean) { - this.canViewDetails = canViewDetails; - this.canArchive = canArchive; - this.canExport = canExport; - this.canDelete = canDelete; - } -} - -export class SessionActionPolicy { - static resolve(scope: SessionActionScope, agentType: string, busy: boolean): SessionActionCapabilities { - if (busy) { - return new SessionActionCapabilities(false, false, false, false); - } - if (scope === SessionActionScope.Remote) { - return new SessionActionCapabilities(true, false, false, true); - } - const isGeneralChat = agentType.toLowerCase() === 'chat'; - return new SessionActionCapabilities(true, isGeneralChat, isGeneralChat, true); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionListProjection.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionListProjection.ets deleted file mode 100644 index d9667d196a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionListProjection.ets +++ /dev/null @@ -1,506 +0,0 @@ -import { RecentWorkspaceEntry, RemoteSession, RemoteWorkspaceIdentity } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { LegacyWorkspaceCompatibility } from '../../services/LegacyWorkspaceCompatibility'; -import { remoteWorkspaceIdentityMatches, remoteWorkspaceKey } from '../../services/RemoteSessionIdentity'; -import { TimeFormat } from '../../services/TimeFormat'; -import { ConversationSessionFilterPolicy } from './ConversationSessionFilterPolicy'; - -/** Everything the sidebar's grouping depends on. */ -export interface SessionListInputs { - sessions: RemoteSession[]; - query: string; - sortMode: string; - workspaceName: string; - workspacePath: string; - /** Stable record ID of the active workspace; absent on pre-ID hosts. */ - workspaceId?: string; - workspaceConnectionId?: string; - workspaceSshHost?: string; - workspaceKind: string; - recentWorkspaces: RecentWorkspaceEntry[]; - workspaceFilter: string; - agentFilter: string; - statusFilter: string; - showWorkspaceMetadata: boolean; - showUpdatedMetadata: boolean; - showStatusMetadata: boolean; -} - -/** - * The session list, already filtered, grouped and labelled. - * - * Every array here is shared, not copied, and must be treated as read-only: - * a cache hands the same instance to every caller until the inputs change. - */ -export interface SessionListProjection { - filtered: RemoteSession[]; - chats: RemoteSession[]; - byTime: RemoteSession[]; - today: RemoteSession[]; - yesterday: RemoteSession[]; - earlier: RemoteSession[]; - projects: RecentWorkspaceEntry[]; - /** Keyed by `remoteWorkspaceKey` of the owning project entry. */ - projectSessions: Map; - metadata: Map; - hasActiveFilter: boolean; -} - -const EMPTY_SESSIONS: RemoteSession[] = []; - -/** The catalog rows and current workspace, resolved once per projection. */ -interface WorkspaceAttribution { - /** Every reference the legacy resolver may attribute an ID-less session to. */ - catalog: RemoteWorkspaceIdentity[]; - /** Section keys of assistant-kind rows. */ - assistantKeys: Set; - /** The active workspace as a catalog row, when the host has one open. */ - current: RecentWorkspaceEntry | undefined; -} - -/** - * Turns the raw session list into the shape the sidebar renders, in one pass. - * - * The sidebar used to derive this inline, and its builders asked for the - * derived values rather than holding them: `filteredSessions()` alone was - * reached around twenty times per build — once per section header, once per - * project group, three times per row — and re-scanned the whole array every - * time, each scan re-deciding whether a session was an assistant session by - * searching the recent-workspace list again. Traced on device, one selection - * change spent 690ms inside the list's rerender with no child layout beneath - * it: all of it was this arithmetic, run again for inputs that had not moved. - */ -export class SessionListProjector { - static project(inputs: SessionListInputs): SessionListProjection { - const attribution = SessionListProjector.workspaceAttribution(inputs); - const hasActiveFilter = inputs.query.trim().length > 0 || inputs.workspaceFilter.length > 0 || - inputs.agentFilter.length > 0 || inputs.statusFilter.length > 0; - const wantsMetadata = inputs.showWorkspaceMetadata || inputs.showUpdatedMetadata || inputs.showStatusMetadata; - - const filtered: RemoteSession[] = []; - const chats: RemoteSession[] = []; - const projectSessions: Map = new Map(); - const metadata: Map = new Map(); - const nowMs = Date.now(); - const projectEntries = SessionListProjector.projectEntries(inputs, attribution); - // Sessions pinned to a workspace ID land in their section by one map - // lookup; only ID-less sessions pay for the legacy resolver. - const keysByWorkspaceId: Map = new Map(); - projectEntries.forEach((entry: RecentWorkspaceEntry) => { - if (entry.workspaceId) { - keysByWorkspaceId.set(entry.workspaceId, remoteWorkspaceKey(entry)); - } - }); - - inputs.sessions.forEach((item: RemoteSession) => { - // Decided once and carried through the rest of the pass. It is the - // expensive predicate — it searches the recent-workspace list — and it - // feeds the filter, the chat/project split and the agent grouping alike. - const assistant = SessionListProjector.isAssistantSession(item, inputs, attribution); - const matches = ConversationSessionFilterPolicy.matches( - item, - inputs.query, - inputs.workspacePath, - inputs.workspaceFilter, - inputs.agentFilter, - inputs.statusFilter, - assistant - ); - if (!matches) { - return; - } - filtered.push(item); - if (assistant) { - chats.push(item); - } else { - const key = SessionListProjector.sectionKey(item, inputs, attribution, projectEntries, keysByWorkspaceId); - const bucket = projectSessions.get(key); - if (bucket === undefined) { - projectSessions.set(key, [item]); - } else { - bucket.push(item); - } - } - if (wantsMetadata) { - metadata.set(item.id, SessionListProjector.metadataText(item, inputs, nowMs)); - } - }); - - const projects = SessionListProjector.visibleProjectEntries(projectEntries, hasActiveFilter, projectSessions); - // Sorting by time parses two timestamps per session per comparison, so it - // stays behind the mode that asks for it. - const byTime = inputs.sortMode === 'time' ? SessionListProjector.sortByTime(filtered) : EMPTY_SESSIONS; - - return { - filtered, - chats, - byTime, - today: SessionListProjector.bucket(byTime, 'today', nowMs), - yesterday: SessionListProjector.bucket(byTime, 'yesterday', nowMs), - earlier: SessionListProjector.bucket(byTime, 'earlier', nowMs), - projects, - projectSessions, - metadata, - hasActiveFilter - }; - } - - /** - * The sessions filed under a workspace, or an empty list when there are none. - * - * A reference with an ID reads its section directly. A pre-ID reference is - * attributed to a project entry through the legacy resolver first, so a - * trailing slash or a missing connection id cannot hide a section. - */ - static sessionsForProject(projection: SessionListProjection, workspace: RemoteWorkspaceIdentity): RemoteSession[] { - const direct = projection.projectSessions.get(remoteWorkspaceKey(workspace)); - if (direct !== undefined) { - return direct; - } - if (workspace.workspaceId) { - return EMPTY_SESSIONS; - } - const owner = projection.projects.find((entry: RecentWorkspaceEntry): boolean => - remoteWorkspaceIdentityMatches(workspace, entry, projection.projects)); - const bucket = owner === undefined ? undefined : projection.projectSessions.get(remoteWorkspaceKey(owner)); - return bucket === undefined ? EMPTY_SESSIONS : bucket; - } - - /** The key a project entry's section is filed under. */ - static sectionKeyFor(entry: RemoteWorkspaceIdentity): string { - return remoteWorkspaceKey(entry); - } - - static metadataFor(projection: SessionListProjection, sessionId: string): string { - const value = projection.metadata.get(sessionId); - return value === undefined ? '' : value; - } - - static empty(): SessionListProjection { - return { - filtered: EMPTY_SESSIONS, - chats: EMPTY_SESSIONS, - byTime: EMPTY_SESSIONS, - today: EMPTY_SESSIONS, - yesterday: EMPTY_SESSIONS, - earlier: EMPTY_SESSIONS, - projects: [], - projectSessions: new Map(), - metadata: new Map(), - hasActiveFilter: false - }; - } - - /** - * The active workspace as a catalog row. - * - * The page state may carry less than the catalog does — an older cache - * without the connection id, or a host that has not sent the ID — so an - * ID-less current workspace is completed from its unique catalog match. - */ - private static currentWorkspaceEntry(inputs: SessionListInputs): RecentWorkspaceEntry | undefined { - const workspaceId = inputs.workspaceId?.trim() || ''; - if (inputs.workspacePath.length === 0 && workspaceId.length === 0) { - return undefined; - } - const reference: RemoteWorkspaceIdentity = { - workspaceId: workspaceId.length > 0 ? workspaceId : undefined, - path: inputs.workspacePath, - remoteConnectionId: inputs.workspaceConnectionId?.trim() || undefined, - remoteSshHost: inputs.workspaceSshHost?.trim() || undefined - }; - const resolved = LegacyWorkspaceCompatibility.resolve(reference, inputs.recentWorkspaces); - return { - workspaceId: reference.workspaceId || resolved?.workspaceId, - path: inputs.workspacePath.length > 0 ? inputs.workspacePath : (resolved?.path || ''), - name: inputs.workspaceName, - remoteConnectionId: reference.remoteConnectionId !== undefined ? reference.remoteConnectionId : resolved?.remoteConnectionId, - remoteSshHost: reference.remoteSshHost !== undefined ? reference.remoteSshHost : resolved?.remoteSshHost, - lastOpened: '', - workspaceKind: inputs.workspaceKind.toLowerCase() === 'assistant' ? 'assistant' : 'normal' - }; - } - - private static workspaceAttribution(inputs: SessionListInputs): WorkspaceAttribution { - const current = SessionListProjector.currentWorkspaceEntry(inputs); - const catalog: RemoteWorkspaceIdentity[] = []; - const assistantKeys: Set = new Set(); - inputs.recentWorkspaces.forEach((item: RecentWorkspaceEntry) => { - catalog.push(item); - if (item.workspaceKind.toLowerCase() === 'assistant') { - assistantKeys.add(remoteWorkspaceKey(item)); - } - }); - if (current !== undefined) { - // The current workspace joins the catalog only when no row already - // names it; a duplicate would make every path lookup ambiguous. - const known = inputs.recentWorkspaces.some((item: RecentWorkspaceEntry): boolean => - remoteWorkspaceIdentityMatches(item, current, inputs.recentWorkspaces)); - if (!known) { - catalog.push(current); - } - if (current.workspaceKind === 'assistant') { - assistantKeys.add(remoteWorkspaceKey(current)); - } - } - return { catalog, assistantKeys, current }; - } - - /** - * Whether a reference names an assistant workspace. - * - * Kind is a fact of the catalog row, so the reference is attributed to its - * row first: by ID when it has one, otherwise through the legacy resolver. - * An unresolvable reference is not an assistant. - */ - private static isAssistantWorkspace(reference: RemoteWorkspaceIdentity, attribution: WorkspaceAttribution): boolean { - if (attribution.assistantKeys.size === 0) { - return false; - } - if (reference.workspaceId) { - return attribution.assistantKeys.has(remoteWorkspaceKey(reference)); - } - const resolved = LegacyWorkspaceCompatibility.resolve(reference, attribution.catalog); - return resolved !== undefined && attribution.assistantKeys.has(remoteWorkspaceKey(resolved)); - } - - private static isAssistantSession( - item: RemoteSession, - inputs: SessionListInputs, - attribution: WorkspaceAttribution - ): boolean { - const agentType = (item.agentType ? item.agentType : '').toLowerCase(); - if (agentType === 'claw' || agentType === 'assistant' || agentType === 'chat') { - return true; - } - if (item.workspaceIdentity) { - return SessionListProjector.isAssistantWorkspace(item.workspaceIdentity, attribution); - } - const path = item.workspacePath ? item.workspacePath : ''; - if (path.length === 0) { - return inputs.workspaceKind.toLowerCase() === 'assistant'; - } - return SessionListProjector.isAssistantWorkspace({ path }, attribution); - } - - /** The section a filtered, non-assistant session is filed under. */ - private static sectionKey( - item: RemoteSession, - inputs: SessionListInputs, - attribution: WorkspaceAttribution, - projectEntries: RecentWorkspaceEntry[], - keysByWorkspaceId: Map - ): string { - const identity = item.workspaceIdentity; - if (identity !== undefined && identity.workspaceId) { - const known = keysByWorkspaceId.get(identity.workspaceId); - // An ID the catalog does not list still keys its own section rather than - // being guessed onto a row by path. - return known === undefined ? remoteWorkspaceKey(identity) : known; - } - // Pre-ID sessions: a legacy reference, attributed to a row through the - // single compatibility resolver. Sessions that name no workspace at all - // belong to the workspace the list was fetched for. - const path = identity !== undefined ? identity.path : (item.workspacePath ? item.workspacePath : ''); - if (path.length === 0 && identity === undefined) { - return attribution.current !== undefined ? remoteWorkspaceKey(attribution.current) : - remoteWorkspaceKey({ path: inputs.workspacePath }); - } - const reference: RemoteWorkspaceIdentity = identity !== undefined ? identity : { path }; - const owner = projectEntries.find((entry: RecentWorkspaceEntry): boolean => - remoteWorkspaceIdentityMatches(reference, entry, attribution.catalog)); - if (owner !== undefined) { - return remoteWorkspaceKey(owner); - } - const resolved = LegacyWorkspaceCompatibility.resolve(reference, attribution.catalog); - return remoteWorkspaceKey(resolved !== undefined ? resolved : reference); - } - - private static projectEntries(inputs: SessionListInputs, attribution: WorkspaceAttribution): RecentWorkspaceEntry[] { - const entries: RecentWorkspaceEntry[] = []; - const current = attribution.current; - if (current !== undefined && current.workspaceKind !== 'assistant' && current.path.length > 0) { - entries.push(current); - } - inputs.recentWorkspaces.forEach((item: RecentWorkspaceEntry) => { - if (item.path.length === 0 || SessionListProjector.isAssistantWorkspace(item, attribution)) { - return; - } - if (entries.some((entry: RecentWorkspaceEntry) => remoteWorkspaceIdentityMatches(entry, item, attribution.catalog))) { - return; - } - entries.push(item); - }); - return entries; - } - - private static visibleProjectEntries( - entries: RecentWorkspaceEntry[], - hasActiveFilter: boolean, - projectSessions: Map - ): RecentWorkspaceEntry[] { - if (!hasActiveFilter) { - return entries; - } - // A filter narrow enough to empty a project takes that project's header off - // the list too, so the sidebar does not read as a wall of empty groups. - return entries.filter((item: RecentWorkspaceEntry) => { - const bucket = projectSessions.get(remoteWorkspaceKey(item)); - return bucket !== undefined && bucket.length > 0; - }); - } - - private static sortByTime(sessions: RemoteSession[]): RemoteSession[] { - // Timestamps are parsed once each and sorted alongside their session, rather - // than re-parsed inside the comparator for every comparison it makes. - const stamped: TimestampedSession[] = sessions.map((item: RemoteSession): TimestampedSession => { - return { session: item, timestamp: SessionListProjector.sessionTimestamp(item) }; - }); - stamped.sort((left: TimestampedSession, right: TimestampedSession) => right.timestamp - left.timestamp); - return stamped.map((item: TimestampedSession) => item.session); - } - - private static bucket(sessions: RemoteSession[], bucket: string, nowMs: number): RemoteSession[] { - if (sessions.length === 0) { - return EMPTY_SESSIONS; - } - return sessions.filter((item: RemoteSession) => SessionListProjector.timeBucket(item, nowMs) === bucket); - } - - private static timeBucket(item: RemoteSession, nowMs: number): string { - const timestamp = SessionListProjector.sessionTimestamp(item); - if (timestamp <= 0) { - return 'earlier'; - } - const sessionDate = new Date(timestamp); - const now = new Date(nowMs); - if (SessionListProjector.sameCalendarDay(sessionDate, now)) { - return 'today'; - } - const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1); - return SessionListProjector.sameCalendarDay(sessionDate, yesterday) ? 'yesterday' : 'earlier'; - } - - private static sessionTimestamp(item: RemoteSession): number { - const updated = TimeFormat.timestampMs(item.updatedAt ? item.updatedAt : ''); - if (!Number.isNaN(updated) && updated > 0) { - return updated; - } - const created = TimeFormat.timestampMs(item.createdAt ? item.createdAt : ''); - return !Number.isNaN(created) && created > 0 ? created : 0; - } - - private static sameCalendarDay(left: Date, right: Date): boolean { - return left.getFullYear() === right.getFullYear() && - left.getMonth() === right.getMonth() && - left.getDate() === right.getDate(); - } - - private static metadataText(item: RemoteSession, inputs: SessionListInputs, nowMs: number): string { - const values: string[] = []; - if (inputs.showWorkspaceMetadata) { - const workspace = item.workspaceName ? item.workspaceName : (item.workspacePath ? item.workspacePath : ''); - if (workspace.length > 0) { - values.push(workspace); - } - } - if (inputs.showUpdatedMetadata && !Number.isNaN(TimeFormat.timestampMs(item.updatedAt))) { - values.push(TimeFormat.relative(item.updatedAt, nowMs)); - } - if (inputs.showStatusMetadata && item.status.length > 0) { - values.push(item.status === 'archived' ? RemoteI18n.t('sidebar.archived') : item.status); - } - return values.join(' · '); - } -} - -interface TimestampedSession { - session: RemoteSession; - timestamp: number; -} - -/** - * Holds the last projection and rebuilds it only when its inputs move. - * - * The point of the cache is the selection change: picking a session rebuilds - * the sidebar's whole builder tree, but touches none of the inputs here, so the - * rerender becomes a property diff over lists that were already computed. - * - * The fast path is reference identity on the two arrays. When that misses — - * a caller handing out a freshly filtered array each build would defeat it — - * the contents are compared field by field, which is still one cheap pass - * instead of twenty expensive ones. - */ -export class SessionListProjectionCache { - private key: string = ''; - private sessionsRef: RemoteSession[] = EMPTY_SESSIONS; - private workspacesRef: RecentWorkspaceEntry[] = []; - private sessionFingerprint: string[] = []; - private workspaceFingerprint: string[] = []; - private projection: SessionListProjection = SessionListProjector.empty(); - - get(inputs: SessionListInputs): SessionListProjection { - const key = SessionListProjectionCache.scalarKey(inputs); - if (key === this.key && inputs.sessions === this.sessionsRef && - inputs.recentWorkspaces === this.workspacesRef) { - return this.projection; - } - const sessionFingerprint = SessionListProjectionCache.sessionFingerprint(inputs.sessions); - const workspaceFingerprint = SessionListProjectionCache.workspaceFingerprint(inputs.recentWorkspaces); - if (key === this.key && - SessionListProjectionCache.sameFingerprint(sessionFingerprint, this.sessionFingerprint) && - SessionListProjectionCache.sameFingerprint(workspaceFingerprint, this.workspaceFingerprint)) { - // Same contents behind a new array. Adopt the new references so the next - // call takes the identity fast path. - this.sessionsRef = inputs.sessions; - this.workspacesRef = inputs.recentWorkspaces; - return this.projection; - } - this.key = key; - this.sessionsRef = inputs.sessions; - this.workspacesRef = inputs.recentWorkspaces; - this.sessionFingerprint = sessionFingerprint; - this.workspaceFingerprint = workspaceFingerprint; - this.projection = SessionListProjector.project(inputs); - return this.projection; - } - - private static scalarKey(inputs: SessionListInputs): string { - // Relative timestamps are rendered from the projection, so when they are on - // screen the minute they were rendered in is part of what the projection - // depends on. Off — which is the default — nothing here moves on its own. - const minute = inputs.showUpdatedMetadata ? Math.floor(Date.now() / 60000) : 0; - return `${inputs.query}${inputs.sortMode}${inputs.workspaceName}${inputs.workspacePath}` + - `${inputs.workspaceId || ''}${inputs.workspaceConnectionId || ''}${inputs.workspaceSshHost || ''}` + - `${inputs.workspaceKind}${inputs.workspaceFilter}${inputs.agentFilter}` + - `${inputs.statusFilter}${inputs.showWorkspaceMetadata ? 1 : 0}` + - `${inputs.showUpdatedMetadata ? 1 : 0}${inputs.showStatusMetadata ? 1 : 0}${minute}`; - } - - private static sessionFingerprint(sessions: RemoteSession[]): string[] { - return sessions.map((item: RemoteSession): string => { - const identity = item.workspaceIdentity; - return `${item.deviceId || ''}${item.id}${item.title}${item.status}${item.agentType}` + - `${item.workspacePath}${item.workspaceName}${item.updatedAt}${item.createdAt}` + - `${identity === undefined ? '' : remoteWorkspaceKey(identity)}`; - }); - } - - private static workspaceFingerprint(entries: RecentWorkspaceEntry[]): string[] { - return entries.map((item: RecentWorkspaceEntry): string => { - return `${remoteWorkspaceKey(item)}${item.name}${item.workspaceKind}${item.remoteSshHost || ''}`; - }); - } - - private static sameFingerprint(left: string[], right: string[]): boolean { - if (left.length !== right.length) { - return false; - } - for (let index = 0; index < left.length; index++) { - if (left[index] !== right[index]) { - return false; - } - } - return true; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionRollbackPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionRollbackPolicy.ets deleted file mode 100644 index 83d2e089cf..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SessionRollbackPolicy.ets +++ /dev/null @@ -1,300 +0,0 @@ -import { REMOTE_CAPABILITY_SESSION_ROLLBACK_V1 } from '../../model/RemoteModels'; - -/** - * Whether a message can start a rollback, and what that rollback is allowed to do. - * - * The frozen interaction (plan decision 4) is staged: choosing "roll back to this - * message" sends nothing to the host. The timeline turns the target turn and - * everything after it into local ghost rows, a rollback bar appears above the - * composer, and the composer is refilled with the withdrawn prompt. Staging is - * memory-only, so a restart or a reconnect simply returns to the real timeline. - * - * Three exits, no confirmation dialog: - * - close: abandon the rollback; ghosts go back to real rows, and the refilled - * prompt is not kept — the composer returns to the snapshot taken when staging - * began; - * - send: roll the host back and then send the (possibly edited) text from that - * point, as two steps in that order; - * - confirm: run the rollback and keep the composer text to edit further. - * - * The policy is pure: it owns the decision and the state machine, and returns - * effects for the viewmodel to apply. It sends no command, reads no composer and - * touches no timeline, which is what keeps every exit host-testable. - */ - -/** Why the rollback entry is not offered on a message. */ -export enum RollbackEntryDenyReason { - /** The entry is offered. */ - None = 'none', - /** Only a user message can be a rollback target. */ - NotUserMessage = 'not_user_message', - /** A dispatch session's history belongs to the target host. */ - DispatchSession = 'dispatch_session', - /** The session is still running a turn; its history cannot change under it. */ - SessionBusy = 'session_busy', - /** The connected host does not advertise `session_rollback_v1`. */ - HostUnsupported = 'host_unsupported' -} - -export interface RollbackEntryRequest { - /** The message the entry belongs to. */ - isUserMessage: boolean; - /** Capability strings the connected host advertised in its handshake. */ - hostCapabilities: string[]; - /** True while a turn is running or a message is still queued. */ - sessionBusy: boolean; - /** True for a detached dispatch session. */ - isDispatchSession: boolean; -} - -export interface RollbackEntryDecision { - allowed: boolean; - reason: RollbackEntryDenyReason; -} - -/** The two states of the staged rollback. */ -export enum SessionRollbackStage { - Idle = 'idle', - Staging = 'staging' -} - -/** No rollback is staged. */ -export class SessionRollbackIdleState { - readonly stage: SessionRollbackStage = SessionRollbackStage.Idle; - /** Always empty while idle; staging carries the payload. */ - readonly targetTurnId: string = ''; - readonly targetText: string = ''; - readonly composerSnapshot: string = ''; -} - -/** - * A rollback is staged locally and has not reached the host. - * - * `targetTurnId` and `targetText` come from the user message the entry was - * opened on; `composerSnapshot` is the composer as it was before staging began, - * which is what closing restores. - */ -export class SessionRollbackStagingState { - readonly stage: SessionRollbackStage = SessionRollbackStage.Staging; - readonly targetTurnId: string; - readonly targetText: string; - readonly composerSnapshot: string; - - constructor(targetTurnId: string, targetText: string, composerSnapshot: string) { - this.targetTurnId = targetTurnId; - this.targetText = targetText; - this.composerSnapshot = composerSnapshot; - } -} - -/** The closed set of staging states; both shapes carry every field. */ -export type SessionRollbackState = SessionRollbackIdleState | SessionRollbackStagingState; - -/** What the user asked for, or what the host reported back. */ -export enum SessionRollbackEventType { - /** Open the entry for a user message: start staging it. */ - EnterStaging = 'enter_staging', - /** Abandon the staged rollback. */ - CloseStaging = 'close_staging', - /** Run the rollback and keep the current composer text. */ - ConfirmRollback = 'confirm_rollback', - /** Run the rollback, then send `text` from the withdrawn point. */ - SendWhileStaging = 'send_while_staging', - /** The host refused the rollback because the view it addresses moved on. */ - StaleViewDetected = 'stale_view_detected', - /** The rollback failed for any other reason. */ - RollbackFailed = 'rollback_failed' -} - -export interface SessionRollbackEvent { - type: SessionRollbackEventType; - /** `EnterStaging`: the user message being withdrawn. */ - targetTurnId?: string; - targetText?: string; - /** `EnterStaging`: the composer text from before staging began. */ - composerSnapshot?: string; - /** `SendWhileStaging`: the text to send once the rollback succeeded. */ - text?: string; -} - -/** What the viewmodel does for one transition. */ -export enum SessionRollbackEffectType { - /** Write `text` into the composer. */ - RefillComposer = 'refill_composer', - /** Put the composer back to `text`, the pre-staging snapshot. */ - RestoreComposerSnapshot = 'restore_composer_snapshot', - /** Leave the composer exactly as the user left it. */ - KeepComposerText = 'keep_composer_text', - /** Render the target turn and everything after it as local ghost rows. */ - ShowGhostRows = 'show_ghost_rows', - /** Drop the ghost rows and show the real transcript again. */ - ClearGhostRows = 'clear_ghost_rows', - /** Send `rollback_session_to_turn` for `targetTurnId`. */ - SendRollbackCommand = 'send_rollback_command', - /** Send `text` as a new message, after the rollback above succeeded. */ - SendMessageAfterRollback = 'send_message_after_rollback', - /** Surface a user-visible notice instead of failing silently. */ - ShowDegradeNotice = 'show_degrade_notice', - /** Reload the authoritative transcript from the host. */ - ResyncTimeline = 'resync_timeline' -} - -export interface SessionRollbackEffect { - type: SessionRollbackEffectType; - /** Composer payload, or the message for `SendMessageAfterRollback`. */ - text?: string; - /** The withdrawn turn, for the ghost preview and the command. */ - targetTurnId?: string; -} - -export interface SessionRollbackTransition { - state: SessionRollbackState; - effects: SessionRollbackEffect[]; -} - -export class SessionRollbackPolicy { - /** - * Decide whether the entry is offered. - * - * The order is the order the user can act on: a message that is not the - * user's own has no entry at all, a dispatch session cannot be rolled back by - * anyone, a busy session only needs to finish, and only then does the host's - * own version decide. Reporting an older host for a session that is merely - * busy would send the user to the wrong fix. - */ - static resolveRollbackEntry(request: RollbackEntryRequest): RollbackEntryDecision { - if (!request.isUserMessage) { - return { allowed: false, reason: RollbackEntryDenyReason.NotUserMessage }; - } - if (request.isDispatchSession) { - return { allowed: false, reason: RollbackEntryDenyReason.DispatchSession }; - } - if (request.sessionBusy) { - return { allowed: false, reason: RollbackEntryDenyReason.SessionBusy }; - } - if (!SessionRollbackPolicy.hostSupportsRollback(request.hostCapabilities)) { - return { allowed: false, reason: RollbackEntryDenyReason.HostUnsupported }; - } - return { allowed: true, reason: RollbackEntryDenyReason.None }; - } - - static initial(): SessionRollbackState { - return new SessionRollbackIdleState(); - } - - /** - * The whole staged-rollback state machine. - * - * `EnterStaging` is the only event that reads the composer's current value; - * every other event either leaves the composer alone or restores the snapshot. - * Staging a second message replaces the target and keeps the first snapshot, - * because closing must return the composer to where it was before staging - * began, not to where it was before the second entry. - */ - static reduce(state: SessionRollbackState, event: SessionRollbackEvent): SessionRollbackTransition { - const staging = state.stage === SessionRollbackStage.Staging; - switch (event.type) { - case SessionRollbackEventType.EnterStaging: - return SessionRollbackPolicy.enterStaging(state, staging, event); - case SessionRollbackEventType.CloseStaging: - if (!staging) { - return SessionRollbackPolicy.noop(state); - } - return { - state: new SessionRollbackIdleState(), - effects: [ - { type: SessionRollbackEffectType.ClearGhostRows }, - { type: SessionRollbackEffectType.RestoreComposerSnapshot, text: state.composerSnapshot } - ] - }; - case SessionRollbackEventType.ConfirmRollback: - if (!staging) { - return SessionRollbackPolicy.noop(state); - } - return { - state: new SessionRollbackIdleState(), - effects: [ - { type: SessionRollbackEffectType.SendRollbackCommand, targetTurnId: state.targetTurnId }, - { type: SessionRollbackEffectType.ClearGhostRows }, - { type: SessionRollbackEffectType.KeepComposerText } - ] - }; - case SessionRollbackEventType.SendWhileStaging: - if (!staging) { - return SessionRollbackPolicy.noop(state); - } - // Two steps, in this order: the host retires the turn first, and the new - // message is sent from the withdrawn point. A rollback that succeeds and - // a send that fails is recoverable — staging is over and the draft stays. - return { - state: new SessionRollbackIdleState(), - effects: [ - { type: SessionRollbackEffectType.SendRollbackCommand, targetTurnId: state.targetTurnId }, - { type: SessionRollbackEffectType.SendMessageAfterRollback, text: event.text || '' }, - { type: SessionRollbackEffectType.ClearGhostRows } - ] - }; - case SessionRollbackEventType.StaleViewDetected: - return { - state: new SessionRollbackIdleState(), - effects: SessionRollbackPolicy.hostOutcomeEffects(staging, false) - }; - case SessionRollbackEventType.RollbackFailed: - return { - state: new SessionRollbackIdleState(), - effects: SessionRollbackPolicy.hostOutcomeEffects(staging, true) - }; - default: - return SessionRollbackPolicy.noop(state); - } - } - - private static enterStaging( - state: SessionRollbackState, - staging: boolean, - event: SessionRollbackEvent - ): SessionRollbackTransition { - const snapshot = staging ? state.composerSnapshot : (event.composerSnapshot || ''); - const target = new SessionRollbackStagingState( - event.targetTurnId || '', - event.targetText || '', - snapshot - ); - return { - state: target, - effects: [ - { type: SessionRollbackEffectType.RefillComposer, text: target.targetText }, - { type: SessionRollbackEffectType.ShowGhostRows, targetTurnId: target.targetTurnId } - ] - }; - } - - /** - * A host outcome is meaningful in either state: confirm and send leave staging - * before the host answers, so a refusal arrives while the client is already - * idle and must still repair the transcript instead of being swallowed. - */ - private static hostOutcomeEffects(staging: boolean, notice: boolean): SessionRollbackEffect[] { - const effects: SessionRollbackEffect[] = []; - if (staging) { - effects.push({ type: SessionRollbackEffectType.ClearGhostRows }); - } - effects.push({ type: SessionRollbackEffectType.ResyncTimeline }); - if (notice) { - effects.push({ type: SessionRollbackEffectType.ShowDegradeNotice }); - } - return effects; - } - - private static noop(state: SessionRollbackState): SessionRollbackTransition { - return { state: state, effects: [] }; - } - - /** - * The capability is matched as the exact advertised string, the same way - * `supportsHostCapability` does: a near-miss is a different promise. - */ - private static hostSupportsRollback(capabilities: string[]): boolean { - return (capabilities || []).indexOf(REMOTE_CAPABILITY_SESSION_ROLLBACK_V1) >= 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPagePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPagePolicy.ets deleted file mode 100644 index 25f4e99e3d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPagePolicy.ets +++ /dev/null @@ -1,12 +0,0 @@ -export type SettingsPage = 'settings' | 'login'; - -/** - * Settings is a single page: account, current control, remote permission mode, - * general preferences, devices and about sit on it inline. Only a signed-out - * account request leaves that page for the separate login step. - */ -export class SettingsPagePolicy { - static resolve(accountRequested: boolean, authenticated: boolean): SettingsPage { - return accountRequested && !authenticated ? 'login' : 'settings'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPlacementPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPlacementPolicy.ets deleted file mode 100644 index c6bb42db65..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SettingsPlacementPolicy.ets +++ /dev/null @@ -1,332 +0,0 @@ -import { AdaptiveLayoutInput } from './AdaptiveLayoutInput'; -import { - ConversationLayoutCrease, - ConversationLayoutHorizontalCrease, - ConversationLayoutPolicy -} from './ConversationLayoutPolicy'; - -export enum SettingsPlacementMode { - Bottom = 'bottom', - Center = 'center', - Side = 'side', - FoldOperate = 'fold_operate' -} - -export enum SettingsSheetKind { - Settings = 'settings', - Connect = 'connect', - SessionDetails = 'session_details', - RemoteViewSettings = 'remote_view_settings', - /** - * The conversation's full-text panel. It is content rather than settings, but - * it is placed by the same contract: an overlay sheet that must land inside a - * foldable's leaf, and inside the operate half of a half-folded screen. - */ - UserMessageFullText = 'user_message_full_text', - /** - * The composer's skill picker. Same reasoning as the full-text panel: it is a - * large multi-step surface opened from the conversation, not an anchored menu, - * so a bottom sheet is its compact form and the placement contract decides - * where it lands on a folded or wide screen. - */ - SkillPicker = 'skill_picker', - /** The composer's session usage report: a read-only metrics list. */ - UsageReport = 'usage_report' -} - -export class SettingsPlacement { - readonly mode: SettingsPlacementMode; - readonly width: number; - readonly height: number; - readonly maxHeight: number; - - constructor( - mode: SettingsPlacementMode, - width: number, - height: number, - maxHeight: number - ) { - this.mode = mode; - this.width = width; - this.height = height; - this.maxHeight = maxHeight; - } -} - -/** - * Overlay-sheet placement from fold posture and creases, not a width boolean. - * Does not import ArkUI types; callers assemble SheetOptions. - */ -export class SettingsPlacementPolicy { - static readonly TABLET_MIN_WIDTH: number = 400; - static readonly TABLET_MAX_WIDTH: number = 520; - static readonly TABLET_WIDTH_RATIO: number = 0.32; - static readonly CONNECT_CENTER_WIDTH_RATIO: number = 0.72; - static readonly LANDSCAPE_WIDTH_RATIO: number = 0.45; - static readonly SIDE_MAX_HEIGHT: number = 760; - static readonly SIDE_MIN_HEIGHT: number = 560; - static readonly SIDE_VERTICAL_MARGIN: number = 80; - static readonly SESSION_DETAILS_HEIGHT: number = 560; - static readonly REMOTE_VIEW_SETTINGS_HEIGHT: number = 520; - /** The skill picker's share of a phone screen, per its approved design. */ - static readonly SKILL_PICKER_HEIGHT: number = 540; - static readonly USAGE_REPORT_HEIGHT: number = 560; - - static compactBottom(kind: SettingsSheetKind = SettingsSheetKind.Settings): SettingsPlacement { - return SettingsPlacementPolicy.bottomPlacement(kind); - } - - static resolve(input: AdaptiveLayoutInput, kind: SettingsSheetKind): SettingsPlacement { - // Settings and profile are one continuous page. Keep that workflow on a - // full-width bottom sheet at every width, even when it crosses a fold. - if (kind === SettingsSheetKind.Settings) { - return SettingsPlacementPolicy.bottomPlacement(kind); - } - if (kind === SettingsSheetKind.Connect && - input.isExpandedFoldable && - !input.isFolded && - SettingsPlacementPolicy.canUseSideSheet(input)) { - const horizontal = SettingsPlacementPolicy.firstUsableHorizontalCrease( - input.viewportHeight, - input.horizontalCreases - ); - if (input.isHoverOperate && horizontal) { - return SettingsPlacementPolicy.foldOperatePlacement(input, kind, horizontal); - } - return SettingsPlacementPolicy.connectCenterPlacement(input); - } - if (input.isHoverOperate) { - return SettingsPlacementPolicy.hoverPlacement(input, kind); - } - if (input.isFolded) { - return SettingsPlacementPolicy.bottomPlacement(kind); - } - return SettingsPlacementPolicy.creaseFreeOrSidePlacement(input, kind); - } - - /** - * ArkUI SheetType.SIDE docks to the trailing edge: right in LTR, left in RTL. - * There is no left/right switch on SheetOptions. - */ - static sheetLeft( - placement: SettingsPlacement, - viewportWidth: number, - isRtl: boolean = false - ): number { - if (placement.mode !== SettingsPlacementMode.Side || placement.width <= 0 || viewportWidth <= 0) { - return 0; - } - return isRtl ? 0 : Math.max(0, viewportWidth - placement.width); - } - - static sheetIntersectsVerticalCrease( - placement: SettingsPlacement, - crease: ConversationLayoutCrease, - viewportWidth: number, - isRtl: boolean = false - ): boolean { - if (placement.mode !== SettingsPlacementMode.Side || placement.width <= 0 || viewportWidth <= 0) { - return false; - } - const sheetLeft = SettingsPlacementPolicy.sheetLeft(placement, viewportWidth, isRtl); - const sheetRight = sheetLeft + placement.width; - const creaseRight = crease.left + crease.width; - return sheetLeft < creaseRight && sheetRight > crease.left; - } - - private static creaseSidePlacement( - input: AdaptiveLayoutInput, - kind: SettingsSheetKind, - usableCreases: ConversationLayoutCrease[] - ): SettingsPlacement { - const crease = input.isRtl ? - usableCreases[0] : usableCreases[usableCreases.length - 1]; - const width = input.isRtl ? - Math.max(0, crease.left) : - Math.max(0, input.viewportWidth - crease.left - crease.width); - const height = SettingsPlacementPolicy.kindSideHeight(input.viewportHeight, kind); - return new SettingsPlacement(SettingsPlacementMode.Side, width, height, 0); - } - - private static tabletSidePlacement( - input: AdaptiveLayoutInput, - kind: SettingsSheetKind - ): SettingsPlacement { - const ratioWidth = Math.round(input.viewportWidth * SettingsPlacementPolicy.TABLET_WIDTH_RATIO); - const clamped = Math.min( - SettingsPlacementPolicy.TABLET_MAX_WIDTH, - Math.max(SettingsPlacementPolicy.TABLET_MIN_WIDTH, ratioWidth) - ); - const width = Math.min(input.viewportWidth, clamped); - const height = SettingsPlacementPolicy.kindSideHeight(input.viewportHeight, kind); - return new SettingsPlacement(SettingsPlacementMode.Side, width, height, 0); - } - - private static connectCenterPlacement(input: AdaptiveLayoutInput): SettingsPlacement { - const ratioWidth = Math.round( - input.viewportWidth * SettingsPlacementPolicy.CONNECT_CENTER_WIDTH_RATIO - ); - const clamped = Math.min( - SettingsPlacementPolicy.TABLET_MAX_WIDTH, - Math.max(SettingsPlacementPolicy.TABLET_MIN_WIDTH, ratioWidth) - ); - const width = Math.min(input.viewportWidth, clamped); - const height = SettingsPlacementPolicy.kindSideHeight( - input.viewportHeight, - SettingsSheetKind.Connect - ); - return new SettingsPlacement(SettingsPlacementMode.Center, width, height, 0); - } - - private static landscapeSidePlacement( - input: AdaptiveLayoutInput, - kind: SettingsSheetKind - ): SettingsPlacement { - const width = Math.round(input.viewportWidth * SettingsPlacementPolicy.LANDSCAPE_WIDTH_RATIO); - const height = SettingsPlacementPolicy.kindSideHeight(input.viewportHeight, kind); - return new SettingsPlacement(SettingsPlacementMode.Side, width, height, 0); - } - - private static hoverPlacement( - input: AdaptiveLayoutInput, - kind: SettingsSheetKind - ): SettingsPlacement { - const horizontal = SettingsPlacementPolicy.firstUsableHorizontalCrease( - input.viewportHeight, - input.horizontalCreases - ); - if (horizontal) { - return SettingsPlacementPolicy.foldOperatePlacement(input, kind, horizontal); - } - return SettingsPlacementPolicy.creaseFreeOrSidePlacement(input, kind); - } - - private static creaseFreeOrSidePlacement( - input: AdaptiveLayoutInput, - kind: SettingsSheetKind - ): SettingsPlacement { - const usableCreases = SettingsPlacementPolicy.usableVerticalCreases( - input.viewportWidth, - input.verticalCreases - ); - if (usableCreases.length > 0 && SettingsPlacementPolicy.canUseSideSheet(input)) { - return SettingsPlacementPolicy.creaseSidePlacement(input, kind, usableCreases); - } - if (SettingsPlacementPolicy.isHeightScarceLandscape(input) && - SettingsPlacementPolicy.canUseSideSheet(input)) { - return SettingsPlacementPolicy.landscapeSidePlacement(input, kind); - } - if (SettingsPlacementPolicy.isWideViewport(input) && - SettingsPlacementPolicy.canUseSideSheet(input)) { - return SettingsPlacementPolicy.tabletSidePlacement(input, kind); - } - return SettingsPlacementPolicy.bottomPlacement(kind); - } - - private static foldOperatePlacement( - input: AdaptiveLayoutInput, - kind: SettingsSheetKind, - crease: ConversationLayoutHorizontalCrease - ): SettingsPlacement { - const maxHeight = Math.max(0, input.viewportHeight - crease.top - crease.height); - const height = SettingsPlacementPolicy.kindOperateHeight(maxHeight, kind); - return new SettingsPlacement(SettingsPlacementMode.FoldOperate, 0, height, maxHeight); - } - - private static bottomPlacement(kind: SettingsSheetKind): SettingsPlacement { - return new SettingsPlacement(SettingsPlacementMode.Bottom, 0, SettingsPlacementPolicy.bottomHeight(kind), 0); - } - - private static bottomHeight(kind: SettingsSheetKind): number { - if (kind === SettingsSheetKind.RemoteViewSettings) { - return SettingsPlacementPolicy.REMOTE_VIEW_SETTINGS_HEIGHT; - } - if (kind === SettingsSheetKind.SkillPicker) { - return SettingsPlacementPolicy.SKILL_PICKER_HEIGHT; - } - if (kind === SettingsSheetKind.UsageReport) { - return SettingsPlacementPolicy.USAGE_REPORT_HEIGHT; - } - return 0; - } - - private static kindSideHeight(viewportHeight: number, kind: SettingsSheetKind): number { - const computed = SettingsPlacementPolicy.sideHeight(viewportHeight); - if (kind === SettingsSheetKind.SessionDetails) { - return Math.min(SettingsPlacementPolicy.SESSION_DETAILS_HEIGHT, computed); - } - if (kind === SettingsSheetKind.RemoteViewSettings) { - return Math.min(SettingsPlacementPolicy.REMOTE_VIEW_SETTINGS_HEIGHT, computed); - } - return computed; - } - - private static kindOperateHeight(maxHeight: number, kind: SettingsSheetKind): number { - if (kind === SettingsSheetKind.RemoteViewSettings) { - return Math.min(SettingsPlacementPolicy.REMOTE_VIEW_SETTINGS_HEIGHT, maxHeight); - } - if (kind === SettingsSheetKind.SessionDetails) { - return Math.min(SettingsPlacementPolicy.SESSION_DETAILS_HEIGHT, maxHeight); - } - return maxHeight; - } - - private static sideHeight(viewportHeight: number): number { - if (viewportHeight <= 0) { - return SettingsPlacementPolicy.SIDE_MAX_HEIGHT; - } - return Math.min( - SettingsPlacementPolicy.SIDE_MAX_HEIGHT, - Math.max( - SettingsPlacementPolicy.SIDE_MIN_HEIGHT, - Math.round(viewportHeight - SettingsPlacementPolicy.SIDE_VERTICAL_MARGIN) - ) - ); - } - - private static canUseSideSheet(input: AdaptiveLayoutInput): boolean { - return input.viewportWidth >= ConversationLayoutPolicy.MD_MIN_WIDTH; - } - - private static isWideViewport(input: AdaptiveLayoutInput): boolean { - return input.wideLayoutMatched || - input.viewportWidth >= ConversationLayoutPolicy.MD_MIN_WIDTH; - } - - private static isHeightScarceLandscape(input: AdaptiveLayoutInput): boolean { - return input.viewportWidth > input.viewportHeight && - input.viewportHeight > 0 && - input.viewportHeight < ConversationLayoutPolicy.MD_MIN_WIDTH; - } - - private static usableVerticalCreases( - viewportWidth: number, - creases: ConversationLayoutCrease[] - ): ConversationLayoutCrease[] { - return creases - .filter((crease: ConversationLayoutCrease): boolean => { - return crease.left > 0 && - crease.width >= 0 && - crease.left + crease.width < viewportWidth; - }) - .sort((left: ConversationLayoutCrease, right: ConversationLayoutCrease): number => { - return left.left - right.left; - }); - } - - private static firstUsableHorizontalCrease( - viewportHeight: number, - creases: ConversationLayoutHorizontalCrease[] - ): ConversationLayoutHorizontalCrease | undefined { - const usable = creases - .filter((crease: ConversationLayoutHorizontalCrease): boolean => { - return crease.top > 0 && - crease.height >= 0 && - crease.top + crease.height < viewportHeight; - }) - .sort((left: ConversationLayoutHorizontalCrease, right: ConversationLayoutHorizontalCrease): number => { - return left.top - right.top; - }); - return usable.length > 0 ? usable[0] : undefined; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarConnectionActionPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarConnectionActionPolicy.ets deleted file mode 100644 index 9b88cdac47..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarConnectionActionPolicy.ets +++ /dev/null @@ -1,31 +0,0 @@ -/** Presentation rules for account-independent sidebar entry and navigation. */ -export type SidebarChatAction = 'assistant' | 'choose-harness' | 'code'; - -export class SidebarConnectionActionPolicy { - /** Match mobile-web: assistant chat, supported harness chooser, or legacy code chat. */ - static chatAction(workspaceKind: string, supportsHarnessProfiles: boolean): SidebarChatAction { - if (workspaceKind === 'assistant') return 'assistant'; - return supportsHarnessProfiles ? 'choose-harness' : 'code'; - } - - static canCreateSession(connectionState: string, isBusy: boolean): boolean { - return connectionState === 'connected' && !isBusy; - } - - /** - * Account identity is optional once a remote control target exists. A legacy - * QR room persisted by an older version therefore still unlocks the same chat/settings shell as an account device, - * including while that remembered target is temporarily reconnecting. - */ - static shouldShowPrimaryNavigation( - accountUserId: string, - controlTargetType: string, - connectionState: string - ): boolean { - return accountUserId.trim().length > 0 || - controlTargetType === 'room' || - controlTargetType === 'account_device' || - connectionState === 'connected' || - connectionState === 'reconnecting'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDeviceProjectionPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDeviceProjectionPolicy.ets deleted file mode 100644 index 24adfdbfb2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDeviceProjectionPolicy.ets +++ /dev/null @@ -1,19 +0,0 @@ -/** Merges the active control target into the account-backed device directory. */ -export class SidebarDeviceProjectionPolicy { - static shouldPrependControlTarget( - directoryDeviceIds: string[], - controlTargetType: string, - controlTargetDeviceId: string, - connectionVisible: boolean, - hasRemoteContent: boolean - ): boolean { - const targetId = controlTargetDeviceId.trim(); - if (controlTargetType === 'none' || targetId.length === 0) { - return false; - } - if (directoryDeviceIds.some((deviceId: string): boolean => deviceId === targetId)) { - return false; - } - return connectionVisible || hasRemoteContent; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDirectoryPreviewPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDirectoryPreviewPolicy.ets deleted file mode 100644 index f2ad24ac73..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/SidebarDirectoryPreviewPolicy.ets +++ /dev/null @@ -1,54 +0,0 @@ -/** - * How many children a sidebar directory row shows before "N more". - * - * Device → workspaces and workspace → sessions use the same batch so - * opening a group never dumps the full list. Each "more" tap adds one batch. - */ -export class SidebarDirectoryPreviewPolicy { - static readonly PREVIEW_COUNT: number = 3; - - static visibleSlice(items: T[], visibleCount: number): T[] { - const limit = Math.max(0, visibleCount); - return items.length <= limit ? items : items.slice(0, limit); - } - - static hiddenCount(total: number, visibleCount: number): number { - return Math.max(0, total - Math.max(0, visibleCount)); - } - - static nextVisibleCount(visibleCount: number, total: number): number { - return Math.min(total, Math.max(0, visibleCount) + SidebarDirectoryPreviewPolicy.PREVIEW_COUNT); - } - - /** - * Session trees are lazy at every surface: a workspace starts folded and - * its session RPC begins only after the user explicitly opens that row. - */ - static workspaceExpandedByDefault(_deviceHeaderVisible: boolean): boolean { - return false; - } - - /** - * ArkUI keeps a ForEach child's local state by key. Use the device plus a - * canonical remote path so two devices never share disclosure state and a - * harmless trailing slash does not destroy and recreate the row. - */ - static workspaceKey(deviceId: string, path: string): string { - let normalizedPath = path.trim(); - while (normalizedPath.length > 1 && - (normalizedPath.endsWith('/') || normalizedPath.endsWith('\\'))) { - normalizedPath = normalizedPath.slice(0, normalizedPath.length - 1); - } - return `${deviceId.trim()}:${normalizedPath}`; - } -} - -export class SidebarPreviewCursor { - readonly path: string; - readonly visibleCount: number; - - constructor(path: string, visibleCount: number) { - this.path = path; - this.visibleCount = visibleCount; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ThinkingPresentationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ThinkingPresentationPolicy.ets deleted file mode 100644 index 37a84f7442..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ThinkingPresentationPolicy.ets +++ /dev/null @@ -1,86 +0,0 @@ -export class ThinkingPresentationPolicy { - static readonly RUNNING_DOT_COUNT: number = 3; - static readonly RUNNING_DOT_WIDTH: number = 6; - static readonly RUNNING_DOT_GAP: number = 6; - - static runningDotsWidth(): number { - return ThinkingPresentationPolicy.RUNNING_DOT_WIDTH * ThinkingPresentationPolicy.RUNNING_DOT_COUNT + - ThinkingPresentationPolicy.RUNNING_DOT_GAP * (ThinkingPresentationPolicy.RUNNING_DOT_COUNT - 1); - } - - static isRunning(status: string): boolean { - const normalized = (status || '').toLowerCase(); - return normalized === 'active' || normalized === 'running'; - } - - static shouldRender(status: string, text: string): boolean { - if (ThinkingPresentationPolicy.isRunning(status)) { - return true; - } - return text.trim().length > 0; - } - - static defaultExpanded(isRunning: boolean, keepExpandedWhenDone: boolean): boolean { - return isRunning || keepExpandedWhenDone; - } - - static allowsToggle(hasBody: boolean): boolean { - return hasBody; - } - - /** - * Option 2: the live thinking block starts expanded. The user may collapse it - * while it streams. Completing always folds it back unless keepExpandedWhenDone. - */ - static expandedForStatus( - isRunning: boolean, - keepExpandedWhenDone: boolean, - userToggled: boolean, - currentlyExpanded: boolean - ): boolean { - if (!isRunning) { - return keepExpandedWhenDone; - } - if (userToggled) { - return currentlyExpanded; - } - return true; - } - - static liveThinkingStatus(messageStatus: string, hasLaterOutput: boolean): string { - if (hasLaterOutput) { - return 'done'; - } - return messageStatus; - } - - static mergedText(parts: string[]): string { - const kept: string[] = []; - parts.forEach((part: string) => { - const text = (part || '').trim(); - if (text.length > 0) { - kept.push(text); - } - }); - return kept.join('\n\n'); - } - - static mergedStatusValue(statuses: string[], streamings: boolean[]): string { - const count = statuses.length > streamings.length ? statuses.length : streamings.length; - for (let index = count - 1; index >= 0; index--) { - const streaming = index < streamings.length ? streamings[index] : false; - const status = index < statuses.length ? statuses[index] : ''; - if (streaming || ThinkingPresentationPolicy.isRunning(status)) { - return status.length > 0 ? status : 'active'; - } - } - if (statuses.length > 0 && statuses[statuses.length - 1].length > 0) { - return statuses[statuses.length - 1]; - } - return 'done'; - } - - static mergedStreaming(streamings: boolean[]): boolean { - return streamings.some((streaming: boolean) => streaming); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets deleted file mode 100644 index 36b0b7c7b7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolCollapsePolicy.ets +++ /dev/null @@ -1,117 +0,0 @@ -import { ConversationUiToolStatus } from '../state/ConversationUiModels'; -import { PlanToolPolicy } from './PlanToolPolicy'; - -export class ToolCollapseGroup { - readonly type: string; - readonly startIndex: number; - readonly tools: ConversationUiToolStatus[]; - - constructor(type: string, startIndex: number, tools: ConversationUiToolStatus[]) { - this.type = type; - this.startIndex = startIndex; - this.tools = tools; - } -} - -export class ToolCollapsePolicy { - static readonly MIN_SUMMARY_COUNT: number = 2; - - static shouldFoldIntoSummary(tool: ConversationUiToolStatus): boolean { - if (PlanToolPolicy.isPlanTool(tool) || - ToolCollapsePolicy.isPending(tool) || - ToolCollapsePolicy.isQuestion(tool) || - ToolCollapsePolicy.isRunning(tool)) { - return false; - } - return ToolCollapsePolicy.isCompleted(tool) || ToolCollapsePolicy.isCancelled(tool) || - ToolCollapsePolicy.hasError(tool); - } - - static collapsedGroups(tools: ConversationUiToolStatus[]): ToolCollapseGroup[] { - return ToolCollapsePolicy.groupTools(tools, false); - } - - static expandedGroups(tools: ConversationUiToolStatus[]): ToolCollapseGroup[] { - return ToolCollapsePolicy.groupTools(tools, true); - } - - private static groupTools( - tools: ConversationUiToolStatus[], - includeMembers: boolean - ): ToolCollapseGroup[] { - const groups: ToolCollapseGroup[] = []; - let folded: ConversationUiToolStatus[] = []; - let foldedStart = 0; - tools.forEach((tool: ConversationUiToolStatus, index: number) => { - if (ToolCollapsePolicy.shouldFoldIntoSummary(tool)) { - if (folded.length === 0) { - foldedStart = index; - } - folded.push(tool); - return; - } - ToolCollapsePolicy.flushFolded(groups, folded, foldedStart, includeMembers); - folded = []; - groups.push(new ToolCollapseGroup('tool', index, [tool])); - }); - ToolCollapsePolicy.flushFolded(groups, folded, foldedStart, includeMembers); - return groups; - } - - private static flushFolded( - groups: ToolCollapseGroup[], - tools: ConversationUiToolStatus[], - startIndex: number, - includeMembers: boolean - ): void { - if (tools.length === 0) { - return; - } - if (tools.length < ToolCollapsePolicy.MIN_SUMMARY_COUNT) { - tools.forEach((tool: ConversationUiToolStatus, offset: number) => { - groups.push(new ToolCollapseGroup('tool', startIndex + offset, [tool])); - }); - return; - } - groups.push(new ToolCollapseGroup('summary', startIndex, tools)); - if (includeMembers) { - tools.forEach((tool: ConversationUiToolStatus, offset: number) => { - groups.push(new ToolCollapseGroup('tool', startIndex + offset, [tool])); - }); - } - } - - private static isRunning(tool: ConversationUiToolStatus): boolean { - const normalized = (tool.status || '').toLowerCase(); - return normalized === 'running' || normalized === 'active'; - } - - private static isCompleted(tool: ConversationUiToolStatus): boolean { - const normalized = (tool.status || '').toLowerCase(); - return normalized === 'completed' || normalized === 'done' || normalized === 'success'; - } - - private static isCancelled(tool: ConversationUiToolStatus): boolean { - const normalized = (tool.status || '').toLowerCase(); - return normalized === 'cancelled' || normalized === 'canceled'; - } - - private static isPending(tool: ConversationUiToolStatus): boolean { - const normalized = (tool.status || '').toLowerCase(); - return normalized === 'pending' || normalized === 'queued' || - normalized === 'pending_confirmation' || normalized === 'needs_confirmation'; - } - - private static isQuestion(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = raw.replace(/[\s-]/g, '_').toLowerCase(); - return raw === 'AskUserQuestion' || normalized === 'askuserquestion' || - normalized === 'ask_user_question'; - } - - private static hasError(tool: ConversationUiToolStatus): boolean { - const normalized = (tool.status || '').toLowerCase(); - return normalized === 'failed' || normalized === 'error' || normalized === 'timeout' || - (tool.error_preview || '').length > 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolFileReferenceResolver.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolFileReferenceResolver.ets deleted file mode 100644 index 2de57cceba..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolFileReferenceResolver.ets +++ /dev/null @@ -1,66 +0,0 @@ -export interface ToolFileInputPayload { - path?: string; - file_path?: string; - filePath?: string; -} - -export class ToolFileReference { - readonly path: string; - readonly label: string; - - constructor(path: string, label: string) { - this.path = path; - this.label = label; - } -} - -export class ToolFileReferenceResolver { - static resolve( - toolName: string, - toolInput?: Object, - inputPreview: string = '' - ): ToolFileReference | undefined { - if (!ToolFileReferenceResolver.supportsTool(toolName)) { - return undefined; - } - const payload = ToolFileReferenceResolver.payload(toolInput, inputPreview); - const path = (payload.file_path || payload.filePath || payload.path || '').trim(); - if (path.length === 0 || path.endsWith('/') || path.endsWith('\\')) { - return undefined; - } - return new ToolFileReference(path, ToolFileReferenceResolver.basename(path)); - } - - private static payload(toolInput?: Object, inputPreview: string = ''): ToolFileInputPayload { - if (toolInput) { - try { - return JSON.parse(JSON.stringify(toolInput)) as ToolFileInputPayload; - } catch (_err) { - } - } - const preview = inputPreview.trim(); - if (preview.length > 0 && preview.indexOf('{') === 0) { - try { - return JSON.parse(preview) as ToolFileInputPayload; - } catch (_err) { - } - } - return {}; - } - - private static supportsTool(toolName: string): boolean { - const normalized = toolName.replace(/[\s-]/g, '_').toLowerCase(); - return '|read|read_file|write|write_file|create|create_file|edit|edit_file|file_edit|strreplace|str_replace|str_replace_editor|replace|replace_file|update_file|'.indexOf(`|${normalized}|`) >= 0; - } - - private static basename(path: string): string { - let normalized = path.replace(/^computer:\/\//, '').replace(/^file:\/\//, '').replace(/\\/g, '/'); - const hash = normalized.lastIndexOf('#'); - if (hash > 0) { - normalized = normalized.slice(0, hash); - } - normalized = normalized.replace(/:\d+(?:-\d+)?$/, ''); - const parts = normalized.split('/'); - return parts[parts.length - 1] || normalized || 'file'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolStatusPresentationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolStatusPresentationPolicy.ets deleted file mode 100644 index a027149ba9..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ToolStatusPresentationPolicy.ets +++ /dev/null @@ -1,301 +0,0 @@ -import { ConversationUiToolStatus } from '../state/ConversationUiModels'; - -interface QuestionPreview { - header?: string; - question?: string; -} - -interface QuestionPreviewPayload { - question?: string; - prompt?: string; - questions?: QuestionPreview[]; -} - -interface TaskPreviewPayload { - description?: string; - task?: string; - task_name?: string; - taskName?: string; - prompt?: string; - message?: string; - content?: string; - title?: string; - name?: string; -} - -/** Pure tool classification and payload projection used by the ArkUI renderer. */ -export class ToolStatusPresentationPolicy { - static normalizedName(tool: ConversationUiToolStatus): string { - const raw = (tool.name || '').trim(); - return (raw.length > 0 ? raw : 'Tool').replace(/[\s-]/g, '_').toLowerCase(); - } - - static isQuestionLike(tool: ConversationUiToolStatus): boolean { - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return ToolStatusPresentationPolicy.isQuestion(tool) || - normalized === 'askuserquestion' || normalized === 'ask_user_question'; - } - - static isTodo(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.normalizedName(tool).indexOf('todo') >= 0; - } - - static isTask(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.normalizedName(tool) === 'task'; - } - - static isDirectoryList(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'LS' || normalized === 'ls' || normalized === 'list_directory'; - } - - static isFileRead(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'Read' || raw === 'LS' || - ToolStatusPresentationPolicy.matches(normalized, ['read', 'read_file', 'ls', 'list_directory']); - } - - static isFileMutation(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return ToolStatusPresentationPolicy.matches(raw, [ - 'Write', 'Create', 'Edit', 'MultiEdit', 'StrReplace', 'ApplyPatch', 'Patch', 'Delete', 'GetFileDiff' - ]) || ToolStatusPresentationPolicy.matches(normalized, [ - 'write', 'write_file', 'create_file', 'edit', 'edit_file', 'file_edit', 'multi_edit', 'multiedit', - 'strreplace', 'str_replace', 'str_replace_editor', 'replace', 'replace_file', 'update_file', - 'delete', 'delete_file', 'remove_file', 'get_file_diff', 'getfilediff', 'apply_patch', 'applypatch', 'patch' - ]); - } - - static isCommand(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return ToolStatusPresentationPolicy.matches(raw, ['Bash', 'Shell', 'Git', 'ExecCommand', 'WriteStdin', 'ExecControl']) || - ToolStatusPresentationPolicy.matches(normalized, [ - 'bash', 'shell', 'git', 'exec_command', 'run_command', 'terminal', 'terminal_command', - 'powershell', 'sh', 'write_stdin', 'writestdin', 'exec_control', 'execcontrol' - ]) || normalized.indexOf('exec_command') >= 0; - } - - static isGit(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'Git' || normalized === 'git' || normalized.indexOf('git_') === 0; - } - - static isWeb(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'WebFetch' || normalized === 'webfetch' || normalized === 'web_fetch'; - } - - static isDiff(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'GetFileDiff' || normalized === 'get_file_diff' || normalized === 'getfilediff'; - } - - static isDelete(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'Delete' || - ToolStatusPresentationPolicy.matches(normalized, ['delete', 'delete_file', 'remove_file']); - } - - static isFileCreate(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'Write' || raw === 'Create' || - ToolStatusPresentationPolicy.matches(normalized, ['write', 'write_file', 'create', 'create_file']); - } - - static isPatch(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return raw === 'ApplyPatch' || raw === 'Patch' || - ToolStatusPresentationPolicy.matches(normalized, ['apply_patch', 'applypatch', 'patch']); - } - - static isSearch(tool: ConversationUiToolStatus): boolean { - const raw = tool.name || ''; - const normalized = ToolStatusPresentationPolicy.normalizedName(tool); - return ToolStatusPresentationPolicy.matches(raw, ['Grep', 'Glob', 'SemanticSearch']) || - ToolStatusPresentationPolicy.matches(normalized, ['grep', 'glob', 'semanticsearch', 'semantic_search']) || - normalized.indexOf('search') >= 0; - } - - static hasError(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return status === 'failed' || status === 'error' || (tool.error_preview || '').length > 0 || - (tool.stderr || '').length > 0; - } - - static isPendingConfirmation(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return (status === 'pending_confirmation' || status === 'needs_confirmation') && (tool.id || '').length > 0; - } - - static isRunning(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return (status === 'running' || status === 'active') && (tool.id || '').length > 0; - } - - static isCompleted(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return status === 'completed' || status === 'done' || status === 'sent'; - } - - static isCancelled(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - return status === 'cancelled' || status === 'canceled' || status === 'rejected'; - } - - static isQuestion(tool: ConversationUiToolStatus): boolean { - const status = (tool.status || '').toLowerCase(); - const name = ToolStatusPresentationPolicy.normalizedName(tool); - return (name === 'askuserquestion' || name === 'ask_user_question') && - !ToolStatusPresentationPolicy.matches(status, [ - 'completed', 'done', 'failed', 'error', 'cancelled', 'canceled', 'rejected' - ]) && (tool.id || '').length > 0; - } - - static canExpand(tool: ConversationUiToolStatus): boolean { - return ToolStatusPresentationPolicy.hasError(tool) || - ToolStatusPresentationPolicy.isPendingConfirmation(tool) || - ToolStatusPresentationPolicy.isQuestion(tool) || - ToolStatusPresentationPolicy.isRunning(tool) || - ToolStatusPresentationPolicy.isCompleted(tool) || - ToolStatusPresentationPolicy.isCancelled(tool); - } - - static hasEditableInput(tool: ConversationUiToolStatus): boolean { - return !!tool.tool_input; - } - - static defaultInputText(tool: ConversationUiToolStatus): string { - if (!tool.tool_input) { - return ''; - } - try { - return JSON.stringify(tool.tool_input, null, 2); - } catch (_err) { - return ''; - } - } - - static inputPreview(tool: ConversationUiToolStatus): string { - if (tool.input_preview && tool.input_preview.length > 0) { - return tool.input_preview; - } - if (tool.tool_input) { - try { - return JSON.stringify(tool.tool_input); - } catch (_err) { - return ''; - } - } - return ''; - } - - static taskTitle(tool: ConversationUiToolStatus): string { - const payload = ToolStatusPresentationPolicy.taskPayload(tool); - const title = payload.description || payload.task || payload.title || payload.prompt || payload.message || - payload.task_name || payload.taskName || payload.name || payload.content || ''; - if (title.trim().length > 0) return title.trim(); - const preview = ToolStatusPresentationPolicy.inputPreview(tool).trim(); - if (preview.length > 0 && !preview.startsWith('{') && !preview.startsWith('[')) return preview; - return ''; - } - - static resultPreview(tool: ConversationUiToolStatus): string { - const parts: string[] = []; - if (tool.result_preview && tool.result_preview.length > 0) parts.push(tool.result_preview); - if (tool.error_preview && tool.error_preview.length > 0) parts.push(tool.error_preview); - if (tool.stdout && tool.stdout.length > 0) parts.push(tool.stdout); - if (tool.stderr && tool.stderr.length > 0) parts.push(tool.stderr); - if (tool.tool_output) { - try { - parts.push(JSON.stringify(tool.tool_output)); - } catch (_err) { - } - } - const text = parts.join('\n').trim(); - return text.length <= 480 ? text : `${text.slice(0, 480)}...`; - } - - static questionInputJson(tool: ConversationUiToolStatus): string { - if (tool.tool_input) { - try { - return JSON.stringify(tool.tool_input); - } catch (_err) { - } - } - return ToolStatusPresentationPolicy.inputPreview(tool); - } - - static questionPromptFromJson(preview: string): string { - if (preview.trim().length === 0) { - return ''; - } - try { - const payload = JSON.parse(preview) as QuestionPreviewPayload; - if (payload.question && payload.question.trim().length > 0) return payload.question.trim(); - if (payload.prompt && payload.prompt.trim().length > 0) return payload.prompt.trim(); - if (payload.questions && payload.questions.length > 0) { - return (payload.questions[0].question || payload.questions[0].header || '').trim(); - } - } catch (_err) { - } - return ''; - } - - static key(tool: ConversationUiToolStatus, index: number): string { - const signature = ToolStatusPresentationPolicy.signature(tool); - return tool.id && tool.id.length > 0 ? `${index}-${tool.id}-${signature}` : - `${index}-${tool.name || 'tool'}-${signature}`; - } - - private static signature(tool: ConversationUiToolStatus): string { - const parts: string[] = [ - tool.status || 'pending', `${tool.duration_ms || 0}`, `${tool.exit_code || 0}`, - `${(tool.input_preview || '').length}`, `${(tool.result_preview || '').length}`, - `${(tool.error_preview || '').length}`, `${(tool.stdout || '').length}`, `${(tool.stderr || '').length}`, - ToolStatusPresentationPolicy.objectSignature(tool.tool_input), - ToolStatusPresentationPolicy.objectSignature(tool.tool_output) - ]; - return ToolStatusPresentationPolicy.stableTextHash(parts.join('|')); - } - - private static taskPayload(tool: ConversationUiToolStatus): TaskPreviewPayload { - const preview = ToolStatusPresentationPolicy.inputPreview(tool); - if (preview.trim().length === 0) return {}; - try { - return JSON.parse(preview) as TaskPreviewPayload; - } catch (_err) { - return {}; - } - } - - private static objectSignature(value?: Object): string { - if (!value) return ''; - try { - return JSON.stringify(value).length.toString(); - } catch (_err) { - return 'object'; - } - } - - private static stableTextHash(text: string): string { - let hash = 0; - for (let index = 0; index < text.length; index++) { - hash = ((hash << 5) - hash + text.charCodeAt(index)) | 0; - } - return Math.abs(hash).toString(36); - } - - private static matches(value: string, candidates: string[]): boolean { - return candidates.indexOf(value) >= 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UsageReportPresentationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UsageReportPresentationPolicy.ets deleted file mode 100644 index e0770f0181..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UsageReportPresentationPolicy.ets +++ /dev/null @@ -1,305 +0,0 @@ -import { - RemoteSessionUsageReport, - RemoteUsageModelRow, - RemoteUsageToolRow -} from '../../model/RemoteModels'; - -/** - * Projects the session usage report into the sheet's rows. - * - * The report is mirrored from the desktop contract and every field of it is - * optional, so this policy renders exactly the metrics the payload carries and - * omits the rest: an unmeasured number must not be drawn as zero, and a row the - * host never sent has nothing to explain. Both spellings of each metric are - * accepted, because the payload travels between two independently built versions. - */ - -export class UsageReportRow { - readonly labelKey: string; - readonly value: string; - /** Set when the value is a catalog word rather than a formatted number. */ - readonly valueKey: string; - - constructor(labelKey: string, value: string, valueKey: string = '') { - this.labelKey = labelKey; - this.value = value; - this.valueKey = valueKey; - } -} - -export class UsageReportSection { - readonly id: string; - readonly titleKey: string; - readonly rows: UsageReportRow[]; - - constructor(id: string, titleKey: string, rows: UsageReportRow[]) { - this.id = id; - this.titleKey = titleKey; - this.rows = rows; - } -} - -export class UsageReportPresentation { - readonly sections: UsageReportSection[]; - /** Coverage below `complete`: the sheet says so instead of implying totals. */ - readonly partial: boolean; - readonly isEmpty: boolean; - - constructor(sections: UsageReportSection[], partial: boolean) { - this.sections = sections; - this.partial = partial; - this.isEmpty = sections.length === 0; - } -} - -export class UsageReportPresentationPolicy { - static readonly partialNoteKey: string = 'usage.partialNote'; - static readonly yesKey: string = 'usage.yes'; - static readonly noKey: string = 'usage.no'; - - static present(report?: RemoteSessionUsageReport): UsageReportPresentation { - if (!report) { - return new UsageReportPresentation([], false); - } - const sections: UsageReportSection[] = []; - const overview = UsageReportPresentationPolicy.overviewRows(report); - if (overview.length > 0) { - sections.push(new UsageReportSection('overview', 'usage.sectionOverview', overview)); - } - const time = UsageReportPresentationPolicy.timeRows(report); - if (time.length > 0) { - sections.push(new UsageReportSection('time', 'usage.sectionTime', time)); - } - const tokens = UsageReportPresentationPolicy.tokenRows(report); - if (tokens.length > 0) { - sections.push(new UsageReportSection('tokens', 'usage.sectionTokens', tokens)); - } - const models = UsageReportPresentationPolicy.modelRows(report); - if (models.length > 0) { - sections.push(new UsageReportSection('models', 'usage.sectionModels', models)); - } - const tools = UsageReportPresentationPolicy.toolRows(report); - if (tools.length > 0) { - sections.push(new UsageReportSection('tools', 'usage.sectionTools', tools)); - } - const files = UsageReportPresentationPolicy.fileRows(report); - if (files.length > 0) { - sections.push(new UsageReportSection('files', 'usage.sectionFiles', files)); - } - const compression = UsageReportPresentationPolicy.compressionRows(report); - if (compression.length > 0) { - sections.push(new UsageReportSection('compression', 'usage.sectionCompression', compression)); - } - const errors = UsageReportPresentationPolicy.errorRows(report); - if (errors.length > 0) { - sections.push(new UsageReportSection('errors', 'usage.sectionErrors', errors)); - } - return new UsageReportPresentation(sections, UsageReportPresentationPolicy.isPartial(report)); - } - - static isPartial(report: RemoteSessionUsageReport): boolean { - const level = UsageReportPresentationPolicy.text(report.coverage?.level).toLowerCase(); - return level.length > 0 && level !== 'complete'; - } - - private static overviewRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const rows: UsageReportRow[] = []; - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.scopeTurns', UsageReportPresentationPolicy.number(report.scope?.turn_count, report.scope?.turnCount)); - const includesSubagents = report.scope?.includes_subagents ?? report.scope?.includesSubagents; - if (includesSubagents !== undefined) { - rows.push(new UsageReportRow( - 'usage.scopeSubagents', - '', - includesSubagents ? UsageReportPresentationPolicy.yesKey : UsageReportPresentationPolicy.noKey)); - } - UsageReportPresentationPolicy.pushText(rows, 'usage.coverageLevel', report.coverage?.level); - const missing = report.coverage?.missing; - if (missing && missing.length > 0) { - rows.push(new UsageReportRow('usage.coverageMissing', missing.join(', '))); - } - UsageReportPresentationPolicy.pushText(rows, 'usage.workspace', report.workspace?.path_label ?? report.workspace?.pathLabel); - return rows; - } - - private static timeRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const rows: UsageReportRow[] = []; - UsageReportPresentationPolicy.pushDuration(rows, 'usage.timeSpan', report.time?.wall_time_ms, report.time?.wallTimeMs); - UsageReportPresentationPolicy.pushDuration( - rows, 'usage.timeTurns', report.time?.active_turn_ms, report.time?.activeTurnMs); - UsageReportPresentationPolicy.pushDuration(rows, 'usage.timeModel', report.time?.model_ms, report.time?.modelMs); - UsageReportPresentationPolicy.pushDuration(rows, 'usage.timeTools', report.time?.tool_ms, report.time?.toolMs); - return rows; - } - - private static tokenRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const rows: UsageReportRow[] = []; - UsageReportPresentationPolicy.pushTokens( - rows, 'usage.tokensInput', report.tokens?.input_tokens, report.tokens?.inputTokens); - UsageReportPresentationPolicy.pushTokens( - rows, 'usage.tokensOutput', report.tokens?.output_tokens, report.tokens?.outputTokens); - UsageReportPresentationPolicy.pushTokens( - rows, 'usage.tokensTotal', report.tokens?.total_tokens, report.tokens?.totalTokens); - UsageReportPresentationPolicy.pushTokens( - rows, 'usage.tokensCached', report.tokens?.cached_tokens, report.tokens?.cachedTokens); - return rows; - } - - private static modelRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const models = report.models; - if (!models || models.length === 0) { - return []; - } - return models.map((model: RemoteUsageModelRow): UsageReportRow => { - const name = UsageReportPresentationPolicy.text(model.model_id ?? model.modelId); - const calls = UsageReportPresentationPolicy.number(model.call_count, model.callCount); - const tokens = UsageReportPresentationPolicy.number(model.total_tokens, model.totalTokens); - const parts: string[] = []; - if (calls !== undefined) { - parts.push(`${calls}`); - } - if (tokens !== undefined) { - parts.push(UsageReportPresentationPolicy.tokenText(tokens)); - } - return new UsageReportRow('usage.modelRow', `${name} · ${parts.join(' · ')}`); - }); - } - - private static toolRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const tools = report.tools; - if (!tools || tools.length === 0) { - return []; - } - return tools.map((tool: RemoteUsageToolRow): UsageReportRow => { - const name = UsageReportPresentationPolicy.text(tool.tool_name ?? tool.toolName); - const calls = UsageReportPresentationPolicy.number(tool.call_count, tool.callCount); - const errors = UsageReportPresentationPolicy.number(tool.error_count, tool.errorCount); - const parts: string[] = []; - if (calls !== undefined) { - parts.push(`${calls}`); - } - if (errors !== undefined) { - parts.push(`${errors}`); - } - return new UsageReportRow('usage.toolRow', `${name} · ${parts.join(' · ')}`); - }); - } - - private static fileRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const rows: UsageReportRow[] = []; - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.filesChanged', UsageReportPresentationPolicy.number(report.files?.changed_files, report.files?.changedFiles)); - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.filesAdded', UsageReportPresentationPolicy.number(report.files?.added_lines, report.files?.addedLines)); - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.filesDeleted', UsageReportPresentationPolicy.number(report.files?.deleted_lines, report.files?.deletedLines)); - return rows; - } - - private static compressionRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const rows: UsageReportRow[] = []; - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.compactionCount', - UsageReportPresentationPolicy.number(report.compression?.compaction_count, report.compression?.compactionCount)); - UsageReportPresentationPolicy.pushTokens( - rows, 'usage.compactionSaved', report.compression?.saved_tokens, report.compression?.savedTokens); - return rows; - } - - private static errorRows(report: RemoteSessionUsageReport): UsageReportRow[] { - const rows: UsageReportRow[] = []; - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.errorsTotal', UsageReportPresentationPolicy.number(report.errors?.total_errors, report.errors?.totalErrors)); - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.errorsTools', UsageReportPresentationPolicy.number(report.errors?.tool_errors, report.errors?.toolErrors)); - UsageReportPresentationPolicy.pushNumber( - rows, 'usage.errorsModels', UsageReportPresentationPolicy.number(report.errors?.model_errors, report.errors?.modelErrors)); - return rows; - } - - private static pushText(rows: UsageReportRow[], labelKey: string, value?: string): void { - const text = UsageReportPresentationPolicy.text(value); - if (text.length > 0) { - rows.push(new UsageReportRow(labelKey, text)); - } - } - - private static pushNumber(rows: UsageReportRow[], labelKey: string, value?: number): void { - if (value === undefined) { - return; - } - rows.push(new UsageReportRow(labelKey, `${value}`)); - } - - private static pushTokens(rows: UsageReportRow[], labelKey: string, camel?: number, snake?: number): void { - const value = UsageReportPresentationPolicy.number(camel, snake); - if (value === undefined) { - return; - } - rows.push(new UsageReportRow(labelKey, UsageReportPresentationPolicy.tokenText(value))); - } - - private static pushDuration(rows: UsageReportRow[], labelKey: string, camel?: number, snake?: number): void { - const value = UsageReportPresentationPolicy.number(camel, snake); - if (value === undefined) { - return; - } - rows.push(new UsageReportRow(labelKey, UsageReportPresentationPolicy.durationText(value))); - } - - private static number(first?: number, second?: number): number | undefined { - if (first !== undefined) { - return first; - } - return second; - } - - private static text(value?: string): string { - return value === undefined ? '' : value; - } - - /** Token counts read in the same compact units the desktop report uses. */ - static tokenText(value: number): string { - if (value < 1000) { - return `${value}`; - } - if (value < 1000000) { - return `${UsageReportPresentationPolicy.rounded(value / 1000)}K`; - } - if (value < 1000000000) { - return `${UsageReportPresentationPolicy.rounded(value / 1000000)}M`; - } - return `${UsageReportPresentationPolicy.rounded(value / 1000000000)}B`; - } - - static durationText(value: number): string { - if (value < 1000) { - return `${value}ms`; - } - const seconds = Math.floor(value / 1000); - if (seconds < 60) { - return `${seconds}s`; - } - const minutes = Math.floor(seconds / 60); - const remaining = seconds % 60; - if (minutes < 60) { - return remaining === 0 ? `${minutes}m` : `${minutes}m ${remaining}s`; - } - const hours = Math.floor(minutes / 60); - const remainingMinutes = minutes % 60; - return remainingMinutes === 0 ? `${hours}h` : `${hours}h ${remainingMinutes}m`; - } - - private static rounded(value: number): string { - const scaled = Math.round(value * 100) / 100; - const whole = Math.floor(scaled); - const fraction = Math.round((scaled - whole) * 100); - if (fraction === 0) { - return `${whole}`; - } - if (fraction % 10 === 0) { - return `${whole}.${fraction / 10}`; - } - return `${whole}.${fraction < 10 ? '0' : ''}${fraction}`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageMenuPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageMenuPolicy.ets deleted file mode 100644 index 195434f299..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageMenuPolicy.ets +++ /dev/null @@ -1,37 +0,0 @@ -/** - * The lightweight menu a truncated user bubble opens on a long press. - * - * Items are resolved as data rather than drawn inline, so an entry arrives as one - * more item plus its action instead of another branch in the bubble's layout. The - * rollback entry is the second of them: the same entry the short bubble and the - * full-text panel hang off the system selection menu, reached here through the - * menu the truncated bubble opens instead of that system menu. - * - * Labels stay as keys so this policy owns no copy and no locale. - */ -export enum UserMessageMenuAction { - /** Copies the whole message, not the truncated preview. */ - CopyFullText = 'copy_full_text', - /** Opens the staged rollback on this message. */ - RollbackToMessage = 'rollback_to_message' -} - -export class UserMessageMenuItem { - readonly action: UserMessageMenuAction; - /** Dotted i18n key, resolved by the bubble at render time. */ - readonly labelKey: string; - - constructor(action: UserMessageMenuAction, labelKey: string) { - this.action = action; - this.labelKey = labelKey; - } -} - -export class UserMessageMenuPolicy { - static items(): UserMessageMenuItem[] { - return [ - new UserMessageMenuItem(UserMessageMenuAction.CopyFullText, 'chat.copyFullText'), - new UserMessageMenuItem(UserMessageMenuAction.RollbackToMessage, 'chat.rollbackItem') - ]; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageTruncationPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageTruncationPolicy.ets deleted file mode 100644 index 6f6f0c8c5c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/UserMessageTruncationPolicy.ets +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Long user messages are read as a truncated preview with an inline affordance - * that opens the whole message. - * - * The rule is frozen at eight lines or 360 characters, whichever comes first, - * with an ellipsis the bubble appends after the cut. The policy is deliberately - * width-agnostic: the bubble's own width changes with the posture and with the - * fold, and measuring the message by its content — the way the composer and the - * markdown parser already measure text — keeps one rule for compact and wide - * instead of a line count that silently moves with the window. - * - * A message is never shown as truncated when the cut would hide nothing but - * trailing whitespace, so the preview and the ellipsis agree with - * `shouldTruncate` by construction. - */ -export class UserMessageTruncationPolicy { - /** Frozen visual threshold: the preview keeps at most this many lines. */ - static readonly MAX_PREVIEW_LINES: number = 8; - /** Frozen visual threshold: the preview keeps at most this many characters. */ - static readonly MAX_PREVIEW_CHARS: number = 360; - /** Appended after the cut, before the inline full-text affordance. */ - static readonly ELLIPSIS: string = '...'; - - /** - * One line-ending convention for counting, the same one `MarkdownParser` - * applies to message text: CRLF collapses to LF so a Windows-authored - * message does not spend two characters per line break. - */ - static normalize(text: string): string { - return text.replace(/\r\n/g, '\n'); - } - - static shouldTruncate(text: string): boolean { - return UserMessageTruncationPolicy.cutIndex( - UserMessageTruncationPolicy.normalize(text) - ) >= 0; - } - - /** - * The text the truncated bubble renders, ending in the ellipsis. A message - * that is not truncated is returned normalized and otherwise untouched, so a - * caller can render this unconditionally. - * - * Trailing whitespace is dropped before the ellipsis: a character cut can - * land just past a line break, and an ellipsis that starts a line of its own - * reads as a separate paragraph rather than as the end of the sentence. - */ - static truncatedPreview(text: string): string { - const normalized = UserMessageTruncationPolicy.normalize(text); - const cut = UserMessageTruncationPolicy.cutIndex(normalized); - if (cut < 0) { - return normalized; - } - const body = normalized.substring(0, cut).replace(/[ \t\n]+$/, ''); - return body + UserMessageTruncationPolicy.ELLIPSIS; - } - - /** - * Where the preview stops, or -1 when the whole message is shown. Line and - * character limits compete: whichever is reached first wins, so a long - * one-liner and a tall short-line message both stop at a readable amount. - */ - private static cutIndex(normalized: string): number { - const cut = UserMessageTruncationPolicy.limitIndex(normalized); - if (cut < 0 || normalized.substring(cut).trim().length === 0) { - return -1; - } - return cut; - } - - private static limitIndex(normalized: string): number { - const lineCut = UserMessageTruncationPolicy.lineCutIndex(normalized); - if (normalized.length <= UserMessageTruncationPolicy.MAX_PREVIEW_CHARS) { - return lineCut; - } - const charCut = UserMessageTruncationPolicy.MAX_PREVIEW_CHARS; - if (lineCut < 0) { - return charCut; - } - return Math.min(lineCut, charCut); - } - - /** - * The index of the line break that starts the ninth line, which is the cut - * that leaves eight whole lines in the preview. A message of eight lines or - * fewer has no such break and is not truncated for being tall. - */ - private static lineCutIndex(normalized: string): number { - let lineBreaks: number = 0; - for (let index: number = 0; index < normalized.length; index += 1) { - if (normalized.charAt(index) !== '\n') { - continue; - } - lineBreaks += 1; - if (lineBreaks === UserMessageTruncationPolicy.MAX_PREVIEW_LINES) { - return index; - } - } - return -1; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CatalogRefreshPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CatalogRefreshPreview.ets deleted file mode 100644 index aae895e592..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CatalogRefreshPreview.ets +++ /dev/null @@ -1,82 +0,0 @@ -import { RecentWorkspaceEntry, RemoteSession } from '../../model/RemoteModels'; -import { RecentRemoteHome } from '../components/RecentRemoteHome'; -import { RemoteSessionList } from '../components/RemoteSessionList'; -import { SidebarDeviceGroup } from '../components/SidebarDeviceGroup'; -import { SidebarWorkspacePicker } from '../components/SidebarWorkspacePicker'; -import { INK, PAGE_BG } from '../components/Theme'; -import { DeviceDirectoryState, emptyDeviceDirectoryEntry } from '../state/DeviceDirectoryState'; - -/** Same-ID replacement fixture. No account, persistence, or remote requests. */ -@ComponentV2 -export struct CatalogRefreshPreview { - @Local directory: DeviceDirectoryState = this.makeDirectory(); - @Local sessions: RemoteSession[] = this.makeSessions(false); - @Local mode: number = 0; - @Local selected: string = ''; - - private workspaces(updated: boolean): RecentWorkspaceEntry[] { - return [{ workspaceId: 'preview-workspace', path: updated ? '/preview-after' : '/preview', name: updated ? 'Workspace after' : 'Workspace before', - lastOpened: '', workspaceKind: 'normal' }]; - } - - private makeSessions(updated: boolean): RemoteSession[] { - return [{ id: 'preview-session', deviceId: 'preview-device', title: updated ? 'Session after' : 'Session before', - agentType: 'code', status: updated ? 'completed' : 'idle', messageCount: updated ? 2 : 0, - createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), workspacePath: updated ? '/preview-after' : '/preview', - workspaceName: updated ? 'Workspace after' : 'Workspace before', - workspaceIdentity: { workspaceId: 'preview-workspace', path: updated ? '/preview-after' : '/preview' } }]; - } - - private makeDirectory(): DeviceDirectoryState { - const state = new DeviceDirectoryState(); - const device = emptyDeviceDirectoryEntry('preview-device', 'Preview host', true); - device.workspaces = this.workspaces(false); - device.sessions = this.makeSessions(false); - device.status = 'ready'; - state.replace([device]); - state.setWorkspaceExpanded(device.deviceId, '/preview', true, undefined, undefined, 'preview-workspace'); - state.workspaceLoadState(device.deviceId, '/preview', undefined, undefined, 'preview-workspace').hasLoadedSessions = true; - return state; - } - - build() { - Column() { - Row() { - Button('Sidebar').id('catalog-sidebar').onClick(() => { this.mode = 0; }) - Button('Recent').id('catalog-recent').onClick(() => { this.mode = 1; }) - Button('All').id('catalog-all').onClick(() => { this.mode = 2; }) - } - Row() { - Button('Projects').id('catalog-projects').onClick(() => { this.mode = 3; }) - Button('Picker').id('catalog-picker').onClick(() => { this.mode = 4; }) - } - Button('Replace same IDs').id('catalog-replace').onClick(() => { - this.directory.devices[0].workspaces = this.workspaces(true); - this.sessions = this.makeSessions(true); - this.directory.devices[0].sessions = this.sessions; - }) - Text(`Source: ${this.sessions[0].title}`).id('catalog-source').fontColor(INK) - Text(this.selected).id('catalog-selected').fontColor(INK) - if (this.mode === 0) { - SidebarDeviceGroup({ device: this.directory.devices[0], directoryState: this.directory, sessions: this.sessions, - onOpenSession: (session: RemoteSession): void => { this.selected = session.title; } }) - } else if (this.mode === 1) { - RecentRemoteHome({ connected: true, sessions: this.sessions, - onOpen: (session: RemoteSession): void => { this.selected = session.title; } }) - .layoutWeight(1) - } else if (this.mode === 2) { - RemoteSessionList({ sessions: this.sessions, sortMode: 'time', showStatusMetadata: true, - onOpenSession: (session: RemoteSession): void => { this.selected = session.title; } }) - .layoutWeight(1) - } else if (this.mode === 3) { - RemoteSessionList({ sessions: this.sessions, recentWorkspaces: this.directory.devices[0].workspaces, - onOpenSession: (session: RemoteSession): void => { this.selected = session.title; } }) - .layoutWeight(1) - } else { - SidebarWorkspacePicker({ workspaces: this.directory.devices[0].workspaces, - onSelectWorkspace: (path: string): void => { this.selected = path; } }) - .layoutWeight(1) - } - }.width('100%').height('100%').backgroundColor(PAGE_BG) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ColdStartHomePreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ColdStartHomePreview.ets deleted file mode 100644 index 6a07aa5747..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ColdStartHomePreview.ets +++ /dev/null @@ -1,32 +0,0 @@ -import { ColdStartPresentationState } from '../state/ColdStartPresentationState'; -import { ColdStartHomeTransition } from '../components/ColdStartHomeTransition'; -import { RecentRemoteHome } from '../components/RecentRemoteHome'; -import { PAGE_BG, INK } from '../components/Theme'; - -/** Isolated native geometry fixture; never loads account or remote state. */ -@ComponentV2 -export struct ColdStartHomePreview { - @Provider() coldStartGeometry: ColdStartPresentationState = new ColdStartPresentationState(); - @Local playing: boolean = false; - @Local compact: boolean = false; - - build() { - Column() { - Row({ space: 12 }) { - Button('Replay').id('launch-replay').onClick(() => { this.playing = true; }) - Button('Resize').id('launch-resize').onClick(() => { this.compact = !this.compact; }) - Text(this.playing ? 'Playing' : 'Home').fontColor(INK) - }.height(60) - Stack() { - RecentRemoteHome() - if (this.playing) { - ColdStartHomeTransition({ geometry: this.coldStartGeometry, onFinished: () => { this.playing = false; } }) - } - }.width(this.compact ? 360 : '100%').layoutWeight(1) - .onAreaChange((_old: Area, area: Area) => { - this.coldStartGeometry.originX = Number(area.globalPosition.x); - this.coldStartGeometry.originY = Number(area.globalPosition.y); - }) - }.width('100%').height('100%').backgroundColor(PAGE_BG) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CommandPalettePreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CommandPalettePreview.ets deleted file mode 100644 index b5d21bd5f8..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CommandPalettePreview.ets +++ /dev/null @@ -1,500 +0,0 @@ -import { - RemoteCommandPaletteClient, - RemoteCommandPaletteController, - RemoteCommandPaletteScope, - RemoteSkillCatalogQuery -} from '../../services/RemoteCommandPaletteController'; -import { CommandCatalogProjection, RemoteModeSkillRow } from '../../services/CommandCatalogProjection'; -import { - CommandPaletteCatalogStatus, - CommandPalettePolicy, - CommandPaletteProbeFailure, - commandPaletteProbeReady -} from '../../services/CommandPalettePolicy'; -import { HostInvokeRefusal } from '../../services/HostInvokeRefusal'; -import { CommandPalettePresentation, CommandPaletteState } from '../state/CommandPaletteState'; -import { CommandPaletteAction, CommandPaletteRequest } from '../actions/ConversationIntent'; -import { RemoteCommandCatalog, RemoteSessionUsageReport } from '../../model/RemoteModels'; -import { ComposerBar, ComposerPresentation } from '../components/ComposerBar'; -import { CommandChipRow } from '../components/CommandChipRow'; -import { SkillPickerSheet } from '../components/SkillPickerSheet'; -import { UsageReportSheet } from '../components/UsageReportSheet'; -import { AdaptiveSheetOptions } from '../components/AdaptiveSheetOptions'; -import { SettingsPlacementPolicy, SettingsSheetKind } from '../policy/SettingsPlacementPolicy'; -import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { INK, MUTED, PAGE_BG } from '../components/Theme'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; - -/** - * The host rows this fixture answers a catalog read with. - * - * Shaped like the real `ModeSkillInfo` payload: built-in skills are the only ones - * that carry a group key, and the custom rows stand for a user skill that reuses - * a built-in name plus one of their own. The last row is one the host will not - * let a user invoke, so the picker must drop it. - */ -const PREVIEW_SKILL_ROWS: RemoteModeSkillRow[] = [ - { - key: 'plan', name: 'Plan', description: 'Break the request into an ordered plan', - level: 'user', isBuiltin: true, groupKey: 'workflow', isShadowed: false, - allowUserInvocation: true, selectedForRuntime: true, effectiveEnabled: true, globallyEnabled: true - }, - { - key: 'review', name: 'Review', description: 'Review the change for real defects', - level: 'user', isBuiltin: true, groupKey: 'workflow', isShadowed: false, - allowUserInvocation: true, selectedForRuntime: true, effectiveEnabled: true, globallyEnabled: true - }, - { - key: 'summarize', name: 'Summarize', description: 'Condense the current thread', - level: 'user', isBuiltin: true, groupKey: 'writing', isShadowed: false, - allowUserInvocation: true, selectedForRuntime: true, effectiveEnabled: true, globallyEnabled: true - }, - { - key: 'changelog', name: 'Changelog', description: 'Draft release notes from the diff', - level: 'project', isBuiltin: false, isShadowed: false, - allowUserInvocation: true, selectedForRuntime: true, effectiveEnabled: true, globallyEnabled: true - }, - { - key: 'plan.team', name: 'Plan', description: 'Plan the work the way this project does', - level: 'user', isBuiltin: false, isShadowed: false, - allowUserInvocation: true, selectedForRuntime: true, effectiveEnabled: true, globallyEnabled: true - }, - { - key: 'implicit', name: 'Implicit only', description: 'Never offered for a manual pick', - level: 'user', isBuiltin: false, isShadowed: false, - allowUserInvocation: false, selectedForRuntime: true, effectiveEnabled: true, globallyEnabled: true - } -]; - -const PREVIEW_USAGE: RemoteSessionUsageReport = { - schemaVersion: 1, - sessionId: 'preview-session', - scope: { kind: 'session', turnCount: 7, includesSubagents: false }, - coverage: { level: 'partial', missing: ['files'] }, - time: { wallTimeMs: 1_842_000, activeTurnMs: 611_000, modelMs: 402_000, toolMs: 121_000 }, - tokens: { inputTokens: 128_400, outputTokens: 22_950, totalTokens: 151_350, cachedTokens: 61_200 }, - models: [{ modelId: 'claude-sonnet-4', callCount: 14, totalTokens: 151_350 }], - tools: [{ toolName: 'read_file', callCount: 21, errorCount: 1 }], - compression: { compactionCount: 1, savedTokens: 48_000 }, - errors: { totalErrors: 1, toolErrors: 1, modelErrors: 0 } -}; - -/** - * The host, minus the network. - * - * Only the four `host_invoke` verbs are answered here, and the catalog read can - * fail in each of the three ways the app distinguishes: a host that names the - * version gap, a host that refuses for its own reason, and a wire that answers - * nothing at all. The held compaction never settles until the fixture releases - * it, which is how the running state is held still for a screenshot. - */ -@ObservedV2 -class CommandPalettePreviewClient implements RemoteCommandPaletteClient { - /** '' | 'version_gap' | 'refused' | 'unreachable' | 'pending'. */ - catalogOutcome: string = ''; - failCompact: boolean = false; - holdCompact: boolean = false; - private release: () => void = () => {}; - - async skillCatalog(_query: RemoteSkillCatalogQuery): Promise { - if (this.catalogOutcome === 'pending') { - // A read that has not answered yet: the row waits rather than degrading. - return new Promise((): void => {}); - } - if (this.catalogOutcome === 'version_gap') { - throw new HostInvokeRefusal('get_mode_skill_configs', - "command 'get_mode_skill_configs' is unknown to this OpenBitFun desktop peer host version; " + - 'upgrade the peer host or check the command name'); - } - if (this.catalogOutcome === 'refused') { - throw new HostInvokeRefusal('get_mode_skill_configs', 'workspace not found for this session'); - } - if (this.catalogOutcome === 'unreachable') { - // The bridge answering without reaching a command handler: `ok: false` on - // the wire, but no command was refused, so the row must not say one was. - throw new HostInvokeRefusal('get_mode_skill_configs', - "peer host invoke timed out after 120s for 'get_mode_skill_configs'"); - } - return CommandCatalogProjection.parseHostCatalog(PREVIEW_SKILL_ROWS); - } - - async compactSession(_query: RemoteCommandPaletteScope): Promise { - if (this.holdCompact) { - await new Promise((resolve: () => void) => { - this.release = resolve; - }); - } - if (this.failCompact) { - throw new Error('The target device did not start the compaction. Try again later.'); - } - return 'Context compacted'; - } - - /** Lets a held compaction finish, so the completion line can be seen too. */ - releaseHeld(): void { - this.release(); - } - - async runInitAgentsMd(_query: RemoteCommandPaletteScope): Promise { - return 'AGENTS.md generated'; - } - - async sessionUsageReport(_query: RemoteCommandPaletteScope): Promise { - return PREVIEW_USAGE; - } -} - -/** - * The real command row, picker and usage sheet over a network-free host. - * - * The controller, its probe and the projection are production code; only the - * verbs are answered here, so what these screenshots show is what the row does - * with a catalog, a refusal, a running verb and a settled failure rather than - * what a mock of the row would draw. - */ -@ComponentV2 -export struct CommandPalettePreview { - @Local draft: string = ''; - @Local showSkillPicker: boolean = false; - @Local showUsageReport: boolean = false; - @Local sheetPresented: boolean = false; - @Local wide: boolean = false; - /** - * Bumped by every state transition. - * - * It is read in `build()` so the fixture re-renders on the controller's - * callbacks, and it doubles as the state name a screenshot can be read - * against. - */ - @Local revision: number = 0; - private palette: CommandPaletteState = new CommandPaletteState(); - private client: CommandPalettePreviewClient = new CommandPalettePreviewClient(); - private controller: RemoteCommandPaletteController = new RemoteCommandPaletteController( - this.client, - { - onCatalogLoading: (): void => { - this.palette.setCatalogLoading(); - this.stateChanged(); - }, - onCatalogReady: (_sessionId: string, catalog: RemoteCommandCatalog): void => { - this.palette.setCatalogReady(catalog); - this.stateChanged(); - }, - onCatalogFailed: (_sessionId: string, errorText: string, failure: string): void => { - this.palette.setCatalogFailed(errorText, failure); - this.stateChanged(); - }, - onCommandStarted: (_sessionId: string, wireAction: string): void => { - this.palette.beginCommand(wireAction); - this.stateChanged(); - }, - onCommandSettled: (_sessionId: string, wireAction: string, errorText: string, _message: string): void => { - this.palette.settleCommand(wireAction, errorText); - this.stateChanged(); - }, - onCommandNoticeExpired: (_sessionId: string, wireAction: string): void => { - this.palette.expireNotice(wireAction); - this.stateChanged(); - }, - onUsageLoading: (): void => { - this.palette.setUsageLoading(); - this.stateChanged(); - }, - onUsageReady: (_sessionId: string, report: RemoteSessionUsageReport | undefined): void => { - this.palette.setUsageReady(report); - this.stateChanged(); - }, - onUsageFailed: (_sessionId: string, errorText: string): void => { - this.palette.setUsageFailed(errorText); - this.stateChanged(); - } - } - ); - - aboutToAppear(): void { - const variant = this.variant(); - this.client.catalogOutcome = CommandPalettePreview.catalogOutcomeFor(variant); - this.client.failCompact = variant === 'failed'; - this.client.holdCompact = variant === 'busy'; - this.draft = variant === 'token' || variant === 'goal' ? '' : 'Check the redirect handler'; - if (variant === 'token' || variant === 'busy') { - this.palette.setSkill('plan', 'Plan'); - } - // The two halves of the goal chip's ownership rule: lit with its prefill in - // the draft, and the state the commit that consumes that draft leaves behind. - // The rule itself lives in `RemotePageState.prepareComposerSubmission` and is - // pinned by `command-palette-composer.test.cjs`; this fixture only frames it. - if (variant === 'goal') { - const toggled = CommandPalettePolicy.toggleGoal(this.draft, false); - this.draft = toggled.draft; - this.palette.setGoalPending(toggled.pending); - } - if (variant === 'goal-sent') { - this.draft = ''; - this.palette.setGoalPending(false); - } - // Both sheets open before the first frame, the way the settings preview - // opens its own: the scenario id is only known once the page is appearing. - if (variant === 'sheet' || CommandPalettePreview.isSkillsSheetVariant(variant)) { - this.openSheet(true); - } - if (variant === 'usage') { - this.openSheet(false); - } - // The catalog read is also the probe, so this is the same first move a - // session entry makes: one read decides whether the picker may list anything. - void this.controller.loadCatalog('preview-session', 'agentic', false, this.canApply()); - if (variant === 'busy' || variant === 'failed') { - void this.controller.runCommand('preview-session', CommandPalettePolicy.compactWireAction, - this.scope, this.canApply()); - } - if (variant === 'usage') { - void this.controller.loadUsageReport('preview-session', this.scope, this.canApply()); - } - } - - /** - * The catalog read each variant stands for. - * - * The three failure kinds are the three the app tells apart, so a screenshot - * can be read against the words a person would actually get: the host naming - * the version gap, the host refusing a command for a reason of its own, and - * the bridge answering without ever reaching a command handler. - */ - private static catalogOutcomeFor(variant: string): string { - if (variant === 'degraded' || variant === 'gap') { - return 'version_gap'; - } - if (variant === 'refused') { - return 'refused'; - } - if (variant === 'unreachable') { - return 'unreachable'; - } - return variant === 'loading' ? 'pending' : ''; - } - - /** - * The variants that are showing the picker rather than the row alone. - * - * The waiting variant keeps its sheet shut on purpose: what it is there to - * show is the row's own waiting chip, which a sheet would cover. - */ - private static isSkillsSheetVariant(variant: string): boolean { - return variant === 'degraded' || variant === 'gap' || - variant === 'refused' || variant === 'unreachable'; - } - - build() { - this.Body() - } - - /** - * The fixture's one screen, in a builder rather than in `build()`. - * - * A sheet binds to the node it is attached to, and the root of `build()` is - * the node a parent can re-address; the app's own sheet hosts attach theirs - * inside a builder for the same reason. - */ - @Builder - private Body() { - Column({ space: 8 }) { - Text(`command-palette · ${this.variant()} · r${this.revision}`) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .id('command-palette-state') - Text(this.stateLine()) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(INK) - .maxLines(3) - .id('command-palette-status') - Row({ space: 6 }) { - Button('Probe') - .id('palette-probe') - .onClick(() => { - void this.controller.loadCatalog('preview-session', 'agentic', true, this.canApply()); - }) - Button('Sheet') - .id('palette-sheet') - .onClick(() => { - this.dispatch(new CommandPaletteRequest(CommandPaletteAction.OpenSkills)); - }) - Button('Usage') - .id('palette-usage') - .onClick(() => { - this.dispatch(new CommandPaletteRequest(CommandPaletteAction.OpenUsage)); - }) - Button('Token') - .id('palette-token') - .onClick(() => { - this.dispatch(new CommandPaletteRequest(CommandPaletteAction.SelectSkill, 'plan', '', 'Plan')); - }) - Button('Release') - .id('palette-release') - .onClick(() => { - this.client.holdCompact = false; - this.client.releaseHeld(); - }) - } - Blank() - CommandChipRow({ - palette: this.presentation(), - presentation: this.wide ? ComposerPresentation.Floating : ComposerPresentation.Compact, - onRequest: (request: CommandPaletteRequest) => { - this.dispatch(request); - } - }) - ComposerBar({ - presentation: this.wide ? ComposerPresentation.Floating : ComposerPresentation.Compact, - chatInput: this.draft, - skillId: this.palette.skillId, - skillLabel: this.palette.skillLabel, - commandRowActive: true, - onChatInputChange: (value: string) => { - this.draft = value; - }, - onRemoveSkillToken: () => { - this.dispatch(new CommandPaletteRequest(CommandPaletteAction.ClearSkill)); - } - }) - } - .width('100%') - .height('100%') - .padding({ left: 12, right: 12, top: 12 }) - .backgroundColor(PAGE_BG) - // One node carries one sheet binding, so the picker and the report take - // turns on it exactly as they do in the conversation pane. - .bindSheet($$this.sheetPresented, this.ActiveSheet(), this.activeSheetOptions()) - .onAreaChange((_old: Area, area: Area) => { - this.wide = Number(area.width) >= 600; - }) - } - - @Builder - private ActiveSheet() { - if (this.showSkillPicker) { - SkillPickerSheet({ - palette: this.presentation(), - onSelect: (skillId: string, skillLabel: string) => { - this.closeSheet(); - this.dispatch(new CommandPaletteRequest(CommandPaletteAction.SelectSkill, skillId, '', skillLabel)); - }, - onRefresh: () => { - void this.controller.loadCatalog('preview-session', 'agentic', true, this.canApply()); - }, - onClose: () => { - this.closeSheet(); - } - }) - } else { - UsageReportSheet({ - palette: this.presentation(), - onRetry: () => { - void this.controller.loadUsageReport('preview-session', this.scope, this.canApply()); - }, - onClose: () => { - this.closeSheet(); - } - }) - } - } - - private activeSheetOptions(): SheetOptions { - return AdaptiveSheetOptions.fromPlacement(SettingsPlacementPolicy.compactBottom( - this.showSkillPicker ? SettingsSheetKind.SkillPicker : SettingsSheetKind.UsageReport), true); - } - - private openSheet(skills: boolean): void { - this.showSkillPicker = skills; - this.showUsageReport = !skills; - this.sheetPresented = true; - } - - private closeSheet(): void { - this.sheetPresented = false; - } - - /** - * The row's one funnel, mirroring the conversation's dispatch. - * - * Opening or closing a sheet is this page's own view state; everything else - * goes through the same controller the conversation uses, so the probe, the - * single-flight guard and the notices behave here exactly as they do in the - * chat page. - */ - private dispatch(request: CommandPaletteRequest): void { - if (request.action === CommandPaletteAction.ToggleGoal) { - const toggled = CommandPalettePolicy.toggleGoal(this.draft, this.palette.goalPending); - this.draft = toggled.draft; - this.palette.setGoalPending(toggled.pending); - this.stateChanged(); - return; - } - if (request.action === CommandPaletteAction.SelectSkill) { - this.palette.setSkill(request.skillId, request.skillLabel); - this.stateChanged(); - return; - } - if (request.action === CommandPaletteAction.ClearSkill) { - this.palette.clearSkill(); - this.stateChanged(); - return; - } - if (request.action === CommandPaletteAction.OpenUsage || - request.action === CommandPaletteAction.RetryUsage) { - this.openSheet(false); - void this.controller.loadUsageReport('preview-session', this.scope, this.canApply()); - return; - } - if (request.action === CommandPaletteAction.OpenSkills || - request.action === CommandPaletteAction.RefreshCatalog) { - this.openSheet(true); - void this.controller.loadCatalog('preview-session', 'agentic', - request.action === CommandPaletteAction.RefreshCatalog, this.canApply()); - return; - } - const wireAction = request.action === CommandPaletteAction.RetryCommand ? - request.wireAction : request.action; - if (CommandPalettePolicy.isRunnable(wireAction)) { - void this.controller.runCommand('preview-session', wireAction, this.scope, this.canApply()); - } - } - - private get scope(): RemoteCommandPaletteScope { - const value: RemoteCommandPaletteScope = { sessionId: 'preview-session' }; - value.workspacePath = '/Users/user/projects/openbitfun'; - return value; - } - - /** Every read here is pinned to the one session this fixture stands for. */ - private canApply(): (sessionId: string) => boolean { - return (sessionId: string): boolean => sessionId === 'preview-session'; - } - - private presentation(): CommandPalettePresentation { - return CommandPalettePresentation.project(this.palette, true, false); - } - - private stateChanged(): void { - this.revision += 1; - } - - /** What the fixture is showing: the read's verdict and the row's own line. */ - private stateLine(): string { - const probe = commandPaletteProbeReady(this.palette.catalogStatus) ? 'probe ok' : 'probe refused'; - const failure = this.palette.catalogFailure.length > 0 ? - ` · ${this.palette.catalogFailure}` : ''; - const goal = this.palette.goalPending ? ' · goal pending' : ''; - const notice = this.palette.notice; - const running = this.palette.runningCommand.length > 0 ? - ` · running ${this.palette.runningCommand}` : ''; - return notice.visible ? - `${probe}${failure}${goal}${running} · ${RemoteI18n.t(notice.labelKey)}` : - `${probe}${failure}${goal}${running}`; - } - - private variant(): string { - const id = AppStorage.get('scenarioId') ?? 'command-palette'; - return id.replace('command-palette', '').replace('-dark', '').replace(/^-/, ''); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerOverflowPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerOverflowPreview.ets deleted file mode 100644 index d0dcf45c7b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerOverflowPreview.ets +++ /dev/null @@ -1,122 +0,0 @@ -import { ChatComposerPolicy } from '../../services/ChatComposerPolicy'; -import { ComposerBar, ComposerPresentation } from '../components/ComposerBar'; -import { INK, PAGE_BG } from '../components/Theme'; - -/** - * One line of draft that is far wider than the collapsed field, so the field has - * to mark what it cannot show. - */ -const OVERFLOW_DRAFT: string = - 'Keep the collapsed composer honest about what it cannot show: this draft is ' - + 'much wider than one line of the field, so the reader must see where it stops.'; - -/** - * A newline puts the same production composer into its tall form, which is the - * other half of the contract: the expanded field keeps a scrollable viewport and - * the expanded action row carries the draft's supplemental microphone beside the - * primary action. - */ -const MULTILINE_DRAFT: string = - 'Expanded draft, first line\nsecond line\nthird line'; - -/** - * The composer's draft chrome as the phone draws it: an empty field reaches - * dictation from the primary slot, a collapsed draft keeps its one line to - * itself and marks the overflow with an ellipsis instead of scrolling sideways, - * and an expanded draft gets the supplemental microphone beside Send. - * - * This mounts the production `ComposerBar` with the same capabilities the remote - * chat surface uses and no host, so the pixels are the shipping pixels. The - * `composer-overflow-state` line asks the production `ChatComposerPolicy` the - * two questions that decide the chrome — which primary action the draft earns, - * and whether the supplemental voice slot is wanted — so a screenshot can be read - * without inferring the decision from the glyphs alone. `supplementalVoice` - * reports the slot as mounted, not the bare policy answer: the collapsed field - * gives its one line to the draft, so the slot only reaches the screen from the - * expanded action row. - * - * **Next draft** cycles the three states on one install: the wide single line, - * the empty field, and the multiline draft. **Resize** swaps the compact and - * floating presentations without restarting the app. - */ -@ComponentV2 -export struct ComposerOverflowPreview { - @Local draftIndex: number = 0; - @Local draft: string = OVERFLOW_DRAFT; - @Local floating: boolean = false; - - aboutToAppear(): void { - // The launcher picks the starting state and the posture through the scenario - // id, so each draft can be captured without an extra tap. - const scenarioId = AppStorage.get('scenarioId') ?? ''; - this.draftIndex = this.startingDraftIndex(scenarioId); - this.draft = this.draftFor(this.draftIndex); - this.floating = scenarioId.endsWith('-wide'); - } - - private startingDraftIndex(scenarioId: string): number { - if (scenarioId.startsWith('composer-overflow-empty')) { - return 1; - } - return scenarioId.startsWith('composer-overflow-expanded') ? 2 : 0; - } - - private draftFor(index: number): string { - if (index === 1) { - return ''; - } - return index === 2 ? MULTILINE_DRAFT : OVERFLOW_DRAFT; - } - - private nextDraft(): void { - this.draftIndex = (this.draftIndex + 1) % 3; - this.draft = this.draftFor(this.draftIndex); - } - - /** The same expansion decision the composer makes, read from the policy. */ - private collapsed(): boolean { - return !ChatComposerPolicy.isExpanded(this.draft, false, false); - } - - private stateLine(): string { - // The remote chat capabilities, an idle connection and no running turn: the - // two draft states this fixture is about are decided by the text alone. - const action = ChatComposerPolicy.primaryAction( - this.draft, 0, false, false, false, true, true, 'connected', true); - const collapsed = this.collapsed(); - // The policy owns whether a draft earns the slot; the collapsed field gives - // its one line to the draft, so the slot only reaches the screen from the - // expanded action row. Report what is mounted, which is what a reader can - // check against the pixels. - const supplementalVoice = !collapsed && - ChatComposerPolicy.shouldShowSupplementalVoice(this.draft, 0, false, true); - const draft = this.draft.length === 0 ? 'empty' : `${this.draft.length} chars`; - return `draft=${draft} collapsed=${collapsed} action=${action} ` + - `supplementalVoice=${supplementalVoice}`; - } - - build() { - Column({ space: 8 }) { - Row({ space: 8 }) { - Button('Next draft').id('composer-overflow-draft').onClick(() => { - this.nextDraft(); - }) - Button('Resize').id('composer-overflow-resize').onClick(() => { - this.floating = !this.floating; - }) - } - Text(this.stateLine()).id('composer-overflow-state').fontColor(INK).fontSize(12) - Blank() - ComposerBar({ - presentation: this.floating ? ComposerPresentation.Floating : ComposerPresentation.Compact, - chatInput: this.draft, - onChatInputChange: (value: string) => { - this.draft = value; - } - }) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerSubmissionPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerSubmissionPreview.ets deleted file mode 100644 index 2b3ddfd0c6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ComposerSubmissionPreview.ets +++ /dev/null @@ -1,69 +0,0 @@ -import { RemoteChatCommandClient, RemoteChatCommandController } from '../../services/RemoteChatCommandController'; -import { RemoteChatCache, RemoteChatCacheStore, RemoteChatCacheSlice } from '../../services/RemoteChatCache'; -import { SessionRolledBackResult, SteerTurnResult } from '../../model/RemoteModels'; -import { ComposerBar, ComposerPresentation } from '../components/ComposerBar'; -import { INK, PAGE_BG } from '../components/Theme'; - -class PendingSubmissionClient implements RemoteChatCommandClient { - complete: (value: string) => void = () => {}; - async sendMessage(): Promise { return new Promise((resolve) => { this.complete = resolve; }); } - async sendMessageWithImages(): Promise { return this.sendMessage(); } - async steerTurn(): Promise { throw new Error('Unused preview operation'); } - async buildPlan(): Promise { throw new Error('Unused preview operation'); } - async cancelTask(): Promise {} - async renameSession(): Promise {} - // The preview exercises submission timing only, and a rollback it never raises - // must not be answerable by a fake success: it throws like the other unused - // operations, so a future preview that reaches it fails loudly. - async rollbackSessionToTurn(): Promise { - throw new Error('Unused preview operation'); - } -} - -class InMemoryPreviewCache implements RemoteChatCacheStore { - async init(_context: Context): Promise {} - async loadSlice(): Promise { return { messages: [], lastMessageId: '' }; } - async appendMessages(): Promise {} - async replaceMessages(): Promise {} - async deleteSession(): Promise {} - async pruneSessions(): Promise {} - async clearAll(): Promise {} -} - -/** Real composer and command owner with a manually acknowledged, network-free send. */ -@ComponentV2 -export struct ComposerSubmissionPreview { - @Local draft: string = 'Submission timing probe'; - @Local bubble: string = ''; - @Local busy: boolean = false; - @Local acknowledged: boolean = false; - @Local wide: boolean = false; - private client: PendingSubmissionClient = new PendingSubmissionClient(); - private command: RemoteChatCommandController = new RemoteChatCommandController(this.client, { - onMessagesLoaded: () => {}, onMessageCountKnown: () => {}, onTimelineReady: () => {}, - onComposerPrepared: () => ({ commit: () => { this.draft = ''; }, rollback: () => {} }), - onSendSucceeded: () => { this.acknowledged = true; }, onSendFailed: () => {}, - onActiveSession: () => {}, onSessionTitleChanged: () => {}, onStatusText: () => {}, - onToast: () => {}, onBusy: (value: boolean) => { this.busy = value; }, onPollRequested: () => {} - }, new RemoteChatCache(new InMemoryPreviewCache(), () => 'preview')); - - build() { - Column({ space: 12 }) { - Button('Acknowledge').id('submission-ack').onClick(() => { this.client.complete('preview-turn'); }) - Button('Next draft').id('submission-next').onClick(() => { this.draft = 'Next draft'; }) - Text(this.acknowledged ? 'Acknowledged' : 'Pending acknowledgment').id('submission-state').fontColor(INK) - Text(this.bubble).id('submission-bubble').fontColor(INK) - Blank() - ComposerBar({ presentation: this.wide ? ComposerPresentation.Floating : ComposerPresentation.Compact, - chatInput: this.draft, isBusy: this.busy, - onChatInputChange: (value: string) => { this.draft = value; }, - onSend: () => { - const text = this.draft; - this.bubble = text; - void this.command.sendPreparedMessage('preview-session', text, 'code', text, [], [], 'preview-message', '', false, true); - } - }) - }.width('100%').height('100%').backgroundColor(PAGE_BG) - .onAreaChange((_old: Area, area: Area) => { this.wide = Number(area.width) >= 600; }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CopySelectionPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CopySelectionPreview.ets deleted file mode 100644 index 079d3e684f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/CopySelectionPreview.ets +++ /dev/null @@ -1,405 +0,0 @@ -import { BusinessError, pasteboard } from '@kit.BasicServicesKit'; -import { ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ChatMessage } from '../../model/RemoteModels'; -import { ClipboardService } from '../../services/ClipboardService'; -import { DeviceApiLevelService } from '../../services/DeviceApiLevelService'; -import { MarkdownHtmlSerializer } from '../../services/MarkdownHtmlSerializer'; -import { ConversationIntent, ConversationIntentType, MessageCopyScope } from '../actions/ConversationIntent'; -import { ComposerPresentation } from '../components/ComposerBar'; -import { ConversationView } from '../components/ConversationView'; -import { ConversationViewOptions } from '../components/ConversationViewContract'; -import { INK, LINE, MUTED, PAGE_BG, SOFT } from '../components/Theme'; -import { WideLayoutGeometry } from '../layout/WideLayoutGeometry'; -import { AdaptiveLayoutInput } from '../policy/AdaptiveLayoutInput'; -import { ConversationLayoutPolicy } from '../policy/ConversationLayoutPolicy'; -import { SelectionCapabilityPolicy } from '../policy/SelectionCapabilityPolicy'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { ChatSurface } from '../state/ChatSurface'; -import { REMOTE_CHAT_COMPOSER_CAPABILITIES } from '../state/ChatComposerCapabilities'; -import { ConversationViewState } from '../state/ConversationViewState'; - -/** - * A message short enough to stay on the ordinary selectable bubble. - */ -const SHORT_USER_TEXT: string = '这段代码为什么会有内存泄漏?'; - -/** - * A message long enough to be cut by the line rule: eleven lines against the - * frozen eight. - */ -const LONG_USER_TEXT: string = [ - '请按下面的清单完整处理这次改动:', - '1. 在会话时间线里定位用户消息的渲染路径;', - '2. 为长消息加截断预览,并在行尾追加可点开的入口;', - '3. 面板内要能长按选择并复制,手柄可以调整范围;', - '4. 截断态气泡不给手柄,长按弹出轻量菜单;', - '5. 复制成功后给出状态提示,不要静默失败;', - '6. 浅色与深色主题都要检查对比度;', - '7. 竖屏与平板横屏两种布局都要走一遍;', - '8. 流式输出期间允许选中态被重置,但不能崩溃;', - '9. 交付前补单测并跑一遍架构检查;', - '10. 最后把设备证据截图归档。' -].join('\n'); - -/** - * A single-line message long enough to be cut by the character rule: the - * preview stops at 360 characters even though the message has one line. It has - * to stay above that count with the preview still measurably shorter, which is - * what makes the character branch distinguishable from the line branch in one - * transcript. - */ -const LONG_SINGLE_LINE_TEXT: string = [ - '下面这一整段是一条没有换行的长提示,用来验证按字符截断的分支:', - '它必须在预览里停在第三百六十个字符处并追加省略号,', - '同时行尾仍然要有可以点开的入口,点开之后面板里要显示完整的这一段内容,', - '面板内长按要能出现系统选择菜单与手柄,选择范围可以拖到整段文字之外,', - '复制全文时写入剪贴板的必须是完整文本而不是这段预览,', - '所以完整文本长度一定要明显大于预览长度,这样设备的回读报文才能把两者区分开,', - '这一条同样要覆盖手柄拖动的边界:从一个字符切到整段,再从整段缩回一个词,', - '手柄在长文里滑过折行位置时不能丢焦点,也不能把选中高亮留在已经离开的段落上,', - '如果预览行的最后一个字符正好落在气泡右边缘,追加的省略号与入口仍然必须完整可见,', - '浅色主题下入口用信息色加下划线,深色主题下同一个色板要保持可读而不刺眼,', - '这条提示后面还要继续补充一些内容,让完整文本长度明显大于三百六十个字符的预览长度,', - '否则回读到的长度数字不足以区分“复制全文”写的是整条消息还是这段预览,', - '所以这里再补两句:第一句确认字符截断以后仍然可以继续长按选择,', - '第二句确认这条消息在平板横屏与竖屏两种布局下都不会把入口挤出气泡,', - '最后还要确认这一条消息在深色主题下同样可读、截断标记与链接颜色不互相干扰。' -].join(''); - -/** - * An answer carrying every block the renderer draws, in one message: the - * cross-block selection has to be able to run paragraph -> list -> code, and - * the table and the code block are the two children that own a horizontal - * `Scroll`, which is the interaction the container has to survive. - */ -const ASSISTANT_MARKDOWN: string = [ - '## 选择与复制验证', - '', - '第一段正文:**加粗**、*斜体*、`行内代码`、~~删除线~~,以及一个 [OpenBitFun 文档](https://example.com/docs) 链接。', - '', - '- 列表项 A:拖动手柄时选择应能越过这一项', - '- 列表项 B:块间拼接应保留换行', - '- [x] 已完成的复选项', - '- [ ] 未完成的复选项', - '', - '1. 有序项一', - '2. 有序项二', - '', - '> 引用块:引用段落也参与连续选择。', - '', - '```ts', - "const message = 'a code block line long enough to overflow the pane horizontally';", - 'console.log(message);', - '```', - '', - '| 列 A | 列 B | 列 C |', - '| --- | --- | --- |', - '| 单元格一 | 单元格二 | 单元格三 |', - '| 更长的单元格内容 | 更长的单元格内容 | 更长的单元格内容 |', - '', - '---', - '', - '结尾段落:用于确认分隔线之后仍可继续选择。' -].join('\n'); - -const ASSISTANT_SHORT_MARKDOWN: string = - '收到,我按清单逐条处理,先给出结论:截断与全文面板都需要自己的选择表面。'; - -function message(id: string, role: string, text: string): ChatMessage { - return { id, role, text, status: 'completed', timestamp: '0' }; -} - -function row(id: string, role: string, text: string): ObservableChatTimelineItem { - return new ObservableChatTimelineItem({ - id, - type: role === 'user' ? 'user_message' : 'assistant_message', - message: message(id, role, text), - isStreaming: false, - isFinalizing: false - }); -} - -function transcript(): ObservableChatTimelineItem[] { - return [ - row('short-user', 'user', SHORT_USER_TEXT), - row('markdown-answer', 'assistant', ASSISTANT_MARKDOWN), - row('long-user', 'user', LONG_USER_TEXT), - row('advice-answer', 'assistant', ASSISTANT_SHORT_MARKDOWN), - row('long-line-user', 'user', LONG_SINGLE_LINE_TEXT) - ]; -} - -/** - * The copy and selection surface, over one transcript that carries every shape - * the feature distinguishes: a short user message, an answer with all of the - * markdown blocks, a line-cut user message, and a character-cut user message. - * - * A device check needs more than the pixels: whether the long press reached the - * system selection menu, what the truncated bubble opened, and which clipboard - * flavors a copy wrote are all invisible in a screenshot of the surface itself. - * The strip above the conversation therefore states what the last intent asked - * for and what the pasteboard actually holds afterwards, read back through the - * same pasteboard the copy wrote to. The last requested copy scope and the - * recorded mime types together are what proves the rich write really produced a - * second flavor rather than a plain text that merely looks right. - * - * The scenario id picks the mount, and nothing else, because the mount is the - * question: `copy-selection` renders the pane the way the wide detail leaf does, - * `copy-selection-nav` pushes it through a `Navigation` the way the compact - * route does, and `copy-selection-wide` forces the floating composer. The - * placement and the composer presentation follow the real window width, so the - * same fixture covers a phone and a tablet without a second scenario. - */ -@ComponentV2 -export struct CopySelectionPreview { - @Local state: ConversationViewState = new ConversationViewState(); - @Local placement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - @Local apiLevel: number = 0; - @Local crossBlock: boolean = false; - @Local lastIntent: string = '(none)'; - @Local clipboardReport: string = '(not read)'; - @Local viewportWidth: number = 0; - private readonly clipboard: ClipboardService = new ClipboardService(); - private readonly navigationStack: NavPathStack = new NavPathStack(); - private routed: boolean = false; - - aboutToAppear(): void { - this.state.surface = ChatSurface.Remote; - this.state.connectionState = 'connected'; - this.state.activeSession = { - sessionId: 'copy-selection-preview', - title: 'Copy and selection', - workspacePath: '/workspace', - agentType: 'code' - }; - this.state.desktopName = 'Studio'; - this.state.composerCapabilities = REMOTE_CHAT_COMPOSER_CAPABILITIES; - this.state.timelineItems = transcript(); - this.state.timelineRevision = 1; - this.apiLevel = DeviceApiLevelService.sdkApiVersion(); - this.crossBlock = SelectionCapabilityPolicy.supportsCrossBlockSelection(this.apiLevel); - if (this.scenarioId() === 'copy-selection-nav' && !this.routed) { - // Pushed rather than mounted as the navigation bar's own content: the - // compact shell opens a conversation as a destination on its stack. - this.routed = true; - this.navigationStack.pushPath({ name: 'copy-selection' }); - } - } - - private scenarioId(): string { - return AppStorage.get('scenarioId') ?? 'copy-selection'; - } - - private isWideViewport(): boolean { - return this.viewportWidth >= ConversationLayoutPolicy.MD_MIN_WIDTH; - } - - /** - * The placement the app root would resolve for this window. The fixture has - * no creases to offer and is not asked to reproduce a foldable, so the input - * carries the measured viewport and nothing else. - */ - private refreshGeometry(width: number, height: number): void { - this.viewportWidth = width; - this.placement = SettingsPlacementPolicy.resolve( - new AdaptiveLayoutInput(width, height, 0, false, false, false, this.isWideViewport(), [], []), - SettingsSheetKind.UserMessageFullText - ); - } - - private options(): ConversationViewOptions { - const options = new ConversationViewOptions(); - options.showSidebarButton = true; - options.showBackButton = false; - options.composerPresentation = - this.isWideViewport() ? ComposerPresentation.Floating : ComposerPresentation.Compact; - options.fullTextSheetPlacement = this.placement; - return options; - } - - private async handleIntent(intent: ConversationIntent): Promise { - if (intent.type === ConversationIntentType.CopyMessage) { - await this.copyWithScope(intent.value, intent.copyScope); - return; - } - if (intent.type === ConversationIntentType.OpenFilePreview) { - // The link span sits inside the selection container; recording the intent - // is what proves the tap still reached it. - this.lastIntent = `open-link ${intent.value}`; - return; - } - if (intent.type === ConversationIntentType.ChatInputChanged) { - this.state.chatInput = intent.value; - return; - } - this.lastIntent = `intent ${intent.type}`; - } - - /** - * The production clipboard write for one scope. The controller does this on a - * paired host; the preview drives the same services directly so the pasteboard - * really holds what a copy wrote. - */ - private async copyWithScope(text: string, scope: MessageCopyScope): Promise { - try { - if (scope === MessageCopyScope.Rich) { - await this.clipboard.copyRich(text, MarkdownHtmlSerializer.toHtml(text)); - } else { - await this.clipboard.writeText(text); - } - this.lastIntent = `copy ${scope} len=${text.length}`; - } catch (err) { - this.lastIntent = `copy ${scope} failed ${JSON.stringify(err)}`; - return; - } - await this.readClipboard(); - } - - /** - * What the pasteboard holds now: the mime types of every record with its - * length, and the primary record's first characters. A rich copy that only - * stated its scope would not be evidence that the html record was written, so - * the readback is what turns one tap into a payload report. - * - * The text is read per record rather than through `PasteData.getPrimaryText()`: - * measured on device, that accessor returns nothing here, so the primary record - * is the first record exactly as the write ordered it. - * - * Measured on the emulator, this readback is not evidence of the payload: the - * platform hands a plain app an empty `PasteData` (no records, no text) even - * while the copy is in the clipboard, and a package without the pasteboard read - * permission cannot go further. The strip therefore reports what the app is - * given, and the authoritative payload read stays - * `hidumper -s PasteboardService -a "--data"`, which states the record count - * and the mime types the copy wrote. - */ - private async readClipboard(): Promise { - try { - const data = await pasteboard.getSystemPasteboard().getData(); - const count = data.getRecordCount(); - const types: string[] = []; - let primaryText: string = ''; - for (let index = 0; index < count; index += 1) { - const record = data.getRecord(index); - const text = String(record.toPlainText()); - if (index === 0) { - primaryText = text; - } - types.push(`${record.mimeType}(${text.length})`); - } - const head = primaryText.substring(0, 40).replace(/\n/g, ' '); - this.clipboardReport = `records=${types.join(',')} plainLen=${primaryText.length} head="${head}"`; - } catch (err) { - const failure = err as BusinessError; - this.clipboardReport = `read refused code=${failure?.code} message=${failure?.message}`; - } - } - - build() { - Column() { - this.Diagnostics() - // The pane takes what is left, not the window's full height: the chat page - // puts its own overlay at the bottom of whatever box it is given, so a pane - // measured at the window's height draws its composer below the screen. - Column() { - if (this.scenarioId() === 'copy-selection-nav') { - this.NavigationLayout() - } else { - this.Conversation() - } - } - .width('100%') - .layoutWeight(1) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - .onAreaChange((_oldArea: Area, newArea: Area) => { - this.refreshGeometry( - WideLayoutGeometry.areaLength(newArea.width), - WideLayoutGeometry.areaLength(newArea.height) - ); - }) - } - - /** - * The compact route's own shape: a `Navigation` whose stack holds the - * conversation as a pushed destination. This exists because a sheet bound - * inside that subtree is the one placement the app has never used. - */ - @Builder - private NavigationLayout() { - Navigation(this.navigationStack) { - Column() - .width('100%') - .height('100%') - } - .width('100%') - .height('100%') - .hideTitleBar(true) - .mode(NavigationMode.Stack) - .navBarWidth('100%') - .minContentWidth(0) - .navDestination(this.Destination) - } - - @Builder - private Destination(name: string) { - NavDestination() { - this.Conversation() - } - .hideTitleBar(true) - .backgroundColor(PAGE_BG) - } - - @Builder - private Conversation() { - ConversationView({ - state: this.state, - options: this.options(), - onIntent: (intent: ConversationIntent): void => { - void this.handleIntent(intent); - } - }) - } - - /** - * The report strip. It lives above the pane rather than inside it so that - * nothing it draws can be mistaken for the surface under test. - */ - @Builder - private Diagnostics() { - Column({ space: 2 }) { - Text(`scenario=${this.scenarioId()} api=${this.apiLevel} crossBlock=${this.crossBlock} ` + - `sheet=${this.placement.mode} w=${Math.round(this.viewportWidth)}`) - .id('copy-selection-scenario') - .fontSize(10) - .fontColor(MUTED) - .width('100%') - Text(`intent=${this.lastIntent}`) - .id('copy-selection-intent') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(2) - Text(`clip=${this.clipboardReport}`) - .id('copy-selection-clipboard') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(3) - } - .width('100%') - // The shell is immersive, so the strip starts at the window's top edge and - // has to clear the status bar itself; without the inset the clock draws over - // the report it is there to be read against. - .padding({ left: 12, right: 12, top: 48, bottom: 6 }) - .backgroundColor(SOFT) - .border({ width: { bottom: 0.5 }, color: LINE }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceModelDefaultsPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceModelDefaultsPreview.ets deleted file mode 100644 index 7240c48378..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceModelDefaultsPreview.ets +++ /dev/null @@ -1,301 +0,0 @@ -import { - REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1, - RemoteDefaultModels, - RemoteModelCatalog, - RemoteModelConfig -} from '../../model/RemoteModels'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; -import { DeviceModelDefaultsRequestPath } from '../state/DeviceModelDefaultsSheetState'; -import { AppRootPresentationActions, emptyAppRootPresentationActions } from '../actions/AppRootPresentationActions'; -import { AppSettingsSurface } from '../components/AppRootOverlaySurfaces'; -import { AppShell } from '../components/AppShell'; -import { PAGE_BG } from '../components/Theme'; -import { AppShellState } from '../state/AppShellState'; -import { RemotePageState } from '../state/RemotePageState'; - -/** - * The device model pages over a fixture desktop: the production sheet, its two - * model pages and the production controller, with the device's answers supplied - * locally. - * - * Nothing here is a picture of a page. The scenario id picks a device state — how - * many models it has, whether it can serve the page at all, whether a write is - * still in flight — and the sheet is mounted the way the app mounts it, so every - * state on screen is one the app can actually reach, and the interaction between - * them (tapping a role, choosing a model, watching the read-back land) works. - */ - -/** One model of the fixture desktop. */ -function previewModel( - id: string, - name: string, - provider: string, - modelName: string, - contextWindow: number, - enabled: boolean, - capabilities: string[] -): RemoteModelConfig { - return { - id, - name, - provider, - base_url: '', - model_name: modelName, - context_window: contextWindow, - enabled, - capabilities - }; -} - -/** - * The fixture desktop's catalog: four roles' worth of models, so `fast` and the - * multimodal slot can be told apart — one text-only model, one that carries both - * capabilities, one multimodal-only model, and one disabled model that no list - * may offer. - */ -function previewModels(): RemoteModelConfig[] { - return [ - previewModel('anthropic/claude-sonnet-4.5', 'Claude Sonnet 4.5', 'anthropic', - 'claude-sonnet-4-5', 200000, true, ['text_chat']), - previewModel('openbitfun:gpt-5-mini', 'GPT-5 mini', 'openai', - 'openbitfun:gpt-5-mini', 128000, true, ['text_chat']), - previewModel('google/gemini-2.5-flash', 'Gemini 2.5 Flash', 'google', - 'gemini-2.5-flash', 1000000, true, ['text_chat', 'image_understanding']), - previewModel('local:qwen3-coder', 'Qwen3 Coder', 'local', - 'qwen3-coder', 32768, true, ['text_chat']), - previewModel('preview/vision-preview', 'Vision Preview', 'openbitfun', - 'vision-preview', 64000, true, ['image_understanding']), - previewModel('legacy/disabled-model', 'Legacy model', 'legacy', - 'legacy-model', 8192, false, ['text_chat']) - ]; -} - -/** A primary model and two empty slots: the state the page opens on. */ -function previewDefaults(): RemoteDefaultModels { - return { - primary: 'anthropic/claude-sonnet-4.5', - fast: null, - image_understanding: null - }; -} - -/** The model the two write-driven scenarios select for the fast slot. */ -const PREVIEW_WRITE_MODEL: string = 'openbitfun:gpt-5-mini'; - -/** - * The fixture desktop's request path. - * - * `hangWrites` is the one behaviour a static fixture cannot express any other - * way: an answer that never arrives is what the locked page looks like, and it - * cannot be faked by a state flag without also faking the busy lock that the - * controller derives from the request being out. - */ -class PreviewModelDefaultsClient implements DeviceModelDefaultsRequestPath { - hangWrites: boolean = false; - /** The desktop stops answering the catalog read, which is a state of its own. */ - failReads: boolean = false; - private models: RemoteModelConfig[]; - private stored: RemoteDefaultModels; - - constructor(models: RemoteModelConfig[], stored: RemoteDefaultModels) { - this.models = models; - this.stored = stored; - } - - // Declared as fields rather than methods: the pages bind the request path as a - // property-typed shape, and ArkTS does not treat a method as one of those. - getModelCatalog: (sessionId?: string) => Promise = - async (): Promise => { - if (this.failReads) { - throw new Error('The desktop stopped answering the model catalog.'); - } - return { - version: 1, - models: this.models.slice(), - default_models: this.stored - }; - }; - - setModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ) => Promise = async ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise => { - if (this.hangWrites) { - return new Promise((): void => {}); - } - this.stored = { - primary, - fast, - search: this.stored.search, - image_understanding: imageUnderstanding, - image_generation: this.stored.image_generation, - speech_recognition: this.stored.speech_recognition - }; - return this.stored; - }; -} - -/** - * The settings surface the production shell mounts, over the fixture's device - * catalog. Only the two device-model requests differ from the app's own wiring. - */ -function previewActions(client: PreviewModelDefaultsClient): AppRootPresentationActions { - const base = emptyAppRootPresentationActions(); - return { - onWorkspaceTools: base.onWorkspaceTools, - onNavigationBack: base.onNavigationBack, - onConversationIntent: base.onConversationIntent, - onCloseSidebar: base.onCloseSidebar, - onCompactLayoutEntered: base.onCompactLayoutEntered, - onLayoutModeChanged: base.onLayoutModeChanged, - onRemoteHome: base.onRemoteHome, - onSidebar: base.onSidebar, - onSettings: { - close: base.onSettings.close, - accountSettled: base.onSettings.accountSettled, - disconnect: base.onSettings.disconnect, - clearPairing: base.onSettings.clearPairing, - reconnect: base.onSettings.reconnect, - openAccount: base.onSettings.openAccount, - cloudCancelLogin: base.onSettings.cloudCancelLogin, - cloudLogin: base.onSettings.cloudLogin, - cloudLogout: base.onSettings.cloudLogout, - cloudListDevices: async (): Promise => [], - cloudSelectDevice: base.onSettings.cloudSelectDevice, - getPermissionMode: base.onSettings.getPermissionMode, - setPermissionMode: base.onSettings.setPermissionMode, - getDeviceModelCatalog: (): Promise => client.getModelCatalog(), - setDeviceModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise => { - return client.setModelDefaults(primary, fast, imageUnderstanding); - }, - setLanguage: base.onSettings.setLanguage - }, - onConnect: base.onConnect, - onFilePreview: base.onFilePreview, - generalStatus: base.generalStatus - }; -} - -@ComponentV2 -export struct DeviceModelDefaultsPreview { - @Local shellState: AppShellState = new AppShellState(); - @Local remotePageState: RemotePageState = new RemotePageState(); - @Local actions: AppRootPresentationActions = emptyAppRootPresentationActions(); - private client: PreviewModelDefaultsClient = - new PreviewModelDefaultsClient(previewModels(), previewDefaults()); - - aboutToAppear(): void { - const scenario = this.scenarioId(); - this.client = new PreviewModelDefaultsClient( - scenario === 'device-model-empty' ? [] : previewModels(), - previewDefaults() - ); - this.client.hangWrites = scenario === 'device-model-writing'; - this.client.failReads = scenario === 'device-model-pick-failed'; - this.remotePageState.setAccountUserId('octocat'); - this.remotePageState.setAccountUsername('octocat'); - this.remotePageState.setControlTarget('account_device', 'account-desktop-1', 'Account desktop 1'); - this.remotePageState.setDesktopIdentity('Account desktop 1', 'account-desktop-1'); - this.remotePageState.connectionState = 'connected'; - // An older desktop is one that never advertised the command, so the page is - // reached through the same capability check the app uses. - this.remotePageState.setHostCapabilities(this.degraded(scenario) ? - ['workspace_id_references_v1'] : [REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1]); - this.actions = previewActions(this.client); - this.shellState.showSettings = true; - this.shellState.settingsSheet.setPage('deviceModels'); - const role = this.pickerRole(scenario); - if (role.length > 0) { - this.shellState.settingsSheet.openModelPick(role); - } - if (scenario === 'device-model-writing' || scenario === 'device-model-updated') { - void this.driveWrite(); - } - } - - /** - * Runs the write the scenario is about, before the first frame. - * - * The sheet arms the same gate a moment later from its own parameters, so this - * only has to happen first: a scenario that has to show a write in flight — or - * its result — cannot wait for the page to be tapped. - */ - private async driveWrite(): Promise { - const deviceModels = this.shellState.settingsSheet.deviceModels; - deviceModels.bind(this.client); - deviceModels.setGate({ supported: true, connected: true, deviceId: 'account-desktop-1' }); - await deviceModels.ensureLoaded(); - await deviceModels.selectRole('fast', PREVIEW_WRITE_MODEL); - } - - private scenarioId(): string { - const scenario = AppStorage.get('scenarioId') ?? ''; - return scenario.endsWith('-dark') ? scenario.slice(0, scenario.length - 5) : scenario; - } - - /** The desktop never advertised the command, on the settings page or its picker. */ - private degraded(scenario: string): boolean { - return scenario === 'device-model-degraded' || scenario === 'device-model-degraded-pick'; - } - - /** The role the picker is opened on, or an empty string for the settings page. */ - private pickerRole(scenario: string): string { - if (scenario === 'device-model-pick-fast') { - return 'fast'; - } - if (scenario === 'device-model-pick-multimodal') { - return 'image_understanding'; - } - if (scenario === 'device-model-pick-primary') { - return 'primary'; - } - // The picker in the two states it has no list for: a desktop that cannot - // answer this page at all, and one that stopped answering it. - if (scenario === 'device-model-degraded-pick' || scenario === 'device-model-pick-failed') { - return 'fast'; - } - return ''; - } - - build() { - AppShell({ - shellState: this.shellState, - allowSidebar: true, - content: () => { - this.EmptyConversation() - }, - settings: () => { - this.Settings() - }, - onCloseSidebar: () => { - this.shellState.showSidebar = false; - } - }) - } - - @Builder - private EmptyConversation() { - Column() - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - @Builder - private Settings() { - AppSettingsSurface({ - shellState: this.shellState, - remotePageState: this.remotePageState, - actions: this.actions - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceSelectorPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceSelectorPreview.ets deleted file mode 100644 index 95706d2db2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DeviceSelectorPreview.ets +++ /dev/null @@ -1,38 +0,0 @@ -import { SidebarWorkspaceSection } from '../components/SidebarWorkspaceSection'; -import { DeviceDirectoryState, emptyDeviceDirectoryEntry } from '../state/DeviceDirectoryState'; -import { PAGE_BG } from '../components/Theme'; - -/** Isolated production-sidebar fixture; never reads credentials or opens a transport. */ -@ComponentV2 -export struct DeviceSelectorPreview { - @Local directory: DeviceDirectoryState = this.makeDirectory(); - - private makeDirectory(): DeviceDirectoryState { - const state = new DeviceDirectoryState(); - const first = emptyDeviceDirectoryEntry('preview-mac', 'MacBook Pro', true); - first.status = 'ready'; - first.workspaces = [{ path: '/workspace/openbitfun', name: 'OpenBitFun', lastOpened: '', workspaceKind: 'normal' }]; - const second = emptyDeviceDirectoryEntry('preview-linux', 'Linux Desktop', true); - second.status = 'ready'; - second.workspaces = [{ path: '/workspace/demo', name: 'Demo', lastOpened: '', workspaceKind: 'normal' }]; - const offline = emptyDeviceDirectoryEntry('preview-offline', 'Offline Desktop', false); - state.replace([first, second, offline]); - state.select(first.deviceId); - return state; - } - - build() { - Scroll() { - SidebarWorkspaceSection({ - directoryState: this.directory, - onSelectDevice: (id: string): void => { this.directory.select(id); } - }) - .width('100%') - .constraintSize({ maxWidth: 360 }) - .padding(16) - } - .align(Alignment.TopStart) - .width('100%').height('100%') - .backgroundColor(PAGE_BG) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DurableTimelinePreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DurableTimelinePreview.ets deleted file mode 100644 index 17acfdfd20..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/DurableTimelinePreview.ets +++ /dev/null @@ -1,94 +0,0 @@ -import { ChatMessage } from '../../model/RemoteModels'; -import { ChatTimelineRowStore, ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { DurableSessionReducer, SessionRecord } from '../../services/DurableSessionReducer'; -import { ChatTimelineStore } from '../../services/ChatTimelineStore'; -import { HostSessionEvent } from '../../services/HostSessionStream'; -import { ChatTimeline } from '../components/ChatTimeline'; -import { ComposerBar } from '../components/ComposerBar'; -import { INK, PAGE_BG } from '../components/Theme'; - -/** Network-free replay through the production reducer, store and native rows. */ -@ComponentV2 -export struct DurableTimelinePreview { - private reducer: DurableSessionReducer = new DurableSessionReducer(); - private timeline: ChatTimelineStore = new ChatTimelineStore(); - private rowStore: ChatTimelineRowStore = new ChatTimelineRowStore(); - @Local rows: ObservableChatTimelineItem[] = []; - @Local revision: number = 0; - @Local step: number = 0; - @Local summary: string = ''; - @Local connectionState: string = 'connected'; - @Local active: boolean = true; - @Local stopRequests: number = 0; - - aboutToAppear(): void { - this.timeline.reset('preview'); - this.reducer.apply(this.record('reason', 'thinking', 0, 1, 'Reason probe')); - this.reducer.apply(this.record('answer', 'text', 2, 2, 'Answer probe')); - this.publish(); - } - - private record(id: string, type: string, order: number, revision: number, - content: string, status: string = 'inprogress'): HostSessionEvent { - const payload: SessionRecord = { - sessionId: 'preview', id: `item/${id}`, revision, - turn: { turnId: 'turn', turnIndex: 0, sessionId: 'preview', timestamp: 1, - userMessage: { id: 'user', content: 'Timeline probe', timestamp: 1 }, status }, - round: { id: 'round', turnId: 'turn', roundIndex: 0, timestamp: 2, status: 'completed' }, - item: { type, data: { id, orderIndex: order, timestamp: 3, content, - toolName: 'Read', toolCall: { id, input: new Object() }, status: 'completed' } } - }; - return { session_id: 'preview', event: 'session-record', payload }; - } - - private publish(): void { - const messages = this.reducer.messages(); - const active = messages.find((message: ChatMessage) => message.role === 'assistant' && message.status === 'active'); - this.timeline.applySnapshot({ sessionId: 'preview', cursor: { - pollVersion: 0, knownMessageCount: messages.length, knownModelCatalogVersion: 0 - }, changed: true, title: '', sessionState: active ? 'active' : 'idle', newMessages: [], - messageSnapshot: messages.filter((message: ChatMessage) => message !== active), activeTurn: active, - shouldSyncAfterTurnEnded: false, historyRewritten: false, completedTurnId: '' }); - this.rows = this.rowStore.reconcile(this.timeline.project(false)); - this.revision++; - const state = this.timeline.snapshot(); - this.active = state.activeTurn !== undefined; - const answer = state.activeTurn || state.persistedMessages.find((message: ChatMessage) => message.role === 'assistant'); - this.summary = `step=${this.step} blocks=${answer?.items?.length || 0} active=${state.activeTurn ? 1 : 0}`; - } - - private next(): void { - this.step++; - if (this.step === 1) this.reducer.apply(this.record('tool', 'tool', 1, 3, '')); - if (this.step === 2) { - for (let index = 0; index < 30; index++) this.publish(); - } - if (this.step === 3) this.reducer.apply(this.record('answer', 'text', 2, 4, 'Corrected probe')); - if (this.step === 4) { - const payload: SessionRecord = { sessionId: 'preview', id: 'item/reason', revision: 5, deleted: true }; - this.reducer.apply({ session_id: 'preview', event: 'session-record', payload }); - } - if (this.step === 5) this.reducer.apply(this.record('answer', 'text', 2, 6, 'Final probe', 'completed')); - this.publish(); - } - - build() { - Column({ space: 8 }) { - Button('Next replay').id('timeline-next').onClick(() => { this.next(); }) - Text(this.summary).id('timeline-summary').fontColor(INK) - Row({ space: 8 }) { - Button('Host offline').id('host-offline').onClick(() => { this.connectionState = 'reconnecting'; }) - Button('Host returned').id('host-returned').onClick(() => { - this.reducer.apply(this.record('answer', 'text', 2, 100, 'Interrupted probe', 'cancelled')); - this.connectionState = 'connected'; - this.publish(); - }) - } - Text(`${this.connectionState} stops=${this.stopRequests}`).id('host-state').fontColor(INK) - ChatTimeline({ timelineItems: this.rows, timelineRevision: this.revision, - connectionState: this.connectionState, isBusy: this.active }).layoutWeight(1) - ComposerBar({ canStop: this.active, connectionState: this.connectionState, - onStop: () => { this.stopRequests++; } }) - }.width('100%').height('100%').backgroundColor(PAGE_BG) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/FileVisibilityPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/FileVisibilityPreview.ets deleted file mode 100644 index a30f68eea4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/FileVisibilityPreview.ets +++ /dev/null @@ -1,453 +0,0 @@ -import { - ChatMessage, - FileInfo, - ReadFileChunkResult, - ReadFileResult, - RuntimeFileLocation, - SessionSummary -} from '../../model/RemoteModels'; -import { ChatTimelineRowStore, ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { DurableSessionReducer, SessionRecord } from '../../services/DurableSessionReducer'; -import { ChatTimelineStore } from '../../services/ChatTimelineStore'; -import { HostSessionEvent } from '../../services/HostSessionStream'; -import { - RemoteFileDownloadClient, - RemoteFileDownloadController, - RemoteFileDownloadScheduler, - RemoteFileSaver -} from '../../services/RemoteFileDownloadController'; -import { Encoding } from '../../services/Encoding'; -import { FilePreviewRequest } from '../../model/FilePreviewTarget'; -import { FilePreviewPhase, FilePreviewState } from '../state/FilePreviewState'; -import { FilePreviewController } from '../viewmodel/FilePreviewController'; -import { AppRoute } from '../navigation/AppRouteContract'; -import { ChatTimeline } from '../components/ChatTimeline'; -import { FilePreviewSurface } from '../components/FilePreviewSurface'; -import { INK, PAGE_BG } from '../components/Theme'; - -/** One file the fixture host can serve, in the shape the wire would carry it. */ -class PreviewFile { - readonly path: string; - readonly name: string; - readonly mimeType: string; - readonly contentBase64: string; - /** Derived from the bytes, so the reported size can never drift from them. */ - readonly size: number; - - constructor(path: string, name: string, mimeType: string, contentBase64: string) { - this.path = path; - this.name = name; - this.mimeType = mimeType; - this.contentBase64 = contentBase64; - this.size = Encoding.base64ToBytes(contentBase64).length; - } - - static text(path: string, mimeType: string, text: string): PreviewFile { - return new PreviewFile( - path, - PreviewFileHost.basename(path), - mimeType, - Encoding.bytesToBase64(Encoding.utf8ToBytes(text)) - ); - } -} - -/** - * A tiny real PNG so the image branch decodes on device instead of failing on a - * placeholder, plus the text files the fixture message links to. - */ -const PREVIEW_PNG_BASE64: string = - 'iVBORw0KGgoAAAANSUhEUgAAAHgAAABICAIAAACyfKYoAAABG0lEQVR42u3XIQ5CQRRD0WocG2BfbInV4pAfhQFDArlvMr3N09PmuMnp+ni7w7xyv13+dfmE1pqD1pqD1pqD1pqDLrf+J/RxHFpD0Fpz0Fpz0Fpz0Fpz0Fpz0Fpz0Fpz0Fpz0Fpz0OXWKHSzNQ1daz0A3Wk9A11oPQbdZj0JXWU9DN1jPQ9dYr0EdIP1KtD+0b9Pfn9Cawhaaw5aaw5aaw5aaw5aaw5aaw5aaw5aaw5aaw5aaw5aaw5aaw5a65BlzdaB+2qtw1d2WmektdA6U8Vt1hnsrrLObH2PdcYXlFhnhREN1llkx/bWWWfK3tZZas3G1llt0K7WWXDTltY5GyRCCy20EVpooSUQWmgjtNBCG6GFNkILLbQh8gRhd1Ue5saG0wAAAABJRU5ErkJggg=='; - -class PreviewFileHost implements RemoteFileDownloadClient { - private readonly files: Map = new Map(); - - constructor() { - this.add(new PreviewFile('png/openbitfun-wordmark.png', 'openbitfun-wordmark.png', 'image/png', - PREVIEW_PNG_BASE64)); - this.add(PreviewFile.text('artifacts/REPORT.md', 'text/markdown', - '# Brand report\n\nThe wordmark and the bundle are ready.\n')); - this.add(new PreviewFile('artifacts/bundle.zip', 'bundle.zip', 'application/zip', 'UEsDBAoAAAAAAA==')); - this.add(PreviewFile.text('artifacts/run.log', 'text/plain', - 'brand export ok\nbundled 2 files\n')); - } - - private add(file: PreviewFile): void { - this.files.set(file.path, file); - } - - static basename(path: string): string { - const parts = path.split('/'); - return parts[parts.length - 1] || path; - } - - async getFileInfo(path: string, _sessionId?: string): Promise { - const file = this.files.get(path); - if (!file) { - throw new Error(`File not found: ${path}`); - } - return { name: file.name, size: file.size, mimeType: file.mimeType }; - } - - async readFileChunk(path: string, offset: number, limit: number, - _sessionId?: string): Promise { - const file = this.files.get(path); - if (!file) { - throw new Error(`File not found: ${path}`); - } - const bytes = Encoding.base64ToBytes(file.contentBase64); - const end = Math.min(bytes.length, offset + limit); - const slice = bytes.slice(offset, end); - return { - revision: '1:1', - name: file.name, - contentBase64: Encoding.bytesToBase64(slice), - offset, - chunkSize: slice.length, - totalSize: bytes.length, - mimeType: file.mimeType - }; - } - - async streamFile(path: string, sessionId: string | undefined, - onChunk: (bytes: Uint8Array, info: FileInfo) => Promise, - onProgress?: (downloaded: number, total: number) => void, - _location?: RuntimeFileLocation): Promise { - const file = this.files.get(path); - if (!file) { - throw new Error(`File not found: ${path}`); - } - const bytes = Encoding.base64ToBytes(file.contentBase64); - const info = await this.getFileInfo(path, sessionId); - await onChunk(bytes, info); - if (onProgress) { - onProgress(bytes.length, bytes.length); - } - return info; - } - - async readFile(path: string, sessionId?: string, onProgress?: (downloaded: number, total: number) => void, - maxBytes?: number): Promise { - const file = this.files.get(path); - if (!file) { - throw new Error(`File not found: ${path}`); - } - if (maxBytes !== undefined && file.size > maxBytes) { - throw new Error('File too large for preview.'); - } - const info = await this.getFileInfo(path, sessionId); - if (onProgress) { - onProgress(file.size, file.size); - } - return { - name: info.name, - mimeType: info.mimeType, - size: info.size, - contentBase64: file.contentBase64 - }; - } -} - -/** - * Stands in for the system document picker and the file it would write, so a - * download can be proved on a device without a destination dialog in the way. - * The production `RemoteFileDownloadController` owns everything else. - */ -class PreviewFileSaver implements RemoteFileSaver { - destinationName: string = ''; - bytesWritten: number = 0; - committed: boolean = false; - aborted: boolean = false; - - reset(): void { - this.destinationName = ''; - this.bytesWritten = 0; - this.committed = false; - this.aborted = false; - } - - async begin(name: string): Promise { - this.destinationName = name; - } - - async write(bytes: Uint8Array): Promise { - this.bytesWritten += bytes.length; - } - - async finish(): Promise { - this.committed = true; - return 'file://preview/download'; - } - - async abort(): Promise { - this.aborted = true; - } -} - -class PreviewDownloadScheduler implements RemoteFileDownloadScheduler { - setTimeout(_callback: () => void, _delayMs: number): number { - return 1; - } - - clearTimeout(_timerId: number): void {} -} - -/** - * The file-visibility chain as the phone walks it, driven by the production - * components: a durable assistant turn whose prose links workspace files is - * projected through the real reducer, timeline store and rows, and a tap on a - * card routes through the real `FilePreviewController` into the real - * `FilePreviewSurface`. - * - * Only the transport is faked. The fixture host answers `get_file_info`, - * `read_file_chunk` and the streamed read exactly like `remote_connect.rs` - * does, so the image branch decodes a real PNG and the text branches show real - * content. **Next shape** swaps the same links between the final-answer body - * and a composite turn's trailing text, which is the two paths that draw cards. - */ -@ComponentV2 -export struct FileVisibilityPreview { - private reducer: DurableSessionReducer = new DurableSessionReducer(); - private readonly timeline: ChatTimelineStore = new ChatTimelineStore(); - private readonly rowStore: ChatTimelineRowStore = new ChatTimelineRowStore(); - private readonly fileHost: PreviewFileHost = new PreviewFileHost(); - private readonly previewState: FilePreviewState = new FilePreviewState(); - private readonly fileSaver: PreviewFileSaver = new PreviewFileSaver(); - private readonly downloads: RemoteFileDownloadController = new RemoteFileDownloadController( - this.fileHost, - (downloadingFilePath: string, downloadedFilePath: string, fileDownloadStatus: string): void => { - this.downloadingFilePath = downloadingFilePath; - this.downloadedFilePath = downloadedFilePath; - this.downloadStatus = fileDownloadStatus; - }, - (): void => { - this.downloadingFilePath = ''; - }, - (statusText: string): void => { - this.downloadStatus = statusText; - this.savedSummary = this.fileSaver.committed ? - `${this.fileSaver.destinationName}:${this.fileSaver.bytesWritten}` : ''; - }, - (_isBusy: boolean): void => {}, - 2500, - new PreviewDownloadScheduler(), - this.fileSaver - ); - @Local rows: ObservableChatTimelineItem[] = []; - @Local revision: number = 0; - @Local shape: number = 0; - @Local routed: string = ''; - @Local previewVisible: boolean = false; - @Local downloadingFilePath: string = ''; - @Local downloadedFilePath: string = ''; - @Local downloadStatus: string = ''; - @Local savedSummary: string = ''; - private previewController?: FilePreviewController = undefined; - - aboutToAppear(): void { - this.previewController = new FilePreviewController( - this.fileHost, - this.previewState, - { - remoteAvailable: (): boolean => true, - activeSession: (): SessionSummary => { - const summary: SessionSummary = { - sessionId: 'preview-file-session', - title: 'File visibility', - workspacePath: '/workspace/project', - agentType: 'code' - }; - return summary; - }, - workspacePath: (): string => '/workspace/project', - openExternalLink: async (_reference: string): Promise => true, - onGeneralStatus: (_statusText: string): void => {}, - onRemoteStatus: (statusText: string): void => { - this.routed = statusText; - } - } - ); - this.timeline.reset('preview-file-session'); - this.publishShape(); - } - - aboutToDisappear(): void { - if (this.previewController) { - this.previewController.close(); - } - } - - private finalAnswer(): string { - return 'Done. The brand export wrote these files:\n\n' + - '- [openbitfun-wordmark.png](computer://png/openbitfun-wordmark.png)\n' + - '- [REPORT.md](computer://artifacts/REPORT.md)\n' + - '- [bundle.zip](computer://artifacts/bundle.zip)\n\n' + - 'The run log is at computer://artifacts/run.log, and the source image is ' + - 'png/openbitfun-wordmark.png.'; - } - - private trailingAnswer(): string { - return 'Checked the workspace files.\n\n' + - '- [openbitfun-wordmark.png](computer://png/openbitfun-wordmark.png)\n' + - '- [REPORT.md](computer://artifacts/REPORT.md)'; - } - - private record(id: string, revision: number, type: string, order: number, content: string, - toolName: string): HostSessionEvent { - const payload: SessionRecord = { - sessionId: 'preview-file-session', - id: `item/${id}`, - revision, - turn: { - turnId: 'turn-file-preview', - turnIndex: 0, - sessionId: 'preview-file-session', - timestamp: 1, - userMessage: { id: 'user-file-preview', content: 'Export the brand assets', timestamp: 1 }, - status: 'completed' - }, - round: { id: 'round-file-preview', turnId: 'turn-file-preview', roundIndex: 0, timestamp: 2, - status: 'completed' }, - item: { - type, - data: { id, orderIndex: order, timestamp: 3, content, toolName, status: 'completed' } - } - }; - return { session_id: 'preview-file-session', event: 'session-record', payload }; - } - - /** Rebuilds the transcript for the selected shape and republishes the rows. */ - private publishShape(): void { - this.reducer = new DurableSessionReducer(); - if (this.shape === 0) { - this.reducer.apply(this.record('final-text', 1, 'text', 0, this.finalAnswer(), '')); - } else { - this.reducer.apply(this.record('think', 1, 'thinking', 0, 'Reading the export output', '')); - this.reducer.apply(this.record('read', 2, 'tool', 1, '', 'Read')); - this.reducer.apply(this.record('trailing-text', 3, 'text', 2, this.trailingAnswer(), '')); - } - this.publish(); - } - - private publish(): void { - const messages = this.reducer.messages(); - this.timeline.applySnapshot({ - sessionId: 'preview-file-session', - cursor: { pollVersion: 0, knownMessageCount: messages.length, knownModelCatalogVersion: 0 }, - changed: true, - title: '', - sessionState: 'idle', - newMessages: [], - messageSnapshot: messages, - activeTurn: undefined, - shouldSyncAfterTurnEnded: false, - historyRewritten: false, - completedTurnId: '' - }); - this.rows = this.rowStore.reconcile(this.timeline.project(false)); - this.revision++; - } - - private openFilePreview(reference: string, label: string): void { - if (!this.previewController) { - return; - } - this.routed = reference; - this.previewController.open(AppRoute.RemoteChat, new FilePreviewRequest(reference, label)); - this.previewVisible = this.previewState.visible; - } - - private routeSummary(): string { - const phase = this.previewState.visible ? this.previewState.phase : FilePreviewPhase.Idle; - const saved = this.savedSummary.length > 0 ? ` saved=${this.savedSummary}` : ''; - return `shape=${this.shape} phase=${phase} kind=${this.previewState.rendererKind} ` + - `bytes=${this.previewState.loadedBytes} last=${this.routed}${saved}`; - } - - private downloadFile(reference: string): void { - this.downloadedFilePath = ''; - this.savedSummary = ''; - this.fileSaver.reset(); - void this.downloads.download( - reference, - 'preview-file-session', - false, - true - ); - } - - private closePreview(): void { - if (this.previewController) { - this.previewController.close(); - } - this.previewVisible = false; - } - - build() { - Stack() { - Column({ space: 8 }) { - Row({ space: 8 }) { - Button('Next shape').id('file-visibility-shape').onClick(() => { - this.shape = this.shape === 0 ? 1 : 0; - this.closePreview(); - this.publishShape(); - }) - } - Text(this.routeSummary()).id('file-visibility-state').fontColor(INK).fontSize(12) - ChatTimeline({ - timelineItems: this.rows, - timelineRevision: this.revision, - connectionState: 'connected', - isBusy: false, - downloadingFilePath: this.downloadingFilePath, - downloadedFilePath: this.downloadedFilePath, - fileDownloadStatus: this.downloadStatus, - activeFilePreviewPath: this.previewState.visible ? this.previewState.target.remotePath : '', - activeFilePreviewLoading: this.previewState.visible && - this.previewState.phase === FilePreviewPhase.Loading, - onOpenFilePreview: (path: string, label: string) => { - this.openFilePreview(path, label); - }, - onDownloadFile: (path: string) => { - this.downloadFile(path); - } - }) - .layoutWeight(1) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - - if (this.previewVisible) { - Column() { - FilePreviewSurface({ - state: this.previewState, - remoteAvailable: true, - downloadPath: this.downloadingFilePath, - downloadedPath: this.downloadedFilePath, - downloadStatus: this.downloadStatus, - onClose: () => { - this.closePreview(); - }, - onRefresh: () => { - if (this.previewController) { - this.previewController.refresh(); - } - }, - onDownload: (path: string) => { - this.downloadFile(path); - }, - onOpenLink: (reference: string, label: string) => { - this.openFilePreview(reference, label); - } - }) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - } - .width('100%') - .height('100%') - } -} \ No newline at end of file diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/HistoryScrollPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/HistoryScrollPreview.ets deleted file mode 100644 index 8f4b196aa5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/HistoryScrollPreview.ets +++ /dev/null @@ -1,59 +0,0 @@ -import { ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ChatTimeline } from '../components/ChatTimeline'; -import { INK, PAGE_BG } from '../components/Theme'; - -/** Hold a history response while exercising the production list's jump button. */ -@ComponentV2 -export struct HistoryScrollPreview { - @Local rows: ObservableChatTimelineItem[] = []; - @Local revision: number = 0; - @Local loading: boolean = false; - @Local failed: boolean = false; - @Local compact: boolean = false; - private page: number = 0; - - aboutToAppear(): void { - this.rows = this.pageRows(0); - } - - private pageRows(page: number): ObservableChatTimelineItem[] { - const rows: ObservableChatTimelineItem[] = []; - for (let index = 0; index < 20; index++) { - const id = `page-${page}-row-${index}`; - rows.push(new ObservableChatTimelineItem({ - id, type: 'user_message', isStreaming: false, isFinalizing: false, - message: { id, role: 'user', text: `History probe ${id}`, status: 'completed', timestamp: `${index}` } - })); - } - return rows; - } - - private finish(failed: boolean): void { - if (!this.loading) return; - if (!failed) { - this.page--; - this.rows = this.pageRows(this.page).concat(this.rows); - this.revision++; - } - this.failed = failed; - this.loading = false; - } - - build() { - Column({ space: 8 }) { - Row({ space: 8 }) { - Button('Complete').id('history-complete').onClick(() => { this.finish(false); }) - Button('Fail').id('history-fail').onClick(() => { this.finish(true); }) - Button('Resize').id('history-resize').onClick(() => { this.compact = !this.compact; }) - } - Text(`loading=${this.loading} failed=${this.failed} compact=${this.compact}`) - .id('history-state').fontColor(INK) - ChatTimeline({ - timelineItems: this.rows, timelineRevision: this.revision, - hasMoreMessages: true, historyLoading: this.loading, historyFailed: this.failed, - maxContentWidth: this.compact ? 360 : 0, - onLoadOlder: () => { this.failed = false; this.loading = true; } - }) - }.width('100%').height('100%').backgroundColor(PAGE_BG) - } -} 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 deleted file mode 100644 index c811a9c572..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ImmersiveBottomPreview.ets +++ /dev/null @@ -1,505 +0,0 @@ -import { ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { - ChatMessage, - RecentWorkspaceEntry, - RemoteSession, - REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1 -} from '../../model/RemoteModels'; -import { MiniAppSummary } from '../../model/MiniAppModels'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; -import { ChatSurface } from '../state/ChatSurface'; -import { REMOTE_CHAT_COMPOSER_CAPABILITIES } from '../state/ChatComposerCapabilities'; -import { AppShellState } from '../state/AppShellState'; -import { MiniAppState } from '../state/MiniAppState'; -import { RemotePageState } from '../state/RemotePageState'; -import { - DeviceDirectoryEntry, - DeviceDirectoryState, - emptyDeviceDirectoryEntry -} from '../state/DeviceDirectoryState'; -import { WorkspaceToolsState, WorkspaceFileEntry } from '../state/WorkspaceToolsState'; -import { ConversationView } from '../components/ConversationView'; -import { AppShell } from '../components/AppShell'; -import { MiniAppSurface } from '../components/MiniAppSurface'; -import { AppConnectSurface, AppSettingsSurface, AppSidebarSurface } from '../components/AppRootOverlaySurfaces'; -import { - RemoteSurfaceHost, - RemoteSurfaceMode, - RemoteSurfaceState -} from '../components/remote/RemoteSurfaceHost'; -import { AdaptiveSheetOptions } from '../components/AdaptiveSheetOptions'; -import { - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { - AppRootPresentationActions, - emptyAppRootPresentationActions -} from '../actions/AppRootPresentationActions'; -import { ComposerPresentation } from '../components/ComposerBar'; -import { ConversationViewOptions } from '../components/ConversationViewContract'; -import { ConversationViewState } from '../state/ConversationViewState'; -import { ConversationIntent } from '../actions/ConversationIntent'; - -/** Turns in the transcript. Long enough that the list has to scroll to reach the end. */ -const TRANSCRIPT_TURNS: number = 16; - -/** Tiles in the mini-app gallery: enough rows that the gallery itself scrolls. */ -const GALLERY_APPS: number = 9; - -/** Devices the account panel lists: enough rows that the settings sheet scrolls. */ -const SETTINGS_DEVICES: number = 9; - -/** Workspaces on the fixture desktop: enough rows that the sidebar's directory scrolls. */ -const SIDEBAR_WORKSPACES: number = 14; - -/** Sessions in the first workspace: the sidebar's own scrollable rows. */ -const SIDEBAR_SESSIONS: number = 36; - -/** Files in the workspace tools sheet: enough rows that the file list scrolls. */ -const TOOLS_FILES: number = 18; - -/** Lines in the seeded editor file: enough that the editor's web view scrolls. */ -const EDITOR_LINES: number = 120; - -/** Prose tall enough to be read while it is already half faded out. */ -const ANSWER_PARAGRAPH: string = - 'The transcript runs the full height of the pane, so the last answer keeps ' - + 'scrolling until it reaches the bottom edge of the screen. The composer ' - + 'floats over it and the fade carries the text into the page colour instead ' - + 'of cutting it off at a hard line.'; - -const FINAL_ANSWER_PARAGRAPH: string = - 'This is the final answer of the transcript, and it decides whether the bottom ' - + 'edge reads as a continuation of the conversation or as a strip of empty page ' - + 'colour: it must be able to scroll above the floating composer, and everything ' - + 'below the composer must still look like the surface the answer is drawn on. A ' - + 'reader who flings the list to the end should see the answer fade into the page ' - + 'rather than stop short of it.'; - -function message(id: string, role: string, text: string): ChatMessage { - return { id, role, text, status: 'completed', timestamp: '0' }; -} - -function row(id: string, role: string, text: string): ObservableChatTimelineItem { - return new ObservableChatTimelineItem({ - id, - type: role === 'user' ? 'user_message' : 'assistant_message', - message: message(id, role, text), - isStreaming: false, - isFinalizing: false - }); -} - -function transcript(): ObservableChatTimelineItem[] { - const rows: ObservableChatTimelineItem[] = []; - for (let index = 0; index < TRANSCRIPT_TURNS; index++) { - const turn = index + 1; - rows.push(row(`turn-${turn}-user`, 'user', `Round ${turn}: how does the bottom of the chat page read?`)); - rows.push(row(`turn-${turn}-assistant`, 'assistant', - turn === TRANSCRIPT_TURNS ? FINAL_ANSWER_PARAGRAPH : ANSWER_PARAGRAPH)); - } - return rows; -} - -function gallery(): MiniAppSummary[] { - const apps: MiniAppSummary[] = []; - for (let index = 0; index < GALLERY_APPS; index++) { - const tile = index + 1; - apps.push({ - id: `gallery-${tile}`, - name: `Mini app ${tile}`, - description: 'Offline sample tile, so the gallery has rows below the fold.' - }); - } - return apps; -} - -function settingsDevices(): DeviceDirectoryEntry[] { - const devices: DeviceDirectoryEntry[] = []; - for (let index = 0; index < SETTINGS_DEVICES; index++) { - const device = index + 1; - const entry = emptyDeviceDirectoryEntry(`account-desktop-${device}`, `Account desktop ${device}`, device % 3 !== 0); - entry.lastSeenAt = device; - devices.push(entry); - } - return devices; -} - -function sidebarWorkspaces(): RecentWorkspaceEntry[] { - const workspaces: RecentWorkspaceEntry[] = []; - for (let index = 0; index < SIDEBAR_WORKSPACES; index++) { - const workspace = index + 1; - workspaces.push({ - path: `/workspace/project-${workspace}`, - name: `Workspace ${workspace}`, - lastOpened: `${workspace}`, - workspaceKind: 'normal', - workspaceId: `ws-${workspace}` - }); - } - return workspaces; -} - -function sidebarSessions(): RemoteSession[] { - const sessions: RemoteSession[] = []; - for (let index = 0; index < SIDEBAR_SESSIONS; index++) { - const session = index + 1; - sessions.push({ - id: `sidebar-session-${session}`, - title: `Sidebar session ${String(session).padStart(2, '0')}`, - agentType: 'code', - status: 'completed', - updatedAt: `${session}`, - createdAt: `${session}`, - messageCount: session * 3, - workspacePath: '/workspace/project-1', - workspaceName: 'Workspace 1', - deviceId: 'fixture-desktop' - }); - } - return sessions; -} - -function toolsFiles(): WorkspaceFileEntry[] { - const entries: WorkspaceFileEntry[] = []; - for (let index = 0; index < TOOLS_FILES; index++) { - const file = index + 1; - const name = `report-${String(file).padStart(2, '0')}.md`; - entries.push({ - path: `/workspace/${name}`, - name, - isDirectory: false, - size: file * 64, - modifiedTime: file - }); - } - return entries; -} - -/** The file the editor tab opens: long enough that its content has to scroll. */ -function toolsEditorContent(): string { - const lines: string[] = []; - for (let index = 0; index < EDITOR_LINES; index++) { - const line = index + 1; - lines.push(`# Section ${line}`); - lines.push(''); - lines.push(`This line is body copy for section ${line}, long enough that the`); - lines.push('editor has to scroll before the last line can come to rest.'); - lines.push(''); - } - return lines.join('\n'); -} - -/** - * The empty actions with one override. The interface's members are readonly, - * so the settings sheet's device catalog is supplied by building the whole - * literal once rather than assigning into it. - */ -function previewActionsWithDevices(devices: CloudAccountDevice[]): AppRootPresentationActions { - const base = emptyAppRootPresentationActions(); - return { - onWorkspaceTools: base.onWorkspaceTools, - onNavigationBack: base.onNavigationBack, - onConversationIntent: base.onConversationIntent, - onCloseSidebar: base.onCloseSidebar, - onCompactLayoutEntered: base.onCompactLayoutEntered, - onLayoutModeChanged: base.onLayoutModeChanged, - onRemoteHome: base.onRemoteHome, - onSidebar: base.onSidebar, - onSettings: { - close: base.onSettings.close, - accountSettled: base.onSettings.accountSettled, - disconnect: base.onSettings.disconnect, - clearPairing: base.onSettings.clearPairing, - reconnect: base.onSettings.reconnect, - openAccount: base.onSettings.openAccount, - cloudCancelLogin: base.onSettings.cloudCancelLogin, - cloudLogin: base.onSettings.cloudLogin, - cloudLogout: base.onSettings.cloudLogout, - cloudListDevices: async (): Promise => devices, - cloudSelectDevice: base.onSettings.cloudSelectDevice, - getPermissionMode: base.onSettings.getPermissionMode, - setPermissionMode: base.onSettings.setPermissionMode, - getDeviceModelCatalog: base.onSettings.getDeviceModelCatalog, - setDeviceModelDefaults: base.onSettings.setDeviceModelDefaults, - setLanguage: base.onSettings.setLanguage - }, - onConnect: base.onConnect, - onFilePreview: base.onFilePreview, - generalStatus: base.generalStatus - }; -} - -/** - * The chat page's bottom edge, drawn by the production `ConversationView` over a - * transcript long enough to scroll: the composer and the status line float over - * the list, and the list carries the page colour down to the bottom of the - * screen. - * - * This fixture exists because the bottom edge cannot be judged from the composer - * alone: where the input ends up, how far the last message can scroll, and which - * colour the fade finishes on are three separate readings of one capture, and the - * layout dump has to show the same pane the pixels do. - * - * The scenario id picks the state, because the shell has to be in it before the - * first frame: `-wide` swaps the composer to the wide detail pane's floating - * presentation, `-drawer` mounts the production `AppShell` with its drawer open - * over the same conversation, `-settings` and `-cover` mount the shell with its - * settings sheet and its compact account cover open, `-miniapps` mounts the - * mini-app gallery, `-tools` opens the workspace tools sheet over the drawer - * (with `-tools-editor` opening it on the editor tab and - * `-tools-file-action` opening its file action form), `-view-settings` opens - * the remote view settings sheet over the same conversation, and `-connect` - * opens the connect sheet. The drawer, settings and tools states seed remote - * content — a device with workspaces and sessions, an account with desktops, a - * directory of files — because a surface whose content fits its viewport has no - * bottom edge to read. None of them changes the window posture: every one of - * these surfaces shares the shell's immersive layout, so every one of them is - * where a control can end up under the navigation bar. - */ -@ComponentV2 -export struct ImmersiveBottomPreview { - @Local state: ConversationViewState = this.initialState(); - @Local shellState: AppShellState = this.initialShellState(); - @Local miniAppState: MiniAppState = this.initialMiniAppState(); - @Local remotePageState: RemotePageState = new RemotePageState(); - @Local directoryState: DeviceDirectoryState = new DeviceDirectoryState(); - @Local previewActions: AppRootPresentationActions = emptyAppRootPresentationActions(); - @Local floating: boolean = false; - @Local drawer: boolean = false; - @Local settings: boolean = false; - @Local cover: boolean = false; - @Local galleryVisible: boolean = false; - @Local wideShell: boolean = false; - @Local viewSettings: boolean = false; - @Local showViewSettingsSheet: boolean = false; - @Local remoteSurfaceState: RemoteSurfaceState = new RemoteSurfaceState(); - - aboutToAppear(): void { - const scenarioId = AppStorage.get('scenarioId') ?? ''; - this.floating = scenarioId.endsWith('-wide') && !scenarioId.endsWith('-wide-shell'); - this.drawer = scenarioId.includes('-drawer') || scenarioId.startsWith('immersive-bottom-tools'); - this.settings = scenarioId.endsWith('-settings') || scenarioId.endsWith('-settings-dark'); - this.cover = scenarioId.endsWith('-cover'); - this.galleryVisible = scenarioId.endsWith('-miniapps'); - // The wide shell keeps the same session list as a master pane instead of a - // drawer, so its bottom edge is the same bottom edge. - this.wideShell = scenarioId.endsWith('-wide-shell'); - this.viewSettings = scenarioId.endsWith('-view-settings'); - this.showViewSettingsSheet = this.viewSettings; - // The shell's own surfaces have to be open before the first frame, and the - // scenario id is only known once the page is appearing, so the flags are - // applied here rather than in the field initialisers. - this.shellState.showSidebar = this.drawer || this.wideShell; - this.shellState.showSettings = this.settings || this.cover; - this.shellState.showConnectSheet = scenarioId.endsWith('-connect'); - if (this.cover) { - this.shellState.settingsMode = 'account'; - } - this.seedRemoteState(scenarioId); - } private initialState(): ConversationViewState { - const state = new ConversationViewState(); - state.surface = ChatSurface.Remote; - state.connectionState = 'connected'; - state.activeSession = { - sessionId: 'immersive-bottom-preview', - title: 'Bottom edge', - workspacePath: '/workspace', - agentType: 'code' - }; - state.desktopName = 'Studio'; - state.composerCapabilities = REMOTE_CHAT_COMPOSER_CAPABILITIES; - state.timelineItems = transcript(); - state.timelineRevision = 1; - return state; - } - - private initialShellState(): AppShellState { - return new AppShellState(); - } - - private initialMiniAppState(): MiniAppState { - const state = new MiniAppState(); - state.visible = true; - state.apps = gallery(); - return state; - } - - /** - * Remote content for the shell's own surfaces. The surfaces under test scroll, - * so their fixture content has to overflow their viewport: the settings sheet - * lists an account's desktops, the drawer carries a device directory with - * workspaces and sessions, and the tools sheet carries a directory of files. - * The connect sheet carries a persisted legacy pairing link, because its - * status strip — the fixed control at its bottom edge — is what that state - * mounts there. The view settings sheet shares the drawer's directory because - * its filters are what scroll in it. - */ - private seedRemoteState(scenarioId: string): void { - if (this.settings) { - this.remotePageState.setAccountUserId('octocat'); - this.remotePageState.setAccountUsername('octocat'); - this.remotePageState.setControlTarget('account_device', 'account-desktop-1', 'Account desktop 1'); - this.remotePageState.setDesktopIdentity('Account desktop 1', 'account-desktop-1'); - this.remotePageState.connectionState = 'connected'; - // The model settings entry on the controlled desktop's row is offered or - // greyed by the desktop's own capability set, and an empty set can only ever - // 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]); - const devices = settingsDevices(); - this.directoryState.replace(devices); - this.previewActions = previewActionsWithDevices(devices); - return; - } - if (scenarioId.endsWith('-connect')) { - this.remotePageState.setPairingInput('https://pair.example/openbitfun/legacy', 'user-1', false); - return; - } - if (this.drawer || this.viewSettings) { - const desktop: DeviceDirectoryEntry = emptyDeviceDirectoryEntry('fixture-desktop', 'Studio', true); - desktop.status = 'ready'; - desktop.workspaces = sidebarWorkspaces(); - this.directoryState.replace([desktop]); - this.directoryState.select('fixture-desktop'); - this.directoryState.setWorkspaceExpanded('fixture-desktop', '/workspace/project-1', true, - undefined, undefined, 'ws-1'); - this.remotePageState.setControlTarget('account_device', 'fixture-desktop', 'Studio'); - this.remotePageState.setDesktopIdentity('Studio', 'fixture-desktop'); - this.remotePageState.connectionState = 'connected'; - this.remotePageState.workspacePath = '/workspace/project-1'; - this.remotePageState.workspaceName = 'Workspace 1'; - this.remotePageState.workspaceId = 'ws-1'; - this.remotePageState.workspaceKind = 'normal'; - this.remotePageState.setSessions(sidebarSessions(), false); - if (scenarioId.startsWith('immersive-bottom-tools')) { - this.remotePageState.workspaceTools.visible = true; - this.remotePageState.workspaceTools.directory = '/workspace'; - this.remotePageState.workspaceTools.entries = toolsFiles(); - if (scenarioId.endsWith('-tools-editor')) { - // The editor tab: the WebView is the tab's bottom edge, so its content - // has to be long enough to scroll inside it. - this.remotePageState.workspaceTools.editorVisible = true; - this.remotePageState.workspaceTools.selectedFile = '/workspace/report-01.md'; - this.remotePageState.workspaceTools.content = toolsEditorContent(); - } - if (scenarioId.endsWith('-tools-file-action')) { - // The file action form: a FIT_CONTENT sheet whose buttons are the - // fixed controls at the screen edge. - this.remotePageState.workspaceTools.fileAction = 'file'; - } - } - } - } - - private options(): ConversationViewOptions { - const options = new ConversationViewOptions(); - options.showSidebarButton = true; - options.showBackButton = false; - options.composerPresentation = - this.floating ? ComposerPresentation.Floating : ComposerPresentation.Compact; - return options; - } - - build() { - if (this.galleryVisible) { - MiniAppSurface({ state: this.miniAppState }) - } else if (this.viewSettings) { - this.ViewSettingsLayout() - } else if (this.drawer || this.settings || this.cover || this.wideShell || - this.shellState.showConnectSheet) { - this.ShellLayout() - } else { - this.Conversation() - } - } - - /** - * The remote view settings sheet, mounted the way the app root mounts it: a - * bindSheet with the compact placement's options over the conversation. The - * sheet is the production `RemoteSurfaceHost` in its settings mode, so the - * surface under test is the production component. - */ - @Builder - private ViewSettingsLayout() { - Column() { - this.Conversation() - } - .width('100%') - .height('100%') - .bindSheet($$this.showViewSettingsSheet, this.ViewSettingsSheet(), AdaptiveSheetOptions.fromPlacement( - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.RemoteViewSettings), true)) - } - - @Builder - private ViewSettingsSheet() { - RemoteSurfaceHost({ - mode: RemoteSurfaceMode.Settings, - remotePageState: this.remotePageState, - presentationState: this.remoteSurfaceState, - actions: this.previewActions, - onCloseSettings: () => { this.showViewSettingsSheet = false; } - }) - } - - /** - * The drawer, the settings sheet, the connect sheet and the compact account - * cover are all shell surfaces rather than pages, so they are mounted through - * the production shell with the production content for their slot. Each of - * them has its own bottom edge, and the shell is what moves them with the - * window. - */ - @Builder - private ShellLayout() { - AppShell({ - shellState: this.shellState, - useWideLayout: this.wideShell, - allowSidebar: true, - compactAccountLogin: this.cover, - content: () => { this.Conversation(); }, - sidebar: () => { this.Sidebar(); }, - settings: () => { this.Settings(); }, - connect: () => { this.Connect(); }, - onCloseSidebar: () => { this.shellState.showSidebar = false; } - }) - } - - @Builder - private Settings() { - AppSettingsSurface({ - deviceDirectoryState: this.directoryState, - shellState: this.shellState, - remotePageState: this.remotePageState, - actions: this.previewActions - }) - } - - @Builder - private Connect() { - AppConnectSurface({ - deviceDirectoryState: this.directoryState, - remotePageState: this.remotePageState, - actions: this.previewActions - }) - } - - @Builder - private Sidebar() { - AppSidebarSurface({ - shellState: this.shellState, - remotePageState: this.remotePageState, - deviceDirectoryState: this.directoryState, - actions: emptyAppRootPresentationActions() - }) - } - - @Builder - private Conversation() { - ConversationView({ - state: this.state, - options: this.options(), - onIntent: (_intent: ConversationIntent): void => {} - }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/InteractionMailboxPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/InteractionMailboxPreview.ets deleted file mode 100644 index 5583f7f921..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/InteractionMailboxPreview.ets +++ /dev/null @@ -1,36 +0,0 @@ -import { InteractionMailboxAction, InteractionMailboxActionType, InteractionMailboxState } from '../../model/InteractionMailbox'; -import { ConversationView } from '../components/ConversationView'; -import { ConversationViewState } from '../state/ConversationViewState'; -import { ChatSurface } from '../state/ChatSurface'; -import { ConversationIntentType, ConversationIntent } from '../actions/ConversationIntent'; - -/** Deterministic native UI fixture; never opens a transport or modifies account state. */ -@ComponentV2 -export struct InteractionMailboxPreview { - @Local state: ConversationViewState = this.initialState(); - - private initialState(): ConversationViewState { - const state = new ConversationViewState(); - state.surface = ChatSurface.Remote; - state.connectionState = 'connected'; - state.activeSession = { sessionId: 'mailbox-preview', title: 'Interaction mailbox', workspacePath: '/workspace', agentType: 'code' }; - state.interactionMailbox.sessionId = 'mailbox-preview'; - state.interactionMailbox.requests = [{ requestId: 'preview-write', sessionId: 'mailbox-preview', - action: 'write', resources: ['/workspace/readme.md'], source: { identity: 'Write' } }]; - return state; - } - - build() { - ConversationView({ state: this.state, onIntent: (intent: ConversationIntent): void => { - if (intent.type === ConversationIntentType.Mailbox && intent.mailboxAction) this.handle(intent.mailboxAction); - } }) - } - - private handle(action: InteractionMailboxAction): void { - const next = this.initialState(); - if (action.type === InteractionMailboxActionType.Approve || action.type === InteractionMailboxActionType.Reject) { - next.interactionMailbox.failure = 'reply'; - } - this.state = next; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/MobileDesignGallery.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/MobileDesignGallery.ets deleted file mode 100644 index f44b5e2446..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/MobileDesignGallery.ets +++ /dev/null @@ -1,214 +0,0 @@ -import { HistoryScrollPreview } from './HistoryScrollPreview'; -import { ColdStartHomePreview } from './ColdStartHomePreview'; -import { ComposerSubmissionPreview } from './ComposerSubmissionPreview'; -import { CopySelectionPreview } from './CopySelectionPreview'; -import { RollbackStagingPreview } from './RollbackStagingPreview'; -import { DurableTimelinePreview } from './DurableTimelinePreview'; -import { DeviceSelectorPreview } from './DeviceSelectorPreview'; -import { CatalogRefreshPreview } from './CatalogRefreshPreview'; -import { ModelRoleSelectorPreview } from './ModelRoleSelectorPreview'; -import { SubagentProcessPreview } from './SubagentProcessPreview'; -import { FileVisibilityPreview } from './FileVisibilityPreview'; -import { ComposerOverflowPreview } from './ComposerOverflowPreview'; -import { CommandPalettePreview } from './CommandPalettePreview'; -import { ImmersiveBottomPreview } from './ImmersiveBottomPreview'; -import { DeviceModelDefaultsPreview } from './DeviceModelDefaultsPreview'; -import { WelcomeHome } from '../components/WelcomeHome'; -import { InteractionMailboxPreview } from './InteractionMailboxPreview'; -import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; -import { - MobilePreviewMessage, - MobilePreviewScenario, - MobilePreviewScenarios -} from '../../generated/MobilePreviewScenarios'; -import { ComposerBar, ComposerPresentation } from '../components/ComposerBar'; -import { ConversationHeader } from '../components/ConversationHeader'; -import { INK, LINE, MUTED, PAGE_BG, SOFT, TRANSPARENT } from '../components/Theme'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; - -@Entry -@ComponentV2 -struct MobileDesignGallery { - @Param scenario: MobilePreviewScenario = MobilePreviewScenarios.connectedConversation; - - private resolvedScenario(): MobilePreviewScenario { - switch (AppStorage.get('scenarioId') ?? '') { - case 'streaming-dark': - return MobilePreviewScenarios.streamingDark; - case 'reconnecting-wide': - return MobilePreviewScenarios.reconnectingWide; - case 'narrow-multiline': return MobilePreviewScenarios.narrowMultiline; - case 'fold-context': return MobilePreviewScenarios.foldContext; - case 'long-reading': return MobilePreviewScenarios.longReading; - case 'connected-conversation': - return MobilePreviewScenarios.connectedConversation; - default: - return this.scenario; - } - } - - build() { - if ((AppStorage.get('scenarioId') || '').startsWith('cold-start-home')) { - ColdStartHomePreview() - } else if (AppStorage.get('scenarioId') === 'history-scroll') { - HistoryScrollPreview() - } else if (AppStorage.get('scenarioId') === 'durable-timeline') { - DurableTimelinePreview() - } else if (AppStorage.get('scenarioId') === 'composer-submit') { - ComposerSubmissionPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('catalog-refresh')) { - CatalogRefreshPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('model-role-selector')) { - ModelRoleSelectorPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('subagent-process') || - (AppStorage.get('scenarioId') || '').startsWith('subagent-swarm')) { - SubagentProcessPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('file-visibility')) { - FileVisibilityPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('composer-overflow')) { - ComposerOverflowPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('command-palette')) { - CommandPalettePreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('immersive-bottom')) { - ImmersiveBottomPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('device-selector')) { - DeviceSelectorPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('device-model')) { - DeviceModelDefaultsPreview() - } else if (AppStorage.get('scenarioId') === 'welcome-home') { - WelcomeHome() - } else if ((AppStorage.get('scenarioId') || '').startsWith('copy-selection')) { - CopySelectionPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('copy-rollback')) { - RollbackStagingPreview() - } else if ((AppStorage.get('scenarioId') || '').startsWith('interaction-mailbox')) { - InteractionMailboxPreview() - } else { - this.ConversationPreview() - } - } - - @Builder - private ConversationPreview() { - Column() { - this.PlatformLabel() - ConversationHeader({ - title: this.resolvedScenario().headerTitle, - subtitle: this.resolvedScenario().headerSubtitle, - showSidebarButton: true, - showActions: true - }) - Column({ space: MobileDesignGeometry.messageSpacing }) { - ForEach(this.resolvedScenario().messages, (message: MobilePreviewMessage) => { - this.MessageRow(message) - }, (message: MobilePreviewMessage) => `${message.role}:${message.text}`) - } - .layoutWeight(1) - .width('100%') - .alignItems(HorizontalAlign.Start) - .padding({ - left: MobileDesignGeometry.contentGutter, - right: MobileDesignGeometry.contentGutter, - top: MobileDesignGeometry.timelineTopPadding - }) - ComposerBar({ - presentation: ComposerPresentation.Compact, - chatInput: this.resolvedScenario().composerDraft, - isBusy: this.resolvedScenario().streaming, - canStop: this.resolvedScenario().streaming, - connectionState: this.resolvedScenario().connectionPhase - }) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - @Builder - private PlatformLabel() { - Row({ space: 8 }) { - Text(RemoteI18n.t('app.title')) - .fontSize(MobileDesignTypography.labelMedium.size) - .fontWeight(FontWeight.Medium) - .fontColor(INK) - Text(RemoteI18n.t('app.title')) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - .padding({ left: 8, right: 8, top: 4, bottom: 4 }) - .backgroundColor(SOFT) - .borderRadius(10) - Blank() - Text(`${this.resolvedScenario().viewportWidth} × ${this.resolvedScenario().viewportHeight}`) - .fontSize(MobileDesignTypography.labelSmall.size) - .fontColor(MUTED) - } - .width('100%') - .height(MobileDesignGeometry.connectionStripHeight) - .padding({ left: MobileDesignGeometry.contentGutter, right: MobileDesignGeometry.contentGutter }) - .border({ width: { bottom: 1 }, color: LINE }) - } - - @Builder - private MessageRow(message: MobilePreviewMessage) { - Row() { - if (message.role === 'user') { - Blank() - } - Text(message.text) - .fontSize(MobileDesignTypography.bodyLarge.size) - .fontColor(INK) - .lineHeight(MobileDesignTypography.bodyLarge.lineHeight) - .constraintSize({ - maxWidth: message.role === 'user' ? MobileDesignGeometry.messageBubbleMaxWidth : '100%' - }) - .padding({ - left: message.role === 'user' ? MobileDesignGeometry.messageBubbleHorizontalPadding : 0, - right: message.role === 'user' ? MobileDesignGeometry.messageBubbleHorizontalPadding : 0, - top: message.role === 'user' ? MobileDesignGeometry.messageBubbleVerticalPadding : 2, - bottom: message.role === 'user' ? MobileDesignGeometry.messageBubbleVerticalPadding : 2 - }) - .backgroundColor(message.role === 'user' ? SOFT : TRANSPARENT) - .borderRadius(message.role === 'user' ? MobileDesignGeometry.messageBubbleRadius : 0) - if (message.role !== 'user') { - Blank() - } - } - .width('100%') - } -} - -@Preview({ - title: 'OpenBitFun Mobile · Compact', - width: 390, - height: 844 -}) -@ComponentV2 -struct MobileDesignCompactPreview { - build() { - MobileDesignGallery({ scenario: MobilePreviewScenarios.connectedConversation }) - } -} - -@Preview({ - title: 'OpenBitFun Mobile · Dark', - width: 390, - height: 844 -}) -@ComponentV2 -struct MobileDesignStreamingDarkPreview { - build() { - MobileDesignGallery({ scenario: MobilePreviewScenarios.streamingDark }) - } -} - -@Preview({ - title: 'OpenBitFun Mobile · Wide', - width: 1024, - height: 768 -}) -@ComponentV2 -struct MobileDesignWidePreview { - build() { - MobileDesignGallery({ scenario: MobilePreviewScenarios.reconnectingWide }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ModelRoleSelectorPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ModelRoleSelectorPreview.ets deleted file mode 100644 index 9f630470a1..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ModelRoleSelectorPreview.ets +++ /dev/null @@ -1,98 +0,0 @@ -import { RemoteModelCatalog, RemoteModelConfig } from '../../model/RemoteModels'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { ConversationUiModelCatalog, toConversationUiModelCatalog } from '../state/ConversationUiModels'; -import { ComposerBar, ComposerPresentation } from '../components/ComposerBar'; -import { INK, PAGE_BG } from '../components/Theme'; - -/** - * Drives the production composer with a model catalog fixture so the - * primary/fast role rows, their resolved metadata, and the concrete-model role - * badges can be inspected on a device. - * - * No account, host, or remote request is involved: the catalog is projected - * through the same `toConversationUiModelCatalog` path the app uses, the - * selection starts from the session model id the same way hydration does, and - * the select handler records the payload it received instead of talking to a - * host. The recorded payload is surfaced on screen so a screenshot can prove it. - */ -@ComponentV2 -export struct ModelRoleSelectorPreview { - @Local catalog: ConversationUiModelCatalog = toConversationUiModelCatalog(this.fixtureCatalog()); - @Local selectedModelId: string = RemoteUiState.selectedModelIdForCatalog(this.fixtureCatalog(), ''); - @Local received: string = ''; - @Local wide: boolean = false; - // The model control lives in the expanded action row, and the composer only - // expands for focus, an open selector, or a multiline draft. A two-line draft - // reaches that state without depending on the emulator's IME. - @Local draft: string = 'Model role selector probe\nor the fallback row'; - - aboutToAppear(): void { - // The launcher decides the posture through the scenario id, so both - // presentations can be captured without an extra tap. Resize still toggles - // the presentation live. - this.wide = (AppStorage.get('scenarioId') ?? '').endsWith('-wide'); - } - - private fixtureModel(id: string, name: string, provider: string, modelName: string, - contextWindow: number, enabled: boolean): RemoteModelConfig { - return { - id: id, - name: name, - provider: provider, - base_url: '', - model_name: modelName, - context_window: contextWindow, - enabled: enabled, - capabilities: [] - }; - } - - /** Four enabled models plus one disabled one, with distinct primary and fast targets. */ - private fixtureCatalog(): RemoteModelCatalog { - return { - version: 1, - models: [ - this.fixtureModel('anthropic/claude-sonnet-4.5', 'Claude Sonnet 4.5', 'anthropic', - 'claude-sonnet-4-5', 200000, true), - this.fixtureModel('openbitfun:gpt-5-mini', 'GPT-5 mini', 'openai', - 'openbitfun:gpt-5-mini', 128000, true), - this.fixtureModel('google/gemini-2.5-flash', 'Gemini 2.5 Flash', 'google', - 'gemini-2.5-flash', 1000000, true), - this.fixtureModel('local:qwen3-coder', 'Qwen3 Coder', 'local', 'qwen3-coder', 32768, true), - this.fixtureModel('legacy/disabled-model', 'Legacy model', 'legacy', 'legacy-model', 8192, false) - ], - default_models: { - primary: 'anthropic/claude-sonnet-4.5', - fast: 'openbitfun:gpt-5-mini', - search: '', - image_understanding: '' - }, - session_model_id: 'fast' - }; - } - - build() { - Column({ space: 8 }) { - Row({ space: 8 }) { - Button('Resize').id('model-role-resize').onClick(() => { this.wide = !this.wide; }) - } - Text(`selected=${this.selectedModelId} received=${this.received}`) - .id('model-role-state').fontColor(INK) - Blank() - ComposerBar({ - presentation: this.wide ? ComposerPresentation.Floating : ComposerPresentation.Compact, - chatInput: this.draft, - modelCatalog: this.catalog, - selectedModelId: this.selectedModelId, - onChatInputChange: (value: string) => { this.draft = value; }, - onSelectModel: (modelId: string) => { - this.received = modelId; - this.selectedModelId = modelId; - } - }) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackPreviewScenario.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackPreviewScenario.ets deleted file mode 100644 index e787c7e589..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackPreviewScenario.ets +++ /dev/null @@ -1,345 +0,0 @@ -import { - ChatMessage, - RemoteImageContext, - REMOTE_CAPABILITY_SESSION_ROLLBACK_V1, - SessionRolledBackResult, - SteerTurnResult -} from '../../model/RemoteModels'; -import { RemoteChatCommandClient } from '../../services/RemoteChatCommandController'; - -/** - * The mock host and the mock transcript behind the staged-rollback fixture. - * - * The frozen interaction (`.openbitfun/plans/mobile-copy-rollback.plan.md`, - * decision 4) can only be read on a device: the entry rides a system selection - * menu, the ghosts and the bar are drawn by the production pane, and the composer - * is refilled through it. No paired host is reachable from an emulator, so the - * fixture poses as one: it answers `rollback_session_to_turn` with a canned - * response derived from the transcript it is showing, and it records the calls it - * received so the order between the rollback and the send that follows it can be - * read off a screenshot. - * - * Everything here is data and a transport, deliberately away from ArkUI: the - * variant table, the transcript, the canned answer and the recorded call order - * are all reachable from a host test (`tools/tests/rollback-preview.test.cjs`), - * so the fixture cannot claim an answer its own transcript would not produce. - */ - -/** Which answer the mock host gives. One variant per device-verification cell. */ -export enum RollbackPreviewVariant { - /** The host retires the target turn and everything after it. */ - Success = 'success', - /** The host refuses the rollback for a reason the client must say out loud. */ - RollbackFailed = 'rollback_failed', - /** The host no longer holds the turn this client addressed. */ - StaleTarget = 'stale_target', - /** A turn is running, so the rollback entry refuses before any command. */ - SessionBusy = 'session_busy', - /** The handshake never advertised `session_rollback_v1`. */ - HostUnsupported = 'host_unsupported', - /** The rollback succeeds and the message staged with it is accepted. */ - SendAccepted = 'send_accepted', - /** The rollback succeeds and the message staged with it is refused. */ - SendFailed = 'send_failed' -} - -/** One mock turn: the user prompt the host can be rolled back to. */ -export class RollbackPreviewTurn { - readonly turnId: string; - readonly prompt: string; - - constructor(turnId: string, prompt: string) { - this.turnId = turnId; - this.prompt = prompt; - } -} - -export class RollbackPreviewScenario { - static readonly DEFAULT_ID: string = 'copy-rollback'; - private static readonly DARK_SUFFIX: string = '-dark'; - /** The refusal every other failure is, as the host words it. */ - static readonly FAILED_ERROR: string = 'Preview rollback was refused'; - /** One of the coordinator's own stale-target markers, verbatim. */ - static readonly STALE_ERROR: string = 'Session rollback target is stale'; - static readonly SEND_FAILED_ERROR: string = 'Preview send was refused'; - /** Two files, so the notice row's file count is a number the transcript cannot supply. */ - static readonly RESTORED_FILES: string[] = [ - 'src/mobile/ChatTimeline.ets', - 'src/mobile/RollbackStagingBar.ets' - ]; - /** The turn the mock host reports for an accepted send. */ - static readonly ACCEPTED_TURN_ID: string = 'turn-7'; - /** - * The draft the composer already holds when the fixture opens, so "close restores - * the pre-staging snapshot" is a comparison between two readable strings rather - * than between one string and an empty field. - */ - static readonly INITIAL_DRAFT: string = 'DRAFT-未发送的草稿-42'; - - /** The scenario id without its colour-mode suffix, which never changes the variant. */ - static baseId(scenarioId: string): string { - const id = scenarioId.length > 0 ? scenarioId : RollbackPreviewScenario.DEFAULT_ID; - return id.endsWith(RollbackPreviewScenario.DARK_SUFFIX) ? - id.substring(0, id.length - RollbackPreviewScenario.DARK_SUFFIX.length) : id; - } - - static isDark(scenarioId: string): boolean { - return (scenarioId.length > 0 ? scenarioId : RollbackPreviewScenario.DEFAULT_ID) - .endsWith(RollbackPreviewScenario.DARK_SUFFIX); - } - - static variant(scenarioId: string): RollbackPreviewVariant { - switch (RollbackPreviewScenario.baseId(scenarioId)) { - case 'copy-rollback-fail': - return RollbackPreviewVariant.RollbackFailed; - case 'copy-rollback-stale': - return RollbackPreviewVariant.StaleTarget; - case 'copy-rollback-busy': - return RollbackPreviewVariant.SessionBusy; - case 'copy-rollback-unsupported': - return RollbackPreviewVariant.HostUnsupported; - case 'copy-rollback-send': - return RollbackPreviewVariant.SendAccepted; - case 'copy-rollback-send-fail': - return RollbackPreviewVariant.SendFailed; - default: - return RollbackPreviewVariant.Success; - } - } - - /** - * What the handshake advertised. A host that never promised the capability is - * the one case where the entry is refused for a fact about the connection - * rather than about the session. - */ - static hostCapabilities(variant: RollbackPreviewVariant): string[] { - if (variant === RollbackPreviewVariant.HostUnsupported) { - return ['dialog_steer_v1']; - } - return ['dialog_steer_v1', REMOTE_CAPABILITY_SESSION_ROLLBACK_V1]; - } - - static sessionBusy(variant: RollbackPreviewVariant): boolean { - return variant === RollbackPreviewVariant.SessionBusy; - } - - static initialDraft(_variant: RollbackPreviewVariant): string { - return RollbackPreviewScenario.INITIAL_DRAFT; - } - - /** The host's refusal for a rollback, or an empty string when it accepts. */ - static rollbackError(variant: RollbackPreviewVariant): string { - if (variant === RollbackPreviewVariant.RollbackFailed) { - return RollbackPreviewScenario.FAILED_ERROR; - } - if (variant === RollbackPreviewVariant.StaleTarget) { - return RollbackPreviewScenario.STALE_ERROR; - } - return ''; - } - - /** Whether the message sent alongside the rollback reaches the host at all. */ - static sendFails(variant: RollbackPreviewVariant): boolean { - return variant === RollbackPreviewVariant.SendFailed; - } -} - -/** - * The mock conversation: three turns, each a user prompt and its answer. - * - * Three shapes are needed and each of them is one entry surface: a short prompt - * whose long press raises the system selection menu, an eleven-line prompt the - * bubble truncates and a long press opens the lightweight menu on, and a - * third turn whose rows make "the target and everything after it" a cut with - * more than one turn behind it. - */ -export class RollbackPreviewTranscript { - static readonly SESSION_ID: string = 'rollback-preview'; - static readonly SHORT_PROMPT: string = '这段代码为什么会有内存泄漏?'; - /** - * Eleven lines against the eight-line rule, so the bubble truncates it and the - * entry is reached through the truncated bubble's own menu. - */ - static readonly LONG_PROMPT: string = [ - '请按下面的清单完整处理这次改动:', - '1. 在会话时间线里定位用户消息的渲染路径;', - '2. 为长消息加截断预览,并在行尾追加可点开的入口;', - '3. 面板内要能长按选择并复制,手柄可以调整范围;', - '4. 截断态气泡不给手柄,长按弹出轻量菜单;', - '5. 暂存回滚要能预览被撤回的消息,再决定去留;', - '6. 关闭、直接发送、确认回滚三条出口都要走一遍;', - '7. 回滚成功后草稿必须保留,并且给出提示行;', - '8. 浅色与深色主题都要检查对比度;', - '9. 竖屏与平板横屏两种布局都要走一遍;', - '10. 最后把设备证据截图归档。' - ].join('\n'); - static readonly TAIL_PROMPT: string = '再补一条:深色主题与平板横屏也各走一遍。'; - - static turns(): RollbackPreviewTurn[] { - return [ - new RollbackPreviewTurn('turn-1', RollbackPreviewTranscript.SHORT_PROMPT), - new RollbackPreviewTurn('turn-3', RollbackPreviewTranscript.LONG_PROMPT), - new RollbackPreviewTurn('turn-5', RollbackPreviewTranscript.TAIL_PROMPT) - ]; - } - - static messages(): ChatMessage[] { - return [ - RollbackPreviewTranscript.message('preview-user-1', 'user', RollbackPreviewTranscript.SHORT_PROMPT, 'turn-1'), - RollbackPreviewTranscript.message('preview-answer-1', 'assistant', - '截断与全文面板都需要自己的选择表面,我先确认这两条路径。', 'turn-1'), - RollbackPreviewTranscript.message('preview-user-3', 'user', RollbackPreviewTranscript.LONG_PROMPT, 'turn-3'), - RollbackPreviewTranscript.message('preview-answer-3', 'assistant', - '清单收到,我先按顺序改渲染路径,再回到这里核对回滚入口。', 'turn-3'), - RollbackPreviewTranscript.message('preview-user-5', 'user', RollbackPreviewTranscript.TAIL_PROMPT, 'turn-5'), - RollbackPreviewTranscript.message('preview-answer-5', 'assistant', - '深色主题与横屏布局会各跑一遍。', 'turn-5') - ]; - } - - /** The prompt a turn was sent with, which is what the host hands back to edit. */ - static promptFor(turnId: string): string { - const turns = RollbackPreviewTranscript.turns(); - for (let index = 0; index < turns.length; index += 1) { - if (turns[index].turnId === turnId) { - return turns[index].prompt; - } - } - return ''; - } - - /** - * The turn ids the host retires for one target, in transcript order. - * - * `retired_turn_ids` includes the target turn itself (see `RemoteModels`), so - * this is the target's turn and every turn after it — derived from the rows the - * fixture shows rather than written out, because a canned list that disagreed - * with the transcript would be a mock answering about history that is not on - * screen. - */ - static retiredTurnIds(targetTurnId: string): string[] { - const rows = RollbackPreviewTranscript.messages(); - const retired: string[] = []; - let started = false; - for (let index = 0; index < rows.length; index += 1) { - const turnId = rows[index].turnId || ''; - if (!started && turnId === targetTurnId) { - started = true; - } - if (started && retired.indexOf(turnId) < 0) { - retired.push(turnId); - } - } - return retired; - } - - /** Index of the first row of one turn, or -1 when the transcript has no such turn. */ - static startIndex(targetTurnId: string): number { - const rows = RollbackPreviewTranscript.messages(); - for (let index = 0; index < rows.length; index += 1) { - if (rows[index].turnId === targetTurnId) { - return index; - } - } - return -1; - } - - /** The rows a successful rollback leaves on screen: everything before the target. */ - static rowsBefore(targetTurnId: string): ChatMessage[] { - const rows = RollbackPreviewTranscript.messages(); - const start = RollbackPreviewTranscript.startIndex(targetTurnId); - if (start < 0) { - return rows; - } - return rows.slice(0, start); - } - - /** The answer the mock host gives one rollback, consistent with this transcript. */ - static cannedResponse(sessionId: string, targetTurnId: string): SessionRolledBackResult { - return { - sessionId, - retiredTurnIds: RollbackPreviewTranscript.retiredTurnIds(targetTurnId), - restoredFiles: RollbackPreviewScenario.RESTORED_FILES.slice(), - composerText: RollbackPreviewTranscript.promptFor(targetTurnId), - changed: true - }; - } - - private static message(id: string, role: string, text: string, turnId: string): ChatMessage { - return { - id, - role, - text, - status: 'completed', - turnId, - detail: '', - timestamp: '0' - }; - } -} - -/** - * The mock host as the command layer sees it: the same interface - * `RemoteChatCommandClient` gives the production transport. - * - * `calls` is the whole point of it. "The mock must observe the rollback before - * the send" is not a claim any screenshot of the pane can carry, so the fixture - * states what its host received, in the order it received it, and the diagnostic - * strip prints that. - */ -export class RollbackPreviewTransport implements RemoteChatCommandClient { - readonly calls: string[] = []; - private readonly variant: RollbackPreviewVariant; - - constructor(variant: RollbackPreviewVariant) { - this.variant = variant; - } - - /** The calls received so far, in order: `rollback→send`, `rollback`, or `(none)`. */ - order(): string { - if (this.calls.length === 0) { - return '(none)'; - } - const steps: string[] = []; - for (let index = 0; index < this.calls.length; index += 1) { - steps.push(this.calls[index].indexOf('rollback') === 0 ? 'rollback' : 'send'); - } - return steps.join('→'); - } - - async rollbackSessionToTurn(sessionId: string, targetTurnId: string): Promise { - this.calls.push(`rollback:${targetTurnId}`); - const failure = RollbackPreviewScenario.rollbackError(this.variant); - if (failure.length > 0) { - throw new Error(failure); - } - return RollbackPreviewTranscript.cannedResponse(sessionId, targetTurnId); - } - - async sendMessage(_sessionId: string, text: string, _agentType?: string, _turnId?: string): Promise { - this.calls.push(`send:${text.length}`); - if (RollbackPreviewScenario.sendFails(this.variant)) { - throw new Error(RollbackPreviewScenario.SEND_FAILED_ERROR); - } - return RollbackPreviewScenario.ACCEPTED_TURN_ID; - } - - async sendMessageWithImages(sessionId: string, text: string, _agentType: string, - _imageContexts: RemoteImageContext[], turnId?: string): Promise { - return this.sendMessage(sessionId, text, _agentType, turnId); - } - - async steerTurn(_sessionId: string, _turnId: string, _text: string, _displayContent: string, - _imageContexts: RemoteImageContext[]): Promise { - throw new Error('Unused preview operation'); - } - - async buildPlan(_sessionId: string, _planFilePath: string, _planName: string, - _agentType: string): Promise { - throw new Error('Unused preview operation'); - } - - async cancelTask(_sessionId: string, _turnId?: string): Promise {} - - async renameSession(_sessionId: string, _title: string): Promise {} -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackStagingPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackStagingPreview.ets deleted file mode 100644 index ab10e7c087..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/RollbackStagingPreview.ets +++ /dev/null @@ -1,504 +0,0 @@ -import { ChatMessage, SelectedImageAttachment, SessionRolledBackResult } from '../../model/RemoteModels'; -import { ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { DeviceApiLevelService } from '../../services/DeviceApiLevelService'; -import { RemoteChatCache, RemoteChatCacheSlice, RemoteChatCacheStore } from '../../services/RemoteChatCache'; -import { RemoteChatCommandController } from '../../services/RemoteChatCommandController'; -import { RollbackFailureKind, RollbackOutcomePolicy } from '../../services/RollbackOutcomePolicy'; -import { ConversationIntent, ConversationIntentType, SessionRollbackRequest } from '../actions/ConversationIntent'; -import { ComposerPresentation } from '../components/ComposerBar'; -import { ConversationView } from '../components/ConversationView'; -import { ConversationViewOptions } from '../components/ConversationViewContract'; -import { INK, LINE, MUTED, PAGE_BG, SOFT } from '../components/Theme'; -import { WideLayoutGeometry } from '../layout/WideLayoutGeometry'; -import { AdaptiveLayoutInput } from '../policy/AdaptiveLayoutInput'; -import { ConversationLayoutPolicy } from '../policy/ConversationLayoutPolicy'; -import { RollbackEntryFacts, RollbackPresentationPolicy } from '../policy/RollbackPresentationPolicy'; -import { SessionRollbackEventType } from '../policy/SessionRollbackPolicy'; -import { - SettingsPlacement, - SettingsPlacementPolicy, - SettingsSheetKind -} from '../policy/SettingsPlacementPolicy'; -import { ChatSurface } from '../state/ChatSurface'; -import { REMOTE_CHAT_COMPOSER_CAPABILITIES } from '../state/ChatComposerCapabilities'; -import { ConversationViewState } from '../state/ConversationViewState'; -import { RemotePageState } from '../state/RemotePageState'; -import { - RollbackPreviewScenario, - RollbackPreviewTranscript, - RollbackPreviewTransport, - RollbackPreviewVariant -} from './RollbackPreviewScenario'; - -/** - * The staged rollback on a device, over a mock host. - * - * The frozen interaction (`.openbitfun/plans/mobile-copy-rollback.plan.md`, - * decision 4) is a chain of things a screenshot can only half show: the entry - * lives inside a system selection menu, the staging is a local preview that sends - * nothing, and the three exits differ in what they do to the composer and to the - * timeline. The production `ConversationView` draws all of it here unchanged; what - * the fixture replaces is the host behind it. - * - * The fake sits at the seam `ComposerSubmissionPreview` already uses — the - * `RemoteChatCommandClient` the production `RemoteChatCommandController` owns — so - * both steps of the send-while-staging exit run through the production command - * layer, and the transport records what it was asked for, in order. The strip - * above the pane prints that record, because "the rollback reached the host before - * the send did" is not a claim the pixels of the pane can carry. - * - * A scenario id picks the mock's answer and nothing else: the pane, the - * presentation and the sheet placement follow the real window, so the same fixture - * covers a phone and a tablet. Colour mode is a launch-level fact owned by - * `EntryAbility`, which is what the `-dark` suffixes are for. - */ -@ComponentV2 -export struct RollbackStagingPreview { - @Local state: ConversationViewState = new ConversationViewState(); - @Local placement: SettingsPlacement = - SettingsPlacementPolicy.compactBottom(SettingsSheetKind.UserMessageFullText); - @Local apiLevel: number = 0; - @Local variantLabel: string = ''; - @Local intentLog: string = '(none)'; - @Local hostLog: string = '(none)'; - @Local recoveryLog: string = '(none)'; - @Local draftLog: string = '(empty)'; - @Local noticeLog: string = '(none)'; - @Local toastLog: string = '(none)'; - @Local statusLog: string = '(none)'; - @Local viewportWidth: number = 0; - @Local compactPane: boolean = false; - private sessionId: string = RollbackPreviewTranscript.SESSION_ID; - private sessionContextRevision: number = 0; - private sessionState: RemotePageState = new RemotePageState(); - - private variant: RollbackPreviewVariant = RollbackPreviewVariant.Success; - private transport: RollbackPreviewTransport = - new RollbackPreviewTransport(RollbackPreviewVariant.Success); - private command: RemoteChatCommandController = this.buildCommand(this.transport); - /** - * The mock transcript as the pane is showing it. A successful rollback takes the - * retired rows out of it and a send adds its optimistic row, which is what the - * production client does to its own rows behind a refetch. - */ - private rows: ChatMessage[] = RollbackPreviewTranscript.messages(); - private draft: string = RollbackPreviewScenario.INITIAL_DRAFT; - private notice: string = ''; - private outcome: string = ''; - private outcomeSeq: number = 0; - private failedLocalId: string = ''; - private busy: boolean = false; - private revision: number = 1; - private sentRowCount: number = 0; - - aboutToAppear(): void { - this.sessionState.setActiveSession({ sessionId: this.sessionId, title: 'Rollback staging', workspacePath: '/workspace', agentType: 'code' }); - const scenarioId = this.scenarioId(); - this.variant = RollbackPreviewScenario.variant(scenarioId); - this.variantLabel = `${RollbackPreviewScenario.baseId(scenarioId)} · ${this.variant}`; - // The command layer is rebuilt over the variant's transport so the strip reads - // the same call log the mock host writes. - this.transport = new RollbackPreviewTransport(this.variant); - this.command = this.buildCommand(this.transport); - this.busy = RollbackPreviewScenario.sessionBusy(this.variant); - this.draft = RollbackPreviewScenario.initialDraft(this.variant); - this.apiLevel = DeviceApiLevelService.sdkApiVersion(); - this.project(); - } - - /** - * The production command layer over the mock transport. - * - * The callbacks are the ones the app wires: the draft is captured before the RPC - * and put back only if the send is refused, and a refused send marks its own row - * while the draft stays editable. - */ - private buildCommand(transport: RollbackPreviewTransport): RemoteChatCommandController { - return new RemoteChatCommandController(transport, { - onMessagesLoaded: () => {}, - onMessageCountKnown: () => {}, - onTimelineReady: () => {}, - onComposerPrepared: (_sessionId: string, rawText: string, _images: SelectedImageAttachment[]) => ({ - commit: (): void => { - this.setDraft(''); - }, - rollback: (): void => { - this.setDraft(rawText); - } - }), - onSendSucceeded: (turnId: string, _pendingActiveId: string, _localMessageId: string) => { - this.recoveryLog = - RollbackStagingPreview.appendLog(this.recoveryLog, `send accepted -> ${turnId}`); - }, - onSendFailed: (rawText: string, _images: SelectedImageAttachment[], localMessageId: string, - _pendingActiveId: string) => { - this.setDraft(rawText); - this.markFailed(localMessageId); - this.recoveryLog = RollbackStagingPreview.appendLog(this.recoveryLog, 'send failed, draft kept'); - this.statusLog = RemoteI18n.t('chat.sendFailed'); - }, - onActiveSession: () => {}, - onSessionTitleChanged: () => {}, - onStatusText: (statusText: string) => { - this.statusLog = statusText.length > 0 ? statusText : '(none)'; - }, - onToast: () => {}, - onBusy: () => {}, - onPollRequested: () => {} - }, new RemoteChatCache(new RollbackPreviewCacheStore(), () => 'rollback-preview')); - } - - private scenarioId(): string { - return AppStorage.get('scenarioId') ?? RollbackPreviewScenario.DEFAULT_ID; - } - - private isWideViewport(): boolean { - return this.viewportWidth >= ConversationLayoutPolicy.MD_MIN_WIDTH; - } - - private refreshGeometry(width: number, height: number): void { - this.viewportWidth = width; - this.placement = SettingsPlacementPolicy.resolve( - new AdaptiveLayoutInput(width, height, 0, false, false, false, this.isWideViewport(), [], []), - SettingsSheetKind.UserMessageFullText - ); - } - - private options(): ConversationViewOptions { - const options = new ConversationViewOptions(); - options.showSidebarButton = true; - options.showBackButton = false; - options.composerPresentation = - this.isWideViewport() ? ComposerPresentation.Floating : ComposerPresentation.Compact; - options.fullTextSheetPlacement = this.placement; - return options; - } - - /** - * One fresh projection, the way the page does it: `ConversationViewState` is a - * plain class the controller re-projects on every change, so a new object is what - * re-renders the pane and what carries a host outcome into it. - */ - private project(): void { - const next = new ConversationViewState(); - next.surface = ChatSurface.Remote; - next.connectionState = 'connected'; - next.activeSession = { - sessionId: this.sessionId, - title: this.sessionId === RollbackPreviewTranscript.SESSION_ID ? 'Rollback staging' : 'Session B', - workspacePath: '/workspace', - agentType: 'code' - }; - next.desktopName = 'Studio'; - next.composerCapabilities = REMOTE_CHAT_COMPOSER_CAPABILITIES; - next.timelineItems = this.timeline(); - next.timelineRevision = this.revision; - next.chatInput = this.draft; - next.isBusy = this.busy; - next.canStop = this.busy; - next.rollbackGate = new RollbackEntryFacts( - RollbackPreviewScenario.hostCapabilities(this.variant), this.busy, false); - next.rollbackNotice = this.notice; - next.rollbackOutcome = this.outcome; - next.rollbackOutcomeSeq = this.outcomeSeq; - next.sessionContextRevision = this.sessionContextRevision; - this.state = next; - this.draftLog = this.draft.length > 0 ? - `"${RollbackStagingPreview.head(this.draft)}" len=${this.draft.length}` : '(empty)'; - this.hostLog = this.transport.order(); - this.noticeLog = this.notice.length > 0 ? this.notice : '(none)'; - } - - private timeline(): ObservableChatTimelineItem[] { - return this.rows.map((message: ChatMessage): ObservableChatTimelineItem => { - return new ObservableChatTimelineItem({ - id: message.id, - type: message.role === 'user' ? 'user_message' : 'assistant_message', - message, - isStreaming: false, - isFinalizing: false, - showRetryAction: message.id === this.failedLocalId - }); - }); - } - - private async handleIntent(intent: ConversationIntent): Promise { - if (intent.type === ConversationIntentType.ChatInputChanged) { - this.draft = intent.value; - this.project(); - return; - } - if (intent.type === ConversationIntentType.RollbackSession) { - const request: SessionRollbackRequest | undefined = intent.rollbackRequest; - await this.runRollback(request ? request.targetTurnId : '', request ? request.sendText : ''); - return; - } - if (intent.type === ConversationIntentType.RollbackResync) { - // What the pane asks for after a refusal: the authoritative transcript, which - // for a mock host that never rewrote it is the transcript it began with. - this.rows = RollbackPreviewTranscript.messages(); - this.failedLocalId = ''; - this.revision += 1; - this.recoveryLog = RollbackStagingPreview.appendLog(this.recoveryLog, 'resync'); - this.project(); - return; - } - if (intent.type === ConversationIntentType.RollbackNotice) { - // A refusal the pane says out loud. It is a toast in the app; here it is also - // the strip, because a toast outlives its screenshot by two seconds. - this.toastLog = RemoteI18n.t(intent.value); - this.intentLog = `notice ${intent.value}`; - return; - } - if (intent.type === ConversationIntentType.Send) { - await this.sendFromComposer(); - return; - } - this.intentLog = `intent ${intent.type}`; - } - - /** - * One staged exit, run the way `RemoteTranscriptController.rollbackRemoteSession` - * runs it: the rollback first, then the message it was staged with. - * - * That order is the contract — the host has to retire the turn before a message - * may be appended to it — and the transport records the calls it received so the - * strip can show `rollback→send` afterwards. The pane has already left staging by - * then (that is the frozen interaction), so the answer comes back as a - * projection: a notice row on success, a host outcome on a refusal. - */ - private async runRollback(targetTurnId: string, sendText: string): Promise { - const target = targetTurnId.trim(); - const text = sendText.trim(); - this.intentLog = text.length > 0 ? - `rollback_session then send (${text.length} chars)` : 'rollback_session'; - try { - const result: SessionRolledBackResult = await this.command.rollbackSessionToTurn( - RollbackPreviewTranscript.SESSION_ID, target); - // The host rewrote history; the production client refetches the transcript - // after a success, and this stands in for that refetch. - this.rows = RollbackPreviewTranscript.rowsBefore(target); - this.revision += 1; - const notice = RemoteI18n.f2( - RollbackPresentationPolicy.ROLLED_BACK_NOTICE_KEY, - `${result.retiredTurnIds.length}`, - `${result.restoredFiles.length}` - ); - if (text.length > 0) { - this.setDraft(text); - // Production publishes the optimistic bubble before the RPC, so the row is - // on screen whether or not the send reaches the host. - const localMessageId = this.appendSentRow(text); - await this.command.sendPreparedMessage( - RollbackPreviewTranscript.SESSION_ID, text, 'code', text, [], [], localMessageId, '', false, true); - } - // Set after the send, the same way the production path does: a rollback that - // succeeded still reports what it withdrew when the send fails. - this.notice = notice; - this.sessionState.setRollbackNotice(notice); - this.recoveryLog = RollbackStagingPreview.appendLog( - this.recoveryLog, result.changed ? 'history rewritten' : 'history unchanged'); - this.project(); - } catch (err) { - const kind = RollbackOutcomePolicy.failureKind(err); - this.outcome = kind === RollbackFailureKind.StaleView ? - SessionRollbackEventType.StaleViewDetected : SessionRollbackEventType.RollbackFailed; - this.outcomeSeq += 1; - this.intentLog = `rollback refused: ${RollbackOutcomePolicy.messageOf(err)}`; - // The projection is what the pane reads the outcome from, and what makes it - // resync and, for a failure, say so out loud. - this.project(); - } - } - - /** The ordinary send, for a session with no rollback staged. */ - private async sendFromComposer(): Promise { - const text = this.draft.trim(); - if (text.length === 0) { - return; - } - this.intentLog = `send (${text.length} chars)`; - this.sessionState.clearRollbackNotice(); - this.notice = this.sessionState.rollbackNotice; - const localMessageId = this.appendSentRow(text); - await this.command.sendPreparedMessage( - RollbackPreviewTranscript.SESSION_ID, text, 'code', text, [], [], localMessageId, '', false, true); - this.project(); - } - - private setDraft(value: string): void { - this.draft = value; - } - - /** Replace the projected session while retaining the same ConversationView. */ - private switchSession(): void { - const returning = this.sessionId !== RollbackPreviewTranscript.SESSION_ID; - this.sessionId = returning ? RollbackPreviewTranscript.SESSION_ID : 'rollback-preview-session-b'; - this.sessionContextRevision += 1; - this.sessionState.setActiveSession({ sessionId: this.sessionId, title: this.sessionId, workspacePath: '/workspace', agentType: 'code' }); - this.rows = returning ? RollbackPreviewTranscript.messages() : []; - this.draft = returning ? RollbackPreviewScenario.INITIAL_DRAFT : 'SESSION-B-DRAFT'; - this.notice = this.sessionState.rollbackNotice; - this.outcome = ''; - this.outcomeSeq = 0; - this.revision += 1; - this.project(); - } - - private appendSentRow(text: string): string { - const id = `preview-sent-${this.sentRowCount}`; - this.sentRowCount += 1; - const row: ChatMessage = { - id, - role: 'user', - text, - status: 'sent', - turnId: RollbackPreviewScenario.ACCEPTED_TURN_ID, - detail: '', - timestamp: '0' - }; - this.rows = this.rows.concat([row]); - this.revision += 1; - return id; - } - - /** Marks the optimistic row the way the app marks one the host refused. */ - private markFailed(localMessageId: string): void { - this.failedLocalId = localMessageId; - const updated: ChatMessage[] = []; - for (let index = 0; index < this.rows.length; index += 1) { - const row = this.rows[index]; - if (row.id !== localMessageId) { - updated.push(row); - continue; - } - updated.push({ - id: row.id, - role: row.role, - text: row.text, - status: 'failed', - turnId: row.turnId, - detail: row.text, - timestamp: row.timestamp - }); - } - this.rows = updated; - this.revision += 1; - } - - private static appendLog(log: string, entry: string): string { - return log === '(none)' ? entry : `${log} · ${entry}`; - } - - private static head(text: string): string { - return text.replace(/\s+/g, ' ').substring(0, 24); - } - - build() { - Column() { - this.Diagnostics() - // The pane takes what is left of the window rather than the whole height: the - // chat page puts its own overlay at the bottom of whatever box it is given, - // so a pane measured at the window's height draws its composer off screen. - Column() { - this.Conversation() - } - .width(this.compactPane ? 360 : '100%') - .layoutWeight(1) - .onAreaChange((_oldArea: Area, newArea: Area) => { - this.refreshGeometry( - WideLayoutGeometry.areaLength(newArea.width), - WideLayoutGeometry.areaLength(newArea.height) - ); - }) - } - .width('100%') - .height('100%') - .backgroundColor(PAGE_BG) - } - - @Builder - private Conversation() { - ConversationView({ - state: this.state, - options: this.options(), - onIntent: (intent: ConversationIntent): void => { - void this.handleIntent(intent); - } - }) - } - - /** - * The report strip: what the mock host was asked for, in order, and what the - * composer and the notice hold after each exit. It sits above the pane so nothing - * it draws can be mistaken for the surface under test, and every line carries an - * id so a layout dump can be read against the screenshot. - */ - @Builder - private Diagnostics() { - Column({ space: 2 }) { - Row({ space: 8 }) { - Button('Switch session').id('rollback-preview-switch-session') - .onClick(() => this.switchSession()) - Button('Resize').id('rollback-preview-resize') - .onClick(() => { this.compactPane = !this.compactPane; }) - } - Text(`scenario=${this.scenarioId()} variant=${this.variantLabel} api=${this.apiLevel} ` + - `w=${Math.round(this.viewportWidth)} busy=${this.busy ? 1 : 0} ` + - `caps=${RollbackPreviewScenario.hostCapabilities(this.variant).length}`) - .id('rollback-preview-scenario') - .fontSize(10) - .fontColor(MUTED) - .width('100%') - .maxLines(2) - Text(`intent=${this.intentLog}`) - .id('rollback-preview-intent') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(2) - Text(`host=${this.hostLog} recovery=${this.recoveryLog}`) - .id('rollback-preview-host') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(2) - Text(`draft=${this.draftLog}`) - .id('rollback-preview-draft') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(1) - Text(`notice=${this.noticeLog}`) - .id('rollback-preview-notice') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(2) - Text(`toast=${this.toastLog} status=${this.statusLog}`) - .id('rollback-preview-toast') - .fontSize(10) - .fontColor(INK) - .width('100%') - .maxLines(2) - } - .width('100%') - // The shell is immersive, so the strip starts at the window's top edge and has - // to clear the status bar itself. - .padding({ left: 12, right: 12, top: 48, bottom: 6 }) - .backgroundColor(SOFT) - .border({ width: { bottom: 0.5 }, color: LINE }) - } -} - -/** A transcript store the fixture never reads from and never writes to. */ -class RollbackPreviewCacheStore implements RemoteChatCacheStore { - async init(_context: Context): Promise {} - async loadSlice(): Promise { return { messages: [], lastMessageId: '' }; } - async appendMessages(): Promise {} - async replaceMessages(): Promise {} - async deleteSession(): Promise {} - async pruneSessions(): Promise {} - async clearAll(): Promise {} -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentProcessPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentProcessPreview.ets deleted file mode 100644 index 49bafe8c3d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentProcessPreview.ets +++ /dev/null @@ -1,333 +0,0 @@ -import { ChatMessage, RemoteModelCatalog } from '../../model/RemoteModels'; -import { ChatTimelineRowStore, ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ChatSessionController, ChatSessionSnapshot } from '../../services/ChatSessionController'; -import { ChatTimelineStore } from '../../services/ChatTimelineStore'; -import { HostSessionCallbacks, HostSessionStream } from '../../services/HostSessionStream'; -import { RemoteChatBranchCache } from '../../services/RemoteChatBranchCache'; -import { RemoteChatCache } from '../../services/RemoteChatCache'; -import { RemoteChatLocalRdbStore } from '../../services/RemoteChatLocalRdbStore'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemoteSessionManager } from '../../services/RemoteSessionManager'; -import { SubagentFollowState } from '../../services/SubagentStreamCoordinator'; -import { ChatMessageStructurePolicy, StructuredRenderGroup } from '../policy/ChatMessageStructurePolicy'; -import { - ConversationUiMessage, - ConversationUiMessageItem, - toConversationUiMessage -} from '../state/ConversationUiModels'; -import { SubagentBranchExpansionState } from '../state/SubagentBranchExpansionState'; -import { ChatTimeline } from '../components/ChatTimeline'; -import { ComposerBar } from '../components/ComposerBar'; -import { INK, PAGE_BG } from '../components/Theme'; -import { - SWARM_PREVIEW_DEVICE_KEY, - SwarmBeatScript, - SwarmLedger, - SwarmScript, - SWARM_WIDE_WORKERS, - SwarmWideScript, - wideSpawnId -} from './SubagentSwarmFixture'; - -/** How long one beat of the swarm waits before it publishes; device capture is manual too. */ -const SWARM_BEAT_INTERVAL_MS: number = 900; -/** - * How far the preview's own controls sit below the top of the screen. - * - * The page draws under the system status bar, and this band is the fixture's - * controls plus the reading a capture has to carry: starting them at the very - * top puts both under the clock and the battery indicator, where half a line is - * unreadable and a control half covered by an overlay is a control that cannot - * be pressed. - */ -const PREVIEW_TOP_INSET: number = 148; -const SWARM_PREVIEW_CATALOG: RemoteModelCatalog = { version: 1, models: [], default_models: {} }; - -/** - * The runtime connection, over the fixture's pages. - * - * Only stream opening and the model catalog are answered: the controller reads - * every session — the one on screen and every spawned worker — through the same - * call production makes, so the fixture exercises the production stream reader, - * reducer, timeline store, projection and card instead of a preview-only path. - */ -class SwarmSessionSource extends RemoteSessionManager { - private fixture: SwarmLedger; - - constructor(fixture: SwarmLedger) { - super(); - this.fixture = fixture; - } - - subscribeSession(sessionId: string, callbacks: HostSessionCallbacks): HostSessionStream { - return this.fixture.openStream(sessionId, callbacks); - } - - async getModelCatalog(_sessionId?: string): Promise { - return SWARM_PREVIEW_CATALOG; - } -} - -/** - * A swarm session rendered by the production transcript. - * - * The fixture publishes a parent session whose delegation items name the child - * sessions they started, and those children publish their own records on their - * own streams. Nothing here hands the timeline a prepared branch: the records go - * through the controller, the reducer and the store, and what the card draws is - * what a live session draws. - * - * Three variants of it are launchable, chosen by the `previewOption` ability - * parameter rather than by a scenario id of their own: - * - * - nothing (`subagent-swarm`): the three-worker swarm, one beat at a time, which - * is the walk through a launch, a running worker and a settled launch; - * - `wide`: the ten-worker delegation, published at once, which is what the - * per-session follow cap is for; - * - `restart`: the same swarm with every worker's own stream answering nothing, - * the way a phone that just started finds them, so every step a card still - * shows came out of the transcript cache. - */ -@ComponentV2 -export struct SubagentProcessPreview { - private fixture: SwarmLedger = new SwarmLedger(); - private script: SwarmBeatScript = new SwarmScript(this.fixture); - private source: SwarmSessionSource = new SwarmSessionSource(this.fixture); - private timeline: ChatTimelineStore = new ChatTimelineStore(); - private rowStore: ChatTimelineRowStore = new ChatTimelineRowStore(); - private transcriptCache: RemoteChatCache = - new RemoteChatCache(new RemoteChatLocalRdbStore(), (): string => SWARM_PREVIEW_DEVICE_KEY); - private branchCache: RemoteChatBranchCache = new RemoteChatBranchCache(this.transcriptCache); - private controller?: ChatSessionController; - private timer: number = -1; - private option: string = ''; - private sessionId: string = ''; - /** The reader's disclosures, kept by this preview exactly as the conversation keeps them. */ - @Local expanded: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - @Local rows: ObservableChatTimelineItem[] = []; - @Local revision: number = 0; - @Local summary: string = ''; - @Local connectionState: string = 'connected'; - @Local active: boolean = true; - @Local paused: boolean = false; - @Local failure: string = ''; - @Local stopRequests: number = 0; - @Local followCursor: number = 0; - - async aboutToAppear(): Promise { - this.option = AppStorage.get('previewOption') ?? ''; - if (this.option === 'wide') this.script = new SwarmWideScript(this.fixture); - this.sessionId = this.script.parentSession(); - this.timeline.reset(this.sessionId); - // The turn's own opening records are published before the session is read, - // like a history page; every later beat arrives as a live publication. - this.script.advance(); - if (this.option === 'restart') { - this.fixture.muteSessions(this.script.childSessions()); - } - const hostContext = this.getUIContext().getHostContext(); - if (hostContext) await this.transcriptCache.init(hostContext); - this.controller = new ChatSessionController(this.source, { - onSnapshot: (snapshot: ChatSessionSnapshot): void => { this.applySnapshot(snapshot); }, - canPoll: (_sessionId: string): boolean => true, - onError: (error: Object): void => { this.report(error); } - }, { initialPollDelayMs: 0, branchCache: this.branchCache }); - this.controller.start(this.sessionId, { - pollVersion: 0, knownMessageCount: 0, knownModelCatalogVersion: 0 - }); - if (this.option === 'wide' || this.option === 'restart') { - // Nothing is left to play beat by beat: the whole delegation is published, - // and what the cards then hold is what the preview is here to state. - this.script.drain(); - this.pause(); - return; - } - this.timer = setInterval((): void => { this.tick(); }, SWARM_BEAT_INTERVAL_MS); - } - - aboutToDisappear(): void { - if (this.timer !== -1) { - clearInterval(this.timer); - this.timer = -1; - } - this.controller?.stop(); - } - - private tick(): void { - if (this.paused) return; - this.nextBeat(); - } - - /** - * Publishes the next beat, whether the automatic beats are running or held. - * - * Stepping by hand is what a capture needs: a card can only be opened while its - * worker is mid-turn if the beats stand still while the reader does it, and a - * held fixture that could not be stepped would make every capture start again. - */ - private nextBeat(): void { - if (!this.script.advance()) { - this.pause(); - return; - } - // The reading follows the script, not only the snapshots: a beat that moves a - // worker without moving the parent transcript publishes no snapshot, and the - // line a capture carries has to keep up with the beats that were played. - this.refreshSummary(); - } - - private pause(): void { - this.paused = true; - if (this.timer !== -1) { - clearInterval(this.timer); - this.timer = -1; - } - this.refreshSummary(); - } - - private applySnapshot(snapshot: ChatSessionSnapshot): void { - this.timeline.applySnapshot(snapshot); - this.rows = this.rowStore.reconcile(this.timeline.project(false)); - this.revision++; - const state = this.timeline.snapshot(); - this.active = state.activeTurn !== undefined; - this.refreshSummary(); - } - - /** - * Asks for one card's worker to be followed, the way opening a card does. - * - * The follow cap releases the oldest working child when a wider delegation - * arrives, so a card can be drawn from a branch whose stream is not open. The - * request is the same one the card raises when the reader opens it, and it is - * idempotent for a worker already being followed. - */ - private followOneCard(): void { - const children = this.script.childSessions(); - if (children.length === 0) return; - const index = this.followCursor % children.length; - this.followCursor++; - const branchId = this.option === 'wide' ? wideSpawnId(index) : 'swarm-docs-spawn'; - this.controller?.ensureBranchSubscribed(branchId); - this.refreshSummary(); - } - - /** - * A stream failure stays visible instead of stopping the fixture: the band - * states it, and the swarm keeps publishing, so a broken child stream cannot - * be mistaken for a worker that had nothing to say. - */ - private report(error: Object): void { - this.failure = (error as Error).message || 'stream failed'; - this.refreshSummary(); - } - - /** - * What the transcript currently holds, read back through the production - * grouping policy: how many cards the turn draws and how many steps each of - * them has. A worker's step count only rises while its stream is live, which - * is the evidence a screenshot alone cannot state. - * - * The follow reading is the other half of that evidence: how many branches the - * session has, how many of their child streams are open, how many are waiting - * for a slot, and how many steps a card is drawing out of the transcript cache - * rather than off a stream. - */ - /** - * Opens or closes one card's disclosure, exactly as the card's own header does. - * - * The preview carries this because the emulator's own input tool cannot deliver - * a tap to a row inside this list: every coordinate inside a card header is - * reported as a clickable node and still reaches nothing, while the controls - * above the list work. The gesture is the card's — the same keyed disclosure, - * the same request to follow the worker — so what a capture then shows is the - * card reading state that outlived its row. - */ - private toggleCard(index: number): void { - const cards = this.branchCards(); - if (cards.length === 0) return; - const card = cards[(index + cards.length) % cards.length]; - const branchId = card.tool?.id || ''; - if (branchId.length === 0) return; - if (this.expanded.toggle(branchId)) this.controller?.ensureBranchSubscribed(branchId); - this.refreshSummary(); - } - - private refreshSummary(): void { - const cards = this.branchCards(); - const steps = cards.map((card: ConversationUiMessageItem) => (card.subItems || []).length).join(','); - const statuses = cards.map((card: ConversationUiMessageItem) => card.tool?.status || '').join(','); - const follow: SubagentFollowState | undefined = this.controller?.subagentFollowState(); - const followText = follow === undefined ? 'streams=?' : - `streams=${follow.subscribed}/${follow.branches} waiting=${follow.waiting} restored=${follow.restored}`; - const open = this.expanded.expandedKeys().join(','); - this.summary = `swarm option=${this.option.length > 0 ? this.option : 'live'} ` + - `step=${this.script.position()}/${this.script.beatCount()} paused=${this.paused ? 1 : 0} ` + - `rows=${this.rows.length} cards=${cards.length} steps=[${steps}] status=[${statuses}] ` + - `open=[${open}] ${followText}` + - (this.failure.length > 0 ? ` failure=${this.failure}` : ''); - // The same reading into the device log, so a run can be checked as text and - // not only as pixels: what a capture shows is one frame of this sequence. - RemoteLogger.info(this.summary); - } - - private branchCards(): ConversationUiMessageItem[] { - const state = this.timeline.snapshot(); - let answer = state.activeTurn; - if (!answer) { - state.persistedMessages.forEach((message: ChatMessage) => { - if (message.role === 'assistant') answer = message; - }); - } - if (!answer) return []; - const message: ConversationUiMessage = toConversationUiMessage(answer); - const groups: StructuredRenderGroup[] = ChatMessageStructurePolicy.structuredGroups( - message.items || [], 'item', (message.status || '') === 'active', message.status || 'done'); - return groups - .filter((group: StructuredRenderGroup) => group.type === 'item' && group.items.length === 1) - .map((group: StructuredRenderGroup) => group.items[0]) - .filter((entry: ConversationUiMessageItem) => ChatMessageStructurePolicy.isSubagentEntry(entry)); - } - - build() { - Column({ space: 6 }) { - Row({ space: 8 }) { - Button('Next beat').id('subagent-next').onClick(() => { this.nextBeat(); }) - Button(this.paused ? 'Resume' : 'Pause').id('subagent-pause').onClick(() => { - if (this.paused) { - this.paused = false; - if (this.timer === -1) this.timer = setInterval((): void => { this.tick(); }, SWARM_BEAT_INTERVAL_MS); - this.refreshSummary(); - } else { - this.pause(); - } - }) - Button(this.option === 'wide' ? `Follow card ${this.followCursor % SWARM_WIDE_WORKERS}` : 'Follow docs card') - .id('subagent-follow-card').onClick(() => { this.followOneCard(); }) - } - Row({ space: 8 }) { - Button('Refresh state').id('subagent-refresh').onClick(() => { this.refreshSummary(); }) - Button('Toggle card').id('subagent-toggle-card').onClick(() => { this.toggleCard(-1); }) - Button('Host offline').id('subagent-offline').onClick(() => { this.connectionState = 'reconnecting'; }) - Button('Host returned').id('subagent-returned').onClick(() => { this.connectionState = 'connected'; }) - } - // Below the controls rather than above them: the reading is the evidence a - // capture has to carry, and the line above the buttons sits under the - // system status bar where half of it cannot be read. - Text(this.summary).id('subagent-summary').fontSize(10).fontColor(INK).width('100%') - Text(`${this.connectionState} stops=${this.stopRequests}`).id('subagent-host-state').fontSize(10).fontColor(INK) - ChatTimeline({ - timelineItems: this.rows, timelineRevision: this.revision, - connectionState: this.connectionState, isBusy: this.active, - subagentBranches: this.expanded, - onBranchExpanded: (branchId: string): void => { - this.controller?.ensureBranchSubscribed(branchId); - } - }).layoutWeight(1) - ComposerBar({ - canStop: this.active, connectionState: this.connectionState, - onStop: () => { this.stopRequests++; } - }) - }.width('100%').height('100%').backgroundColor(PAGE_BG).padding({ top: PREVIEW_TOP_INSET }) - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentSwarmFixture.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentSwarmFixture.ets deleted file mode 100644 index cff5dd838d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/SubagentSwarmFixture.ets +++ /dev/null @@ -1,822 +0,0 @@ -import { - HostSessionCallbacks, - HostSessionSource, - HostSessionStream, - HostStreamEventWire, - HostStreamHint, - HostStreamPage, - HostStreamReadRequest -} from '../../services/HostSessionStream'; - -/** - * A swarm session, published the way a live host publishes one. - * - * Two facts this fixture exists to keep straight, both read off a real - * `Ultimate` session's record stream: - * - * 1. The parent stream carries the launch and nothing of the child. An - * `AgentSpawn` tool item names the child Session id it started - * (`subagentSessionId`, camelCase, exactly as `records_from_turns` serializes - * `ToolItemData`), holds the full task brief in `toolCall.input.prompt`, and - * answers with a text table of `agent_id / bg_task_id / status`. The rest of - * the parent's items are ordinary tool rows. - * 2. A child's records are an ordinary session's records on the child's own - * stream id: thinking, tool and text items with the same key shapes and no - * subagent marker anywhere. A worker that ran to completion holds hundreds of - * records, so the fixture publishes its history in one page before the - * branch that reads it is opened. - * - * Nothing here fabricates a child item inside the parent stream. The records a - * client reads are either the parent's own or a child's own, grouped by which - * stream they arrived on. - */ - -/** Host stream epoch for every fixture stream. */ -const SWARM_PREVIEW_EPOCH: number = 1; -/** Fixture-local clock origin; the host stamps real epoch milliseconds. */ -const SWARM_PREVIEW_CLOCK: number = 1767225600000; -const SWARM_PREVIEW_TOOL_MS: number = 640; - -export const SWARM_PREVIEW_HOST: string = 'swarm-preview-host'; -export const SWARM_PARENT_SESSION: string = 'swarm-preview-parent'; -/** First worker: finished before its branch was opened, so its history backfills. */ -export const SWARM_PAYMENTS_SESSION: string = 'swarm-preview-child-payments'; -/** Second worker: still running while the parent's turn is on screen. */ -export const SWARM_DOCS_SESSION: string = 'swarm-preview-child-docs'; -/** Third worker: its own tools failed and it reported the failure. */ -export const SWARM_FLAKY_SESSION: string = 'swarm-preview-child-flaky'; -/** The wide delegation: ten workers launched at once, which is what the cap is for. */ -export const SWARM_WIDE_PARENT_SESSION: string = 'swarm-preview-parent-wide'; -/** Session id a wide worker runs in; the index is appended. */ -export const SWARM_WIDE_CHILD_PREFIX: string = 'swarm-preview-wide-child-'; -/** How many workers the wide delegation hands out at once. */ -export const SWARM_WIDE_WORKERS: number = 10; -/** The dev key the preview's cold start stores its transcripts under. */ -export const SWARM_PREVIEW_DEVICE_KEY: string = 'swarm-preview-device'; - -/** - * The beats a preview can play, whichever delegation it is playing. - * - * The parent session id is part of the script because it is the session a - * preview opens, and the children are the sessions a cold-start preview has to - * mute so that only the transcript cache can answer for them. - */ -export interface SwarmBeatScript { - parentSession(): string; - childSessions(): string[]; - beatCount(): number; - position(): number; - advance(): boolean; - drain(): void; -} - -interface SwarmUserMessage { id: string; content: string; timestamp: number; } -interface SwarmTurnHeader { - turnId: string; turnIndex: number; sessionId: string; timestamp: number; - userMessage: SwarmUserMessage; status: string; -} -interface SwarmRoundHeader { id: string; turnId: string; roundIndex: number; timestamp: number; status: string; } -/** A tool call's own input: one flat object, holding only the keys that tool takes. */ -export interface SwarmToolInput { - pattern?: string; - path?: string; - glob?: string; - output_mode?: string; - file_path?: string; - offset?: number; - limit?: number; - cmd?: string; - workdir?: string; - yield_time_ms?: number; - agent_id?: string; - agent_type?: string; - prompt?: string; - bg_task_ids?: string[]; - timeout_seconds?: number; -} -interface SwarmToolCall { id: string; input: SwarmToolInput; } -interface SwarmToolResult { - result: string; - success: boolean; - resultForAssistant?: string; - error?: string; - durationMs?: number; -} -interface SwarmThinkingData { - id: string; content: string; isStreaming: boolean; isCollapsed: boolean; - timestamp: number; orderIndex: number; status: string; -} -interface SwarmTextData { - id: string; content: string; isStreaming: boolean; timestamp: number; - isMarkdown: boolean; orderIndex: number; status: string; -} -interface SwarmToolData { - id: string; toolName: string; toolCall: SwarmToolCall; startTime: number; - orderIndex: number; status: string; toolResult?: SwarmToolResult; - endTime?: number; durationMs?: number; subagentSessionId?: string; -} -interface SwarmItem { type: string; data: Object; } -interface SwarmRecord { - sessionId: string; id: string; revision: number; turn: SwarmTurnHeader; - round?: SwarmRoundHeader; item?: SwarmItem; -} - -/** Optional facts a published tool call can carry. */ -export interface SwarmToolOptions { - subagentSessionId?: string; - success?: boolean; - status?: string; - error?: string; - resultForAssistant?: string; -} - -/** - * One session's record log, published in the host's own order. - * - * Records are stamped with a per-session revision that rises with every - * publication, which is what lets a client deduplicate a replayed page and - * accept an updated status for an item it already has. - */ -export class SwarmSessionLog { - readonly sessionId: string; - private wake: (sessionId: string) => void; - private turnId: string; - private userText: string; - private turnIndex: number; - private published: HostStreamEventWire[] = []; - private seq: number = 0; - private revision: number = 0; - private itemSeq: number = 0; - private roundCount: number = -1; - private roundId: string = ''; - private order: number = 0; - private clock: number = SWARM_PREVIEW_CLOCK; - private turnStatus: string = 'inprogress'; - - constructor(sessionId: string, turnId: string, userText: string, turnIndex: number, - wake: (sessionId: string) => void) { - this.sessionId = sessionId; - this.turnId = turnId; - this.userText = userText; - this.turnIndex = turnIndex; - this.wake = wake; - } - - records(): HostStreamEventWire[] { return this.published.slice(); } - newestSeq(): number { return this.seq; } - - /** Publishes the turn record, which every later record of this log repeats. */ - openTurn(): void { - this.publish(this.record(`turn/${this.turnId}`, undefined, undefined, true)); - } - - /** - * Ends the turn this log is publishing, without publishing another item. - * - * A host writes a turn's own terminal status when the turn ends, and that - * status is the only place a finished worker says it is finished: its step - * count does not change at that moment, so nothing else in the log moves. It is - * the turn's own record, not a round's: a turn record carries the header the - * rounds repeat, which is what makes it the state of the turn. - */ - settleTurn(status: string): void { - this.turnStatus = status; - this.publish(this.record(`turn/${this.turnId}`, undefined, undefined, true)); - } - - /** Opens the next model round and publishes it. */ - beginRound(status: string = 'inprogress'): void { - this.roundCount++; - this.roundId = `${this.turnId}-round-${this.roundCount}`; - this.order = 0; - const round: SwarmRoundHeader = { - id: this.roundId, turnId: this.turnId, roundIndex: this.roundCount, - timestamp: this.clock, status - }; - this.publish(this.record(`round/${this.roundId}`, undefined, round)); - } - - thinking(content: string): void { - const id = this.nextItemId('thinking'); - const data: SwarmThinkingData = { - id, content, isStreaming: false, isCollapsed: false, - timestamp: this.now(), orderIndex: this.order++, status: 'completed' - }; - this.publishItem('thinking', id, data); - } - - text(content: string): void { - const id = this.nextItemId('text'); - const data: SwarmTextData = { - id, content, isStreaming: false, - timestamp: this.now(), isMarkdown: true, orderIndex: this.order++, status: 'completed' - }; - this.publishItem('text', id, data); - } - - /** A tool call the host has recorded but not finished: status running, no result. */ - toolStarted(id: string, name: string, input: SwarmToolInput, options?: SwarmToolOptions): void { - this.publishTool(id, name, input, undefined, 'running', options); - } - - /** The same tool call once its result is known, in the host's status vocabulary. */ - toolFinished(id: string, name: string, input: SwarmToolInput, output: string, options?: SwarmToolOptions): void { - const status = options?.status ?? ((options?.success === false) ? 'failed' : 'completed'); - this.publishTool(id, name, input, output, status, options); - } - - private publishTool(id: string, name: string, input: SwarmToolInput, output: string | undefined, - status: string, options?: SwarmToolOptions): void { - const start = this.now(); - const data: SwarmToolData = { - id, toolName: name, toolCall: { id, input }, startTime: start, - orderIndex: this.order++, status, subagentSessionId: options?.subagentSessionId - }; - if (output !== undefined) { - data.endTime = start + SWARM_PREVIEW_TOOL_MS; - data.durationMs = SWARM_PREVIEW_TOOL_MS; - data.toolResult = { - result: output, success: options?.success !== false, - resultForAssistant: options?.resultForAssistant, error: options?.error, - durationMs: SWARM_PREVIEW_TOOL_MS - }; - } - this.publishItem('tool', id, data); - } - - private publishItem(type: string, id: string, data: Object): void { - this.publish(this.record(`item/${id}`, { type, data })); - } - - private nextItemId(kind: string): string { - this.itemSeq++; - return `${this.turnId}-${kind}-${this.itemSeq}`; - } - - private now(): number { - this.clock += SWARM_PREVIEW_TOOL_MS; - return this.clock; - } - - /** - * One record of this session's log. - * - * A record of a turn's own state carries no round: `turnOnly` is what a turn - * header published on its own looks like, and a record stamped with the round - * the log happens to be in is a round's record, not the turn's. - */ - private record(id: string, item?: SwarmItem, round?: SwarmRoundHeader, - turnOnly: boolean = false): SwarmRecord { - this.revision++; - const record: SwarmRecord = { - sessionId: this.sessionId, id, revision: this.revision, turn: this.turnHeader() - }; - if (round) { - record.round = round; - } else if (!turnOnly && this.roundId.length > 0) { - record.round = { - id: this.roundId, turnId: this.turnId, roundIndex: this.roundCount, - timestamp: this.clock, status: this.turnStatus - }; - } - if (item) record.item = item; - return record; - } - - private turnHeader(): SwarmTurnHeader { - return { - turnId: this.turnId, turnIndex: this.turnIndex, sessionId: this.sessionId, timestamp: this.clock, - userMessage: { id: `${this.turnId}-user`, content: this.userText, timestamp: this.clock }, - status: this.turnStatus - }; - } - - private publish(payload: Object): void { - this.seq++; - this.published.push({ seq: this.seq, event: 'session-record', payload }); - this.wake(this.sessionId); - } -} - -/** Serves every fixture stream out of the one record log of its session. */ -class SwarmStreamSource implements HostSessionSource { - target: string = SWARM_PREVIEW_HOST; - private ledger: SwarmLedger; - private sessionId: string; - - constructor(ledger: SwarmLedger, sessionId: string) { - this.ledger = ledger; - this.sessionId = sessionId; - } - - async read(request: HostStreamReadRequest): Promise { - return this.ledger.page(this.sessionId, request); - } - - async unsubscribe(): Promise {} - - /** The fixture never pushes hints; a publication wakes the stream instead. */ - onHint(_listener: (hint: HostStreamHint) => void): () => void { - return (): void => {}; - } - - onReconnect(_listener: () => void): () => void { - return (): void => {}; - } -} - -/** - * The fixture's stream transport: one log per session id, opened on demand. - * - * `openStream` is the same call the runtime connection makes for a session on - * screen, so a child stream is read by the production stream reader — paging, - * epoch, cursor and dedup included — and not by a fixture-shaped shortcut. - */ -export class SwarmLedger { - private logs: Map = new Map(); - private streams: Map = new Map(); - private muted: Set = new Set(); - - /** Creates (once) the log a session publishes into. */ - open(sessionId: string, turnId: string, userText: string, turnIndex: number = 0): SwarmSessionLog { - const existing = this.logs.get(sessionId); - if (existing) return existing; - const log = new SwarmSessionLog(sessionId, turnId, userText, turnIndex, - (woken: string): void => { this.wake(woken); }); - this.logs.set(sessionId, log); - return log; - } - - /** - * Stops these sessions from answering, the way a host that is gone answers. - * - * A cold-start preview reads the session on screen from the record log it - * publishes, and the workers it launched from nowhere at all: whatever a card - * still shows at that point came from the transcript cache, which is exactly - * what a phone that just restarted has. - */ - muteSessions(sessionIds: string[]): void { - sessionIds.forEach((sessionId: string): void => { this.muted.add(sessionId); }); - } - - openStream(sessionId: string, callbacks: HostSessionCallbacks): HostSessionStream { - const stream = new HostSessionStream(sessionId, new SwarmStreamSource(this, sessionId), callbacks); - this.streams.set(sessionId, stream); - return stream; - } - - /** A read page for one session: everything after the caller's cursor. */ - page(sessionId: string, request: HostStreamReadRequest): HostStreamPage { - const log = this.logs.get(sessionId); - const records: HostStreamEventWire[] = log && !this.muted.has(sessionId) ? log.records() : []; - const cursor = log ? log.newestSeq() : 0; - const after = request.after ?? 0; - const page: HostStreamPage = { - resp: 'stream_page', stream_id: sessionId, epoch: SWARM_PREVIEW_EPOCH, cursor, - events: records.filter((entry: HostStreamEventWire) => entry.seq > after), - has_more: false, oldest_seq: records.length > 0 ? records[0].seq : 1, truncated: false - }; - return page; - } - - private wake(sessionId: string): void { - this.streams.get(sessionId)?.wake(); - } -} - -/** - * The swarm the preview plays out, one beat at a time. - * - * Each beat publishes the records a live host would publish at that moment. - * Beats exist so the fixture can be captured mid-flight — a worker's steps - * arriving one page at a time — instead of only in its finished state. - */ -export class SwarmScript implements SwarmBeatScript { - private ledger: SwarmLedger; - private parent: SwarmSessionLog; - private payments: SwarmSessionLog; - private docs: SwarmSessionLog; - private flaky: SwarmSessionLog; - private beats: (() => void)[] = []; - private cursor: number = 0; - - constructor(ledger: SwarmLedger) { - this.ledger = ledger; - this.parent = ledger.open(SWARM_PARENT_SESSION, 'swarm-parent-turn-1', - 'Audit the payments module with a swarm and report what each worker found.', 0); - this.payments = ledger.open(SWARM_PAYMENTS_SESSION, 'swarm-payments-turn-1', SWARM_PAYMENTS_BRIEF, 0); - this.docs = ledger.open(SWARM_DOCS_SESSION, 'swarm-docs-turn-1', SWARM_DOCS_BRIEF, 0); - this.flaky = ledger.open(SWARM_FLAKY_SESSION, 'swarm-flaky-turn-1', SWARM_FLAKY_BRIEF, 0); - this.beats = [ - (): void => { this.beatOpening(); }, - (): void => { this.beatSpawnPayments(); }, - (): void => { this.beatSpawnFlaky(); }, - (): void => { this.beatSpawnDocs(); }, - (): void => { this.beatDocsThinking(); }, - (): void => { this.beatDocsSearchStarted(); }, - (): void => { this.beatDocsSearchFinished(); }, - (): void => { this.beatWait(); }, - (): void => { this.beatParentRows(); }, - (): void => { this.beatDocsReadPlan(); }, - (): void => { this.beatDocsGrepStarted(); }, - (): void => { this.beatDocsGrepFinished(); }, - (): void => { this.beatDocsReadStarted(); }, - (): void => { this.beatDocsSpawnSettles(); }, - // The workers answer, one turn at a time, after the parent has collected - // them: a worker's turn can end without publishing another step, so these - // beats are the only thing that moves a card's status. - (): void => { this.payments.settleTurn('completed'); }, - (): void => { this.flaky.settleTurn('error'); }, - (): void => { this.docs.settleTurn('completed'); } - ]; - } - - parentSession(): string { return SWARM_PARENT_SESSION; } - childSessions(): string[] { return [SWARM_PAYMENTS_SESSION, SWARM_FLAKY_SESSION, SWARM_DOCS_SESSION]; } - - /** How many beats the swarm has; a driver stops when `advance` answers false. */ - beatCount(): number { return this.beats.length; } - /** The beat that will be published next; equals `beatCount` when finished. */ - position(): number { return this.cursor; } - - /** Publishes the next beat; false when the swarm script has nothing left. */ - advance(): boolean { - if (this.cursor >= this.beats.length) return false; - const beat = this.beats[this.cursor]; - this.cursor++; - beat(); - return true; - } - - /** Publishes every remaining beat at once. */ - drain(): void { - while (this.advance()) { - } - } - - // ── Beats ──────────────────────────────────────────────────────────────── - - /** The parent's turn opens and it states what it is about to hand out. */ - private beatOpening(): void { - const parent = this.parent; - parent.openTurn(); - parent.beginRound(); - parent.thinking(PARENT_PLAN_REASONING); - parent.text(PARENT_PLAN_TEXT); - } - - /** - * First worker launched, and it had already finished by the time the parent - * published the launch: its history arrives as the child page the branch - * reads, not as records inside the parent stream. - */ - private beatSpawnPayments(): void { - const payments = this.payments; - payments.openTurn(); - payments.beginRound(); - payments.thinking('Locate every payment entry point before reading any of them.'); - payments.toolFinished('swarm-payments-search', 'Grep', - { pattern: 'charge|refund|invoice', path: 'src/payments', output_mode: 'files_with_matches' }, - PAYMENTS_GREP_OUTPUT); - payments.beginRound(); - payments.toolFinished('swarm-payments-read-a', 'Read', - { file_path: 'src/payments/charge.ts', limit: 120 }, PAYMENTS_READ_A_OUTPUT); - payments.thinking('The retry path re-enters the charge guard without the idempotency key.'); - payments.toolFinished('swarm-payments-read-b', 'Read', - { file_path: 'src/payments/retry.ts', limit: 80 }, PAYMENTS_READ_B_OUTPUT); - payments.beginRound(); - payments.text(PAYMENTS_REPORT); - this.parent.toolFinished('swarm-payments-spawn', 'AgentSpawn', { - agent_id: 'swarm-payments', agent_type: 'Explore', prompt: SWARM_PAYMENTS_BRIEF - }, spawnTable('swarm-payments', 'bg-7f21c9'), { - subagentSessionId: SWARM_PAYMENTS_SESSION, resultForAssistant: PAYMENTS_REPORT - }); - } - - /** Third worker: its own tools failed, and it reported that back. */ - private beatSpawnFlaky(): void { - const flaky = this.flaky; - flaky.openTurn(); - flaky.beginRound(); - flaky.thinking('Run the migration check first; it is the only way to know the schema state.'); - flaky.toolFinished('swarm-flaky-exec', 'ExecCommand', { - cmd: 'pnpm run migrate:check --json', workdir: '/workspace/app', yield_time_ms: 20000 - }, FLAKY_EXEC_OUTPUT, { - success: false, error: 'script "migrate:check" does not exist in this workspace' - }); - flaky.beginRound(); - flaky.text(FLAKY_REPORT); - this.parent.toolFinished('swarm-flaky-spawn', 'AgentSpawn', { - agent_id: 'swarm-flaky', agent_type: 'Explore', prompt: SWARM_FLAKY_BRIEF - }, 'agent_id bg_task_id status\nswarm-flaky bg-3c81ab failed', { - subagentSessionId: SWARM_FLAKY_SESSION, success: false, status: 'error', - error: 'the worker could not run its workspace check' - }); - } - - /** Second worker launched into the background: the call returns, the worker keeps going. */ - private beatSpawnDocs(): void { - this.parent.beginRound(); - this.parent.toolStarted('swarm-docs-spawn', 'AgentSpawn', { - agent_id: 'swarm-docs', agent_type: 'Explore', prompt: SWARM_DOCS_BRIEF - }, { subagentSessionId: SWARM_DOCS_SESSION }); - } - - private beatDocsThinking(): void { - const docs = this.docs; - docs.openTurn(); - docs.beginRound(); - docs.thinking('Start from the documentation index, then follow every link into the guides.'); - } - - private beatDocsSearchStarted(): void { - this.docs.toolStarted('swarm-docs-search', 'Grep', { - pattern: 'quickstart|getting-started', path: 'docs', glob: '*.md' - }); - } - - private beatDocsSearchFinished(): void { - this.docs.toolFinished('swarm-docs-search', 'Grep', { - pattern: 'quickstart|getting-started', path: 'docs', glob: '*.md' - }, DOCS_GREP_OUTPUT); - } - - /** The parent collects the background workers it handed out. */ - private beatWait(): void { - this.parent.beginRound(); - this.parent.toolFinished('swarm-wait', 'AgentWait', { - bg_task_ids: ['bg-7f21c9', 'bg-3c81ab', 'bg-9d40e2'], timeout_seconds: 600 - }, SWARM_WAIT_REPORT); - } - - /** - * Ordinary parent work, published while the last worker is still streaming. - * - * These rows are the parent's own: nothing may fold them into a card just - * because a launch precedes them. - */ - private beatParentRows(): void { - const parent = this.parent; - parent.beginRound(); - parent.toolFinished('swarm-parent-grep', 'Grep', { - pattern: 'swarm', path: 'src/agents', output_mode: 'files_with_matches' - }, PARENT_GREP_OUTPUT); - parent.toolFinished('swarm-parent-read', 'Read', { - file_path: 'src/agents/swarm.ts', limit: 60 - }, PARENT_READ_OUTPUT); - } - - private beatDocsReadPlan(): void { - const docs = this.docs; - docs.beginRound(); - docs.thinking('Two guides disagree about the install step; read both before writing the summary.'); - } - - private beatDocsGrepStarted(): void { - this.docs.toolStarted('swarm-docs-links', 'Grep', { - pattern: 'npm install|pnpm install', path: 'docs/guides' - }); - } - - private beatDocsGrepFinished(): void { - this.docs.toolFinished('swarm-docs-links', 'Grep', { - pattern: 'npm install|pnpm install', path: 'docs/guides' - }, DOCS_LINKS_OUTPUT); - } - - private beatDocsReadStarted(): void { - this.docs.toolStarted('swarm-docs-read', 'Read', { - file_path: 'docs/guides/install.md', offset: 1, limit: 60 - }); - } - - /** The launch settles while its worker is still running. */ - private beatDocsSpawnSettles(): void { - this.parent.toolFinished('swarm-docs-spawn', 'AgentSpawn', { - agent_id: 'swarm-docs', agent_type: 'Explore', prompt: SWARM_DOCS_BRIEF - }, spawnTable('swarm-docs', 'bg-9d40e2'), { subagentSessionId: SWARM_DOCS_SESSION }); - } -} - -/** - * The wide delegation: ten workers handed out at once. - * - * This is the delegation the follow cap exists for. Every launch is answered with - * the status the host answers a background worker with, so every card's own - * launch record says the call is done while its worker has only just started; - * each worker then publishes one step of its own. What the preview reads back is - * ten cards holding ten workers' process while only the cap's worth of child - * streams are open, and which of those streams is open follows what the reader - * opened and what finished. - */ -export class SwarmWideScript implements SwarmBeatScript { - private parent: SwarmSessionLog; - private children: SwarmSessionLog[] = []; - private beats: (() => void)[] = []; - private cursor: number = 0; - - constructor(ledger: SwarmLedger) { - this.parent = ledger.open(SWARM_WIDE_PARENT_SESSION, 'swarm-wide-turn-1', SWARM_WIDE_PROMPT, 0); - for (let index = 0; index < SWARM_WIDE_WORKERS; index++) { - this.children.push(ledger.open(wideChildSession(index), `swarm-wide-turn-${index}`, - SWARM_WIDE_BRIEF, 0)); - } - this.beats.push((): void => { this.beatOpening(); }); - for (let index = 0; index < SWARM_WIDE_WORKERS; index++) { - this.beats.push((): void => { this.beatSpawn(index); }); - } - for (let index = 0; index < SWARM_WIDE_WORKERS; index++) { - this.beats.push((): void => { this.beatWorkerStep(index); }); - } - } - - parentSession(): string { return SWARM_WIDE_PARENT_SESSION; } - - childSessions(): string[] { - const sessions: string[] = []; - for (let index = 0; index < this.children.length; index++) sessions.push(wideChildSession(index)); - return sessions; - } - - beatCount(): number { return this.beats.length; } - position(): number { return this.cursor; } - - advance(): boolean { - if (this.cursor >= this.beats.length) return false; - const beat = this.beats[this.cursor]; - this.cursor++; - beat(); - return true; - } - - drain(): void { - while (this.advance()) { - } - } - - private beatOpening(): void { - const parent = this.parent; - parent.openTurn(); - parent.beginRound(); - parent.thinking(SWARM_WIDE_PLAN_REASONING); - parent.text(SWARM_WIDE_PLAN_TEXT); - } - - /** One launch, answered at once: the worker behind it has not reported yet. */ - private beatSpawn(index: number): void { - this.parent.beginRound(); - this.parent.toolFinished(wideSpawnId(index), 'AgentSpawn', { - agent_id: wideAgentId(index), agent_type: 'Explore', prompt: SWARM_WIDE_BRIEF - }, spawnTable(wideAgentId(index), `bg-${index}4c0a1`), { subagentSessionId: wideChildSession(index) }); - } - - /** The worker's own first step, published on the worker's own stream. */ - private beatWorkerStep(index: number): void { - const child = this.children[index]; - child.openTurn(); - child.beginRound(); - child.thinking(SWARM_WIDE_WORKER_THINKING); - child.toolFinished(wideStepId(index), 'Grep', { - pattern: 'audit', path: `src/area-${index}`, output_mode: 'files_with_matches' - }, `src/area-${index}/index.ts`); - } -} - -/** The session one wide worker runs in. */ -export function wideChildSession(index: number): string { - return `${SWARM_WIDE_CHILD_PREFIX}${index}`; -} - -/** The tool call that launched one wide worker; what its card is keyed by. */ -export function wideSpawnId(index: number): string { - return `swarm-wide-spawn-${index}`; -} - -function wideAgentId(index: number): string { - return `audit-area-${index}`; -} - -function wideStepId(index: number): string { - return `swarm-wide-grep-${index}`; -} - -/** The text table an `AgentSpawn` answers with while its worker runs. */ -function spawnTable(agentId: string, bgTaskId: string): string { - return ['agent_id bg_task_id status', `${agentId} ${bgTaskId} started`].join('\n'); -} - -/** - * The brief a worker is spawned with: the full task text, mixed Markdown, long - * enough that the card's one-line title is the part a reader can see. - */ -const SWARM_PAYMENTS_BRIEF: string = [ - 'Audit the payments module and report only what you can prove from the code.', - '', - 'Steps:', - '1. find every entry point that can charge or refund a customer;', - '2. read the retry, idempotency and ledger paths end to end;', - '3. name each defect with file, symbol and the input that triggers it;', - '4. state explicitly what you could not verify.', - '', - 'Do not refactor anything. Do not run the test suite; this workspace has no', - 'payment fixtures. Your report is read by another agent, so keep it factual.' -].join('\n'); - -const SWARM_DOCS_BRIEF: string = [ - 'Check the documentation for drift against the shipped CLI.', - '', - 'Walk docs/ from the index, follow every internal link, and record each place', - 'where a command, flag or default differs from what the binary does today.', - 'Report the drift with the file and the line that has to change.' -].join('\n'); - -const SWARM_FLAKY_BRIEF: string = [ - 'Verify the database migrations can be replayed from an empty schema.', - 'Run the workspace check script and report its exit status verbatim.' -].join('\n'); - -const PARENT_PLAN_REASONING: string = - 'The audit splits into independent areas, so hand each one to a worker and collect their reports.'; -const PARENT_PLAN_TEXT: string = - 'I will run three workers in parallel: payment entry points, documentation drift, and a migration replay.'; - -const SWARM_WIDE_PROMPT: string = - 'Audit every area of the workspace at once and report which ones a reader should look at first.'; -const SWARM_WIDE_BRIEF: string = [ - 'Audit one area of the workspace and report the entry points it exposes.', - 'Name each file you read and state what the area is responsible for.' -].join('\n'); -const SWARM_WIDE_PLAN_REASONING: string = - 'Ten areas, one worker each: the widest delegation this phone has had to draw.'; -const SWARM_WIDE_PLAN_TEXT: string = - 'I will hand the audit to ten workers and follow every one of their streams.'; -const SWARM_WIDE_WORKER_THINKING: string = - 'Read the area index first, then name what it covers.'; - -const PAYMENTS_GREP_OUTPUT: string = [ - 'src/payments/charge.ts', 'src/payments/refund.ts', 'src/payments/retry.ts', - 'src/payments/invoice.ts', 'src/payments/ledger.ts' -].join('\n'); - -const PAYMENTS_READ_A_OUTPUT: string = [ - 'export async function charge(request: ChargeRequest): Promise {', - ' const key = request.idempotencyKey ?? randomKey();', - ' return ledger.append(await gateway.charge(request, key));', - '}' -].join('\n'); - -const PAYMENTS_READ_B_OUTPUT: string = [ - 'export async function retry(captured: Captured): Promise {', - ' // The guard runs again before the key is restored from the capture.', - ' if (captured.attempts > MAX_ATTEMPTS) throw new RetryExhausted(captured);', - ' return charge(captured.request);', - '}' -].join('\n'); - -const PAYMENTS_REPORT: string = [ - 'Reported two defects and one gap.', - '', - '- retry.ts re-enters charge() without restoring the captured idempotency key,', - ' so a retried charge is recorded twice in the ledger (charge.ts:12, retry.ts:4).', - '- invoice.ts rounds the taxable amount before summing line items, which drifts', - ' by one cent on invoices with more than four lines.', - '- I could not verify the refund path: it needs a signed ledger entry this', - ' workspace cannot produce.' -].join('\n'); - -const FLAKY_EXEC_OUTPUT: string = - 'ERR_PNPM_NO_SCRIPT Missing script: migrate:check\nCommand failed with exit code 1.'; - -const FLAKY_REPORT: string = [ - 'The migration replay could not be attempted.', - '', - 'The workspace has no migrate:check script, so the check I was asked to run does', - 'not exist here. Everything else in this brief depends on it, so this worker', - 'stopped rather than reporting a result it could not prove.' -].join('\n'); - -const DOCS_GREP_OUTPUT: string = [ - 'docs/index.md', 'docs/guides/quickstart.md', 'docs/guides/install.md', 'docs/reference/cli.md' -].join('\n'); - -const DOCS_LINKS_OUTPUT: string = [ - 'docs/guides/install.md:18: pnpm install', - 'docs/guides/install.md:31: pnpm add -g openbitfun', - 'docs/guides/quickstart.md:12: npm install -g openbitfun' -].join('\n'); - -const SWARM_WAIT_REPORT: string = [ - 'Two workers reported, one failed.', - '', - 'payments: double ledger entry on retry, invoice rounding drift.', - 'docs: quickstart.md still installs with npm while the CLI ships as pnpm.', - 'flaky: could not run its check; the script it was told to use does not exist.' -].join('\n'); - -const PARENT_GREP_OUTPUT: string = 'src/agents/swarm.ts\nsrc/agents/swarm/plan.ts'; - -const PARENT_READ_OUTPUT: string = [ - 'export function planWorkers(areas: AuditArea[]): WorkerPlan {', - ' return areas.map((area) => ({ area, agentType: area.preferredAgent }));', - '}' -].join('\n'); diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets deleted file mode 100644 index 0ae02575d5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntime.ets +++ /dev/null @@ -1,688 +0,0 @@ -import { - RecentWorkspaceEntry, - RemoteSession, - RemoteWorkspaceIdentity, - SessionSummary, - SessionListResult -} from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { - remoteWorkspaceIdentityMatches, - stampRemoteSessionsDevice -} from '../../services/RemoteSessionIdentity'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { AppRootHostPort } from '../host/AppRootHostAdapter'; -import { - AppNavigationBackAction, - AppRoute, - AppRouteContract -} from '../navigation/AppRouteContract'; -import { - AppRootRuntimeComposition, - ConnectionState -} from './AppRootRuntimeComposition'; - -/** - * How stale an account device presence answer may be before returning to the - * foreground, or opening the sidebar, refetches it. Short enough that a - * desktop coming online is noticed in the same sitting, long enough that the - * two events firing together on a cold start cost one request, not three. - */ -const DEVICE_PRESENCE_MAX_AGE_MS: number = 15000; - -export class AppRootRuntime extends AppRootRuntimeComposition { - private directorySelectionVersion: number = 0; - - constructor(host: AppRootHostPort) { - super(host); - } - - async aboutToAppear(onAccountRestored?: (signedIn: boolean) => void): Promise { - // Account login can be tapped while the rest of the cold-start work is - // still running. Initialize its secure store first so the login path never - // races the asynchronous cache and onboarding setup below. - await this.settingsController.initializeCloudAccount(this.host.context()); - await this.localeController.initialize(this.host.context()); - if (this.host.offerTaskNotifications) { - await this.taskCompletionNotificationPort.offerOnboarding( - (): Promise => this.host.offerTaskNotifications!() - ); - } - this.syncRemotePageSummary(); - await this.remoteChatCache.init(this.host.context()); - await this.remoteSessionListCache.init(this.host.context()); - await this.restoreCachedRemoteSessions(); - if (onAccountRestored) onAccountRestored(this.settingsController.hasCloudAccountSession()); - if (this.settingsController.hasCloudAccountSession()) { - try { - await this.settingsController.listCloudAccountDevices(); - await this.deviceDirectoryViewModel.hydrateKnownDevices(); - } catch (err) { - RemoteLogger.warn(`device directory restore failed: ${err instanceof Error ? err.message : String(err)}`); - } - } - await this.restoreIdentity(); - await this.startWatchProvisioning(); - } - - /** - * Only ask for distributed data sync once the phone actually has something to - * provision a watch with. A fresh install has nothing, and a permission - * prompt at first launch would have no explanation behind it. - * - * A signed-in account counts on its own, with no desktop in sight: the phone - * mints the watch's credential itself in that case, so waiting for a live - * connection would keep the listener down exactly when it is not needed. - */ - protected async startWatchProvisioning(): Promise { - if (!this.settingsController.hasCloudAccountSession() && !this.hasRemoteBindingForResume()) { - return; - } - await this.watchProvisionController.start(this.host.context()); - } - - onPageShow(): void { - RemoteLogger.info(`page show state=${(this.remotePageState.connectionState as ConnectionState)} route=${this.appShellViewModel.currentRoute()}`); - this.settingsController.setAuthorizationForeground(true); - this.taskCompletionNotificationController.onForeground(); - this.remoteActivityViewModel.resume(); - // Idempotent: covers the pairing that happened after the last cold start. - void this.startWatchProvisioning(); - void this.settingsController.refreshAccountDevicesIfStale(DEVICE_PRESENCE_MAX_AGE_MS); - this.settingsController.startPresencePolling(DEVICE_PRESENCE_MAX_AGE_MS); - } - - onPageHide(): void { - RemoteLogger.info(`page hide state=${(this.remotePageState.connectionState as ConnectionState)} route=${this.appShellViewModel.currentRoute()}`); - this.settingsController.setAuthorizationForeground(false); - this.settingsController.stopPresencePolling(); - const activeRemoteTurn = this.remotePageState.activeTurnMessage; - if (this.isRemoteConversationContext(this.remotePageState.activeSession.sessionId)) { - this.trackRemoteTaskCompletion(this.remotePageState.activeSession.sessionId, activeRemoteTurn); - } - const keepRemotePolling = this.taskCompletionNotificationController.isTracking('remote'); - const watchingCompletion = this.taskCompletionNotificationController.onBackground(); - if (keepRemotePolling && watchingCompletion) { - this.remoteActivityViewModel.suspendKeepingActiveTurnPoll(); - } else { - this.remoteActivityViewModel.invalidate(); - } - this.remoteConnectionCoordinator.invalidate(); - this.remotePageState.setBusy(false); - } - - aboutToDisappear(): void { - this.miniAppViewModel.close(); - this.settingsController.stopPresencePolling(); - this.watchProvisionController.stop(); - this.taskCompletionNotificationController.stop(); - this.remoteActivityViewModel.invalidate(); - this.remoteConnectionCoordinator.invalidate(); - this.remotePageState.setBusy(false); - this.remoteFileDownloadController.cancel(); - this.filePreviewController.close(); - this.voiceInputLifecycleController.cancel(`${this.appShellViewModel.currentRoute()}`, () => { - this.conversationController.clearAllVoiceListening(); - }); - } - - isRemoteConversationContext(sessionId: string): boolean { - if (sessionId.length === 0 || this.remotePageState.activeSession.sessionId !== sessionId) { - return false; - } - return this.appShellViewModel.isRoute(AppRoute.RemoteChat) || this.appShellViewModel.isRoute(AppRoute.RemoteHome); - } - - handleNavigationBack(route: AppRoute): boolean { - if (this.appShellState.showConnectSheet) { - this.appShellState.setConnectSheetVisible(false); - return true; - } - if (this.filePreviewState.visible) { - this.filePreviewController.close(); - return true; - } - const action = this.appShellViewModel.backAction(route); - if (action === AppNavigationBackAction.CloseSidebar) { - this.closeAppSidebar(); - return true; - } - if (action === AppNavigationBackAction.CloseActiveChat) { - this.exitActiveChat(); - return true; - } - if (action === AppNavigationBackAction.PopRemoteHome) { - this.appShellViewModel.popRoute(AppRoute.RemoteHome); - return true; - } - return false; - } - - handleRootBack(): boolean { - if (this.appShellState.showConnectSheet) { - this.appShellState.setConnectSheetVisible(false); - return true; - } - if (!this.filePreviewState.visible) { - return false; - } - this.filePreviewController.close(); - return true; - } - - - async restoreIdentity(): Promise { - // Read the install id and old target hint without reconnecting an old room. - // The authenticated directory is the sole authority for restoring control. - await this.remoteConnectionController.restoreWithoutReconnect(this.host.context()); - if (!this.settingsController.hasCloudAccountSession()) { - this.remotePageState.clearControlTarget(); - this.remotePageState.setConnectionState(ConnectionState.Disconnected); - if (this.remotePageState.remoteUrl.length > 0) { - this.remotePageState.setStatusText(RemoteI18n.t('connect.legacySignInRequired')); - } - return; - } - if (this.settingsController.preferredCloudTarget()) { - await this.restoreAccountDeviceTarget(false); - } - } - - /** Restores only a device proven by the current authenticated directory. */ - private async restoreAccountDeviceTarget(navigateHome: boolean): Promise { - const preferredTarget = this.settingsController.preferredCloudTarget(); - const deviceId = preferredTarget?.deviceId || this.remotePageState.controlTargetDeviceId.trim(); - if (deviceId.length === 0) { - return; - } - this.remotePageState.setConnectionState(ConnectionState.Reconnecting); - this.remotePageState.setStatusText(RemoteI18n.t('status.restoringConnection')); - await this.settingsController.restoreCloudTarget( - deviceId, - preferredTarget?.deviceName || this.remotePageState.controlTargetDeviceName, - navigateHome - ); - } - - async connect(autoReconnect: boolean = false, accountPassword: string = ''): Promise { - this.handleDetectedRemoteUrl(this.remotePageState.remoteUrl); - } - - async reconnect(): Promise { - if (this.settingsController.preferredCloudTarget()) { - await this.restoreAccountDeviceTarget(true); - return; - } - this.appShellState.openSettings('account'); - } - - async disconnect(clearPairing: boolean): Promise { - this.filePreviewController.invalidate(); - await this.remoteConnectionController.disconnect(clearPairing); - } - - syncRemotePageSummary(): void { - if (this.remotePageState.statusText.length === 0) { - this.remotePageState.setStatusText(RemoteI18n.t('status.waitingConnection')); - } - if (this.remotePageState.workspaceName.length === 0) { - this.remotePageState.setWorkspace(RemoteI18n.t('status.notConnected'), '', '', '', 'normal'); - } - } - - /** - * A request that failed against a link the phone still has a binding for is a - * link that dropped, not one that ended, so the heartbeat stays up and its - * next ping is what notices the desktop coming back. Killing it here is what - * used to make a momentary drop permanent: `failed` disables every remote - * action, and nothing was left running to lift it again. - */ - failRemoteConnection(err: Object): void { - this.remotePageState.setStatusText(ConnectionErrorPolicy.errorText(err)); - if (this.hasRemoteBindingForResume()) { - this.remotePageState.setConnectionState(ConnectionState.Reconnecting); - this.remoteActivityViewModel.startHeartbeat(); - return; - } - this.remotePageState.setConnectionState(ConnectionState.Failed); - this.remoteActivityViewModel.stopHeartbeat(); - } - - async selectWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - this.filePreviewController.close(); - await this.remoteWorkspaceViewModel.selectWorkspace(path, connectionId, sshHost, workspaceId); - } - - async selectWorkspaceOnDevice(path: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - await this.conversationController.ensureRemoteControlTarget(deviceId); - await this.selectWorkspace(path, connectionId, sshHost, workspaceId); - } - - async selectDirectoryDevice(deviceId: string): Promise { - const selectionVersion = ++this.directorySelectionVersion; - // Re-selecting the current context never hides its workspace panel. - if (this.deviceDirectoryState.selectedDeviceId === deviceId && - this.isConnectedDirectoryTarget(deviceId)) { - return; - } - await this.deviceDirectoryViewModel.selectDevice(deviceId); - if (selectionVersion !== this.directorySelectionVersion) { - return; - } - const entry = this.deviceDirectoryState.find(deviceId); - if (entry && !entry.online && !this.isConnectedDirectoryTarget(deviceId)) { - return; - } - try { - await this.conversationController.ensureRemoteControlTarget(deviceId); - if (selectionVersion !== this.directorySelectionVersion) { - return; - } - this.filePreviewController.close(); - if (this.appShellState.wideLayout) { - await this.enterRemoteSurfaceWide(); - } else { - // Keep the compact drawer visible to show the selected workspace panel; - // entering Remote from any other compact entry point still dismisses - // the drawer through the method's default behavior. - await this.enterRemoteSurfaceCompact(false); - } - this.appShellViewModel.replaceRouteWithoutAnimation(AppRoute.RemoteHome); - } catch (err) { - RemoteLogger.warn(`device directory switch failed device=${deviceId}: ${String(err)}`); - } - } - - async openWorkspacePickerOnDevice(deviceId: string): Promise { - await this.deviceDirectoryViewModel.selectDevice(deviceId); - const entry = this.deviceDirectoryState.find(deviceId); - if (entry && !entry.online && !this.isConnectedDirectoryTarget(deviceId)) { - return; - } - if (this.isConnectedDirectoryTarget(deviceId)) { - await this.remoteWorkspaceViewModel.loadRecentWorkspacesInBackground(); - } - } - - async retryDirectoryDevice(deviceId: string): Promise { - if (this.isConnectedDirectoryTarget(deviceId)) { - await this.remoteWorkspaceViewModel.loadRecentWorkspacesInBackground(); - return; - } - await this.deviceDirectoryViewModel.retryDevice(deviceId); - } - - async loadWorkspaceSessionsOnDevice(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): Promise { - const targetDeviceId = deviceId.trim(); - const targetPath = path.trim(); - if (targetDeviceId.length === 0 || targetPath.length === 0) { - return; - } - await this.deviceDirectoryViewModel.loadWorkspaceSessions(targetDeviceId, targetPath, remoteConnectionId, remoteSshHost, workspaceId); - } - - publishWorkspaceSessionPage(path: string, result: SessionListResult, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): void { - const workspace: RemoteWorkspaceIdentity = { - workspaceId: workspaceId?.trim() || undefined, - path, - remoteConnectionId, - remoteSshHost - }; - this.remoteWorkspaceSessions = this.replaceWorkspaceSessions(workspace, result.sessions); - if (this.isCurrentWorkspace(workspace)) { - // Update the controller as well as the sidebar so a later title change - // cannot republish the old current-workspace list. - this.remoteSessionController.setSessions(result.sessions, result.hasMore); - } else { - this.publishRemoteWorkspaceSessions(); - } - } - - private isConnectedDirectoryTarget(deviceId: string): boolean { - return deviceId === this.remotePageState.controlTargetDeviceId && - RemoteUiState.canUseRemote((this.remotePageState.connectionState as ConnectionState)); - } - - async selectAssistant(path: string, workspaceId?: string): Promise { - this.filePreviewController.close(); - await this.remoteWorkspaceViewModel.selectAssistant(path, workspaceId); - } - - /** Catalog rows the legacy resolver may attribute an ID-less reference to. */ - private workspaceAttributionCatalog(): RemoteWorkspaceIdentity[] { - const recent = this.remotePageState.recentWorkspaces; - const rows: RemoteWorkspaceIdentity[] = []; - recent.forEach((entry: RecentWorkspaceEntry) => rows.push(entry)); - const current = this.remotePageState.workspaceIdentity(); - if (current.path.length > 0 || current.workspaceId !== undefined) { - // The current workspace joins the catalog only when no row already names - // it; a duplicate row would make every legacy path lookup ambiguous. - const known = recent.some((entry: RecentWorkspaceEntry): boolean => - remoteWorkspaceIdentityMatches(entry, current, recent)); - if (!known) { - rows.push(current); - } - } - return rows; - } - - /** Whether a reference names the desktop's active workspace. */ - private isCurrentWorkspace(workspace: RemoteWorkspaceIdentity): boolean { - return remoteWorkspaceIdentityMatches(workspace, this.remotePageState.workspaceIdentity(), this.workspaceAttributionCatalog()); - } - - private sessionOwnedBy(item: RemoteSession, workspace: RemoteWorkspaceIdentity): boolean { - return item.workspaceIdentity !== undefined && - remoteWorkspaceIdentityMatches(item.workspaceIdentity, workspace, this.workspaceAttributionCatalog()); - } - - openAppSidebar(): void { - this.host.animate(230, () => { - this.appShellState.setSidebarVisible(true); - }); - // The device rows are only on screen from here, and a desktop that came - // online since the last look would otherwise stay grey. - void this.settingsController.refreshAccountDevicesIfStale(DEVICE_PRESENCE_MAX_AGE_MS).then(() => - this.deviceDirectoryViewModel.refreshExpandedWorkspaceSessions() - ); - } - - closeAppSidebar(): void { - this.host.animate(210, () => { - this.appShellState.setSidebarVisible(false); - }); - } - - async enterRemoteSurfaceWide(): Promise { - if (AppRouteContract.isRemoteRoute(this.appShellViewModel.currentRoute())) { - return; - } - if (this.conversationController.visibleVoiceListening()) { - await this.stopVoiceInput(false); - } - const activeRemoteSessionId = this.remotePageState.isConversationDismissed ? '' : - (this.remotePageState.activeSession.sessionId || ''); - const target = AppRouteContract.remoteSurfaceDestination( - RemoteUiState.canUseRemote((this.remotePageState.connectionState as ConnectionState)), - activeRemoteSessionId - ); - this.appShellViewModel.replaceRouteWithoutAnimation( - target.name, - target.hasSessionParam() ? target.routeParam().sessionId : '' - ); - if (target.name === AppRoute.RemoteChat) { - this.conversationController.startRemotePolling(); - await this.conversationController.loadRemoteMessages(); - } - } - - /** - * Compact counterpart of enterRemoteSurfaceWide. Reaching the remote surface - * is a change of context, not a command to start something: it resumes the - * session the user was last in, and otherwise rests on the Remote landing - * surface rather than opening the create composer for them. - */ - async enterRemoteSurfaceCompact(closeSidebar: boolean = true): Promise { - if (closeSidebar) { - this.closeAppSidebar(); - } - if (AppRouteContract.isRemoteRoute(this.appShellViewModel.currentRoute())) { - return; - } - if (this.conversationController.visibleVoiceListening()) { - await this.stopVoiceInput(false); - } - const activeRemoteSessionId = RemoteUiState.canUseRemote((this.remotePageState.connectionState as ConnectionState)) && - !this.remotePageState.isConversationDismissed ? - (this.remotePageState.activeSession.sessionId || '') : ''; - if (activeRemoteSessionId.length === 0) { - this.appShellViewModel.replaceRouteWithoutAnimation(AppRoute.RemoteHome); - return; - } - this.appShellViewModel.replaceRouteWithoutAnimation(AppRoute.RemoteChat, activeRemoteSessionId); - this.conversationController.startRemotePolling(); - await this.conversationController.loadRemoteMessages(); - } - - enterCompactLayout(): void { - const sessionId = this.remotePageState.activeSession.sessionId || ''; - if (this.appShellViewModel.isRoute(AppRoute.RemoteHome) && - !this.remotePageState.isConversationDismissed && sessionId.length > 0) { - this.appShellViewModel.pushRoute(AppRoute.RemoteChat, sessionId, false); - } - } - - /** - * Exit control for an open conversation. Leaving a remote conversation on a - * compact layout lands on Remote Home with no visible session list, so reveal - * the drawer that owns navigation there. Compact chats have no back button of - * their own, so this runs for the system back gesture. - */ - exitActiveChat(): void { - const revealSidebar = !this.appShellState.wideLayout && - this.appShellViewModel.isRoute(AppRoute.RemoteChat); - this.conversationController.closeActiveChat(); - if (revealSidebar) { - this.openAppSidebar(); - } - } - - /** - * Reconciles the workspace row that owns a newly created remote session. - * - * Creating from the sidebar deliberately does not switch the desktop's - * active workspace. A normal session refresh therefore still lists the old - * active workspace and cannot discover the new row. Publish the confirmed - * create immediately, then refresh the workspace named by the response. - */ - async reconcileCreatedRemoteSession(session: SessionSummary): Promise { - const workspacePath = session.workspacePath.trim(); - const workspace: RemoteWorkspaceIdentity = { - workspaceId: session.workspaceId?.trim() || undefined, - path: workspacePath, - remoteConnectionId: session.remoteConnectionId, - remoteSshHost: session.remoteSshHost - }; - if ((workspacePath.length === 0 && !workspace.workspaceId) || this.isCurrentWorkspace(workspace)) { - await this.remoteSessionViewModel.refreshSessions(); - return; - } - - const now = new Date().toISOString(); - const created: RemoteSession = { - id: session.sessionId, - title: session.title, - agentType: session.agentType, - status: 'active', - updatedAt: now, - createdAt: now, - messageCount: session.initialTurnId ? 1 : 0, - workspacePath, - workspaceIdentity: workspace - }; - this.remoteWorkspaceSessions = this.replaceWorkspaceSessions( - workspace, - this.mergeSessions([created], this.sessionsForWorkspace(workspace)) - ); - this.publishRemoteWorkspaceSessions(); - - try { - const refreshed = await this.sessionManager.listSessionsForWorkspace(workspace, 50); - const containsCreated = refreshed.some((item: RemoteSession): boolean => item.id === session.sessionId); - this.remoteWorkspaceSessions = this.replaceWorkspaceSessions( - workspace, - containsCreated ? refreshed : this.mergeSessions([created], refreshed) - ); - this.publishRemoteWorkspaceSessions(); - } catch (err) { - // The create already succeeded and is on screen. Keep that confirmed row - // instead of turning a follow-up list failure into a false create error. - RemoteLogger.warn(`created session workspace refresh failed workspace=${workspace.workspaceId || ''} path=${workspacePath}: ${String(err)}`); - } - } - - private sessionsForWorkspace(workspace: RemoteWorkspaceIdentity): RemoteSession[] { - return this.remotePageState.sessions.filter((item: RemoteSession): boolean => this.sessionOwnedBy(item, workspace)); - } - - private replaceWorkspaceSessions(workspace: RemoteWorkspaceIdentity, replacement: RemoteSession[]): RemoteSession[] { - const preserved = this.remotePageState.sessions.filter((item: RemoteSession): boolean => { - return !this.sessionOwnedBy(item, workspace); - }); - return replacement.concat(preserved); - } - - private publishRemoteWorkspaceSessions(): void { - const currentWorkspace = this.remotePageState.workspaceIdentity(); - const current = this.remotePageState.sessions.filter((item: RemoteSession): boolean => { - return !item.workspaceIdentity || this.sessionOwnedBy(item, currentWorkspace); - }); - const extras = this.remoteWorkspaceSessions.filter((item: RemoteSession): boolean => { - return !item.workspaceIdentity || !this.sessionOwnedBy(item, currentWorkspace); - }); - this.publishRemoteSessions(this.mergeSessions(current, extras), this.remotePageState.hasMoreSessions); - } - - /** - * The single way a session list reaches the screen, so everything the user - * sees is also what the next launch starts from. - * - * The write is deliberately not awaited: the list is on screen either way, - * and making a repaint wait on disk is the one way this cache could make the - * app feel slower than it did without it. - */ - publishRemoteSessions(sessions: RemoteSession[], hasMore: boolean): void { - const deviceId = this.remotePageState.controlTargetDeviceId || this.remotePageState.desktopId; - const scoped = sessions; - const stamped = stampRemoteSessionsDevice(scoped, deviceId); - this.remotePageState.setSessions(stamped, hasMore); - this.remoteSessionListCache.save(stamped, hasMore); - const currentWorkspace = this.remotePageState.workspaceIdentity(); - if (currentWorkspace.path.length > 0) { - const currentSessions = stamped.filter((item: RemoteSession): boolean => this.sessionOwnedBy(item, currentWorkspace)); - this.deviceDirectoryViewModel.captureWorkspaceSessions( - deviceId, - currentWorkspace.path, - currentSessions, - currentWorkspace.remoteConnectionId, - currentWorkspace.remoteSshHost, - currentWorkspace.workspaceId - ); - } - this.deviceDirectoryViewModel.captureLive( - deviceId, - this.remotePageState.recentWorkspaces, - stamped - ); - } - - /** - * Fills Remote Home from disk before anything is connected. - * - * Runs against whichever desktop was used last, because the device to key on - * is not known this early — identity is still being restored, and the - * auto-reconnect that follows targets exactly that desktop. Anything the - * desktop reports replaces this, so a stale entry costs a repaint. - */ - private async restoreCachedRemoteSessions(): Promise { - if (this.remotePageState.sessions.length > 0) { - return; - } - const cached = await this.remoteSessionListCache.restoreLast(); - // Checked again: a connection may have landed while the read was in flight, - // and the desktop's answer outranks the stored one. - if (cached.sessions.length === 0 || this.remotePageState.sessions.length > 0) { - return; - } - RemoteLogger.info(`session list from cache count=${cached.sessions.length}`); - this.remotePageState.setSessions(cached.sessions, cached.hasMore); - } - - mergeSessions(primary: RemoteSession[], extras: RemoteSession[]): RemoteSession[] { - return RemoteUiState.mergeSessions(primary, extras); - } - - async toggleVoiceInput(): Promise { - const route = this.appShellViewModel.currentRoute(); - await this.voiceInputLifecycleController.toggle( - this.host.context(), this.conversationController.voiceInputSnapshot(route) - ); - } - - async stopVoiceInput(showStatus: boolean): Promise { - const route = this.appShellViewModel.currentRoute(); - await this.voiceInputLifecycleController.stop( - this.conversationController.voiceInputSnapshot(route), showStatus - ); - } - - showVoiceInputError(message: string): void { - const text = message.length > 0 ? message : RemoteI18n.t('errors.voiceInputUnavailable'); - this.conversationController.setVisibleStatusText(text); - this.host.showToast(text, 2600); - } - - async pickImages(): Promise { - if (this.conversationController.visibleBusy()) { - return; - } - const route = this.appShellViewModel.currentRoute(); - if (this.conversationController.visibleVoiceListening()) { - await this.stopVoiceInput(false); - } - try { - this.conversationController.setVisibleStatusText(RemoteI18n.t('status.pickImage')); - const picked = await this.imagePickerService.pickImages( - 3, - this.conversationController.visibleSelectedImages().length - ); - if (picked.length === 0) { - this.conversationController.setVisibleStatusText(RemoteI18n.t('status.noImageSelected')); - return; - } - this.conversationController.addSelectedImages(route, picked); - this.conversationController.setVisibleStatusText(RemoteI18n.f( - 'status.imagesSelected', - `${this.conversationController.visibleSelectedImages().length}` - )); - } catch (err) { - this.conversationController.setVisibleStatusText(ConnectionErrorPolicy.errorText(err)); - } - } - - currentActiveTurnId(): string { - return this.conversationController.remoteActiveTurnId(); - } - - hasRemoteBindingForResume(): boolean { - if (this.remotePageState.controlTargetType === 'account_device') { - return this.remotePageState.accountUserId.trim().length > 0 && - this.remotePageState.controlTargetDeviceId.trim().length > 0 && - (this.remotePageState.connectionState as ConnectionState) !== ConnectionState.Idle && - (this.remotePageState.connectionState as ConnectionState) !== ConnectionState.Disconnected; - } - return false; - } - - async reconnectActiveRemote(): Promise { - const preferredTarget = this.settingsController.preferredCloudTarget(); - if (!preferredTarget) { - throw new Error(RemoteI18n.t('connect.legacySignInRequired')); - } - const targetId = preferredTarget.deviceId; - const device = (await this.settingsController.listCloudAccountDevices()) - .find((item: CloudAccountDevice): boolean => item.deviceId === targetId); - if (!device) { - throw new Error(RemoteI18n.t('remote.settings.deviceOffline')); - } - await this.settingsController.selectCloudAccountDevice(device); - } - - hasRemoteBindingForCodeHome(): boolean { - return this.hasRemoteBindingForResume(); - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets deleted file mode 100644 index 9097816d56..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets +++ /dev/null @@ -1,1171 +0,0 @@ -import { MessageQueueAction, MessageQueueState } from '../../model/MessageQueue'; -import { InteractionMailboxAction, InteractionMailboxState } from '../../model/InteractionMailbox'; -import { HostCatalogChange, HostCatalogObserver } from '../../services/HostCatalogObserver'; -import { WorkspaceToolsViewModel } from '../viewmodel/WorkspaceToolsViewModel'; -import { WorkspaceToolsIntent } from '../state/WorkspaceToolsState'; -import { BuiltinMiniAppHost } from '../../services/BuiltinMiniAppHost'; -import { MiniAppViewModel } from '../viewmodel/MiniAppViewModel'; -import { SidebarConnectionActionPolicy } from '../policy/SidebarConnectionActionPolicy'; -import { accountDeviceLink } from '../../services/AccountDeviceLink'; -import { - ChatMessage, - RemoteCommandCatalog, - RemoteDefaultModels, - RemoteModelCatalog, - RemotePermissionMode, - RemoteQuestionAnswerPayload, - RemoteSession, - RemoteSessionUsageReport, - RecentWorkspaceEntry, - SelectedImageAttachment, - SessionSummary, - SessionListResult, - WorkspaceInfo -} from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { LocalePreferenceStore } from '../../services/LocalePreferenceStore'; -import { ClipboardService } from '../../services/ClipboardService'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { ConnectionStatusPresenter } from '../../services/ConnectionStatusPresenter'; -import { ImagePickerService } from '../../services/ImagePickerService'; -import { MobileIdentityStore } from '../../services/MobileIdentityStore'; -import { CloudAccountClient, CloudAccountDevice } from '../../services/CloudAccountClient'; -import { GitHubAccountProfileClient } from '../../services/GitHubAccountProfile'; -import { CloudAccountSessionStore } from '../../services/CloudAccountSessionStore'; -import { RemoteActivityLifecycleController } from '../../services/RemoteActivityLifecycleController'; -import { RemoteChatCache } from '../../services/RemoteChatCache'; -import { RemoteChatBranchCache } from '../../services/RemoteChatBranchCache'; -import { RemoteChatCommandController } from '../../services/RemoteChatCommandController'; -import { RemoteChatLocalRdbStore } from '../../services/RemoteChatLocalRdbStore'; -import { RemoteChatPollingLifecycleController, RemoteChatPollingSnapshot } from '../../services/RemoteChatPollingLifecycleController'; -import { RemoteFileDownloadController } from '../../services/RemoteFileDownloadController'; -import { FilePreviewController } from '../viewmodel/FilePreviewController'; -import { DeviceDirectoryViewModel } from '../viewmodel/DeviceDirectoryViewModel'; -import { SettingsController } from '../viewmodel/SettingsController'; -import { LocaleController } from '../viewmodel/LocaleController'; -import { ConversationController } from '../viewmodel/ConversationController'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemoteModelController } from '../../services/RemoteModelController'; -import { RemoteCommandPaletteController } from '../../services/RemoteCommandPaletteController'; -import { RemoteSessionController } from '../../services/RemoteSessionController'; -import { RemoteSessionListCache } from '../../services/RemoteSessionListCache'; -import { RemoteSessionListRdbStore } from '../../services/RemoteSessionListRdbStore'; -import { RemoteSessionManager } from '../../services/RemoteSessionManager'; -import { SubagentBranchCache } from '../../services/SubagentStreamCoordinator'; -import { RemoteWorkspaceRepository } from '../../services/RemoteWorkspaceRepository'; -import { RemoteWorkspaceCoordinator } from '../../services/RemoteWorkspaceCoordinator'; -import { RemoteConnectionCoordinator } from '../../services/RemoteConnectionCoordinator'; -import { RemoteToolActionController } from '../../services/RemoteToolActionController'; -import { AsyncLifecycleGate } from '../../services/AsyncLifecycleGate'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { VoiceInputLifecycleController } from '../../services/VoiceInputLifecycleController'; -import { VoiceInputService } from '../../services/VoiceInputService'; -import { ConversationIntent, CommandPaletteRequest, MessageCopyScope, SessionRollbackRequest } from '../actions/ConversationIntent'; -import { AppRootHostPort } from '../host/AppRootHostAdapter'; -import { AppRootPresentationActions } from '../actions/AppRootPresentationActions'; -import { - AppNavigationBackAction, - AppRoute, - AppRouteContract -} from '../navigation/AppRouteContract'; -import { AppShellState } from '../state/AppShellState'; -import { - RemoteConnectEntryKind, - RemoteSurfaceEntryPolicy -} from '../policy/RemoteSurfaceEntryPolicy'; -import { AppShellViewModel } from '../viewmodel/AppShellViewModel'; -import { RemoteActivityViewModel } from '../viewmodel/RemoteActivityViewModel'; -import { - RemoteConnectionController -} from '../viewmodel/RemoteConnectionController'; -import { ConversationIntentDispatcher } from '../actions/ConversationIntentDispatcher'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { DeviceDirectoryState } from '../state/DeviceDirectoryState'; -import { RemotePageState } from '../state/RemotePageState'; -import { WatchProvisionState } from '../state/WatchProvisionState'; -import { - WatchProvisionController, - WatchProvisionOutcome, - WatchProvisionPort -} from '../../services/WatchProvisionController'; -import { ConversationViewModel } from '../viewmodel/ConversationViewModel'; -import { FilePreviewState } from '../state/FilePreviewState'; -import { FilePreviewRequest } from '../../model/FilePreviewTarget'; -import { RemoteWorkspaceViewModel } from '../viewmodel/RemoteWorkspaceViewModel'; -import { RemoteSessionViewModel } from '../viewmodel/RemoteSessionViewModel'; -import { HarmonyTaskCompletionNotificationPort } from '../../services/HarmonyTaskCompletionNotificationPort'; -import { - TaskCompletionNotificationController, - TaskCompletionObservation -} from '../../services/TaskCompletionNotificationController'; - -export enum ConnectionState { - Idle = 'idle', - Parsing = 'parsing', - Pairing = 'pairing', - Connected = 'connected', - Reconnecting = 'reconnecting', - Failed = 'failed', - Disconnected = 'disconnected' -} - - -export abstract class AppRootRuntimeComposition { - readonly host: AppRootHostPort; - - constructor(host: AppRootHostPort) { - this.host = host; - } - - abstract closeAppSidebar(): void; - abstract connect(autoReconnect?: boolean, accountPassword?: string): Promise; - abstract currentActiveTurnId(): string; - abstract disconnect(clearPairing: boolean): Promise; - abstract enterCompactLayout(): void; - abstract enterRemoteSurfaceCompact(closeSidebar?: boolean): Promise; - abstract enterRemoteSurfaceWide(): Promise; - abstract exitActiveChat(): void; - abstract failRemoteConnection(err: Object): void; - abstract handleNavigationBack(route: AppRoute): boolean; - abstract hasRemoteBindingForResume(): boolean; - protected abstract startWatchProvisioning(): Promise; - abstract isRemoteConversationContext(sessionId: string): boolean; - abstract mergeSessions(primary: RemoteSession[], extras: RemoteSession[]): RemoteSession[]; - abstract loadWorkspaceSessionsOnDevice(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): Promise; - abstract openAppSidebar(): void; - abstract openWorkspacePickerOnDevice(deviceId: string): Promise; - abstract pickImages(): Promise; - abstract publishRemoteSessions(sessions: RemoteSession[], hasMore: boolean): void; - abstract publishWorkspaceSessionPage(path: string, result: SessionListResult, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): void; - abstract reconcileCreatedRemoteSession(session: SessionSummary): Promise; - abstract reconnect(): Promise; - abstract reconnectActiveRemote(): Promise; - abstract retryDirectoryDevice(deviceId: string): Promise; - abstract selectDirectoryDevice(deviceId: string): Promise; - abstract selectAssistant(path: string, workspaceId?: string): Promise; - abstract selectWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise; - abstract selectWorkspaceOnDevice(path: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise; - abstract showVoiceInputError(message: string): void; - abstract stopVoiceInput(showStatus: boolean): Promise; - abstract toggleVoiceInput(): Promise; - - readonly sessionManager: RemoteSessionManager = new RemoteSessionManager(); - readonly miniAppViewModel: MiniAppViewModel = new MiniAppViewModel(new BuiltinMiniAppHost((): Context => this.host.context())); - readonly taskCompletionNotificationPort: HarmonyTaskCompletionNotificationPort = - new HarmonyTaskCompletionNotificationPort((): Context => this.host.context()); - readonly taskCompletionNotificationController: TaskCompletionNotificationController = - new TaskCompletionNotificationController( - this.taskCompletionNotificationPort, - (observation: TaskCompletionObservation): void => { - if (observation.source === 'remote') { - this.remoteChatPollingLifecycleController.stop(); - } - } - ); - readonly workspaceRepository: RemoteWorkspaceRepository = - new RemoteWorkspaceRepository(this.sessionManager); - readonly workspaceCoordinator: RemoteWorkspaceCoordinator = - new RemoteWorkspaceCoordinator(this.workspaceRepository); - readonly remoteResumeGate: AsyncLifecycleGate = new AsyncLifecycleGate(); - readonly remoteConnectionGate: AsyncLifecycleGate = new AsyncLifecycleGate(); - readonly filePreviewState: FilePreviewState = new FilePreviewState(); - readonly identityStore: MobileIdentityStore = new MobileIdentityStore(); - readonly clipboardService: ClipboardService = new ClipboardService(); - readonly imagePickerService: ImagePickerService = new ImagePickerService(); - readonly remoteConnectionCoordinator: RemoteConnectionCoordinator = - new RemoteConnectionCoordinator( - this.sessionManager, - this.remoteConnectionGate - ); - readonly generalChatPageState: GeneralChatPageState = new GeneralChatPageState(); - readonly remotePageState: RemotePageState = new RemotePageState(); - readonly deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); - readonly watchProvisionState: WatchProvisionState = new WatchProvisionState(); - private readonly watchProvisionPort: WatchProvisionPort = { - canProvision: (): boolean => this.settingsController.canMintWatchCredential(), - provision: (deviceId: string, deviceName: string, requestId: string, password: string): Promise => - this.provisionWatchDevice(deviceId, deviceName, requestId, password) - }; - readonly watchProvisionController: WatchProvisionController = - new WatchProvisionController(this.watchProvisionState, this.watchProvisionPort); - - private async provisionWatchDevice( - deviceId: string, - deviceName: string, - requestId: string, - password: string - ): Promise { - return await this.settingsController.provisionWatchCredential(deviceId, deviceName, requestId, password) || - AppRootRuntimeComposition.provisionUnavailable(); - } - - private static provisionUnavailable(): WatchProvisionOutcome { - return { - ok: false, passwordRequired: false, relayUrl: '', token: '', userId: '', masterKeyBase64: '', deviceId: '', - failure: '', desktopReported: false - }; - } - readonly localePreferenceStore: LocalePreferenceStore = new LocalePreferenceStore(); - readonly chatTimelineStore: ConversationViewModel = new ConversationViewModel(); - // Scoped to the desktop currently being controlled: session ids are issued by - // the desktop, so two of them on one account can name different conversations - // with the same id. - readonly remoteChatCache: RemoteChatCache = - new RemoteChatCache( - new RemoteChatLocalRdbStore(), - (): string => this.remotePageState.controlTargetDeviceId || this.remotePageState.desktopId - ); - readonly remoteSessionListStore: RemoteSessionListRdbStore = new RemoteSessionListRdbStore(); - readonly remoteSessionListCache: RemoteSessionListCache = - new RemoteSessionListCache( - this.remoteSessionListStore, - (): string => this.remotePageState.controlTargetDeviceId || this.remotePageState.desktopId - ); - // Both caches hold what one account saw on one desktop, so they are dropped - // together whenever that binding ends. - readonly clearCachedRemoteData: () => Promise = async (): Promise => { - await this.remoteChatCache.clear(); - await this.remoteSessionListCache.clear(); - }; - readonly voiceInputService: VoiceInputService = new VoiceInputService(); - readonly remoteActivityLifecycleController: RemoteActivityLifecycleController = - new RemoteActivityLifecycleController((): Promise => { - // Returned, not fired and forgotten: the heartbeat skips its next tick - // while this one is still out, and it can only do that if it is handed - // something to wait on. - return this.remoteActivityViewModel.checkConnectionHealth(); - }); - private readonly hostCatalogObserver: HostCatalogObserver = new HostCatalogObserver( - this.sessionManager, - async (change: HostCatalogChange): Promise => { - const initial = change.initial === true || - (change.sessionsRevision === undefined && change.workspacesRevision === undefined); - const refreshSessions = initial || change.sessionsRevision !== undefined; - const refreshWorkspaces = initial || change.workspacesRevision !== undefined; - const jobs: Promise[] = []; - if (refreshSessions) { - jobs.push(this.remoteSessionViewModel.refreshSessions(true)); - jobs.push(this.remoteChatPollingLifecycleController.refreshModelCatalog()); - } - if (refreshWorkspaces) jobs.push(this.remoteWorkspaceViewModel.loadRecentWorkspacesInBackground(true)); - await Promise.all(jobs); - }, - (error: Error): void => { this.remotePageState.setError(ConnectionErrorPolicy.errorText(error)); } - ); - readonly remoteActivityViewModel: RemoteActivityViewModel = - new RemoteActivityViewModel( - this.remoteActivityLifecycleController, - this.remoteConnectionCoordinator, - this.remoteResumeGate, - { - isConnected: (): boolean => (this.remotePageState.connectionState as ConnectionState) === ConnectionState.Connected, - isReconnecting: (): boolean => (this.remotePageState.connectionState as ConnectionState) === ConnectionState.Reconnecting, - isBusy: (): boolean => this.remotePageState.isBusy, - hasRemoteBinding: (): boolean => this.hasRemoteBindingForResume(), - isRemoteChat: (): boolean => this.appShellViewModel.isRoute(AppRoute.RemoteChat), - activeSession: (): SessionSummary => this.remotePageState.activeSession, - onConnectionState: (state: string): void => this.remotePageState.setConnectionState(state as ConnectionState), - onStatus: (status: string): void => this.remotePageState.setStatusText(status), - onConnectionError: async (err: Object): Promise => this.settingsController.handleRemoteConnectionError(err), - onObserveCatalog: (): void => this.hostCatalogObserver.start(this.remotePageState.controlTargetDeviceId), - onStopCatalog: (): void => this.hostCatalogObserver.stop(), - onStartPolling: (): void => this.conversationController.startRemotePolling(), - onStopPolling: (): void => this.remoteChatPollingLifecycleController.stop(), - onPoll: async (): Promise => { - await this.remoteChatPollingLifecycleController.pollNow(); - }, - onReconnect: async (): Promise => { - await this.reconnectActiveRemote(); - }, - onRestoreSession: async (session: SessionSummary): Promise => { - this.conversationController.applyRemoteActiveSession(session); - await this.conversationController.loadRemoteMessages(); - } - } - ); - readonly remoteWorkspaceViewModel: RemoteWorkspaceViewModel = - new RemoteWorkspaceViewModel( - this.remotePageState, - this.workspaceCoordinator, - { - isRemoteAvailable: (): boolean => this.remoteConnectionController.ensureAvailable(), - remoteTargetId: (): string => this.remotePageState.controlTargetDeviceId, - isBusy: (): boolean => this.remotePageState.isBusy, - onBusy: (isBusy: boolean): void => { - this.remotePageState.setBusy(isBusy); - }, - onStatus: (statusText: string): void => { - this.remotePageState.setStatusText(statusText); - }, - onWorkspaceSelected: (workspace: WorkspaceInfo): void => { - this.remoteConnectionController.applyWorkspace(workspace); - this.remoteSessionController.clearSessions(); - }, - onCatalogLoading: (targetId: string): void => { - this.deviceDirectoryViewModel.beginLiveCatalog(targetId); - }, - onCatalogLoaded: (targetId: string, workspaces: RecentWorkspaceEntry[], source?: string, recentWorkspaces?: RecentWorkspaceEntry[]): void => { - this.deviceDirectoryViewModel.completeLiveCatalog(targetId, workspaces, source, recentWorkspaces); - }, - onCatalogFailed: (targetId: string): void => { - this.deviceDirectoryViewModel.failLiveCatalog(targetId); - }, - onRefreshSessions: async (): Promise => { - await this.remoteSessionViewModel.refreshSessions(); - }, - onConnectionFailure: (error: Object): void => { - this.failRemoteConnection(error); - } - } - ); - remoteWorkspaceSessions: RemoteSession[] = []; - readonly appShellViewModel: AppShellViewModel = new AppShellViewModel(); - readonly appShellState: AppShellState = this.appShellViewModel.state; - readonly localeController: LocaleController = new LocaleController( - this.localePreferenceStore, - { - onLanguageChanged: (_language: string): void => { - this.appShellState.setLocaleRevision(RemoteI18n.revision()); - this.refreshLocalizedRuntimeCopy(); - } - } - ); - readonly voiceInputLifecycleController: VoiceInputLifecycleController = - new VoiceInputLifecycleController( - this.voiceInputService, - { - currentInputText: (): string => this.conversationController.visibleChatInput(), - currentStatusText: (): string => this.conversationController.visibleStatusText(), - onInputText: (routeId: string, text: string) => { - this.conversationController.setChatInput(routeId as AppRoute, text); - }, - onListening: (routeId: string, isListening: boolean) => { - this.conversationController.setVoiceListening(routeId as AppRoute, isListening); - }, - onStatusText: (statusText: string) => { - this.conversationController.setVisibleStatusText(statusText); - }, - onError: (message: string) => { - this.showVoiceInputError(message); - } - } - ); - readonly remoteSessionController: RemoteSessionController = - new RemoteSessionController( - this.sessionManager, - 8, - { - onSessions: (sessions: RemoteSession[], hasMore: boolean) => { - const extras = this.remoteWorkspaceSessions.filter((item: RemoteSession) => { - return item.workspacePath !== this.remotePageState.workspacePath; - }); - this.publishRemoteSessions(this.mergeSessions(sessions, extras), hasMore); - }, - onActiveSession: (session: SessionSummary) => { - this.conversationController.applyRemoteActiveSession(session); - }, - onStatusText: (statusText: string) => { - this.remotePageState.setStatusText(statusText); - }, - onBusy: (isBusy: boolean) => { - this.remotePageState.setBusy(isBusy); - }, - onLoading: (isLoading: boolean) => { - this.remotePageState.setLoading(isLoading); - }, - onSessionError: (errorText: string) => { - this.remotePageState.setError(errorText); - }, - onReconnecting: () => { - this.remotePageState.setConnectionState(ConnectionState.Reconnecting); - }, - onConnected: () => { - this.remotePageState.setConnectionState(ConnectionState.Connected); - // A live link outranks the relay's presence answer, and that override - // is applied where the list is published, not where it is read. - this.settingsController.resyncAccountDevicePresence(); - }, - onConnectionFailed: (err: Object) => { - this.failRemoteConnection(err); - }, - onStartHeartbeat: () => { - this.remoteActivityViewModel.startHeartbeat(); - } - } - ); - readonly remoteChatCommandController: RemoteChatCommandController = - new RemoteChatCommandController( - this.sessionManager, - { - onHistoryRequested: (sessionId: string, older: boolean): void => { - if (this.remotePageState.activeSession.sessionId !== sessionId) return; - if (older) this.remoteChatPollingLifecycleController.loadOlder(); - else this.conversationController.startRemotePolling(); - }, - onMessagesLoaded: (messages: ChatMessage[], hasMoreMessages: boolean) => { - this.chatTimelineStore.setPersistedMessages(messages); - this.remotePageState.setHasMoreMessages(hasMoreMessages); - this.conversationController.syncRemoteTimeline(); - }, - onMessageCountKnown: (pollVersion: number, knownMessageCount: number) => { - this.conversationController.updateKnownMessageCount(pollVersion, knownMessageCount); - }, - onTimelineReady: () => { - this.remoteSessionViewModel.settleTranscriptLoading(); - }, - onComposerPrepared: (sessionId: string, text: string, images: SelectedImageAttachment[]) => { - return this.remotePageState.prepareComposerSubmission(sessionId, text, images); - }, - onSendSucceeded: (turnId: string, pendingActiveId: string, localMessageId: string) => { - this.chatTimelineStore.acknowledgeOptimisticTurn(localMessageId, turnId); - if (turnId.length > 0) { - this.chatTimelineStore.setLocalActiveTurn(turnId); - this.conversationController.syncRemoteTimeline(); - } else if (pendingActiveId.length > 0) { - this.chatTimelineStore.clearPendingActiveTurn(pendingActiveId); - this.conversationController.syncRemoteTimeline(); - } - this.taskCompletionNotificationController.track({ - source: 'remote', - sessionId: this.remotePageState.activeSession.sessionId || '', - turnId - }); - this.remoteChatPollingLifecycleController.nudge(); - }, - onSteerSucceeded: ( - steeringId: string, - turnId: string, - displayText: string, - images: SelectedImageAttachment[] - ) => { - this.chatTimelineStore.appendSteeringItem(turnId, steeringId, displayText, images); - this.conversationController.syncRemoteTimeline(); - this.remoteChatPollingLifecycleController.nudge(); - }, - onSendFailed: ( - rawText: string, - images: SelectedImageAttachment[], - localMessageId: string, - pendingActiveId: string - ) => { - this.chatTimelineStore.markOptimisticMessageFailed(localMessageId); - if (pendingActiveId.length > 0) { - this.chatTimelineStore.clearPendingActiveTurn(pendingActiveId); - } - this.conversationController.syncRemoteTimeline(); - }, - onActiveSession: (session: SessionSummary) => { - this.conversationController.applyRemoteActiveSession(session); - }, - onSessionTitleChanged: (sessionId: string, title: string) => { - this.remoteSessionController.updateSessionTitle(sessionId, title); - }, - onStatusText: (statusText: string) => { - this.remotePageState.setStatusText(statusText); - }, - onToast: (message: string) => { - this.conversationController.showHomeToast(message); - }, - onBusy: (isBusy: boolean) => { - this.remotePageState.setBusy(isBusy); - }, - onPollRequested: () => { - this.remoteChatPollingLifecycleController.nudge(); - } - }, - this.remoteChatCache - ); - readonly remoteFileDownloadController: RemoteFileDownloadController = - new RemoteFileDownloadController( - this.sessionManager, - (downloadingFilePath: string, downloadedFilePath: string, fileDownloadStatus: string) => { - this.remotePageState.setDownloadStatus(downloadingFilePath, downloadedFilePath, fileDownloadStatus); - }, - () => { - this.remotePageState.clearDownloadingFilePath(); - }, - (statusText: string) => { - this.remotePageState.setStatusText(statusText); - }, - (isBusy: boolean) => { - this.remotePageState.setBusy(isBusy); - } - ); - readonly filePreviewController: FilePreviewController = - new FilePreviewController( - this.sessionManager, - this.filePreviewState, - { - remoteAvailable: (): boolean => RemoteUiState.canUseRemote((this.remotePageState.connectionState as ConnectionState)), - activeSession: (): SessionSummary => this.remotePageState.conversation.activeSession, - workspacePath: (): string => this.remotePageState.workspacePath, - openExternalLink: async (reference: string): Promise => - this.host.openExternalLink ? await this.host.openExternalLink(reference) : false, - onGeneralStatus: (statusText: string): void => this.generalChatPageState.setStatus(statusText), - onRemoteStatus: (statusText: string): void => this.remotePageState.setStatusText(statusText) - } - ); - readonly remoteToolActionController: RemoteToolActionController = - new RemoteToolActionController( - this.sessionManager, - (statusText: string) => { - this.remotePageState.setStatusText(statusText); - }, - (isBusy: boolean) => { - this.remotePageState.setBusy(isBusy); - }, - () => { - this.remoteChatPollingLifecycleController.nudge(); - } - ); - readonly remoteChatBranchCache: SubagentBranchCache = new RemoteChatBranchCache(this.remoteChatCache); - readonly remoteChatPollingLifecycleController: RemoteChatPollingLifecycleController = - new RemoteChatPollingLifecycleController( - this.sessionManager, - { - canPoll: (sessionId: string) => { - return this.remotePageState.activeSession.sessionId === sessionId && - this.isRemoteConversationContext(sessionId) && - this.remoteConnectionController.ensureAvailable(); - }, - onQueue: (state: MessageQueueState): void => { - if (!state.sessionId || this.remotePageState.activeSession.sessionId === state.sessionId) this.remotePageState.messageQueue = state; - }, - onMailbox: (state: InteractionMailboxState): void => { - if (!state.sessionId || this.remotePageState.activeSession.sessionId === state.sessionId) { - this.remotePageState.interactionMailbox = state; - } - }, - onSnapshot: (snapshot: RemoteChatPollingSnapshot) => { - // A snapshot is the transcript on screen, which is what an open was - // waiting for. Snapshots are already fenced to the active session by - // the poller's canPoll guard, so this cannot end another tap's wait. - this.remoteSessionViewModel.settleTranscriptLoading(); - this.remotePageState.setConversationLoading(false); - if (snapshot.hasMoreMessages !== undefined) this.remotePageState.setHasMoreMessages(snapshot.hasMoreMessages); - this.remotePageState.setHistoryLoadState(snapshot.historyLoading === true, snapshot.historyFailed === true); - this.conversationController.applyRemoteSnapshot(snapshot); - if (snapshot.activeTurn && snapshot.activeTurn.id.length > 0) { - const status = (snapshot.activeTurn.status || '').toLowerCase(); - if (status === 'failed' || status === 'error' || status === 'cancelled' || status === 'canceled') { - if (this.taskCompletionNotificationController.cancel('remote', snapshot.sessionId)) { - // Keep observing the session after one turn settles. - } - } else { - this.trackRemoteTaskCompletion(snapshot.sessionId, snapshot.activeTurn); - } - } else if (snapshot.sessionState.toLowerCase() === 'idle' && snapshot.completedTurnId.length === 0 && - this.taskCompletionNotificationController.cancel('remote', snapshot.sessionId)) { - // Keep observing the session after one turn settles. - } - if (snapshot.completedTurnId.length > 0 && - this.taskCompletionNotificationController.complete( - 'remote', snapshot.sessionId, snapshot.completedTurnId - )) { - // Keep observing the session after one turn settles. - } - }, - onError: (error: Object) => { - this.remoteSessionViewModel.settleTranscriptLoading(); - this.remotePageState.setConversationLoading(false); - this.remotePageState.setStatusText(ConnectionErrorPolicy.errorText(error)); - // Confirm host reachability immediately; transcript errors alone do - // not prove disconnection, and the probe is generation-fenced. - void this.remoteActivityViewModel.checkConnectionHealth(); - } - }, - this.remoteChatBranchCache - ); - readonly remoteModelController: RemoteModelController = - new RemoteModelController( - this.sessionManager, - this.identityStore, - (modelCatalog: RemoteModelCatalog, selectedModelId: string, knownModelCatalogVersion: number) => { - this.conversationController.updateKnownModelCatalogVersion(knownModelCatalogVersion); - this.remotePageState.setModelCatalog(modelCatalog, selectedModelId); - }, - (modelCatalog: RemoteModelCatalog, selectedModelId: string, knownModelCatalogVersion: number) => { - this.conversationController.updateKnownModelCatalogVersion(knownModelCatalogVersion); - this.chatTimelineStore.setModelCatalog(modelCatalog, selectedModelId); - this.remotePageState.setModelCatalog(modelCatalog, selectedModelId); - }, - (statusText: string) => { - this.remotePageState.setStatusText(statusText); - }, - (isBusy: boolean) => { - this.remotePageState.setBusy(isBusy); - } - ); - /** - * The composer command palette's host traffic. - * - * Every callback is fenced to the session that asked for it: a catalog read or - * a usage report that lands after the user moved to another conversation would - * otherwise paint one session's data over another's. - */ - readonly remoteCommandPaletteController: RemoteCommandPaletteController = - new RemoteCommandPaletteController( - this.sessionManager, - { - onCatalogLoading: (sessionId: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.setCatalogLoading(); - }, - onCatalogReady: (sessionId: string, catalog: RemoteCommandCatalog): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.setCatalogReady(catalog); - }, - onCatalogFailed: (sessionId: string, errorText: string, failure: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.setCatalogFailed(errorText, failure); - }, - onCommandStarted: (sessionId: string, wireAction: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.beginCommand(wireAction); - }, - onCommandSettled: (sessionId: string, wireAction: string, errorText: string, message: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.settleCommand(wireAction, errorText); - if (errorText.length > 0) { - // The host's own words, kept out of the notice's one line so a long - // refusal does not push the composer's hint out of shape. - this.remotePageState.setStatusText(errorText); - } else if (message.length > 0) { - RemoteLogger.info( - `command palette completed session=${sessionId} action=${wireAction}`); - } - }, - onCommandNoticeExpired: (sessionId: string, wireAction: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.expireNotice(wireAction); - }, - onUsageLoading: (sessionId: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.setUsageLoading(); - }, - onUsageReady: (sessionId: string, report: RemoteSessionUsageReport | undefined): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.setUsageReady(report); - }, - onUsageFailed: (sessionId: string, errorText: string): void => { - if (!this.isCommandPaletteSession(sessionId)) return; - this.remotePageState.commandPalette.setUsageFailed(errorText); - } - } - ); - - private isCommandPaletteSession(sessionId: string): boolean { - return sessionId.length > 0 && this.remotePageState.activeSession.sessionId === sessionId; - } - - readonly remoteSessionViewModel: RemoteSessionViewModel = - new RemoteSessionViewModel( - this.remotePageState, - this.remoteSessionController, - this.remoteChatCommandController, - this.remoteModelController, - this.remoteFileDownloadController, - { - remoteAvailable: (): boolean => this.remoteConnectionController.ensureAvailable(), - isConnected: (): boolean => (this.remotePageState.connectionState as ConnectionState) === ConnectionState.Connected, - isBusy: (): boolean => this.remotePageState.isBusy, - onBusy: (busy: boolean): void => this.remotePageState.setBusy(busy), - onRouteChat: (sessionId: string): void => this.conversationController.routeCreatedRemoteSession(sessionId), - onRouteHome: (): void => this.appShellViewModel.replaceRouteWithoutAnimation(AppRoute.RemoteHome), - onStopPolling: (): void => this.remoteChatPollingLifecycleController.stop(), - onStartPolling: (): void => this.conversationController.startRemotePolling(), - onNudgePolling: (): void => this.remoteChatPollingLifecycleController.nudge(), - onResetTimeline: (sessionId: string): void => this.conversationController.resetRemoteTimeline(sessionId), - onClearRemoteFiles: (): void => this.remoteFileDownloadController.clear(), - onKnownStateReset: (): void => this.conversationController.resetKnownRemoteState(), - onLoadActiveMessages: async (): Promise => { - await this.conversationController.loadRemoteMessages(); - }, - onCreatedSession: async (session: SessionSummary): Promise => { - await this.reconcileCreatedRemoteSession(session); - }, - onRefreshSessions: async (): Promise => { - await this.remoteSessionController.refresh( - this.remotePageState.sessionQuery, - this.remotePageState.sessionFilter, - this.remoteConnectionController.ensureAvailable(), - (this.remotePageState.connectionState as ConnectionState) === ConnectionState.Connected - ); - }, - onSelectWorkspace: async (path: string, workspaceId?: string): Promise => { - await this.selectWorkspace(path, undefined, undefined, workspaceId); - } - } - ); - protected trackRemoteTaskCompletion(sessionId: string, activeTurn: ChatMessage): void { - const status = (activeTurn.status || '').toLowerCase(); - if (status !== 'active' && status !== 'completed' && status !== 'done' && status !== 'success') { - return; - } - const explicitTurnId = (activeTurn.turnId || '').trim(); - const turnId = explicitTurnId.length > 0 ? explicitTurnId : - (activeTurn.id.indexOf('active-') === 0 ? activeTurn.id.slice('active-'.length) : ''); - this.taskCompletionNotificationController.track({ source: 'remote', sessionId, turnId }); - } - readonly remoteConnectionController: RemoteConnectionController = - new RemoteConnectionController( - this.remotePageState, - this.identityStore, - this.remoteConnectionCoordinator, - this.remoteSessionController, - this.remoteModelController, - this.remoteFileDownloadController, - (sessionId: string): void => this.conversationController.resetRemoteTimeline(sessionId), - (): void => this.conversationController.resetKnownRemoteState(), - (): void => this.remoteActivityViewModel.startHeartbeat(), - (): void => this.remoteActivityViewModel.stopHeartbeat(), - (): void => this.remoteChatPollingLifecycleController.stop(), - async (): Promise => { - await this.remoteWorkspaceViewModel.loadRecentWorkspacesInBackground(); - }, - this.clearCachedRemoteData, - (route: AppRoute): void => this.appShellViewModel.replaceRouteWithoutAnimation(route), - (): void => this.dismissConnectSheetAfterSuccess(), - (): void => this.openConnectSheet() - ); - readonly settingsController: SettingsController = - new SettingsController( - { - client: new CloudAccountClient(), - sessionStore: new CloudAccountSessionStore(), - profileLoader: new GitHubAccountProfileClient(), - sessionManager: this.sessionManager, - remoteState: this.remotePageState, - hooks: { - deviceId: (): string => this.remoteConnectionController.getDeviceId(), - openAuthorization: async (url: string): Promise => { - const localizedUrl = url.includes('https://auth.openbitfun.com/sign-in') - ? url.replace('/sign-in?', `/sign-in?locale=${encodeURIComponent(RemoteI18n.language())}&`) - : url; - return this.host.openExternalLink ? await this.host.openExternalLink(localizedUrl) : false; - }, - remoteAvailable: (): boolean => this.remoteConnectionController.ensureAvailable(), - invalidatePreview: (): void => this.filePreviewController.invalidate(), - invalidateRemoteActivity: (): void => this.remoteActivityViewModel.invalidate(), - invalidateRemoteConnection: (): void => this.remoteConnectionCoordinator.invalidate(), - stopPolling: (): void => this.remoteChatPollingLifecycleController.stop(), - stopHeartbeat: (): void => this.remoteActivityViewModel.stopHeartbeat(), - startHeartbeat: (): void => this.remoteActivityViewModel.startHeartbeat(), - resetTimeline: (): void => this.conversationController.resetRemoteTimeline(''), - resetKnownRemoteState: (): void => this.conversationController.resetKnownRemoteState(), - clearCachedRemoteData: this.clearCachedRemoteData, - closeSettings: (): void => this.appShellState.setSettingsVisible(false), - closeConnectSheet: (): void => this.dismissConnectSheetAfterSuccess(), - navigateRemoteHome: (): void => this.appShellViewModel.replaceRouteWithoutAnimation(AppRoute.RemoteHome), - loadRecentWorkspaces: async (): Promise => { - await this.remoteWorkspaceViewModel.loadRecentWorkspacesInBackground(); - }, - saveControlTargetType: async (controlTargetType: string): Promise => { - await this.remoteConnectionController.rememberControlTargetType(controlTargetType); - }, - onAccountDevices: (devices: CloudAccountDevice[]): void => { - this.deviceDirectoryViewModel.syncDevices(devices); - }, - onBeforeControlTargetChange: (): void => { - this.captureLiveControlTarget(); - }, - onControlTargetLoading: (deviceId: string): void => { - this.deviceDirectoryViewModel.beginLiveCatalog(deviceId); - }, - onControlTargetChanged: (): void => { - this.activateLiveControlTarget(); - } - } - } - ); - readonly deviceDirectoryViewModel: DeviceDirectoryViewModel = - new DeviceDirectoryViewModel( - this.deviceDirectoryState, - { - credentials: () => this.settingsController.activeCloudAccount(), - activeDeviceId: (): string => { - return this.remotePageState.controlTargetDeviceId || this.remotePageState.desktopId; - }, - activeDeviceConnected: (): boolean => - (this.remotePageState.connectionState as ConnectionState) === ConnectionState.Connected, - loadActiveWorkspaceSessions: (path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): Promise => - this.sessionManager.listSessionPageForWorkspace({ - workspaceId: workspaceId || undefined, - path, - remoteConnectionId, - remoteSshHost - }, 50), - onActiveWorkspaceSessions: (path: string, result: SessionListResult, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): void => - this.publishWorkspaceSessionPage(path, result, remoteConnectionId, remoteSshHost, workspaceId) - }, - this.remoteSessionListStore - ); - readonly conversationController: ConversationController = - new ConversationController( - this.generalChatPageState, - this.remotePageState, - { currentRoute: (): AppRoute => this.appShellViewModel.currentRoute() }, - { - timeline: this.chatTimelineStore, - chat: this.remoteChatCommandController, - chatCache: this.remoteChatCache, - polling: this.remoteChatPollingLifecycleController, - models: this.remoteModelController, - commandPalette: this.remoteCommandPaletteController, - files: this.remoteFileDownloadController, - tools: this.remoteToolActionController, - connection: this.remoteConnectionController, - imagePicker: this.imagePickerService, - clipboard: this.clipboardService, - sessions: this.remoteSessionViewModel, - sessionManager: this.sessionManager, - workspace: this.workspaceCoordinator, - settings: this.settingsController, - appShell: this.appShellViewModel, - filePreview: this.filePreviewController, - hooks: { - isConversationContext: (sessionId: string): boolean => this.isRemoteConversationContext(sessionId), - isFilePreviewVisible: (): boolean => this.filePreviewState.visible, - stopVoiceInput: async (): Promise => this.stopVoiceInput(false), - showToast: (message: string): boolean => this.host.showToast(message, 2600), - selectAssistantWorkspace: async (path: string, workspaceId?: string): Promise => { - await this.selectAssistant(path, workspaceId); - } - } - } - ); - readonly conversationIntentDispatcher: ConversationIntentDispatcher = - new ConversationIntentDispatcher({ - queue: async (action: MessageQueueAction): Promise => { await this.remoteChatPollingLifecycleController.dispatchQueue(action); }, - mailbox: async (action: InteractionMailboxAction): Promise => { await this.remoteChatPollingLifecycleController.dispatchMailbox(action); }, - openSidebar: (): void => this.openAppSidebar(), - back: (): void => this.exitActiveChat(), - newRemoteSession: (): void => { this.conversationController.createRemoteSession('code'); }, - unsupported: (): void => this.conversationController.showHomeToast(RemoteI18n.t('remote.actionUnsupported')), - stop: async (): Promise => { await this.conversationController.stopVisibleTask(); }, - loadOlder: async (): Promise => { this.remoteChatPollingLifecycleController.loadOlder(); }, - approve: async (id: string, input?: Object): Promise => { - await this.conversationController.approveRemoteTool(id, input); - }, - reject: async (id: string): Promise => { await this.conversationController.rejectRemoteTool(id); }, - cancel: async (id: string): Promise => { await this.conversationController.cancelRemoteTool(id); }, - answer: async (id: string, answers: RemoteQuestionAnswerPayload): Promise => { - await this.conversationController.answerRemoteQuestion(id, answers); - }, - rename: async (title: string): Promise => { - await this.conversationController.renameVisibleSession(title); - }, - copy: async (text: string, scope: MessageCopyScope): Promise => { - await this.conversationController.copyRemoteMessage(text, scope); - }, - retry: async (text: string): Promise => { await this.conversationController.retryVisibleMessage(text); }, - selectModel: async (id: string): Promise => { await this.conversationController.selectVisibleModel(id); }, - pickImages: async (): Promise => { await this.pickImages(); }, - removeImage: (id: string): void => this.conversationController.removeSelectedImage(this.appShellViewModel.currentRoute(), id), - openFilePreview: (route: AppRoute, request: FilePreviewRequest): void => - this.filePreviewController.open(route, request), - downloadFile: (path: string): void => this.conversationController.downloadVisibleFile(path), - buildPlan: async (path: string, name: string): Promise => { - await this.conversationController.buildRemotePlan(path, name); - }, - // Opening a delegation card is a request to watch that worker: the branch - // may have lost its stream to the follow cap, and the card has to fill in. - branchExpanded: (branchId: string): void => { - this.remoteChatPollingLifecycleController.ensureBranchSubscribed(branchId); - }, - commandPalette: async (request: CommandPaletteRequest): Promise => { - await this.conversationController.dispatchCommandPalette(request); - }, - rollback: async (request: SessionRollbackRequest): Promise => { - await this.conversationController.rollbackRemoteSession(request); - }, - rollbackResync: async (): Promise => { - await this.conversationController.resyncRemoteTranscriptAfterRollback(); - }, - rollbackNotice: (key: string): void => { - // The policy owns which key a refusal resolves to; the host's own text is - // already in the log, where a support report can read it. - this.conversationController.showHomeToast(RemoteI18n.t(key)); - }, - send: async (): Promise => { await this.conversationController.sendVisibleMessage(); }, - voiceInput: async (): Promise => { await this.toggleVoiceInput(); }, - inputChanged: (route: AppRoute, value: string): void => - this.conversationController.onVisibleChatInputChange(route, value) - }); - readonly workspaceToolsViewModel: WorkspaceToolsViewModel = new WorkspaceToolsViewModel( - this.remotePageState.workspaceTools, this.sessionManager, () => this.remotePageState.controlTargetDeviceId); - readonly presentationActions: AppRootPresentationActions = { - onWorkspaceTools: (intent: WorkspaceToolsIntent): void => this.workspaceToolsViewModel.dispatch(intent), - onNavigationBack: (route: AppRoute): boolean => this.handleNavigationBack(route), - onConversationIntent: (route: AppRoute, intent: ConversationIntent): void => - this.conversationIntentDispatcher.dispatch(route, intent), - onCloseSidebar: (): void => this.closeAppSidebar(), - onCompactLayoutEntered: (): void => this.enterCompactLayout(), - onLayoutModeChanged: (wideLayout: boolean): void => this.appShellState.setWideLayout(wideLayout), - onRemoteHome: { - openMiniApps: (): void => { this.closeAppSidebar(); this.miniAppViewModel.actions.open(); }, - openSidebar: (): void => this.openAppSidebar(), - connectWorkspace: (): void => this.openConnectSheet(), - addConnection: (): void => this.openConnectSheet(), - refresh: (): void => { this.remoteSessionViewModel.refreshSessions(); }, - showWorkspaces: (): void => { this.remoteWorkspaceViewModel.toggleRecentWorkspaces(); }, - showAssistants: (): void => { this.remoteWorkspaceViewModel.toggleAssistants(); }, - selectWorkspace: (path: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string): void => { - void this.selectWorkspaceOnDevice(path, deviceId, connectionId, sshHost, workspaceId); - }, - selectAssistant: (path: string, workspaceId?: string): void => { this.selectAssistant(path, workspaceId); }, - cancelWorkspace: (): void => this.remotePageState.setWorkspacePickerVisible(false), - cancelAssistant: (): void => this.remotePageState.setAssistantPickerVisible(false), - queryChanged: (query: string): void => this.remotePageState.setQuery(query), - search: (): void => { this.remoteSessionViewModel.refreshSessions(); }, - loadMore: (): void => { this.remoteSessionViewModel.loadMoreSessions(); }, - reconnect: (): void => { this.reconnect(); }, - disconnect: (): void => { this.disconnect(false); }, - clearPairing: (): void => { this.disconnect(true); }, - create: (agentType: string): void => { this.conversationController.createRemoteSession(agentType); }, - createInPlace: (agentType: string): void => { - this.conversationController.createRemoteSession(agentType, true); - }, - createInWorkspace: (path: string, agentType: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string): void => { - this.conversationController.createRemoteSessionInWorkspace(path, agentType, false, deviceId, connectionId, sshHost, workspaceId); - }, - createInWorkspaceInPlace: (path: string, agentType: string, deviceId?: string, connectionId?: string, sshHost?: string, workspaceId?: string): void => { - this.conversationController.createRemoteSessionInWorkspace(path, agentType, true, deviceId, connectionId, sshHost, workspaceId); - }, - selectDirectoryDevice: (deviceId: string): void => { - void this.selectDirectoryDevice(deviceId); - }, - addDirectoryWorkspace: (deviceId: string): void => { - void this.openWorkspacePickerOnDevice(deviceId); - }, - retryDirectoryDevice: (deviceId: string): void => { - void this.retryDirectoryDevice(deviceId); - }, - loadWorkspaceSessions: async (deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): Promise => { - await this.loadWorkspaceSessionsOnDevice(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId); - }, - openSession: (session: RemoteSession): void => this.conversationController.openHomeSession(session), - openSessionInPlace: (session: RemoteSession): void => this.conversationController.openHomeSession(session, true), - deleteSession: (session: RemoteSession): void => { this.conversationController.deleteHomeSession(session); } - }, - onSidebar: { - close: (): void => this.closeAppSidebar(), - newChat: async (agentType: string = 'code'): Promise => { - if (!SidebarConnectionActionPolicy.canCreateSession(this.remotePageState.connectionState, this.remotePageState.isBusy)) return; - this.closeAppSidebar(); - await this.conversationController.createRemoteSession(agentType); - }, - enterCode: (): void => { this.closeAppSidebar(); this.enterCodeEntry(); }, - openAccountDevices: (): void => { - this.closeAppSidebar(); - this.appShellState.openSettings('account'); - }, - refreshDevices: async (): Promise => { - await this.deviceDirectoryViewModel.refreshDevices(async (): Promise => { - await this.settingsController.listCloudAccountDevices(); - }); - }, - refreshSessions: (): Promise => this.deviceDirectoryViewModel.refreshExpandedWorkspaceSessions(), - settings: (): void => { this.closeAppSidebar(); this.appShellState.openSettings('general'); }, - openAccount: (): void => { - this.closeAppSidebar(); - setTimeout(() => this.appShellState.openSettings('account'), 180); - }, - openSession: (session: RemoteSession): void => { - // The shell supplies the horizontal motion; do not stack a second - // NavDestination push animation on top of the closing drawer. - this.closeAppSidebar(); - this.conversationController.openHomeSession(session, true); - }, - deleteSession: (session: RemoteSession): void => { this.conversationController.deleteHomeSession(session); } - }, - onSettings: { - close: (): void => this.appShellState.leaveSettings(), - accountSettled: (): void => this.appShellState.settleAccountSettings(), - disconnect: (): void => { this.disconnect(false); }, - clearPairing: (): void => { - this.appShellState.setSettingsVisible(false); - this.disconnect(true); - }, - reconnect: (): void => { this.reconnect(); }, - openAccount: (): void => { this.appShellState.openSettings('account'); }, - cloudCancelLogin: (): void => this.settingsController.cancelCloudLogin(), - cloudLogin: async (): Promise => { - const user = await this.settingsController.loginCloudAccount(); - // Returning from authorization can show the page before the account - // session is saved. Start listening after login completes as well. - await this.startWatchProvisioning(); - const pending = this.pendingAccountDeviceId; - this.pendingAccountDeviceId = ''; - if (pending.length > 0) { - await this.connectAccountDeviceLink(pending); - } - return user; - }, - cloudLogout: (): Promise => this.settingsController.logoutCloudAccount(), - cloudListDevices: (): Promise => this.settingsController.listCloudAccountDevices(), - cloudSelectDevice: (device: CloudAccountDevice): Promise => - this.settingsController.selectCloudAccountDevice(device), - getPermissionMode: (): Promise => this.settingsController.getRemotePermissionMode(), - setPermissionMode: (mode: RemotePermissionMode): Promise => - this.settingsController.setRemotePermissionMode(mode), - getDeviceModelCatalog: (): Promise => - this.settingsController.getDeviceModelCatalog(), - setDeviceModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise => - this.settingsController.setDeviceModelDefaults(primary, fast, imageUnderstanding), - setLanguage: async (language: string): Promise => { - await this.localeController.setLanguage(language); - } - }, - onConnect: { - back: (): void => this.appShellState.setConnectSheetVisible(false), - openAccount: (): void => { - this.appShellState.setConnectSheetVisible(false); - setTimeout(() => this.appShellState.openSettings('account'), 180); - }, - connect: (password?: string): void => { - this.connect(false, password || ''); - }, - clearPairing: (): void => { this.appShellState.setConnectSheetVisible(false); this.disconnect(true); }, - cloudListDevices: (): Promise => this.settingsController.listCloudAccountDevices(), - cloudSelectDevice: (device: CloudAccountDevice): Promise => - this.settingsController.selectCloudAccountDevice(device) - }, - onFilePreview: { - close: (): void => this.filePreviewController.close(), - refresh: (): void => this.filePreviewController.refresh(), - download: (path: string): void => this.conversationController.downloadVisibleFile(path), - openLink: (reference: string, label: string): void => this.filePreviewController.openLink(reference, label) - }, - generalStatus: (): string => '' - }; - readonly navigationStack: NavPathStack = this.appShellViewModel.navigationStack; - - private captureLiveControlTarget(): void { - const deviceId = this.remotePageState.controlTargetDeviceId || this.remotePageState.desktopId; - this.deviceDirectoryViewModel.captureLive( - deviceId, - this.remotePageState.recentWorkspaces, - this.remotePageState.sessions - ); - } - - private activateLiveControlTarget(): void { - const deviceId = this.remotePageState.controlTargetDeviceId || this.remotePageState.desktopId; - this.deviceDirectoryViewModel.activateLive( - deviceId, - this.remotePageState.recentWorkspaces, - this.remotePageState.sessions - ); - } - - enterCodeEntry(): void { - this.enterRemoteSurface(); - } - - enterRemoteSurface(): void { - this.appShellState.setConnectSheetVisible(false); - if (this.appShellState.wideLayout) { - void this.enterRemoteSurfaceWide(); - return; - } - void this.enterRemoteSurfaceCompact(); - } - - openConnectSheet(): void { - if (!RemoteSurfaceEntryPolicy.shouldOpenConnectSheet(RemoteConnectEntryKind.OpenConnect)) { - this.enterRemoteSurface(); - return; - } - this.appShellState.setConnectSheetVisible(true); - } - - /** - * Close the sheet only after a connect that the user is watching on it. - * Heartbeat reconnects and background restores must not steal the current - * route just because they also go through the same success path. - */ - dismissConnectSheetAfterSuccess(): void { - const opened = this.appShellState.showConnectSheet; - this.appShellState.setConnectSheetVisible(false); - if (opened) { - this.appShellViewModel.replaceRouteWithoutAnimation(AppRoute.RemoteHome); - } - } - - refreshLocalizedRuntimeCopy(): void { - this.remotePageState.setStatusText(RemoteI18n.retranslate(RemoteI18n.retranslateKnown( - this.remotePageState.statusText, - [ - ConnectionStatusPresenter.labelKey(this.remotePageState.connectionState), - 'status.restoringConnection', - 'status.waitingConnection', - 'status.notConnected' - ] - ))); - this.remotePageState.setError(RemoteI18n.retranslate(this.remotePageState.sessionErrorText)); - this.remotePageState.setWorkspace( - RemoteI18n.retranslateWorkspaceName( - this.remotePageState.workspaceName, this.remotePageState.workspacePath, this.remotePageState.workspaceId - ), - this.remotePageState.workspacePath, - this.remotePageState.assistantId, - this.remotePageState.workspaceBranch, - this.remotePageState.workspaceKind, - this.remotePageState.workspaceConnectionId, - this.remotePageState.workspaceSshHost, - this.remotePageState.workspaceId - ); - this.remotePageState.setDownloadStatus( - this.remotePageState.downloadingFilePath, - this.remotePageState.downloadedFilePath, - RemoteI18n.retranslate(this.remotePageState.fileDownloadStatus) - ); - this.filePreviewState.errorText = RemoteI18n.retranslate(this.filePreviewState.errorText); - } - - private pendingAccountDeviceId: string = ''; - - /** - * Retries a persisted legacy device link. New links are no longer captured on - * the phone; this only keeps an existing record usable after an upgrade. - */ - handleDetectedRemoteUrl(url: string): void { - const link = accountDeviceLink(url); - if (!link) { - this.remotePageState.setStatusText(RemoteI18n.t('connect.deviceLinkInvalid')); - this.remotePageState.setConnectionState(ConnectionState.Failed); - return; - } - const deviceId = link.deviceId; - this.remotePageState.setRemoteUrl(url); - if (this.settingsController.cloudRelayEndpoint() !== link.relayUrl) { - this.settingsController.selectAccountRelay(link.relayUrl); - } - if (!this.settingsController.hasCloudAccountSession()) { - this.pendingAccountDeviceId = deviceId; - this.appShellState.setConnectSheetVisible(false); - this.appShellState.openSettings('account'); - return; - } - void this.connectAccountDeviceLink(deviceId); - } - - private async connectAccountDeviceLink(deviceId: string): Promise { - try { - const devices = await this.settingsController.listCloudAccountDevices(); - const device = devices.find((item: CloudAccountDevice): boolean => item.deviceId === deviceId && item.online); - if (!device) { - throw new Error(RemoteI18n.t('connect.deviceLinkUnavailable')); - } - await this.settingsController.selectCloudAccountDevice(device); - } catch (err) { - this.remotePageState.setStatusText(ConnectionErrorPolicy.errorText(err)); - this.remotePageState.setConnectionState(ConnectionState.Failed); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/AppShellState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/AppShellState.ets deleted file mode 100644 index bc058aecdb..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/AppShellState.ets +++ /dev/null @@ -1,103 +0,0 @@ -import { AppRoute } from '../navigation/AppRouteContract'; -import { SettingsSheetState } from './SettingsSheetState'; - -/** - * Settings is one page ('general'). 'account' is the signed-out login step that - * returns to that page once the account settles. - */ -export type SettingsMode = 'general' | 'account'; - -@ObservedV2 -export class AppShellState { - /** - * Mirror of the navigation stack top. NavPathStack is not observable, so - * surfaces that live outside Navigation — the drawer above all — have no way - * to follow the route without this traced copy. - */ - @Trace activeRoute: AppRoute = AppRoute.RemoteHome; - @Trace showSidebar: boolean = false; - @Trace showSettings: boolean = false; - @Trace settingsMode: SettingsMode = 'general'; - @Trace showConnectSheet: boolean = false; - /** - * Mirror of the resolved master-detail layout mode. Only the presentation - * layer measures the viewport, so runtime logic that must branch on compact - * versus wide reads it from here. - */ - @Trace wideLayout: boolean = false; - /** - * Bumped when the in-app locale changes so shell consumers that already - * observe this object rebuild even if they do not call RemoteI18n.t(). - */ - @Trace localeRevision: number = 0; - readonly settingsSheet: SettingsSheetState = new SettingsSheetState(); - private accountReturnsToSettings: boolean = false; - - setSidebarVisible(visible: boolean): void { - this.showSidebar = visible; - } - - setWideLayout(wide: boolean): void { - this.wideLayout = wide; - } - - setLocaleRevision(revision: number): void { - this.localeRevision = revision; - } - - setSettingsVisible(visible: boolean): void { - this.showSettings = visible; - if (!visible) { - this.accountReturnsToSettings = false; - this.settingsSheet.resetOnClose(); - } - } - - openSettings(mode: SettingsMode): void { - if (mode === 'account') { - this.accountReturnsToSettings = this.showSettings; - } else { - this.accountReturnsToSettings = false; - if (mode === 'general' && !this.showSettings) { - this.settingsSheet.resetOnClose(); - } - } - this.settingsMode = mode; - this.showSettings = true; - } - - leaveSettings(): void { - if (this.settingsMode === 'account' && this.accountReturnsToSettings) { - this.settingsMode = 'general'; - this.accountReturnsToSettings = false; - this.showSettings = true; - return; - } - this.setSettingsVisible(false); - } - - /** - * The account request is settled (signed in, or signed out from the inline - * account section). Stay in settings and land on the single settings page. - */ - settleAccountSettings(): void { - if (this.settingsMode !== 'account') { - return; - } - this.settingsMode = 'general'; - this.accountReturnsToSettings = false; - this.showSettings = true; - } - - setConnectSheetVisible(visible: boolean): void { - this.showConnectSheet = visible; - } - - closeGlobalSurfaces(): void { - this.showSidebar = false; - this.showSettings = false; - this.accountReturnsToSettings = false; - this.settingsSheet.resetOnClose(); - this.showConnectSheet = false; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatComposerCapabilities.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatComposerCapabilities.ets deleted file mode 100644 index 911be61ed3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatComposerCapabilities.ets +++ /dev/null @@ -1,36 +0,0 @@ -import { ChatSurface } from './ChatSurface'; - -export class ChatComposerCapabilities { - readonly surface: ChatSurface; - readonly supportsAttachments: boolean; - readonly requiresRemoteConnection: boolean; - readonly showAddButton: boolean; - readonly showVoiceInput: boolean; - // Whether a message typed while a turn is still running can be handed over - // right away. The desktop relay queues it server-side and lets the current - // turn yield to it, so on that surface the draft outranks the stop button. - // Where nothing queues, holding the draft back is the honest behaviour. - readonly supportsMidRunSend: boolean; - - constructor( - surface: ChatSurface, - supportsAttachments: boolean, - requiresRemoteConnection: boolean, - showAddButton: boolean = true, - showVoiceInput: boolean = true, - supportsMidRunSend: boolean = false - ) { - this.surface = surface; - this.supportsAttachments = supportsAttachments; - this.requiresRemoteConnection = requiresRemoteConnection; - this.showAddButton = showAddButton; - this.showVoiceInput = showVoiceInput; - this.supportsMidRunSend = supportsMidRunSend; - } -} - -export const GENERAL_CHAT_COMPOSER_CAPABILITIES: ChatComposerCapabilities = - new ChatComposerCapabilities(ChatSurface.General, true, false); - -export const REMOTE_CHAT_COMPOSER_CAPABILITIES: ChatComposerCapabilities = - new ChatComposerCapabilities(ChatSurface.Remote, true, true, true, true, true); diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatSurface.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatSurface.ets deleted file mode 100644 index 284d69a2a4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ChatSurface.ets +++ /dev/null @@ -1,4 +0,0 @@ -export enum ChatSurface { - General = 'general', - Remote = 'remote' -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ColdStartPresentationState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ColdStartPresentationState.ets deleted file mode 100644 index df2e0e8f12..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ColdStartPresentationState.ets +++ /dev/null @@ -1,16 +0,0 @@ -/** Launch-only presentation state; no account credentials or transport ownership. */ -@ObservedV2 -export class ColdStartPresentationState { - private static processClaimed: boolean = false; - - static claimProcess(): boolean { - if (ColdStartPresentationState.processClaimed) return false; - ColdStartPresentationState.processClaimed = true; - return true; - } - @Trace targetX: number = 0; - @Trace targetY: number = 0; - @Trace targetSize: number = 0; - @Trace originX: number = 0; - @Trace originY: number = 0; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/CommandPaletteState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/CommandPaletteState.ets deleted file mode 100644 index 680676b196..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/CommandPaletteState.ets +++ /dev/null @@ -1,317 +0,0 @@ -import { RemoteCommandCatalog, RemoteSessionUsageReport } from '../../model/RemoteModels'; -import { - CommandPaletteAvailability, - CommandPaletteCatalogStatus, - CommandPaletteChip, - CommandPaletteChipKind, - CommandPaletteChipState, - CommandPaletteNoticeKind, - CommandPalettePolicy, - CommandPaletteProbeFailure -} from '../../services/CommandPalettePolicy'; -import { - UsageReportPresentationPolicy, - UsageReportSection -} from '../policy/UsageReportPresentationPolicy'; - -export enum CommandPaletteUsageStatus { - Idle = 'idle', - Loading = 'loading', - Ready = 'ready', - Failed = 'failed' -} - -/** - * What the chip row says under itself after a verb ran. - * - * One line at a time: a second verb replaces the first notice rather than - * stacking a second line above the composer. - */ -export class CommandPaletteNotice { - readonly kind: CommandPaletteNoticeKind; - readonly labelKey: string; - /** Host error text for a failure, empty otherwise. */ - readonly detail: string; - /** The verb a retry would repeat, empty when there is nothing to repeat. */ - readonly retryCommand: string; - - constructor(kind: CommandPaletteNoticeKind, labelKey: string, detail: string, retryCommand: string) { - this.kind = kind; - this.labelKey = labelKey; - this.detail = detail; - this.retryCommand = retryCommand; - } - - static none(): CommandPaletteNotice { - return new CommandPaletteNotice(CommandPaletteNoticeKind.Done, '', '', ''); - } - - get visible(): boolean { - return this.labelKey.length > 0; - } - - get retryable(): boolean { - return CommandPalettePolicy.canRetry(this.kind, this.retryCommand); - } -} - -/** - * Observable command-palette state for the remote conversation. - * - * Owned by `RemotePageState`, written by `RemoteCommandPaletteController` through - * the composition, and read only through `CommandPalettePresentation` so the - * view never has to know which half of this is host truth and which half is a - * local draft decision. - */ -@ObservedV2 -export class CommandPaletteState { - @Trace catalogStatus: string = CommandPaletteCatalogStatus.Idle; - @Trace catalog: RemoteCommandCatalog | undefined = undefined; - /** - * Why the skill read failed, when it did. - * - * Kept beside the host's text because the two answer different questions: the - * kind decides whether this app may tell the user their desktop is out of - * date, and the text is the host's own account of what went wrong. - */ - @Trace catalogFailure: string = CommandPaletteProbeFailure.None; - /** - * The host's own text for a failed read. - * - * A verb can fail for a reason the user can act on — a locked workspace, a - * session the desktop cannot find — and the host already said which. Restating - * that in this app's words would lose it. - */ - @Trace catalogErrorText: string = ''; - @Trace runningCommand: string = ''; - @Trace notice: CommandPaletteNotice = CommandPaletteNotice.none(); - @Trace usageStatus: string = CommandPaletteUsageStatus.Idle; - @Trace usageReport: RemoteSessionUsageReport | undefined = undefined; - @Trace usageErrorText: string = ''; - /** The key of the single selected skill, or '' when the composer carries none. */ - @Trace skillId: string = ''; - /** The selected skill's name, which is the text its token carries. */ - @Trace skillLabel: string = ''; - /** The goal chip is lit and its `/goal ` prefill is in the composer. */ - @Trace goalPending: boolean = false; - - /** - * The row's inputs, read from this state rather than passed in. - * - * The skill read's verdict belongs to whoever holds the answer, so the - * projection no longer takes a pre-computed `probeReady` that could disagree - * with the status sitting right beside it. - */ - availability(hasSession: boolean, isBusy: boolean): CommandPaletteAvailability { - return new CommandPaletteAvailability( - this.catalogStatus, this.catalogFailure, hasSession, isBusy, - this.runningCommand, this.goalPending); - } - - setCatalogLoading(): void { - this.catalogStatus = CommandPaletteCatalogStatus.Loading; - this.catalogFailure = CommandPaletteProbeFailure.None; - this.catalogErrorText = ''; - } - - setCatalogReady(catalog: RemoteCommandCatalog): void { - this.catalog = catalog; - this.catalogStatus = CommandPaletteCatalogStatus.Ready; - this.catalogFailure = CommandPaletteProbeFailure.None; - this.catalogErrorText = ''; - } - - setCatalogFailed(errorText: string, failure: string): void { - this.catalog = undefined; - this.catalogErrorText = errorText; - this.catalogFailure = failure; - this.catalogStatus = CommandPaletteCatalogStatus.Failed; - } - - beginCommand(wireAction: string): void { - this.runningCommand = wireAction; - this.notice = CommandPaletteNotice.none(); - } - - settleCommand(wireAction: string, errorText: string): void { - this.runningCommand = ''; - if (errorText.length === 0) { - this.notice = new CommandPaletteNotice( - CommandPaletteNoticeKind.Done, - CommandPalettePolicy.doneNoticeKey(wireAction), - '', - ''); - return; - } - this.notice = new CommandPaletteNotice( - CommandPaletteNoticeKind.Failed, - CommandPalettePolicy.failedNoticeKey(wireAction), - errorText, - wireAction); - } - - /** The completion line's dwell time ran out. */ - expireNotice(wireAction: string): void { - if (this.notice.visible && this.notice.retryCommand.length === 0 && - CommandPalettePolicy.doneNoticeKey(wireAction) === this.notice.labelKey) { - this.notice = CommandPaletteNotice.none(); - } - } - - clearNotice(): void { - this.notice = CommandPaletteNotice.none(); - } - - setUsageLoading(): void { - this.usageStatus = CommandPaletteUsageStatus.Loading; - this.usageErrorText = ''; - } - - setUsageReady(report: RemoteSessionUsageReport | undefined): void { - this.usageReport = report; - this.usageStatus = CommandPaletteUsageStatus.Ready; - } - - setUsageFailed(errorText: string): void { - this.usageReport = undefined; - this.usageErrorText = errorText; - this.usageStatus = CommandPaletteUsageStatus.Failed; - } - - /** Picks a skill. The key decides whether it is a new pick; the label is its token. */ - setSkill(skillId: string, skillLabel: string): void { - const next = CommandPalettePolicy.applySkillSelection(this.skillId, skillId); - if (next === this.skillId && next.length > 0) { - // Re-picking the row that is already in the composer: the token stays the - // one already drawn rather than being rewritten under the user. - return; - } - this.skillId = next; - this.skillLabel = next.length > 0 ? skillLabel.trim() : ''; - } - - clearSkill(): void { - this.skillId = ''; - this.skillLabel = ''; - } - - setGoalPending(pending: boolean): void { - this.goalPending = pending; - } - - /** Everything the previous conversation owned, dropped with it. */ - reset(): void { - this.catalogStatus = CommandPaletteCatalogStatus.Idle; - this.catalog = undefined; - this.catalogFailure = CommandPaletteProbeFailure.None; - this.catalogErrorText = ''; - this.runningCommand = ''; - this.notice = CommandPaletteNotice.none(); - this.usageStatus = CommandPaletteUsageStatus.Idle; - this.usageReport = undefined; - this.usageErrorText = ''; - this.skillId = ''; - this.skillLabel = ''; - this.goalPending = false; - } -} - -/** - * The command palette as the conversation view reads it. - * - * Immutable, computed once per projection: the chips a tap may act on, the - * explanation the row owes the user, the notice line, and the two sheets' data. - */ -export class CommandPalettePresentation { - readonly visible: boolean; - readonly chips: CommandPaletteChip[]; - /** Persistent explanation under the row: a session-less surface. */ - readonly rowReasonKey: string; - readonly notice: CommandPaletteNotice; - readonly catalogStatus: string; - readonly catalog?: RemoteCommandCatalog; - /** Why the read failed, which is what the picker's copy follows. */ - readonly catalogFailure: string; - /** The host's own text for a failed read, empty otherwise. */ - readonly catalogErrorText: string; - readonly usageStatus: string; - readonly usageSections: UsageReportSection[]; - readonly usagePartial: boolean; - readonly usageErrorText: string; - /** The selected skill's key, which is what its row's check mark compares. */ - readonly skillId: string; - /** The selected skill's name, which is the text its token carries. */ - readonly skillLabel: string; - - constructor( - visible: boolean, - chips: CommandPaletteChip[], - rowReasonKey: string, - notice: CommandPaletteNotice, - catalogStatus: string, - catalog: RemoteCommandCatalog | undefined, - catalogFailure: string, - catalogErrorText: string, - usageStatus: string, - usageSections: UsageReportSection[], - usagePartial: boolean, - usageErrorText: string, - skillId: string, - skillLabel: string - ) { - this.visible = visible; - this.chips = chips; - this.rowReasonKey = rowReasonKey; - this.notice = notice; - this.catalogStatus = catalogStatus; - this.catalog = catalog; - this.catalogFailure = catalogFailure; - this.catalogErrorText = catalogErrorText; - this.usageStatus = usageStatus; - this.usageSections = usageSections; - this.usagePartial = usagePartial; - this.usageErrorText = usageErrorText; - this.skillId = skillId; - this.skillLabel = skillLabel; - } - - /** No row at all: the general surface, or a conversation with no session. */ - static hidden(): CommandPalettePresentation { - return new CommandPalettePresentation( - false, [], '', CommandPaletteNotice.none(), - CommandPaletteCatalogStatus.Idle, undefined, CommandPaletteProbeFailure.None, '', - CommandPaletteUsageStatus.Idle, [], false, '', '', ''); - } - - static project( - state: CommandPaletteState, - hasSession: boolean, - isBusy: boolean - ): CommandPalettePresentation { - if (!CommandPalettePolicy.visible(hasSession)) { - return CommandPalettePresentation.hidden(); - } - const availability = state.availability(hasSession, isBusy); - const usage = UsageReportPresentationPolicy.present(state.usageReport); - return new CommandPalettePresentation( - true, - CommandPalettePolicy.chips(availability), - CommandPalettePolicy.rowReasonKey(availability), - state.notice, - state.catalogStatus, - state.catalog, - state.catalogFailure, - state.catalogErrorText, - state.usageStatus, - usage.sections, - usage.partial, - state.usageErrorText, - state.skillId, - state.skillLabel); - } - - chipState(kind: CommandPaletteChipKind): CommandPaletteChipState { - const match = this.chips.find((chip: CommandPaletteChip): boolean => chip.kind === kind); - return match ? match.state : CommandPaletteChipState.Dimmed; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationCoreState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationCoreState.ets deleted file mode 100644 index 3a95ebaf43..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationCoreState.ets +++ /dev/null @@ -1,272 +0,0 @@ -import { ComposerSubmission } from '../../model/ComposerSubmission'; -import { - ChatMessage, - RemoteModelCatalog, - RemoteModelConfig, - RemoteSession, - SelectedImageAttachment, - SessionSummary -} from '../../model/RemoteModels'; -import { - ChatTimelineItem, - ObservableChatTimelineItem, - ChatTimelineRevisionTracker, - ChatTimelineRowStore -} from '../../model/ChatTimelineModels'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { SubagentBranchExpansionState } from './SubagentBranchExpansionState'; - -/** Shared observable state for General Chat and Remote Chat conversations. */ -@ObservedV2 -export class ConversationCoreState { - @Trace sessions: RemoteSession[] = []; - @Trace activeSession: SessionSummary; - @Trace persistedMessages: ChatMessage[] = []; - @Trace optimisticMessages: ChatMessage[] = []; - @Trace activeTurnMessage: ChatMessage = RemoteUiState.emptyActiveTurn(); - @Trace hasMoreMessages: boolean = false; - @Trace historyLoading: boolean = false; - @Trace historyFailed: boolean = false; - @Trace timelineItems: ObservableChatTimelineItem[] = []; - @Trace timelineRevision: number = 0; - @Trace isBusy: boolean = false; - @Trace modelCatalog: RemoteModelCatalog = RemoteUiState.emptyModelCatalog(); - @Trace selectedModelId: string = ''; - @Trace statusText: string = ''; - @Trace chatInput: string = ''; - @Trace promptSuggestion: string = ''; - @Trace selectedImages: SelectedImageAttachment[] = []; - @Trace isVoiceListening: boolean = false; - /** - * Which delegation cards are open. Disclosures outlive the rows that draw - * them, so they are owned by the conversation rather than by a card, and they - * are shared by every surface that projects this conversation. - */ - readonly subagentBranches: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - private composerRevision: number = 0; - private readonly defaultAgentType: string; - private readonly timelineRevisionTracker: ChatTimelineRevisionTracker = new ChatTimelineRevisionTracker(); - private readonly timelineRowStore: ChatTimelineRowStore = new ChatTimelineRowStore(); - - constructor(defaultAgentType: string) { - this.defaultAgentType = defaultAgentType; - this.activeSession = ConversationCoreState.emptySession(defaultAgentType); - } - - setSessions(sessions: RemoteSession[]): void { - this.sessions = sessions.slice(); - } - - setActiveSession(session: SessionSummary): void { - if (this.activeSession.sessionId !== session.sessionId) { - this.composerRevision++; - this.promptSuggestion = ''; - } - this.activeSession = { - sessionId: session.sessionId, - title: session.title, - workspacePath: session.workspacePath, - remoteConnectionId: session.remoteConnectionId, - agentType: this.defaultAgentType === 'chat' ? 'chat' : session.agentType, - initialTurnId: session.initialTurnId - }; - } - - clearActiveSession(): void { - this.composerRevision++; - this.activeSession = ConversationCoreState.emptySession(this.defaultAgentType); - this.clearTimeline(); - } - - setTimelineProjection( - persistedMessages: ChatMessage[], - optimisticMessages: ChatMessage[], - activeTurnMessage: ChatMessage, - hasMoreMessages: boolean, - timelineItems: ChatTimelineItem[] - ): void { - this.timelineRevision = this.timelineRevisionTracker.update(timelineItems); - this.persistedMessages = persistedMessages.slice(); - this.optimisticMessages = optimisticMessages.slice(); - this.activeTurnMessage = activeTurnMessage.id.length > 0 ? - ConversationCoreState.copyMessage(activeTurnMessage) : - RemoteUiState.emptyActiveTurn(); - this.hasMoreMessages = hasMoreMessages; - this.timelineItems = this.timelineRowStore.reconcile(timelineItems); - } - - setHasMoreMessages(hasMoreMessages: boolean): void { - this.hasMoreMessages = hasMoreMessages; - } - - clearTimeline(): void { - this.promptSuggestion = ''; - this.persistedMessages = []; - this.optimisticMessages = []; - this.activeTurnMessage = RemoteUiState.emptyActiveTurn(); - this.hasMoreMessages = false; - this.historyLoading = false; - this.historyFailed = false; - this.timelineItems = []; - this.timelineRowStore.clear(); - this.timelineRevision = this.timelineRevisionTracker.reset(); - } - - setBusy(isBusy: boolean): void { - this.isBusy = isBusy; - } - - setModelCatalog(modelCatalog: RemoteModelCatalog, selectedModelId: string): void { - this.modelCatalog = ConversationCoreState.copyModelCatalog(modelCatalog); - this.selectedModelId = selectedModelId; - } - - setStatusText(statusText: string): void { - this.statusText = statusText; - } - - setChatInput(chatInput: string): void { - if (this.chatInput === chatInput) return; - this.composerRevision++; - this.chatInput = chatInput; - } - - setSelectedImages(selectedImages: SelectedImageAttachment[]): void { - this.composerRevision++; - this.selectedImages = selectedImages.slice(); - } - - addSelectedImages(selectedImages: SelectedImageAttachment[]): void { - this.composerRevision++; - this.selectedImages = this.selectedImages.concat(selectedImages); - } - - removeSelectedImage(imageId: string): void { - this.composerRevision++; - this.selectedImages = this.selectedImages.filter((image: SelectedImageAttachment) => image.id !== imageId); - } - - clearComposer(): void { - this.composerRevision++; - this.chatInput = ''; - this.selectedImages = []; - } - - /** Capture ownership before any await; later callbacks cannot consume a newer draft. */ - prepareComposerSubmission(sessionId: string, text: string, images: SelectedImageAttachment[]): ComposerSubmission { - const originalText = this.chatInput; - const originalImages = this.selectedImages.slice(); - const capturedRevision = this.composerRevision; - let committedRevision = -1; - let committed = false; - let finished = false; - return { - commit: (): void => { - if (finished || committed || this.composerRevision !== capturedRevision || - this.activeSession.sessionId !== sessionId) return; - this.promptSuggestion = ''; - if (this.chatInput.trim() === text.trim()) this.setChatInput(''); - this.setSelectedImages(this.selectedImages.filter((image: SelectedImageAttachment): boolean => - !images.some((sent: SelectedImageAttachment): boolean => sent.id === image.id))); - committedRevision = this.composerRevision; - committed = true; - }, - rollback: (): void => { - if (finished) return; - finished = true; - if (!committed || this.composerRevision !== committedRevision || this.activeSession.sessionId !== sessionId) return; - this.setChatInput(originalText); - this.setSelectedImages(originalImages); - } - }; - } - - /** - * Drops the complete observable projection of one conversation context. - * - * Account logout, disconnect and workspace replacement must not rebuild this - * list field-by-field: leaving even one field behind makes the next surface - * look as if it still belongs to the previous identity. - */ - reset(): void { - this.sessions = []; - this.clearActiveSession(); - this.isBusy = false; - this.modelCatalog = RemoteUiState.emptyModelCatalog(); - this.selectedModelId = ''; - this.statusText = ''; - this.clearComposer(); - this.isVoiceListening = false; - } - - setVoiceListening(isVoiceListening: boolean): void { - this.isVoiceListening = isVoiceListening; - } - - hasRunningActiveTurn(): boolean { - return this.activeTurnMessage.id.length > 0 && - (this.activeTurnMessage.status || '').toLowerCase() === 'active'; - } - - latestUserMessageText(): string { - const candidates = this.persistedMessages.concat(this.optimisticMessages); - for (let index = candidates.length - 1; index >= 0; index--) { - if (candidates[index].role === 'user' && candidates[index].text.trim().length > 0) { - return candidates[index].text; - } - } - return ''; - } - - private static emptySession(agentType: string): SessionSummary { - return { - sessionId: '', - title: '', - workspacePath: '', - agentType - }; - } - - private static copyMessage(message: ChatMessage): ChatMessage { - return { - id: message.id, - role: message.role, - text: message.text, - status: message.status, - renderVersion: message.renderVersion, - turnId: message.turnId, - detail: message.detail, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools ? message.tools.slice() : undefined, - items: message.items ? message.items.slice() : undefined, - images: message.images ? message.images.slice() : undefined - }; - } - - private static copyModelCatalog(modelCatalog: RemoteModelCatalog): RemoteModelCatalog { - return { - version: modelCatalog.version, - models: modelCatalog.models.map((model): RemoteModelConfig => { - return { - id: model.id, - name: model.name, - provider: model.provider, - base_url: model.base_url, - model_name: model.model_name, - context_window: model.context_window, - enabled: model.enabled, - capabilities: model.capabilities.slice(), - reasoning: model.reasoning - }; - }), - default_models: { - primary: modelCatalog.default_models.primary, - fast: modelCatalog.default_models.fast, - search: modelCatalog.default_models.search, - image_understanding: modelCatalog.default_models.image_understanding - }, - session_model_id: modelCatalog.session_model_id - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationUiModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationUiModels.ets deleted file mode 100644 index 773175ea62..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationUiModels.ets +++ /dev/null @@ -1,293 +0,0 @@ -// Presentation-owned structures. Protocol DTOs are mapped at the boundary and -// never imported by leaf rendering components. -import { - ChatMessage, - ChatMessageItemResponse, - ImageAttachment, - RemoteModelCatalog, - RemoteModelConfig, - RemoteReasoningCatalogProjection, - RemoteQuestionAnswerPayload, - SelectedImageAttachment, - SessionSummary, - RemoteToolStatusResponse -} from '../../model/RemoteModels'; - -export interface ConversationUiPlanTool { - file_path: string; - name: string; - overview?: string; -} - -export interface ConversationUiSession { - sessionId: string; - title: string; - workspacePath: string; - agentType: string; - initialTurnId?: string; -} - -export interface ConversationUiModel { - id: string; - name: string; - provider: string; - base_url: string; - model_name: string; - context_window?: number; - enabled: boolean; - capabilities: string[]; - reasoning?: RemoteReasoningCatalogProjection; -} - -export interface ConversationUiDefaultModels { - primary?: string; - fast?: string; - search?: string; - image_understanding?: string; -} - -export interface ConversationUiModelCatalog { - version: number; - models: ConversationUiModel[]; - default_models: ConversationUiDefaultModels; - session_model_id?: string; -} -export interface ConversationUiToolStatus { - permission_request_id?: string; - id?: string; - name?: string; - status?: string; - duration_ms?: number; - start_ms?: number; - input_preview?: string; - tool_input?: Object; - stdout?: string; - stderr?: string; - tool_output?: Object; - result_preview?: string; - error_preview?: string; - exit_code?: number; - plan?: ConversationUiPlanTool; -} - -export interface ConversationUiMessageItem { - type?: string; - steering_id?: string; - round_index?: number; - content?: string; - tool?: ConversationUiToolStatus; - is_subagent?: boolean; - subItems?: ConversationUiMessageItem[]; - images?: ConversationUiImage[]; -} - -export interface ConversationUiImage { - name: string; - data_url: string; -} - -export interface ConversationUiSelectedImage extends ConversationUiImage { - id: string; - uri: string; - mime_type: string; - size: number; - original_size: number; - compressed: boolean; -} - -export interface ConversationUiMessage { - id: string; - role: string; - text: string; - status: string; - renderVersion?: number; - turnId?: string; - detail?: string; - error?: string; - timestamp?: string; - thinking?: string; - tools?: ConversationUiToolStatus[]; - items?: ConversationUiMessageItem[]; - images?: ConversationUiImage[]; -} - -/** Stable observable projection consumed by retained/reused message rows. */ -@ObservedV2 -export class ObservableConversationUiMessage implements ConversationUiMessage { - @Trace id: string = ''; - @Trace role: string = 'assistant'; - @Trace text: string = ''; - @Trace status: string = ''; - @Trace renderVersion: number | undefined = undefined; - @Trace turnId: string | undefined = undefined; - @Trace detail: string | undefined = undefined; - @Trace error: string | undefined = undefined; - @Trace timestamp: string | undefined = undefined; - @Trace thinking: string | undefined = undefined; - @Trace tools: ConversationUiToolStatus[] | undefined = undefined; - @Trace items: ConversationUiMessageItem[] | undefined = undefined; - @Trace images: ConversationUiImage[] | undefined = undefined; - - updateFrom(source: ConversationUiMessage): void { - this.id = source.id; - this.role = source.role; - this.text = source.text; - this.status = source.status; - this.renderVersion = source.renderVersion; - this.turnId = source.turnId; - this.detail = source.detail; - this.error = source.error; - this.timestamp = source.timestamp; - this.thinking = source.thinking; - this.tools = source.tools; - this.items = source.items; - this.images = source.images; - } -} - -export interface ConversationUiQuestionAnswer { - answer?: string; - '0'?: string | string[]; - '1'?: string | string[]; - '2'?: string | string[]; - '3'?: string | string[]; -} - -export function toConversationUiSession(source: SessionSummary): ConversationUiSession { - return { - sessionId: source.sessionId, - title: source.title, - workspacePath: source.workspacePath, - agentType: source.agentType, - initialTurnId: source.initialTurnId - }; -} - -export function toConversationUiModel(source: RemoteModelConfig): ConversationUiModel { - return { - id: source.id, - name: source.name, - provider: source.provider, - base_url: source.base_url, - model_name: source.model_name, - context_window: source.context_window, - enabled: source.enabled, - capabilities: source.capabilities.slice(), - reasoning: source.reasoning - }; -} - -export function toConversationUiModelCatalog(source: RemoteModelCatalog): ConversationUiModelCatalog { - return { - version: source.version, - models: source.models.map((model: RemoteModelConfig) => toConversationUiModel(model)), - default_models: { - primary: projectedDefaultModelId(source.default_models.primary), - fast: projectedDefaultModelId(source.default_models.fast), - search: projectedDefaultModelId(source.default_models.search), - image_understanding: projectedDefaultModelId(source.default_models.image_understanding) - }, - session_model_id: source.session_model_id - }; -} - -/** - * The wire says `null` for a slot with no model; this projection says the same - * by leaving the id absent. Both mean "nothing configured" to every reader. - */ -function projectedDefaultModelId(value: string | null | undefined): string | undefined { - return value === undefined || value === null || value.length === 0 ? undefined : value; -} - -export function toConversationUiSelectedImage(source: SelectedImageAttachment): ConversationUiSelectedImage { - return { - id: source.id, - name: source.name, - data_url: source.data_url, - uri: source.uri, - mime_type: source.mime_type, - size: source.size, - original_size: source.original_size, - compressed: source.compressed - }; -} - -export function toConversationUiToolStatus(source: RemoteToolStatusResponse): ConversationUiToolStatus { - return { - permission_request_id: source.permission_request_id, - id: source.id, - name: source.name, - status: source.status, - duration_ms: source.duration_ms, - start_ms: source.start_ms, - input_preview: source.input_preview, - tool_input: source.tool_input, - stdout: source.stdout, - stderr: source.stderr, - tool_output: source.tool_output, - result_preview: source.result_preview, - error_preview: source.error_preview, - exit_code: source.exit_code, - plan: source.plan ? { - file_path: source.plan.file_path, - name: source.plan.name, - overview: source.plan.overview - } : undefined - }; -} - -export function toConversationUiMessageItem(source: ChatMessageItemResponse): ConversationUiMessageItem { - return { - type: source.type, - steering_id: source.steering_id, - round_index: source.round_index, - content: source.content, - tool: source.tool ? toConversationUiToolStatus(source.tool) : undefined, - is_subagent: source.is_subagent, - subItems: source.subItems ? source.subItems.map((item: ChatMessageItemResponse) => toConversationUiMessageItem(item)) : undefined, - images: source.images ? source.images.map((image: ImageAttachment) => toConversationUiImage(image)) : undefined - }; -} - -export function toConversationUiImage(source: ImageAttachment): ConversationUiImage { - return { name: source.name, data_url: source.data_url }; -} - -export function toConversationUiMessage(source: ChatMessage): ConversationUiMessage { - return { - id: source.id, - role: source.role, - text: source.text, - status: source.status, - renderVersion: source.renderVersion, - turnId: source.turnId, - detail: source.detail, - error: source.error, - timestamp: source.timestamp, - thinking: source.thinking, - tools: source.tools ? source.tools.map((tool: RemoteToolStatusResponse) => toConversationUiToolStatus(tool)) : undefined, - items: source.items ? source.items.map((item: ChatMessageItemResponse) => toConversationUiMessageItem(item)) : undefined, - images: source.images ? source.images.map((image: ImageAttachment) => toConversationUiImage(image)) : undefined - }; -} - -export function toRemoteQuestionAnswer(source: ConversationUiQuestionAnswer): RemoteQuestionAnswerPayload { - const result: Record = {}; - const values = source as Record; - if (source.answer !== undefined) { - result['answer'] = source.answer as Object; - } - if (values['0'] !== undefined) { - result['0'] = values['0']; - } - if (values['1'] !== undefined) { - result['1'] = values['1']; - } - if (values['2'] !== undefined) { - result['2'] = values['2']; - } - if (values['3'] !== undefined) { - result['3'] = values['3']; - } - return result as RemoteQuestionAnswerPayload; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets deleted file mode 100644 index 4a67a62074..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets +++ /dev/null @@ -1,181 +0,0 @@ -import { MessageQueueState } from '../../model/MessageQueue'; -import { InteractionMailboxState } from '../../model/InteractionMailbox'; -import { ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { - GeneralChatServiceStatus -} from '../../services/general-chat/GeneralChatServiceState'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { - ChatComposerCapabilities, - GENERAL_CHAT_COMPOSER_CAPABILITIES, - REMOTE_CHAT_COMPOSER_CAPABILITIES -} from './ChatComposerCapabilities'; -import { ChatSurface } from './ChatSurface'; -import { - ConversationUiModelCatalog, - ConversationUiSelectedImage, - ConversationUiSession, - toConversationUiModelCatalog, - toConversationUiSelectedImage, - toConversationUiSession -} from './ConversationUiModels'; -import { AppRoute } from '../navigation/AppRouteContract'; -import { ConversationCoreState } from './ConversationCoreState'; -import { GeneralChatPageState } from './GeneralChatPageState'; -import { RemotePageState } from './RemotePageState'; -import { SubagentBranchExpansionState } from './SubagentBranchExpansionState'; -import { CommandPalettePresentation } from './CommandPaletteState'; -import { RollbackEntryFacts } from '../policy/RollbackPresentationPolicy'; - -/** Immutable presentation state consumed by ConversationView. */ -export class ConversationViewState { - messageQueue: MessageQueueState = new MessageQueueState(); - interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - activeSession: ConversationUiSession = ConversationViewState.emptySession(); - surface: ChatSurface = ChatSurface.General; - desktopName: string = ''; - workspaceBranch: string = ''; - statusText: string = ''; - inlineStatusText: string = ''; - connectionState: string = 'idle'; - composerCapabilities: ChatComposerCapabilities = GENERAL_CHAT_COMPOSER_CAPABILITIES; - isBusy: boolean = false; - isLoadingConversation: boolean = false; - isLoadingTranscript: boolean = false; - canStop: boolean = false; - hasMoreMessages: boolean = false; - historyLoading: boolean = false; - historyFailed: boolean = false; - timelineItems: ObservableChatTimelineItem[] = []; - timelineRevision: number = 0; - showSuggestionsWhenEmpty: boolean = false; - modelCatalog: ConversationUiModelCatalog = toConversationUiModelCatalog(RemoteUiState.emptyModelCatalog()); - selectedModelId: string = ''; - isSessionPinned: boolean = false; - downloadingFilePath: string = ''; - downloadedFilePath: string = ''; - fileDownloadStatus: string = ''; - selectedImages: ConversationUiSelectedImage[] = []; - isVoiceListening: boolean = false; - chatInput: string = ''; - /** - * Disclosure of the conversation's delegation cards; the projection carries the - * owner's instance so a card the reader opened stays open across repaints. - */ - subagentBranches: SubagentBranchExpansionState = new SubagentBranchExpansionState(); - /** - * The composer's command row. Hidden on the general surface and whenever the - * conversation has no session, so the row can never act on a stale target. - */ - commandPalette: CommandPalettePresentation = CommandPalettePresentation.hidden(); - promptSuggestion: string = ''; - /** - * The facts a tap on the rollback entry is judged with. - * - * Projected, not decided: the entry can be tapped long after the row was drawn, - * so the pane resolves these facts into a decision at tap time. `none()` is the - * default because a surface with no host behind it — the local General Chat pane - * — has nothing to roll back to. - */ - rollbackGate: RollbackEntryFacts = RollbackEntryFacts.none(); - /** The system hint row a successful rollback left in this session's transcript. */ - rollbackNotice: string = ''; - /** Host outcome of a rollback this client asked for, or empty for none. */ - rollbackOutcome: string = ''; - /** Monotonic id of that outcome, so two identical failures are two outcomes. */ - rollbackOutcomeSeq: number = 0; - /** Identity generation for a reused pane; a resize alone does not change it. */ - sessionContextRevision: number = 0; - - static project( - route: AppRoute, - remote: RemotePageState, - general: GeneralChatPageState, - generalInlineStatus: string - ): ConversationViewState { - if (route === AppRoute.RemoteChat) { - return ConversationViewState.remote(remote); - } - return ConversationViewState.general(general, generalInlineStatus); - } - - private static remote(remote: RemotePageState): ConversationViewState { - const state = ConversationViewState.fromCore(remote.conversation); - state.surface = ChatSurface.Remote; - state.desktopName = remote.desktopName; - state.workspaceBranch = remote.workspaceBranch; - state.connectionState = remote.connectionState; - state.isLoadingConversation = remote.isLoadingConversation; - // Nothing is being waited for once the pane has no session: a skeleton left - // standing after a disconnect or a delete would describe a load that was - // abandoned rather than one still running. - state.isLoadingTranscript = remote.isLoadingTranscript && remote.activeSession.sessionId.length > 0; - if (state.isLoadingConversation) { - state.activeSession = ConversationViewState.emptySession(); - } - state.composerCapabilities = REMOTE_CHAT_COMPOSER_CAPABILITIES; - state.showSuggestionsWhenEmpty = false; - state.downloadingFilePath = remote.downloadingFilePath; - state.downloadedFilePath = remote.downloadedFilePath; - state.fileDownloadStatus = remote.fileDownloadStatus; - state.interactionMailbox = remote.interactionMailbox; - state.messageQueue = remote.messageQueue; - state.commandPalette = CommandPalettePresentation.project( - remote.commandPalette, - state.activeSession.sessionId.length > 0, - state.isBusy); - // A rollback needs an idle session on a host that serves the capability; a - // dispatch session cannot be proven from this controller (see - // `RollbackEntryFacts.isDispatchSession`), so the host's own refusal stays the - // loud answer rather than a silent "no" invented here. - state.rollbackGate = new RollbackEntryFacts( - remote.hostCapabilities.slice(), - remote.isBusy || state.canStop, - false - ); - state.rollbackNotice = remote.rollbackNotice; - state.rollbackOutcome = remote.rollbackOutcome; - state.rollbackOutcomeSeq = remote.rollbackOutcomeSeq; - state.sessionContextRevision = remote.sessionContextRevision; - return state; - } - - private static general(general: GeneralChatPageState, inlineStatus: string): ConversationViewState { - const state = ConversationViewState.fromCore(general.conversation); - state.inlineStatusText = inlineStatus; - state.connectionState = GeneralChatServiceStatus.connectionState(general.serviceState); - state.isSessionPinned = general.conversation.activeSession.sessionId.length > 0 && - general.pinnedSessionId() === general.conversation.activeSession.sessionId; - return state; - } - - private static fromCore(core: ConversationCoreState): ConversationViewState { - const state = new ConversationViewState(); - state.activeSession = toConversationUiSession(core.activeSession); - state.statusText = core.statusText; - state.isBusy = core.isBusy; - state.canStop = core.hasRunningActiveTurn(); - state.hasMoreMessages = core.hasMoreMessages; - state.historyLoading = core.historyLoading; - state.historyFailed = core.historyFailed; - state.timelineItems = core.timelineItems; - state.timelineRevision = core.timelineRevision; - state.modelCatalog = toConversationUiModelCatalog(core.modelCatalog); - state.selectedModelId = core.selectedModelId; - state.selectedImages = core.selectedImages.map((image) => toConversationUiSelectedImage(image)); - state.isVoiceListening = core.isVoiceListening; - state.chatInput = core.chatInput; - state.subagentBranches = core.subagentBranches; - state.promptSuggestion = core.promptSuggestion; - return state; - } - - private static emptySession(): ConversationUiSession { - return { - sessionId: '', - title: '', - workspacePath: '', - agentType: 'chat' - }; - } -} 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 deleted file mode 100644 index 24931d4b45..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets +++ /dev/null @@ -1,202 +0,0 @@ -import { RecentWorkspaceEntry, RemoteSession, RemoteWorkspaceIdentity } from '../../model/RemoteModels'; -import { remoteWorkspaceIdentityMatches } from '../../services/RemoteSessionIdentity'; - -export type DeviceDirectoryStatus = 'idle' | 'cached' | 'loading' | 'ready' | 'failed'; -export type WorkspaceDirectoryStatus = 'idle' | 'loading' | 'ready' | 'failed'; - -/** Disclosure and lazy-load state that must outlive a sidebar component. */ -@ObservedV2 -export class WorkspaceDirectoryState { - @Trace deviceId: string = ''; - @Trace path: string = ''; - @Trace remoteConnectionId: string = ''; - @Trace remoteSshHost: string = ''; - /** Stable record ID of the disclosed row; empty for rows from pre-ID hosts. */ - @Trace workspaceId: string = ''; - @Trace expanded: boolean = false; - @Trace status: WorkspaceDirectoryStatus = 'idle'; - @Trace hasLoadedSessions: boolean = false; - - /** The disclosed row as a workspace reference for listings and attribution. */ - workspaceIdentity(): RemoteWorkspaceIdentity { - return { - workspaceId: this.workspaceId.length > 0 ? this.workspaceId : undefined, - path: this.path, - remoteConnectionId: this.remoteConnectionId.length > 0 ? this.remoteConnectionId : undefined, - remoteSshHost: this.remoteSshHost.length > 0 ? this.remoteSshHost : undefined - }; - } -} - -/** - * 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. - */ -@ObservedV2 -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 = ''; - @Trace workspaces: RecentWorkspaceEntry[] = []; - @Trace catalogSource: string = ''; - @Trace recentWorkspaces: RecentWorkspaceEntry[] = []; - @Trace sessions: RemoteSession[] = []; - - get displayName(): string { - return this.deviceAlias ?? (this.deviceName || this.deviceId); - } -} - -/** Shared observable directory of account desktops. */ -@ObservedV2 -export class DeviceDirectoryState { - @Trace refreshing: boolean = false; - @Trace refreshError: string = ''; - refreshGeneration: number = 0; - @Trace devices: DeviceDirectoryEntry[] = []; - /** Disclosure state is independent of device catalog projection instances. */ - @Trace workspaceDirectory: WorkspaceDirectoryState[] = []; - /** Device whose workspaces are projected below the flat device list. */ - @Trace selectedDeviceId: string = ''; - - replace(devices: DeviceDirectoryEntry[]): void { - this.devices = devices; - } - - clear(): void { - this.refreshGeneration++; this.refreshing = false; this.refreshError = ''; - this.devices = []; - this.workspaceDirectory = []; - this.selectedDeviceId = ''; - } - - select(deviceId: string): void { - this.selectedDeviceId = deviceId.trim(); - } - - find(deviceId: string): DeviceDirectoryEntry | undefined { - return this.devices.find((item: DeviceDirectoryEntry): boolean => item.deviceId === deviceId); - } - - workspaceExpanded(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): boolean { - return this.findWorkspace(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId)?.expanded || false; - } - - workspaceStatus(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): WorkspaceDirectoryStatus { - return this.findWorkspace(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId)?.status || 'idle'; - } - - workspaceHasLoadedSessions(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): boolean { - return this.findWorkspace(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId)?.hasLoadedSessions || false; - } - - /** A request retains this object so a reset cannot publish into its successor. */ - workspaceLoadState(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): WorkspaceDirectoryState { - return this.ensureWorkspace(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId); - } - - isCurrentWorkspaceLoad(state: WorkspaceDirectoryState): boolean { - return this.findWorkspace(state.deviceId, state.path, state.remoteConnectionId, state.remoteSshHost, state.workspaceId) === state; - } - - setWorkspaceExpanded(deviceId: string, path: string, expanded: boolean, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): void { - this.ensureWorkspace(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId).expanded = expanded; - } - - setWorkspaceStatus(deviceId: string, path: string, status: WorkspaceDirectoryStatus, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): void { - this.ensureWorkspace(deviceId, path, remoteConnectionId, remoteSshHost, workspaceId).status = status; - } - - /** - * Drops disclosure and load facts produced by an older connection to one device. - * - * A fresh control-target handshake only contains the current workspace's - * sessions. Keeping a sibling workspace marked `ready` after that partial - * snapshot replaces the directory makes its next disclosure skip the RPC and - * render a false empty result. Other devices keep their independent state. - */ - resetWorkspaceDirectory(deviceId: string): void { - const targetDeviceId = deviceId.trim(); - if (targetDeviceId.length === 0) { - return; - } - this.workspaceDirectory = this.workspaceDirectory.filter((item: WorkspaceDirectoryState): boolean => - item.deviceId !== targetDeviceId - ); - } - - /** - * Rows are matched like every other workspace reference: by ID when both - * sides carry one, by the legacy triple otherwise. Disclosure rows are - * device-local, so no catalog is needed to attribute an ID-less side. - */ - private findWorkspace( - deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string - ): WorkspaceDirectoryState | undefined { - const targetDeviceId = deviceId.trim(); - const target: RemoteWorkspaceIdentity = DeviceDirectoryState.identityOf(path, remoteConnectionId, remoteSshHost, workspaceId); - return this.workspaceDirectory.find((item: WorkspaceDirectoryState): boolean => - item.deviceId === targetDeviceId && remoteWorkspaceIdentityMatches(item.workspaceIdentity(), target, []) - ); - } - - private ensureWorkspace( - deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string - ): WorkspaceDirectoryState { - const targetDeviceId = deviceId.trim(); - const target: RemoteWorkspaceIdentity = DeviceDirectoryState.identityOf(path, remoteConnectionId, remoteSshHost, workspaceId); - const existing = this.findWorkspace(targetDeviceId, target.path, target.remoteConnectionId, target.remoteSshHost, target.workspaceId); - if (existing) { - if (existing.workspaceId.length === 0 && target.workspaceId !== undefined) { - existing.workspaceId = target.workspaceId; - } - return existing; - } - const created = new WorkspaceDirectoryState(); - created.deviceId = targetDeviceId; - created.path = target.path; - created.remoteConnectionId = target.remoteConnectionId || ''; - created.remoteSshHost = target.remoteSshHost || ''; - created.workspaceId = target.workspaceId || ''; - this.workspaceDirectory = this.workspaceDirectory.concat([created]); - return created; - } - - private static identityOf( - path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string - ): RemoteWorkspaceIdentity { - const id = workspaceId?.trim() || ''; - const connectionId = remoteConnectionId?.trim() || ''; - const sshHost = remoteSshHost?.trim() || ''; - return { - workspaceId: id.length > 0 ? id : undefined, - path: DeviceDirectoryState.normalizeWorkspacePath(path), - remoteConnectionId: connectionId.length > 0 ? connectionId : undefined, - remoteSshHost: sshHost.length > 0 ? sshHost : undefined - }; - } - - private static normalizeWorkspacePath(path: string): string { - const normalized = path.trim().replace(/\/+$/, ''); - return normalized.length > 0 ? normalized : path.trim(); - } -} - -export function emptyDeviceDirectoryEntry( - deviceId: string, - deviceName: string, - online: boolean -): DeviceDirectoryEntry { - const entry = new DeviceDirectoryEntry(); - entry.deviceId = deviceId; - entry.deviceName = deviceName; - entry.online = online; - return entry; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceModelDefaultsSheetState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceModelDefaultsSheetState.ets deleted file mode 100644 index a0bf242e98..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceModelDefaultsSheetState.ets +++ /dev/null @@ -1,219 +0,0 @@ -import { RemoteDefaultModels, RemoteModelCatalog } from '../../model/RemoteModels'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { - RemoteModelDefaultsClient, - RemoteModelDefaultsController, - RemoteModelDefaultsGate, - RemoteModelDefaultsRole, - RemoteModelDefaultsState -} from '../../services/RemoteModelDefaultsController'; -import { ModelRoleCandidatesPolicy } from '../policy/ModelRoleCandidatesPolicy'; - -/** How long the confirmed-write line stays on screen. */ -export const MODEL_DEFAULTS_FEEDBACK_MS: number = 2000; - -/** - * The state a page shows before anything has been read or bound. - * - * It is the same shape `RemoteModelDefaultsController` publishes for a closed - * gate, so a page mounted before its client is bound renders an empty page - * instead of nothing at all. The controller's own snapshot is what a page - * normally sees; `model-role-pages.test.cjs` pins the two together so this copy - * cannot drift away from it. - */ -export function emptyModelDefaultsState(): RemoteModelDefaultsState { - return { - available: false, - loading: false, - busy: false, - catalog: RemoteUiState.emptyModelCatalog(), - roles: { primary: null, fast: null, image_understanding: null }, - error: '', - failure: '', - statusText: '', - loaded: false - }; -} - -/** - * The request path the sheet hands to the pages: the same two calls - * `RemoteModelDefaultsClient` describes, declared as properties. - * - * ArkTS only accepts an object literal against a type whose members are - * properties, and the sheet binds its two request events as a literal, because - * the desktop they go to is chosen by the sheet and not by either page. The - * shape is the same one the controller calls, so this is a spelling of that - * interface rather than a second protocol. - */ -export interface DeviceModelDefaultsRequestPath { - getModelCatalog: (sessionId?: string) => Promise; - setModelDefaults: ( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ) => Promise; -} - -/** - * Device model role defaults for the connected desktop, owned by the settings - * sheet. - * - * The sheet's two model pages (`deviceModels` and the `modelPick` level above - * it) are one workflow over one controller: the picker writes, the settings page - * shows the read-back, and swapping between them must not re-read the device or - * lose a write in flight. So the controller lives here, on the sheet state the - * two pages are both handed, rather than inside either page. - * - * It is also the client the controller calls: `bind` decides which desktop the - * pages are talking to, and the sheet rebinds the same object when it opens on - * another one. Everything else — gating, the write, the read-back, the stale - * result fence — belongs to the controller. - */ -@ObservedV2 -export class DeviceModelDefaultsSheetState implements RemoteModelDefaultsClient { - /** The controller's latest snapshot; the only thing the pages render. */ - @Trace state: RemoteModelDefaultsState = emptyModelDefaultsState(); - /** The role a write is running for, or the one that just failed. */ - @Trace pendingRole: RemoteModelDefaultsRole | '' = ''; - /** The value that write carries; `null` is a value, not an absence. */ - @Trace pendingModelId: string | null = null; - /** True while a confirmed write's result line is on screen. */ - @Trace feedbackVisible: boolean = false; - - private readonly feedbackDurationMs: number; - private readonly controller: RemoteModelDefaultsController; - private target?: DeviceModelDefaultsRequestPath; - private feedbackTimer: number = 0; - - constructor(feedbackDurationMs: number = MODEL_DEFAULTS_FEEDBACK_MS) { - this.feedbackDurationMs = feedbackDurationMs; - this.controller = new RemoteModelDefaultsController(this, { - onStateChanged: (state: RemoteModelDefaultsState): void => { - this.state = state; - } - }); - this.state = this.controller.getState(); - } - - /** Points the pages at one desktop's request path. */ - bind(target: DeviceModelDefaultsRequestPath): void { - this.target = target; - } - - /** Re-gates the pages; true when what is on screen has to be read again. */ - setGate(gate: RemoteModelDefaultsGate): boolean { - return this.controller.setGate(gate); - } - - /** Reads once per gate: a page that opens twice does not read twice. */ - async ensureLoaded(): Promise { - if (this.state.loaded || this.state.loading) { - return; - } - await this.controller.load(); - } - - async load(): Promise { - await this.controller.load(); - } - - /** - * Sets one role and waits for the controller's read-back. - * - * The feedback line is raised only after that read returns, and only when a - * write really happened: selecting the value a role already holds writes - * nothing, and an unavailable gate writes nothing either, so neither may claim - * the device was updated. What the line says is derived from the read-back - * value at render time — the desktop may have repaired the selection, and the - * intent is not the result. - */ - async selectRole(role: RemoteModelDefaultsRole, modelId: string | null): Promise { - // One write at a time, and none while the read that answers the page is still - // out: either one would leave the intent recorded here describing a value no - // request ever carried. - if (this.state.busy || this.state.loading) { - return; - } - const requested = modelId === null ? '' : modelId; - const current = ModelRoleCandidatesPolicy.selectedValue(this.state.roles, role); - this.pendingRole = role; - this.pendingModelId = modelId; - this.clearFeedback(); - if (current === requested) { - return; - } - await this.controller.applyRoleSelection(role, modelId); - if (this.state.available && this.state.error.length === 0) { - this.showFeedback(); - } - } - - /** - * Repeats whatever failed: the write that was rejected, or the read that failed - * after an accepted write. The failure the controller reported decides which, - * because a retry of the wrong one would ask the user to re-answer a question - * they already answered. - */ - async retry(): Promise { - const role = this.pendingRole; - if (this.state.failure === 'write' && role !== '') { - const modelId = this.pendingModelId; - await this.controller.applyRoleSelection(role, modelId); - if (this.state.available && this.state.error.length === 0) { - this.showFeedback(); - } - return; - } - this.clearFeedback(); - await this.controller.load(); - } - - /** Clears the pages while the sheet is closed. */ - reset(): void { - this.clearFeedback(); - this.pendingRole = ''; - this.pendingModelId = null; - this.controller.reset(); - } - - getModelCatalog(sessionId?: string): Promise { - const target = this.target; - if (!target) { - return Promise.reject(new Error('The device model pages have no client bound.')); - } - return target.getModelCatalog(sessionId); - } - - setModelDefaults( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise { - const target = this.target; - if (!target) { - return Promise.reject(new Error('The device model pages have no client bound.')); - } - return target.setModelDefaults(primary, fast, imageUnderstanding); - } - - private showFeedback(): void { - this.feedbackVisible = true; - this.cancelTimer(); - this.feedbackTimer = setTimeout(() => { - this.feedbackTimer = 0; - this.feedbackVisible = false; - }, this.feedbackDurationMs); - } - - private clearFeedback(): void { - this.cancelTimer(); - this.feedbackVisible = false; - } - - private cancelTimer(): void { - if (this.feedbackTimer !== 0) { - clearTimeout(this.feedbackTimer); - this.feedbackTimer = 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/FilePreviewState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/FilePreviewState.ets deleted file mode 100644 index 7d51e1a0a7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/FilePreviewState.ets +++ /dev/null @@ -1,107 +0,0 @@ -import { FilePreviewTarget } from '../../model/FilePreviewTarget'; - -export enum FilePreviewPhase { - Idle = 'idle', - Loading = 'loading', - Ready = 'ready', - Unsupported = 'unsupported', - Error = 'error' -} - -export enum FilePreviewRendererKind { - Text = 'text', - Markdown = 'markdown', - Image = 'image', - Unsupported = 'unsupported' -} - -@ObservedV2 -export class FilePreviewState { - @Trace visible: boolean = false; - @Trace phase: FilePreviewPhase = FilePreviewPhase.Idle; - @Trace target: FilePreviewTarget = FilePreviewTarget.empty(); - @Trace fileName: string = ''; - @Trace mimeType: string = ''; - @Trace fileSize: number = 0; - @Trace rendererKind: FilePreviewRendererKind = FilePreviewRendererKind.Unsupported; - @Trace textContent: string = ''; - @Trace contentBase64: string = ''; - @Trace truncated: boolean = false; - @Trace loadedBytes: number = 0; - @Trace errorText: string = ''; - @Trace errorRetryable: boolean = true; - @Trace requestVersion: number = 0; - scrollOffsetX: number = 0; - scrollOffsetY: number = 0; - hasRecordedScroll: boolean = false; - - begin(target: FilePreviewTarget): number { - this.requestVersion += 1; - this.visible = true; - this.phase = FilePreviewPhase.Loading; - this.target = target; - this.fileName = target.displayName; - this.mimeType = ''; - this.fileSize = 0; - this.rendererKind = FilePreviewRendererKind.Unsupported; - this.textContent = ''; - this.contentBase64 = ''; - this.truncated = false; - this.loadedBytes = 0; - this.errorText = ''; - this.errorRetryable = true; - this.resetScroll(); - return this.requestVersion; - } - - close(): void { - this.requestVersion += 1; - this.visible = false; - this.phase = FilePreviewPhase.Idle; - this.target = FilePreviewTarget.empty(); - this.fileName = ''; - this.mimeType = ''; - this.fileSize = 0; - this.rendererKind = FilePreviewRendererKind.Unsupported; - this.textContent = ''; - this.contentBase64 = ''; - this.truncated = false; - this.loadedBytes = 0; - this.errorText = ''; - this.errorRetryable = true; - this.resetScroll(); - } - - isCurrent(version: number, target: FilePreviewTarget): boolean { - return this.visible && this.requestVersion === version && - this.target.remotePath === target.remotePath && - this.target.sessionId === target.sessionId && - this.target.controlTargetEpoch === target.controlTargetEpoch; - } - - recordScroll(xOffset: number, yOffset: number): void { - this.scrollOffsetX = Math.max(0, xOffset); - this.scrollOffsetY = Math.max(0, yOffset); - this.hasRecordedScroll = true; - } - - initialScrollX(): number { - return this.hasRecordedScroll ? this.scrollOffsetX : 0; - } - - initialScrollY(lineHeight: number = 19, contextLines: number = 2): number { - if (this.hasRecordedScroll) { - return this.scrollOffsetY; - } - if (this.target.lineStart <= 1) { - return 0; - } - return Math.max(0, this.target.lineStart - 1 - contextLines) * lineHeight; - } - - private resetScroll(): void { - this.scrollOffsetX = 0; - this.scrollOffsetY = 0; - this.hasRecordedScroll = false; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/GeneralChatPageState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/GeneralChatPageState.ets deleted file mode 100644 index a4e6d65e13..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/GeneralChatPageState.ets +++ /dev/null @@ -1,148 +0,0 @@ -import { - ChatMessage, - RemoteModelCatalog, - RemoteSession, - SelectedImageAttachment, - SessionSummary -} from '../../model/RemoteModels'; -import { ChatTimelineItem, ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { GeneralChatServiceState } from '../../services/general-chat/GeneralChatServiceState'; -import { ConversationCoreState } from './ConversationCoreState'; - -@ObservedV2 -export class GeneralChatPageState { - @Trace conversation: ConversationCoreState = new ConversationCoreState('chat'); - @Trace serviceState: GeneralChatServiceState = GeneralChatServiceState.Unconfigured; - @Trace apiUrl: string = ''; - @Trace modelName: string = ''; - @Trace hasApiKey: boolean = false; - - get activeSession(): SessionSummary { return this.conversation.activeSession; } - get sessions(): RemoteSession[] { return this.conversation.sessions; } - get persistedMessages(): ChatMessage[] { return this.conversation.persistedMessages; } - get optimisticMessages(): ChatMessage[] { return this.conversation.optimisticMessages; } - get activeTurnMessage(): ChatMessage { return this.conversation.activeTurnMessage; } - get hasMoreMessages(): boolean { return this.conversation.hasMoreMessages; } - get timelineItems(): ObservableChatTimelineItem[] { return this.conversation.timelineItems; } - get timelineRevision(): number { return this.conversation.timelineRevision; } - get isBusy(): boolean { return this.conversation.isBusy; } - get modelCatalog(): RemoteModelCatalog { return this.conversation.modelCatalog; } - get selectedModelId(): string { return this.conversation.selectedModelId; } - get statusText(): string { return this.conversation.statusText; } - get chatInput(): string { return this.conversation.chatInput; } - get selectedImages(): SelectedImageAttachment[] { return this.conversation.selectedImages; } - get isVoiceListening(): boolean { return this.conversation.isVoiceListening; } - - setActiveSession(session: SessionSummary): void { - this.conversation.setActiveSession(session); - } - - clearActiveSession(): void { - this.conversation.clearActiveSession(); - } - - setSessions(sessions: RemoteSession[]): void { - this.conversation.setSessions(sessions); - } - - setTimelineProjection( - persistedMessages: ChatMessage[], - optimisticMessages: ChatMessage[], - activeTurnMessage: ChatMessage, - hasMoreMessages: boolean, - timelineItems: ChatTimelineItem[] - ): void { - this.conversation.setTimelineProjection( - persistedMessages, - optimisticMessages, - activeTurnMessage, - hasMoreMessages, - timelineItems - ); - } - - clearTimeline(): void { - this.conversation.clearTimeline(); - } - - setBusy(isBusy: boolean): void { - this.conversation.setBusy(isBusy); - } - - setConfiguration( - apiUrl: string, - modelName: string, - hasApiKey: boolean, - serviceState: GeneralChatServiceState - ): void { - this.apiUrl = apiUrl; - this.modelName = modelName; - this.hasApiKey = hasApiKey; - this.serviceState = serviceState; - } - - setServiceState(serviceState: GeneralChatServiceState): void { - this.serviceState = serviceState; - } - - setModelCatalog(modelCatalog: RemoteModelCatalog, selectedModelId: string): void { - this.conversation.setModelCatalog(modelCatalog, selectedModelId); - } - - setStatus(statusText: string): void { - this.conversation.setStatusText(statusText); - } - - setChatInput(chatInput: string): void { - this.conversation.setChatInput(chatInput); - } - - setSelectedImages(selectedImages: SelectedImageAttachment[]): void { - this.conversation.setSelectedImages(selectedImages); - } - - addSelectedImages(selectedImages: SelectedImageAttachment[]): void { - this.conversation.addSelectedImages(selectedImages); - } - - removeSelectedImage(imageId: string): void { - this.conversation.removeSelectedImage(imageId); - } - - clearComposer(): void { - this.conversation.clearComposer(); - } - - setVoiceListening(isVoiceListening: boolean): void { - this.conversation.setVoiceListening(isVoiceListening); - } - - recentSessions(): RemoteSession[] { - const recent = this.conversation.sessions.slice(); - recent.sort((first: RemoteSession, second: RemoteSession) => { - if ((first.pinned === true) !== (second.pinned === true)) { - return first.pinned === true ? -1 : 1; - } - return this.sessionTimeValue(second.updatedAt) - this.sessionTimeValue(first.updatedAt); - }); - return recent; - } - - pinnedSessionId(): string { - const pinned = this.conversation.sessions.find((session: RemoteSession) => session.pinned === true); - return pinned ? pinned.id : ''; - } - - hasRunningActiveTurn(): boolean { - return this.conversation.hasRunningActiveTurn(); - } - - latestUserMessageText(): string { - return this.conversation.latestUserMessageText(); - } - - private sessionTimeValue(value: string): number { - const parsed = new Date(value).getTime(); - return Number.isNaN(parsed) ? 0 : parsed; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/MiniAppState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/MiniAppState.ets deleted file mode 100644 index c5bba426ab..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/MiniAppState.ets +++ /dev/null @@ -1,13 +0,0 @@ -import { MiniAppSummary } from '../../model/MiniAppModels'; - -@ObservedV2 -export class MiniAppState { - @Trace visible: boolean = false; - @Trace loading: boolean = false; - @Trace error: string = ''; - @Trace apps: MiniAppSummary[] = []; - @Trace appId: string = ''; - @Trace name: string = ''; - @Trace document: string = ''; - @Trace revision: number = 0; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets deleted file mode 100644 index bec9860e8b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets +++ /dev/null @@ -1,579 +0,0 @@ -import { MessageQueueState } from '../../model/MessageQueue'; -import { TimeFormat } from '../../services/TimeFormat'; -import { InteractionMailboxState } from '../../model/InteractionMailbox'; -import { WorkspaceToolsState } from './WorkspaceToolsState'; -import { - SavedRuntimeConnection, - AssistantEntry, - ChatMessage, - RecentWorkspaceEntry, - RemoteModelCatalog, - RemoteSession, - RemoteWorkspaceIdentity, - SelectedImageAttachment, - SessionSummary -} from '../../model/RemoteModels'; -import { ChatTimelineItem, ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ComposerSubmission } from '../../model/ComposerSubmission'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { ConversationCoreState } from './ConversationCoreState'; -import { CommandPaletteState } from './CommandPaletteState'; - -/** - * Observable projection for the Remote home page. - * Connection, persistence and transport ownership stay outside this object. - */ -@ObservedV2 -export class RemotePageState { - @Trace messageQueue: MessageQueueState = new MessageQueueState(); - @Trace interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); - readonly workspaceTools: WorkspaceToolsState = new WorkspaceToolsState(); - /** - * The composer command palette. Session-scoped, so it is dropped with the - * conversation it belongs to rather than outliving it. - */ - readonly commandPalette: CommandPaletteState = new CommandPaletteState(); - @Trace conversation: ConversationCoreState = new ConversationCoreState('code'); - @Trace desktopName: string = ''; - @Trace desktopId: string = ''; - @Trace remoteUrl: string = ''; - @Trace userId: string = ''; - @Trace requiresAccountAuth: boolean = false; - @Trace accountUsername: string = ''; - @Trace accountAvatarUrl: string = ''; - @Trace accountUserId: string = ''; - @Trace authenticatedUserId: string = ''; - @Trace hostCapabilities: string[] = []; - @Trace controlTargetType: string = 'none'; - @Trace controlTargetDeviceId: string = ''; - @Trace controlTargetDeviceName: string = ''; - @Trace connectionState: string = 'idle'; - @Trace connectionFailureKind: string = ''; - @Trace isLoadingHome: boolean = false; - @Trace showRemoteUrlInput: boolean = false; - @Trace workspaceName: string = ''; - @Trace workspacePath: string = ''; - /** Stable record ID of the active workspace; empty for pre-ID hosts. */ - @Trace workspaceId: string = ''; - @Trace workspaceConnectionId: string = ''; - @Trace workspaceSshHost: string = ''; - @Trace workspaceBranch: string = ''; - @Trace workspaceKind: string = 'normal'; - @Trace assistantId: string = ''; - @Trace savedConnections: SavedRuntimeConnection[] = []; - @Trace savedConnectionsTargetId: string = ''; - @Trace recentWorkspaces: RecentWorkspaceEntry[] = []; - @Trace assistants: AssistantEntry[] = []; - @Trace showWorkspacePicker: boolean = false; - @Trace showAssistantPicker: boolean = false; - @Trace downloadingFilePath: string = ''; - @Trace downloadedFilePath: string = ''; - @Trace fileDownloadStatus: string = ''; - @Trace sessionQuery: string = ''; - @Trace sessionFilter: string = 'all'; - @Trace hasMoreSessions: boolean = false; - @Trace isLoadingSessions: boolean = false; - @Trace isLoadingConversation: boolean = false; - // Separate from isLoadingConversation, which means the session itself is not - // known yet and so blanks the header. Here the session is known and named; - // only its transcript is still on the way, and the header should keep saying - // which conversation the pane is about while the body says it is filling. - @Trace isLoadingTranscript: boolean = false; - @Trace pendingSessionId: string = ''; - @Trace isConversationDismissed: boolean = false; - @Trace sessionErrorText: string = ''; - /** - * The system hint row a successful rollback leaves in the transcript. - * - * It belongs to the page rather than to the pane that sent the command because - * the host's answer arrives after the staged preview is already gone: the pane - * is idle by then, and what it has to show is a fact about the session. It - * stays until the session changes or the conversation moves on, since the host - * has no such row of its own to resend. - */ - @Trace rollbackNotice: string = ''; - /** - * The host outcome of a rollback this client asked for, in the reducer's own - * vocabulary (`SessionRollbackEventType`), paired with a monotonic sequence. - * - * The pane consumes it by sequence rather than by value, because the same - * failure twice is two outcomes and a value comparison would drop the second. - * It covers the case the staged preview cannot: confirm and send leave staging - * before the host answers, so a refusal arrives while the pane is already idle - * and must still repair the transcript. - */ - @Trace rollbackOutcome: string = ''; - @Trace rollbackOutcomeSeq: number = 0; - /** Changes even when navigation leaves a session and later returns to it. */ - @Trace sessionContextRevision: number = 0; - // Deliberately untraced: the memo behind visibleSessions(), not state anything - // renders. Tracing it would make reading the list a write to the list. - private visibleSessionsCache: RemoteSession[] = []; - private visibleSessionsSource: RemoteSession[] | undefined = undefined; - private visibleSessionsQuery: string = ' '; - get activeSession(): SessionSummary { return this.conversation.activeSession; } - get sessions(): RemoteSession[] { return this.conversation.sessions; } - get persistedMessages(): ChatMessage[] { return this.conversation.persistedMessages; } - get optimisticMessages(): ChatMessage[] { return this.conversation.optimisticMessages; } - get activeTurnMessage(): ChatMessage { return this.conversation.activeTurnMessage; } - get hasMoreMessages(): boolean { return this.conversation.hasMoreMessages; } - get timelineItems(): ObservableChatTimelineItem[] { return this.conversation.timelineItems; } - get timelineRevision(): number { return this.conversation.timelineRevision; } - get isBusy(): boolean { return this.conversation.isBusy; } - get modelCatalog(): RemoteModelCatalog { return this.conversation.modelCatalog; } - get selectedModelId(): string { return this.conversation.selectedModelId; } - get statusText(): string { return this.conversation.statusText; } - get chatInput(): string { return this.conversation.chatInput; } - get selectedImages(): SelectedImageAttachment[] { return this.conversation.selectedImages; } - get isVoiceListening(): boolean { return this.conversation.isVoiceListening; } - - setQuery(query: string): void { - this.sessionQuery = query; - } - - setFilter(filter: string): void { - this.sessionFilter = filter; - } - - setDesktopName(desktopName: string): void { - this.desktopName = desktopName; - } - - setDesktopIdentity(desktopName: string, desktopId: string): void { - this.desktopName = desktopName; - this.desktopId = desktopId; - } - - setPairingInput(remoteUrl: string, userId: string, showRemoteUrlInput: boolean): void { - this.remoteUrl = remoteUrl; - this.userId = userId; - this.showRemoteUrlInput = showRemoteUrlInput; - } - - setAccountPairing(requiresAccountAuth: boolean, accountUsername: string): void { - this.requiresAccountAuth = requiresAccountAuth; - this.accountUsername = accountUsername; - } - - setAccountAvatarUrl(avatarUrl: string): void { - this.accountAvatarUrl = avatarUrl; - } - - setAccountUsername(accountUsername: string): void { - this.accountUsername = accountUsername; - } - - setAccountUserId(accountUserId: string): void { - this.accountUserId = accountUserId; - } - - setControlTarget(type: string, deviceId: string, deviceName: string): void { - if (deviceId !== this.controlTargetDeviceId) { - this.workspaceTools.visible = false; this.workspaceTools.busy = false; - this.workspaceTools.entries = []; this.workspaceTools.content = ''; - this.workspaceTools.output = ''; this.workspaceTools.terminalId = ''; - } - this.controlTargetType = type; - this.controlTargetDeviceId = deviceId; - this.controlTargetDeviceName = deviceName; - } - - clearControlTarget(): void { - this.setControlTarget('none', '', ''); - } - - setRemoteUrl(remoteUrl: string): void { - this.remoteUrl = remoteUrl; - } - - setUserId(userId: string): void { - this.userId = userId; - } - - setAuthenticatedUserId(authenticatedUserId: string): void { - this.authenticatedUserId = authenticatedUserId; - } - - setHostCapabilities(capabilities: string[]): void { - this.hostCapabilities = capabilities.slice(); - } - - supportsHostCapability(capability: string): boolean { - return this.hostCapabilities.indexOf(capability) >= 0; - } - - setStatusText(statusText: string): void { - this.conversation.setStatusText(statusText); - } - - setConnectionState(connectionState: string): void { - this.connectionState = connectionState; - } - - setConnectionFailureKind(connectionFailureKind: string): void { - this.connectionFailureKind = connectionFailureKind; - } - - setBusy(isBusy: boolean): void { - this.conversation.setBusy(isBusy); - } - - setLoadingHome(isLoadingHome: boolean): void { - this.isLoadingHome = isLoadingHome; - } - - setRemoteUrlInputVisible(visible: boolean): void { - this.showRemoteUrlInput = visible; - } - - setWorkspace( - workspaceName: string, - workspacePath: string, - assistantId: string, - workspaceBranch: string = '', - workspaceKind: string = 'normal', - remoteConnectionId: string = '', - remoteSshHost: string = '', - workspaceId: string = '' - ): void { - this.workspaceName = workspaceName; - this.workspacePath = workspacePath; - this.workspaceConnectionId = remoteConnectionId; - this.workspaceSshHost = remoteSshHost; - this.workspaceId = workspaceId; - this.assistantId = assistantId; - this.workspaceBranch = workspaceBranch; - this.workspaceKind = workspaceKind; - } - - /** - * The active workspace as a reference. Empty strings from the page state - * become absent fields so the identity compares like catalog rows do. - */ - workspaceIdentity(): RemoteWorkspaceIdentity { - return { - workspaceId: this.workspaceId.length > 0 ? this.workspaceId : undefined, - path: this.workspacePath, - remoteConnectionId: this.workspaceConnectionId.length > 0 ? this.workspaceConnectionId : undefined, - remoteSshHost: this.workspaceSshHost.length > 0 ? this.workspaceSshHost : undefined - }; - } - - setRecentWorkspaces(recentWorkspaces: RecentWorkspaceEntry[]): void { - this.recentWorkspaces = recentWorkspaces.slice(); - } - - setAssistants(assistants: AssistantEntry[]): void { - this.assistants = assistants.slice(); - } - - setWorkspacePickerVisible(visible: boolean): void { - this.showWorkspacePicker = visible; - } - - setAssistantPickerVisible(visible: boolean): void { - this.showAssistantPicker = visible; - } - - closePickers(): void { - this.showWorkspacePicker = false; - this.showAssistantPicker = false; - } - - setSessions(sessions: RemoteSession[], hasMore: boolean): void { - this.conversation.setSessions(sessions); - this.hasMoreSessions = hasMore; - this.sessionErrorText = ''; - } - - setActiveSession(session: SessionSummary): void { - if (this.conversation.activeSession.sessionId !== session.sessionId) { - this.sessionContextRevision += 1; - this.interactionMailbox = new InteractionMailboxState(); - this.messageQueue = new MessageQueueState(); - this.clearRollbackNotice(); - this.clearRollbackOutcome(); - // A skill catalog, a usage report and a lit goal chip all belong to the - // session that produced them. Carrying them into another conversation - // would show one session's numbers over another's messages. - this.commandPalette.reset(); - } - this.conversation.setActiveSession(session); - } - - clearActiveSession(): void { - this.sessionContextRevision += 1; - this.clearRollbackNotice(); - this.clearRollbackOutcome(); - this.interactionMailbox = new InteractionMailboxState(); - this.messageQueue = new MessageQueueState(); - this.commandPalette.reset(); - this.conversation.clearActiveSession(); - this.isLoadingConversation = false; - this.isLoadingTranscript = false; - this.pendingSessionId = ''; - this.isConversationDismissed = false; - this.setModelCatalog(RemoteUiState.emptyModelCatalog(), ''); - } - - setTimelineProjection( - persistedMessages: ChatMessage[], - optimisticMessages: ChatMessage[], - activeTurnMessage: ChatMessage, - hasMoreMessages: boolean, - timelineItems: ChatTimelineItem[] - ): void { - this.conversation.setTimelineProjection( - persistedMessages, - optimisticMessages, - activeTurnMessage, - hasMoreMessages, - timelineItems - ); - } - - setHasMoreMessages(hasMoreMessages: boolean): void { - this.conversation.setHasMoreMessages(hasMoreMessages); - } - - setHistoryLoadState(loading: boolean, failed: boolean): void { - this.conversation.historyLoading = loading; - this.conversation.historyFailed = failed; - } - - clearTimeline(): void { - this.conversation.clearTimeline(); - } - - setModelCatalog(modelCatalog: RemoteModelCatalog, selectedModelId: string): void { - this.conversation.setModelCatalog(modelCatalog, selectedModelId); - } - - setDownloadStatus(downloadingFilePath: string, downloadedFilePath: string, fileDownloadStatus: string): void { - this.downloadingFilePath = downloadingFilePath; - this.downloadedFilePath = downloadedFilePath; - this.fileDownloadStatus = fileDownloadStatus; - } - - clearDownloadingFilePath(): void { - this.downloadingFilePath = ''; - } - - clearDownloadStatus(): void { - this.downloadingFilePath = ''; - this.downloadedFilePath = ''; - this.fileDownloadStatus = ''; - } - - setChatInput(chatInput: string): void { - this.conversation.setChatInput(chatInput); - } - - /** Replace the rollback hint row; it describes the history as it now stands. */ - setRollbackNotice(notice: string): void { - this.rollbackNotice = notice; - } - - /** The conversation moved on, so the rolled-back history is no longer news. */ - clearRollbackNotice(): void { - this.rollbackNotice = ''; - } - - /** - * Report one host outcome to the pane, in the reducer's vocabulary. - * - * The sequence is bumped whether or not the value changed, so a repeated - * failure is a second outcome rather than a state that already looked like it. - */ - reportRollbackOutcome(event: string): void { - this.rollbackOutcome = event; - this.rollbackOutcomeSeq += 1; - } - - clearRollbackOutcome(): void { - this.rollbackOutcome = ''; - this.rollbackOutcomeSeq = 0; - } - - setSelectedImages(selectedImages: SelectedImageAttachment[]): void { - this.conversation.setSelectedImages(selectedImages); - } - - addSelectedImages(selectedImages: SelectedImageAttachment[]): void { - this.conversation.addSelectedImages(selectedImages); - } - - removeSelectedImage(imageId: string): void { - this.conversation.removeSelectedImage(imageId); - } - - clearComposer(): void { - this.conversation.clearComposer(); - } - - /** - * Draft ownership for a send, including the palette's two local picks. - * - * The skill token and the lit goal chip are the composer's local state rather - * than text in the field, so each travels with the draft's own ownership rules: - * consumed by the commit the host accepted, and put back by the rollback that - * it did not. A goal chip left lit over a sent `/goal` would say the objective - * is still missing after it just went out. - */ - prepareComposerSubmission( - sessionId: string, - text: string, - images: SelectedImageAttachment[] - ): ComposerSubmission { - const inner = this.conversation.prepareComposerSubmission(sessionId, text, images); - const skillId = this.commandPalette.skillId; - const skillLabel = this.commandPalette.skillLabel; - const goalPending = this.commandPalette.goalPending; - return { - commit: (): void => { - const hadSkill = this.commandPalette.skillId.length > 0; - inner.commit(); - if (hadSkill) { - this.commandPalette.clearSkill(); - } - if (goalPending) { - this.commandPalette.setGoalPending(false); - } - }, - rollback: (): void => { - inner.rollback(); - if (skillId.length > 0 && this.commandPalette.skillId.length === 0) { - this.commandPalette.setSkill(skillId, skillLabel); - } - if (goalPending && !this.commandPalette.goalPending) { - this.commandPalette.setGoalPending(true); - } - } - }; - } - - setVoiceListening(isVoiceListening: boolean): void { - this.conversation.setVoiceListening(isVoiceListening); - } - - setLoading(loading: boolean): void { - this.isLoadingSessions = loading; - } - - setConversationLoading(loading: boolean): void { - this.isLoadingConversation = loading; - } - - setTranscriptLoading(loading: boolean): void { - this.isLoadingTranscript = loading; - } - - setPendingSessionId(sessionId: string): void { - this.pendingSessionId = sessionId; - } - - setConversationDismissed(dismissed: boolean): void { - this.isConversationDismissed = dismissed; - } - - setError(errorText: string): void { - this.sessionErrorText = errorText; - this.isLoadingSessions = false; - } - - clear(): void { - this.conversation.setSessions([]); - this.hasMoreSessions = false; - this.isLoadingSessions = false; - this.isLoadingConversation = false; - this.isLoadingTranscript = false; - this.pendingSessionId = ''; - this.isConversationDismissed = false; - this.isLoadingHome = false; - this.sessionErrorText = ''; - this.hostCapabilities = []; - } - - /** Clears every conversation-scoped value when its remote identity ends. */ - resetConversationContext(): void { - this.sessionContextRevision += 1; - this.interactionMailbox = new InteractionMailboxState(); - this.messageQueue = new MessageQueueState(); - this.commandPalette.reset(); - this.conversation.reset(); - this.hasMoreSessions = false; - this.isLoadingSessions = false; - this.isLoadingConversation = false; - this.isLoadingTranscript = false; - this.pendingSessionId = ''; - this.isConversationDismissed = false; - this.isLoadingHome = false; - this.sessionErrorText = ''; - this.hostCapabilities = []; - this.clearDownloadStatus(); - // Both rollback traces describe one session's history: the hint row counts - // what that rollback withdrew and the outcome sequence orders its answers, so - // neither means anything once the session they belong to is gone. - this.clearRollbackNotice(); - this.clearRollbackOutcome(); - } - - clearWorkspaceActions(): void { - this.recentWorkspaces = []; - this.assistants = []; - this.closePickers(); - } - - /** - * The sessions the sidebar may show, as a stable array. - * - * This is read straight into a `@Param`, so returning a fresh array each call - * marked the session list dirty on every rebuild of its parent — including - * the rebuild that a selection change causes, which is the one case where - * nothing about the list has moved. Handing back the same instance until the - * source or the query changes lets the list keep what it already computed. - */ - visibleSessions(): RemoteSession[] { - const source = this.conversation.sessions; - const query = this.sessionQuery.trim().toLowerCase(); - if (source === this.visibleSessionsSource && query === this.visibleSessionsQuery) { - return this.visibleSessionsCache; - } - this.visibleSessionsSource = source; - this.visibleSessionsQuery = query; - this.visibleSessionsCache = source.filter((item: RemoteSession) => { - if (item.id.length === 0 || item.status === 'archived') { - return false; - } - return query.length === 0 || item.title.toLowerCase().indexOf(query) >= 0; - }); - return this.visibleSessionsCache; - } - - private recentHomeSource: RemoteSession[] | undefined = undefined; - private recentHomeCache: RemoteSession[] = []; - - recentHomeSessions(): RemoteSession[] { - const source = this.conversation.sessions; - if (this.recentHomeSource === source) return this.recentHomeCache; - this.recentHomeSource = source; - this.recentHomeCache = source.filter((session: RemoteSession): boolean => - session.id.trim().length > 0 && session.status !== 'archived') - .sort((left: RemoteSession, right: RemoteSession): number => - this.recentSessionTime(right) - this.recentSessionTime(left)) - .filter((session: RemoteSession, index: number, rows: RemoteSession[]): boolean => - rows.findIndex((row: RemoteSession): boolean => row.id === session.id) === index).slice(0, 3); - return this.recentHomeCache; - } - - private recentSessionTime(session: RemoteSession): number { - const updated = TimeFormat.timestampMs(session.updatedAt); - if (Number.isFinite(updated) && updated > 0) return updated; - const created = TimeFormat.timestampMs(session.createdAt); - return Number.isFinite(created) ? created : 0; - } - - hasRunningActiveTurn(): boolean { - return this.conversation.hasRunningActiveTurn(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SettingsSheetState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SettingsSheetState.ets deleted file mode 100644 index 4ed2410bee..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SettingsSheetState.ets +++ /dev/null @@ -1,81 +0,0 @@ -import { DeviceModelDefaultsSheetState } from './DeviceModelDefaultsSheetState'; - -/** - * Settings sheet navigation and editor drafts live here so a fold-driven - * rebuild does not send the user back to the home list or wipe in-progress - * local-model fields. - * - * It is also where the device model pages' controller lives. Those pages are two - * levels of one workflow over the connected desktop — the settings page and the - * role picker it pushes — so the controller outlives either of them and belongs - * to the sheet state the sheet hands to both. - */ -@ObservedV2 -export class SettingsSheetState { - @Trace page: string = 'main'; - /** - * The role the second-level picker edits. Empty while the picker is closed, - * so a page rebuilt from the wrong level cannot open someone else's list. - */ - @Trace pickRole: string = ''; - /** Device model role defaults for the connected desktop; reset when the sheet closes. */ - readonly deviceModels: DeviceModelDefaultsSheetState = new DeviceModelDefaultsSheetState(); - @Trace savedGeneralChatApiUrl: string = ''; - @Trace savedGeneralChatModelName: string = ''; - @Trace savedGeneralChatHasApiKey: boolean = false; - @Trace draftApiUrl: string = ''; - @Trace draftApiKey: string = ''; - @Trace draftModelName: string = ''; - @Trace draftClearApiKey: boolean = false; - @Trace editorDraftHydrated: boolean = false; - - setPage(page: string): void { - if (page !== 'modelPick') { - this.pickRole = ''; - } - this.page = page; - } - - /** - * Pushes the role picker: the second level of the sheet's own page stack - * (`main` → `deviceModels` → `modelPick`). - */ - openModelPick(role: string): void { - this.pickRole = role; - this.page = 'modelPick'; - } - - /** Returns one level: the picker goes back to the settings page that pushed it. */ - backFromModelPick(): void { - this.pickRole = ''; - this.page = 'deviceModels'; - } - - syncSaved(apiUrl: string, modelName: string, hasApiKey: boolean): void { - this.savedGeneralChatApiUrl = apiUrl; - this.savedGeneralChatModelName = modelName; - this.savedGeneralChatHasApiKey = hasApiKey; - } - - hydrateEditorDraft(apiUrl: string, modelName: string): void { - if (this.editorDraftHydrated) { - return; - } - this.draftApiUrl = apiUrl; - this.draftModelName = modelName; - this.draftApiKey = ''; - this.draftClearApiKey = false; - this.editorDraftHydrated = true; - } - - resetOnClose(): void { - this.page = 'main'; - this.pickRole = ''; - this.deviceModels.reset(); - this.draftApiUrl = ''; - this.draftApiKey = ''; - this.draftModelName = ''; - this.draftClearApiKey = false; - this.editorDraftHydrated = false; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SubagentBranchExpansionState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SubagentBranchExpansionState.ets deleted file mode 100644 index 8e1153d6ae..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/SubagentBranchExpansionState.ets +++ /dev/null @@ -1,83 +0,0 @@ -/** - * One delegation card's disclosure, keyed by the branch it belongs to. - * - * `@Trace` is what the card reads: a component that renders `expanded` is - * repainted when it changes, wherever the change came from. - */ -@ObservedV2 -export class SubagentBranchDisclosure { - readonly key: string; - @Trace expanded: boolean = false; - - constructor(key: string) { - this.key = key; - } -} - -/** - * Which delegation cards the reader has opened, keyed by branch identity. - * - * The card cannot own this itself. Its row is rebuilt whenever the turn it sits - * in is republished — a launch settling reorders the structured groups of the - * turn, and the row's keyed subtree is rebuilt with it — and a card that kept - * its disclosure in its own `@Local` state collapsed under the reader at exactly - * that moment. Hoisting the boolean to owner state that outlives the row keeps - * what the reader opened open, which is the same reason the sidebar's workspace - * disclosure lives in `DeviceDirectoryState` rather than in its row — and it is - * why this container is observed the same way that one is: `@Trace` on the - * collection as well as on the entry, so a card that reads a key it has not - * looked up before is still repainted when that key's entry arrives. - * - * The key is the branch, not the view path or the row: a card keeps its - * disclosure while its worker streams, while the transcript around it changes, - * and while the list recycles its row — until the session's state itself is - * replaced. Disclosure deliberately does not survive an app restart; that is a - * separate promise nothing here makes. - */ -@ObservedV2 -export class SubagentBranchExpansionState { - @Trace disclosures: SubagentBranchDisclosure[] = []; - - isExpanded(key: string): boolean { - const found = this.find(key); - return found !== undefined && found.expanded; - } - - /** - * Which branches the reader has open, in the order they were opened. - * - * Disclosure is the reader's, and this is the only reading of it that outlives - * a row: it is what a preview states and what a test asserts, in place of - * looking for the pixels a card happens to draw. - */ - expandedKeys(): string[] { - return this.disclosures - .filter((entry: SubagentBranchDisclosure): boolean => entry.expanded) - .map((entry: SubagentBranchDisclosure): string => entry.key); - } - - setExpanded(key: string, expanded: boolean): void { - if (key.length === 0) return; - this.ensure(key).expanded = expanded; - } - - /** Flips one card and answers what it now is, so the caller can act on opening. */ - toggle(key: string): boolean { - if (key.length === 0) return false; - const disclosure = this.ensure(key); - disclosure.expanded = !disclosure.expanded; - return disclosure.expanded; - } - - private find(key: string): SubagentBranchDisclosure | undefined { - return this.disclosures.find((entry: SubagentBranchDisclosure): boolean => entry.key === key); - } - - private ensure(key: string): SubagentBranchDisclosure { - const found = this.find(key); - if (found !== undefined) return found; - const created = new SubagentBranchDisclosure(key); - this.disclosures.push(created); - return created; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WatchProvisionState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WatchProvisionState.ets deleted file mode 100644 index a186e538b6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WatchProvisionState.ets +++ /dev/null @@ -1,66 +0,0 @@ -import { WatchProvisionProtocol } from '../../services/WatchProvisionProtocol'; -import { WatchProvisionDisplay } from '../../services/WatchProvisionDisplay'; - -export enum WatchProvisionPhase { - /** No watch is waiting; the card is not on screen. */ - Hidden = 'hidden', - /** A request arrived and its owner has not answered yet. */ - Asking = 'asking', - /** The relay needs a normal account login to add this watch. */ - Password = 'password', - /** Approved; the phone is obtaining and handing off the credential. */ - Working = 'working', - Done = 'done', - Failed = 'failed' -} - -@ObservedV2 -export class WatchProvisionState implements WatchProvisionDisplay { - @Trace phase: WatchProvisionPhase = WatchProvisionPhase.Hidden; - @Trace deviceName: string = ''; - @Trace deviceIdLabel: string = ''; - @Trace message: string = ''; - - ask(deviceName: string, deviceId: string): void { - this.phase = WatchProvisionPhase.Asking; - this.deviceName = deviceName; - this.deviceIdLabel = WatchProvisionProtocol.shortDeviceId(deviceId); - this.message = ''; - } - - working(): void { - this.phase = WatchProvisionPhase.Working; - this.message = ''; - } - - requirePassword(message: string): void { - this.phase = WatchProvisionPhase.Password; - this.message = message; - } - - done(message: string): void { - this.phase = WatchProvisionPhase.Done; - this.message = message; - } - - fail(message: string): void { - this.phase = WatchProvisionPhase.Failed; - this.message = message; - } - - hide(): void { - this.phase = WatchProvisionPhase.Hidden; - this.deviceName = ''; - this.deviceIdLabel = ''; - this.message = ''; - } - - visible(): boolean { - return this.phase !== WatchProvisionPhase.Hidden; - } - - /** The card is only dismissible when nothing is in flight behind it. */ - dismissible(): boolean { - return this.phase !== WatchProvisionPhase.Working; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WorkspaceToolsState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WorkspaceToolsState.ets deleted file mode 100644 index fd65ddc454..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/WorkspaceToolsState.ets +++ /dev/null @@ -1,42 +0,0 @@ -export interface WorkspaceToolLocation { id: string; name: string; } -export interface WorkspaceFileEntry { path: string; name: string; isDirectory: boolean; size?: number; modifiedTime?: number; } -export interface WorkspaceTerminalEntry { id: string; name?: string; initialCwd?: string; cwd?: string; connectionId?: string; } -export interface WorkspaceToolsIntent { type: string; path?: string; text?: string; deviceId?: string; connectionId?: string; tab?: number; } -@ObservedV2 -export class WorkspaceToolsState { - @Trace fileAction: string = ''; - @Trace fileActionPath: string = ''; - @Trace fileActionName: string = ''; - @Trace browsePath: string = ''; - @Trace browseEntries: WorkspaceFileEntry[] = []; - @Trace browseHasMore: boolean = false; - @Trace browseBusy: boolean = false; - @Trace browseError: string = ''; - @Trace visible: boolean = false; - @Trace deviceScope: boolean = false; - @Trace connectionId: string = ''; - @Trace locations: WorkspaceToolLocation[] = []; - @Trace busy: boolean = false; - @Trace error: string = ''; - get saveConflict(): boolean { - return this.error.startsWith('FILE_CONFLICT:') || this.error.startsWith('Error: FILE_CONFLICT:'); - } - @Trace downloadStatus: string = ''; - @Trace uploadPending: boolean = false; - @Trace uploadProgress: number = 0; - @Trace directory: string = ''; - @Trace entries: WorkspaceFileEntry[] = []; - @Trace hasMore: boolean = false; - @Trace initialTab: number = 0; - @Trace sort: number = 0; - @Trace editorVisible: boolean = false; - @Trace editing: boolean = false; - @Trace dirty: boolean = false; - @Trace confirmDiscard: boolean = false; - @Trace lineNumbers: boolean = true; - @Trace selectedFile: string = ''; - @Trace content: string = ''; - @Trace terminals: WorkspaceTerminalEntry[] = []; - @Trace terminalId: string = ''; - @Trace output: string = ''; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/AppShellViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/AppShellViewModel.ets deleted file mode 100644 index 6e6e7c387e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/AppShellViewModel.ets +++ /dev/null @@ -1,110 +0,0 @@ -import { - AppNavigationBackAction, - AppNavigationPathSpec, - AppRoute, - AppRouteContract -} from '../navigation/AppRouteContract'; -import { AppShellState } from '../state/AppShellState'; - -/** Owns application navigation and global overlay state. */ -export class AppShellViewModel { - readonly state: AppShellState = new AppShellState(); - readonly navigationStack: NavPathStack = new NavPathStack(); - - currentRoute(): AppRoute { - return AppRouteContract.currentRoute(this.navigationStack.getAllPathName()); - } - - isRoute(route: AppRoute): boolean { - return this.currentRoute() === route; - } - - isGeneralChatVisible(): boolean { - return AppRouteContract.isGeneralComposerRoute(this.currentRoute()); - } - - pushRoute(route: AppRoute, sessionId: string = '', animated: boolean = true): void { - const spec: AppNavigationPathSpec | undefined = AppRouteContract.pathSpec( - this.currentRoute(), - route, - sessionId - ); - if (!spec) { - return; - } - if (spec.hasSessionParam()) { - this.navigationStack.pushPath({ name: spec.name, param: spec.routeParam() }, animated); - } else { - this.navigationStack.pushPath({ name: spec.name }, animated); - } - this.syncActiveRoute(); - } - - replaceRoute(route: AppRoute, sessionId: string = ''): void { - this.navigationStack.clear(); - if (route !== AppRoute.RemoteHome) { - this.pushRoute(route, sessionId); - } - this.syncActiveRoute(); - } - - /** - * Makes [route] the whole stack, or does nothing if it already is. - * - * The guard deliberately ignores [sessionId]. A route names a screen, not the - * conversation on it — which session is open is read from page state, and no - * component ever reads the path param back. Treating a session switch as a - * navigation meant clearing the stack and pushing a fresh `NavDestination`, - * and on the wide layout the master pane lives inside that destination: every - * tap on a row tore down and rebuilt the whole sidebar. Measured on tablet, - * that rebuild was ~2.1s of the ~3.5s the main thread spent blocked before - * the transcript appeared. - */ - replaceRouteWithoutAnimation(route: AppRoute, sessionId: string = ''): void { - if (this.currentRoute() === route) { - return; - } - this.navigationStack.clear(false); - if (route !== AppRoute.RemoteHome) { - this.pushRoute(route, sessionId, false); - } - this.syncActiveRoute(); - } - - replaceCurrentRoute(route: AppRoute, sessionId: string = ''): void { - if (this.navigationStack.getAllPathName().length === 0) { - this.pushRoute(route, sessionId); - return; - } - if (sessionId.length > 0) { - this.navigationStack.replacePath({ - name: route, - param: AppRouteContract.routeParam(sessionId) - }, false); - } else { - this.navigationStack.replacePath({ name: route }, false); - } - this.syncActiveRoute(); - } - - popRoute(fallback: AppRoute): void { - if (this.navigationStack.getAllPathName().length > 0) { - this.navigationStack.pop(); - this.syncActiveRoute(); - return; - } - this.replaceRoute(fallback); - } - - /** - * Republish the stack top as traced state. Every navigation goes through this - * view model, so this is the one place the mirror can be kept honest. - */ - private syncActiveRoute(): void { - this.state.activeRoute = this.currentRoute(); - } - - backAction(route: AppRoute): AppNavigationBackAction { - return AppRouteContract.backAction(route, this.state.showSidebar); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationController.ets deleted file mode 100644 index 8f5ee5fa10..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationController.ets +++ /dev/null @@ -1,220 +0,0 @@ -import { - RemoteQuestionAnswerPayload, - RemoteSession, - SelectedImageAttachment, - SessionSummary -} from '../../model/RemoteModels'; -import { ChatTimelineItem } from '../../model/ChatTimelineModels'; -import { VoiceInputRouteSnapshot } from '../../services/VoiceInputLifecycleController'; -import { AppRootRouteState } from '../navigation/AppRootRouteState'; -import { AppRoute, AppRouteContract } from '../navigation/AppRouteContract'; -import { MessageCopyScope, CommandPaletteRequest, SessionRollbackRequest } from '../actions/ConversationIntent'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { RemotePageState } from '../state/RemotePageState'; -import { RemoteChatPollingSnapshot } from '../../services/RemoteChatPollingLifecycleController'; -import { - ConversationControllerHooks, - RemoteConversationDependencies, - RemoteConversationHooks -} from './ConversationRuntime'; -import { RemoteCreateFlowController } from './RemoteCreateFlowController'; -import { RemoteTranscriptController } from './RemoteTranscriptController'; -import { VisibleConversationController } from './VisibleConversationController'; - -export { - ConversationControllerHooks, - RemoteConversationDependencies, - RemoteConversationHooks -} from './ConversationRuntime'; - -/** Owns route-dependent composer state and delegates feature work. */ -export class ConversationController { - private readonly general: GeneralChatPageState; - private readonly remote: RemotePageState; - private readonly hooks: ConversationControllerHooks; - private readonly remoteRuntime?: RemoteConversationDependencies; - private readonly transcript: RemoteTranscriptController; - private readonly createFlow: RemoteCreateFlowController; - private readonly visible: VisibleConversationController; - - constructor( - general: GeneralChatPageState, - remote: RemotePageState, - hooks: ConversationControllerHooks, - remoteRuntime?: RemoteConversationDependencies - ) { - this.general = general; - this.remote = remote; - this.hooks = hooks; - this.remoteRuntime = remoteRuntime; - this.transcript = new RemoteTranscriptController(remote, remoteRuntime, (message: string) => { - this.showHomeToast(message); - }); - this.createFlow = new RemoteCreateFlowController(remote, remoteRuntime); - this.visible = new VisibleConversationController( - remote, - remoteRuntime, - this.transcript, - this.createFlow, - (route: AppRoute, value: string) => this.setChatInput(route, value), - (statusText: string) => this.setVisibleStatusText(statusText), - (message: string) => this.showHomeToast(message) - ); - } - - visibleChatInput(): string { - return AppRootRouteState.chatInput(this.hooks.currentRoute(), this.general, this.remote); - } - - visibleSelectedImages(): SelectedImageAttachment[] { - return AppRootRouteState.selectedImages(this.hooks.currentRoute(), this.general, this.remote); - } - - visibleVoiceListening(): boolean { - return AppRootRouteState.voiceListening(this.hooks.currentRoute(), this.general, this.remote); - } - - setChatInput(route: AppRoute, value: string): void { - AppRootRouteState.setChatInput(route, value, this.general, this.remote); - } - - addSelectedImages(route: AppRoute, images: SelectedImageAttachment[]): void { - AppRootRouteState.addSelectedImages(route, images, this.general, this.remote); - } - - removeSelectedImage(route: AppRoute, imageId: string): void { - AppRootRouteState.removeSelectedImage(route, imageId, this.general, this.remote); - } - - setVoiceListening(route: AppRoute, isVoiceListening: boolean): void { - AppRootRouteState.setVoiceListening(route, isVoiceListening, this.general, this.remote); - } - - clearAllVoiceListening(): void { - this.general.setVoiceListening(false); - this.remote.setVoiceListening(false); - } - - visibleBusy(): boolean { - return this.isGeneralComposerRoute(this.hooks.currentRoute()) ? - this.general.isBusy : this.remote.isBusy; - } - - visibleStatusText(): string { - return this.isGeneralComposerRoute(this.hooks.currentRoute()) ? - this.general.statusText : this.remote.statusText; - } - - setVisibleStatusText(statusText: string): void { - if (this.isGeneralComposerRoute(this.hooks.currentRoute())) { - this.general.setStatus(statusText); - return; - } - this.remote.setStatusText(statusText); - } - - voiceInputSnapshot(route: AppRoute): VoiceInputRouteSnapshot { - return AppRootRouteState.snapshot(route, this.visibleBusy(), this.general, this.remote); - } - - isGeneralComposerRoute(route: AppRoute): boolean { - return AppRouteContract.isGeneralComposerRoute(route); - } - - knownPollVersion(): number { return this.transcript.knownPollVersion(); } - resetKnownRemoteState(): void { this.transcript.resetKnownRemoteState(); } - updateKnownMessageCount(pollVersion: number, knownMessageCount: number): void { - this.transcript.updateKnownMessageCount(pollVersion, knownMessageCount); - } - updateKnownModelCatalogVersion(version: number): void { - this.transcript.updateKnownModelCatalogVersion(version); - } - async loadRemoteMessages(): Promise { await this.transcript.loadRemoteMessages(); } - async selectRemoteModel(modelId: string): Promise { await this.transcript.selectRemoteModel(modelId); } - async loadOlderRemoteMessages(): Promise { await this.transcript.loadOlderRemoteMessages(); } - async sendRemoteMessage(): Promise { await this.transcript.sendRemoteMessage(); } - async buildRemotePlan(path: string, name: string): Promise { - await this.transcript.buildRemotePlan(path, name); - } - async stopRemoteTask(): Promise { await this.transcript.stopRemoteTask(); } - async renameRemoteSession(title: string): Promise { await this.transcript.renameRemoteSession(title); } - async copyRemoteMessage(text: string, scope: MessageCopyScope): Promise { - await this.transcript.copyRemoteMessage(text, scope); - } - async rollbackRemoteSession(request: SessionRollbackRequest): Promise { - await this.transcript.rollbackRemoteSession(request); - } - async resyncRemoteTranscriptAfterRollback(): Promise { - this.transcript.resyncAfterRollback(); - } - async downloadRemoteFile(path: string): Promise { await this.transcript.downloadRemoteFile(path); } - retryRemoteMessage(text: string): void { this.transcript.retryRemoteMessage(text); } - async approveRemoteTool(toolId: string, updatedInput?: Object): Promise { - await this.transcript.approveRemoteTool(toolId, updatedInput); - } - async rejectRemoteTool(toolId: string): Promise { await this.transcript.rejectRemoteTool(toolId); } - async cancelRemoteTool(toolId: string): Promise { await this.transcript.cancelRemoteTool(toolId); } - async answerRemoteQuestion(toolId: string, answers: RemoteQuestionAnswerPayload): Promise { - await this.transcript.answerRemoteQuestion(toolId, answers); - } - resetRemoteTimeline(sessionId: string): void { this.transcript.resetRemoteTimeline(sessionId); } - syncRemoteTimeline(): void { this.transcript.syncRemoteTimeline(); } - startRemotePolling(): void { this.transcript.startRemotePolling(); } - applyRemoteSnapshot(snapshot: RemoteChatPollingSnapshot): void { - this.transcript.applyRemoteSnapshot(snapshot); - } - hasRunningRemoteTurn(): boolean { return this.transcript.hasRunningRemoteTurn(); } - remoteActiveTurnId(): string { return this.transcript.remoteActiveTurnId(); } - projectedRemoteTimelineItems(): ChatTimelineItem[] { return this.transcript.projectedRemoteTimelineItems(); } - - async createRemoteSession(agentType: string, inPlace: boolean = false): Promise { - await this.createFlow.createRemoteSession(agentType, inPlace); - } - async createRemoteSessionInWorkspace( - path: string, - agentType: string = 'code', - inPlace: boolean = false, - deviceId: string = '', - remoteConnectionId?: string, - remoteSshHost?: string, - workspaceId?: string - ): Promise { - await this.createFlow.createRemoteSessionInWorkspace(path, agentType, inPlace, deviceId, remoteConnectionId, remoteSshHost, workspaceId); - } - - async ensureRemoteControlTarget(deviceId?: string): Promise { - await this.createFlow.ensureRemoteControlTarget(deviceId); - } - async openRemoteSession(item: RemoteSession, inPlace: boolean = false): Promise { - await this.createFlow.openRemoteSession(item, inPlace); - } - applyRemoteActiveSession(session: SessionSummary): void { - this.createFlow.applyRemoteActiveSession(session); - } - async deleteRemoteSession(item: RemoteSession): Promise { - await this.createFlow.deleteRemoteSession(item); - } - routeCreatedRemoteSession(sessionId: string): void { - this.createFlow.routeCreatedRemoteSession(sessionId); - } - - openHomeSession(session: RemoteSession, inPlace: boolean = false): void { - this.visible.openHomeSession(session, inPlace); - } - async deleteHomeSession(session: RemoteSession): Promise { await this.visible.deleteHomeSession(session); } - async sendVisibleMessage(): Promise { await this.visible.sendVisibleMessage(); } - async stopVisibleTask(): Promise { await this.visible.stopVisibleTask(); } - closeActiveChat(): void { this.visible.closeActiveChat(); } - async renameVisibleSession(title: string): Promise { await this.visible.renameVisibleSession(title); } - async retryVisibleMessage(text: string): Promise { await this.visible.retryVisibleMessage(text); } - downloadVisibleFile(path: string): void { this.visible.downloadVisibleFile(path); } - async selectVisibleModel(modelId: string): Promise { await this.visible.selectVisibleModel(modelId); } - async dispatchCommandPalette(request: CommandPaletteRequest): Promise { - await this.visible.dispatchCommandPalette(request); - } - onVisibleChatInputChange(route: AppRoute, value: string): void { - this.visible.onVisibleChatInputChange(route, value); - } - latestUserMessageText(): string { return this.visible.latestUserMessageText(); } - showHomeToast(message: string): void { this.visible.showHomeToast(message); } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationRuntime.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationRuntime.ets deleted file mode 100644 index 3aa96977cf..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationRuntime.ets +++ /dev/null @@ -1,90 +0,0 @@ -import { ImagePickerService } from '../../services/ImagePickerService'; -import { ClipboardService } from '../../services/ClipboardService'; -import { RemoteChatCache } from '../../services/RemoteChatCache'; -import { RemoteChatCommandController } from '../../services/RemoteChatCommandController'; -import { RemoteChatPollingLifecycleController } from '../../services/RemoteChatPollingLifecycleController'; -import { RemoteFileDownloadController } from '../../services/RemoteFileDownloadController'; -import { RemoteModelController } from '../../services/RemoteModelController'; -import { RemoteCommandPaletteController } from '../../services/RemoteCommandPaletteController'; -import { RemoteToolActionController } from '../../services/RemoteToolActionController'; -import { RemoteSessionManager } from '../../services/RemoteSessionManager'; -import { RemoteWorkspaceCoordinator } from '../../services/RemoteWorkspaceCoordinator'; -import { AppRoute, AppRouteContract } from '../navigation/AppRouteContract'; -import { ConversationViewModel } from './ConversationViewModel'; -import { AppShellViewModel } from './AppShellViewModel'; -import { FilePreviewController } from './FilePreviewController'; -import { RemoteConnectionController } from './RemoteConnectionController'; -import { RemoteSessionViewModel } from './RemoteSessionViewModel'; -import { SettingsController } from './SettingsController'; - - -export interface ConversationControllerHooks { - readonly currentRoute: () => AppRoute; -} - -export interface RemoteConversationHooks { - readonly isConversationContext: (sessionId: string) => boolean; - readonly isFilePreviewVisible: () => boolean; - readonly stopVoiceInput: () => Promise; - readonly showToast: (message: string) => boolean; - readonly selectAssistantWorkspace: (path: string, workspaceId?: string) => Promise; -} - -export interface RemoteConversationDependencies { - readonly timeline: ConversationViewModel; - readonly chat: RemoteChatCommandController; - readonly chatCache: RemoteChatCache; - readonly polling: RemoteChatPollingLifecycleController; - readonly models: RemoteModelController; - readonly commandPalette: RemoteCommandPaletteController; - readonly files: RemoteFileDownloadController; - readonly tools: RemoteToolActionController; - readonly connection: RemoteConnectionController; - readonly imagePicker: ImagePickerService; - readonly clipboard: ClipboardService; - readonly sessions: RemoteSessionViewModel; - readonly sessionManager: RemoteSessionManager; - readonly workspace: RemoteWorkspaceCoordinator; - readonly settings: SettingsController; - readonly appShell: AppShellViewModel; - readonly filePreview: FilePreviewController; - readonly hooks: RemoteConversationHooks; -} - -export function requireRemoteRuntime( - remoteRuntime?: RemoteConversationDependencies -): RemoteConversationDependencies { - if (!remoteRuntime) { - throw new Error('Remote conversation dependencies are not configured.'); - } - return remoteRuntime; -} - -export function shortSessionId(sessionId: string): string { - return sessionId.length <= 8 ? sessionId : - sessionId.slice(0, 4) + '...' + sessionId.slice(sessionId.length - 4); -} - -export function routeCreatedRemoteSession( - sessionId: string, - remoteRuntime: RemoteConversationDependencies, - setDismissed: (dismissed: boolean) => void -): void { - remoteRuntime.filePreview.close(); - setDismissed(false); - if (remoteRuntime.appShell.isRoute(AppRoute.RemoteChat)) { - return; - } - remoteRuntime.appShell.pushRoute(AppRoute.RemoteChat, sessionId); -} - -export function routeRemoteSessionInPlace( - sessionId: string, - remoteRuntime: RemoteConversationDependencies, - setDismissed: (dismissed: boolean) => void -): void { - remoteRuntime.filePreview.close(); - setDismissed(false); - const target = AppRouteContract.remoteSessionDestination(sessionId); - remoteRuntime.appShell.replaceRouteWithoutAnimation(target.name, target.routeParam().sessionId); -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationViewModel.ets deleted file mode 100644 index c5c1747815..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/ConversationViewModel.ets +++ /dev/null @@ -1,22 +0,0 @@ -import { ConversationEvent } from '../../services/ConversationEvent'; -import { ChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ChatTimelineState, ChatTimelineStore } from '../../services/ChatTimelineStore'; - -/** - * Conversation-facing MVVM boundary. - * The store remains independently testable; the ViewModel is the page-facing - * owner of projected conversation state and transport-neutral events. - */ -export class ConversationViewModel extends ChatTimelineStore { - dispatch(event: ConversationEvent): void { - this.applyEvent(event); - } - - viewState(hasMoreMessages: boolean): ChatTimelineItem[] { - return this.project(hasMoreMessages); - } - - snapshotState(): ChatTimelineState { - return this.snapshot(); - } -} 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 deleted file mode 100644 index fb994fe035..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/DeviceDirectoryViewModel.ets +++ /dev/null @@ -1,625 +0,0 @@ -import { RecentWorkspaceEntry, RemoteSession, RemoteWorkspaceIdentity, SessionListResult } from '../../model/RemoteModels'; -import { - AccountDeviceDirectory, - AccountDeviceDirectorySource -} from '../../services/AccountDeviceDirectory'; -import { CloudAccountBinding, CloudAccountDevice, CloudAccountSession } from '../../services/CloudAccountClient'; -import { DeviceDirectoryCoordinator } from '../../services/DeviceDirectoryCoordinator'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemoteSessionListStore } from '../../services/RemoteSessionListCache'; -import { remoteSessionBelongsToWorkspace, stampRemoteSessionsWorkspace, stampRemoteSessionsDevice } from '../../services/RemoteSessionIdentity'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { mapInConcurrentBatches, CONCURRENT_WORKSPACE_LISTINGS } from '../../services/ConcurrentWorkspaceListing'; -import { - DeviceDirectoryEntry, - DeviceDirectoryState, - WorkspaceDirectoryState, - emptyDeviceDirectoryEntry -} from '../state/DeviceDirectoryState'; - -export interface DeviceDirectoryViewModelHooks { - readonly credentials: () => CloudAccountBinding | undefined; - readonly activeDeviceId: () => string; - /** Whether the conversation link to [activeDeviceId] is currently live. */ - readonly activeDeviceConnected: () => boolean; - readonly loadActiveWorkspaceSessions?: (path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string) => Promise; - readonly onActiveWorkspaceSessions?: (path: string, result: SessionListResult, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string) => void; -} - -interface DeviceCatalogRequest { - entry: DeviceDirectoryEntry; - session: CloudAccountSession | undefined; - relayUrl: string | undefined; -} - -/** Selection, loading, and retry for the sidebar's device directory. */ -export class DeviceDirectoryViewModel { - private readonly state: DeviceDirectoryState; - private readonly store?: RemoteSessionListStore; - private readonly hooks: DeviceDirectoryViewModelHooks; - private readonly directory?: AccountDeviceDirectorySource; - private readonly inFlight: Map = new Map(); - private readonly workspaceInFlight: Map> = - new Map>(); - /** Device whose control-target catalog request currently owns `loading`. */ - private liveCatalogDeviceId: string = ''; - - constructor( - state: DeviceDirectoryState, - hooks: DeviceDirectoryViewModelHooks, - store?: RemoteSessionListStore, - directory?: AccountDeviceDirectorySource - ) { - this.state = state; - this.hooks = hooks; - this.store = store; - this.directory = directory; - } - - async refreshDevices(load: () => Promise): Promise { - if (this.state.refreshing) return; - const binding = this.hooks.credentials(); - if (!binding) return; - const generation = ++this.state.refreshGeneration; - const current = (): boolean => { - const now = this.hooks.credentials(); - return generation === this.state.refreshGeneration && binding.session === now?.session && binding.relayUrl === now?.relayUrl; - }; - this.state.refreshing = true; this.state.refreshError = ''; - try { - await load(); - if (current()) await this.refreshExpandedWorkspaceSessions(); - } catch (error) { - if (current()) this.state.refreshError = error instanceof Error ? error.message : RemoteI18n.t('remote.settings.deviceLoadFailed'); - } finally { - if (generation === this.state.refreshGeneration) this.state.refreshing = false; - } - } - - /** - * Re-runs the device sync against the current active id. - * - * Nothing about a row's own fields changes here — that is the point. It is - * the seam the control-target switch goes through, so what it guards is that - * a catalog captured off the live page survives the device ceasing to be - * live. - */ - refreshActive(): void { - this.syncDevices(this.state.devices.map((item: DeviceDirectoryEntry): CloudAccountDevice => { - return { - deviceId: item.deviceId, - deviceName: item.deviceName, - deviceAlias: item.deviceAlias, - deviceKind: item.deviceKind, - lastSeenAt: item.lastSeenAt, - compatible: item.compatible, - online: item.online - }; - })); - } - - /** - * Mirrors the live conversation device onto its directory row. - * - * The active row reads RemotePageState, so this snapshot is what remains - * after the control target moves on. Empty payloads are ignored so the - * teardown that clears the live page cannot wipe a row we just captured. - */ - captureLive( - deviceId: string, - workspaces: RecentWorkspaceEntry[], - sessions: RemoteSession[] - ): void { - const target = deviceId.trim(); - if (target.length === 0) { - return; - } - const entry = this.state.find(target); - if (!entry) { - return; - } - if (workspaces.length === 0 && sessions.length === 0) { - return; - } - if (workspaces.length > 0 && entry.catalogSource.length === 0) { - entry.workspaces = workspaces; - } - if (sessions.length > 0) { - entry.sessions = RemoteUiState.mergeSessions( - stampRemoteSessionsDevice(sessions, target), - entry.sessions - ); - } - if (entry.status === 'loading') { - // A live-catalog request belongs to the control-target lifecycle. Once - // that target is being torn down, the request can no longer complete - // this row. Leave any captured snapshot as cache, otherwise make the row - // fetchable again instead of stranding it in a false loading state. - entry.status = entry.workspaces.length > 0 || entry.sessions.length > 0 ? 'cached' : 'idle'; - } else if (entry.status === 'idle' || entry.status === 'cached') { - entry.status = 'ready'; - } - } - - /** Marks the incoming target's catalog request before its handshake starts. */ - beginLiveCatalog(deviceId: string): void { - const target = deviceId.trim(); - if (target.length === 0) { - return; - } - if (this.liveCatalogDeviceId.length > 0 && this.liveCatalogDeviceId !== target) { - this.releaseAbandonedLiveCatalog(this.liveCatalogDeviceId); - } - const entry = this.state.find(target); - if (!entry) { - return; - } - this.inFlight.delete(target); - this.liveCatalogDeviceId = target; - entry.status = 'loading'; - entry.errorText = ''; - } - - /** - * Starts the directory projection for a newly activated control target. - * - * This is deliberately different from `captureLive`: the outgoing snapshot - * ignores empty teardown values, while an incoming empty catalog is real and - * must replace whatever was cached for this row. Conflating the two lifecycle - * edges is what allowed one desktop's workspaces to be stamped onto another. - */ - activateLive( - deviceId: string, - workspaces: RecentWorkspaceEntry[], - sessions: RemoteSession[] - ): void { - const target = deviceId.trim(); - if (target.length === 0) { - return; - } - const entry = this.state.find(target); - if (!entry) { - return; - } - // A successful handshake starts a new directory generation even when the - // transport changed while the desktop id stayed the same (for example, - // scan-room -> account-device). The handshake replaces cross-workspace - // sessions below, so the old generation's `ready` flags cannot survive it. - this.state.resetWorkspaceDirectory(target); - if (entry.catalogSource.length === 0) entry.workspaces = []; - // The workspace catalog is loaded independently of the handshake. - // The handshake is the authoritative snapshot for the incoming target. - // Merging the row's old cache here makes any historical cross-device - // misattribution immortal, because those stale sessions never disappear. - entry.sessions = stampRemoteSessionsDevice(sessions, target); - // The handshake only carries the current workspace and sessions. The full - // recent-workspace request starts immediately afterwards, so even an empty - // target-scoped projection is still loading rather than a confirmed empty - // catalog. - entry.status = 'loading'; - entry.errorText = ''; - } - - /** Publishes the authoritative full catalog returned by the live target. */ - completeLiveCatalog(deviceId: string, workspaces: RecentWorkspaceEntry[], source?: string, recentWorkspaces?: RecentWorkspaceEntry[]): void { - const target = deviceId.trim(); - const entry = this.state.find(target); - if (!entry) { - RemoteLogger.warn(`workspace catalog ignored device=${target} reason=device_not_in_directory count=${workspaces.length}`); - return; - } - entry.workspaces = workspaces.slice(); - entry.catalogSource = source || "recent"; - entry.recentWorkspaces = recentWorkspaces || workspaces; - entry.status = 'ready'; - entry.errorText = ''; - if (this.liveCatalogDeviceId === target) { - this.liveCatalogDeviceId = ''; - } - } - - /** Ends a live catalog request as failed so retry reflects real transport state. */ - failLiveCatalog(deviceId: string): void { - const target = deviceId.trim(); - const entry = this.state.find(target); - if (!entry) { - return; - } - entry.status = 'failed'; - entry.errorText = ''; - if (this.liveCatalogDeviceId === target) { - this.liveCatalogDeviceId = ''; - } - } - - private releaseAbandonedLiveCatalog(deviceId: string): void { - const entry = this.state.find(deviceId); - if (entry && entry.status === 'loading') { - entry.status = entry.workspaces.length > 0 || entry.sessions.length > 0 ? 'cached' : 'idle'; - } - this.liveCatalogDeviceId = ''; - } - - syncDevices(devices: CloudAccountDevice[]): void { - const activeId = this.hooks.activeDeviceId(); - const activeConnected = this.hooks.activeDeviceConnected(); - const next: DeviceDirectoryEntry[] = devices.map((device: CloudAccountDevice): DeviceDirectoryEntry => { - // The relay's presence flag is hearsay: it is a projection of a socket - // registry that can lag or lose an entry. A live conversation link is - // first-hand proof, so it wins. Without this the desktop we are pinging - // every fifteen seconds can render as a greyed-out offline row. - const online = device.online || - (device.deviceId === activeId && activeId.length > 0 && activeConnected); - if (online !== device.online) { - // Only the disagreement is worth a line. It is rare, it is the whole - // reason this branch exists, and it is what the next person chasing a - // wrongly-greyed row will grep for. - RemoteLogger.info(`device presence override device=${device.deviceId} relay=offline link=live`); - } - 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'; - } - existing.online = online; - return existing; - } - const created = emptyDeviceDirectoryEntry( - device.deviceId, - 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); - if (this.state.find(this.state.selectedDeviceId) || - (this.state.selectedDeviceId === activeId && activeId.length > 0 && activeConnected)) { - return; - } - // Restore the persisted control target without selecting a different device - // merely because it happens to be online. - this.state.select(activeId); - - } - - async hydrateKnownDevices(): Promise { - const devices = this.state.devices; - for (let index = 0; index < devices.length; index++) { - await this.hydrateDevice(devices[index]); - } - } - - async selectDevice(deviceId: string): Promise { - const target = deviceId.trim(); - const entry = this.state.find(target); - if (!entry) { - // A QR-paired desktop is projected into the sidebar without belonging to - // the account directory. It is still a real selectable device row - // while its control link is live; accepting only directory entries made - // that row render normally but ignore every tap. - if (target.length > 0 && target === this.hooks.activeDeviceId().trim() && - this.hooks.activeDeviceConnected()) { - this.state.select(target); - RemoteLogger.info(`device directory select active projection device=${target}`); - } - return; - } - this.state.select(target); - RemoteLogger.info(`device directory select device=${target}`); - if (this.shouldFetch(entry)) { - entry.status = 'loading'; - entry.errorText = ''; - } - await this.ensureLoaded(target); - } - - async retryDevice(deviceId: string): Promise { - const entry = this.state.find(deviceId); - if (!entry) { - return; - } - this.state.select(deviceId); - await this.loadDevice(deviceId); - } - - /** - * Loads exactly one workspace after its disclosure opens. - * - * Device selection deliberately stops at the workspace catalog; fanning out - * every workspace here was both expensive and the source of unrelated row - * updates while the user was only opening one branch. - */ - async loadWorkspaceSessions(deviceId: string, path: string, remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): Promise { - const entry = this.state.find(deviceId); - const normalizedPath = path.trim(); - const active = deviceId === this.hooks.activeDeviceId() && this.hooks.activeDeviceConnected(); - if (normalizedPath.length === 0 || (!active && (!entry || !entry.online))) { - return; - } - const scope = this.state.workspaceLoadState(deviceId, normalizedPath, remoteConnectionId, remoteSshHost, workspaceId); - const pending = this.workspaceInFlight.get(scope); - if (pending) { - return pending; - } - const request = this.fetchWorkspaceSessions(scope, entry, normalizedPath, active); - this.workspaceInFlight.set(scope, request); - try { - await request; - } finally { - this.workspaceInFlight.delete(scope); - } - } - - /** Refresh only the workspace branches actually disclosed in the sidebar. */ - async refreshExpandedWorkspaceSessions(): Promise { - const selected = this.state.selectedDeviceId; - const scopes = this.state.workspaceDirectory.filter((item: WorkspaceDirectoryState): boolean => - item.deviceId === selected && item.expanded - ); - await mapInConcurrentBatches(scopes, async (scope: WorkspaceDirectoryState): Promise => { - if (!this.state.isCurrentWorkspaceLoad(scope) || !scope.expanded || - this.state.selectedDeviceId !== selected) return; - try { - await this.loadWorkspaceSessions(scope.deviceId, scope.path, scope.remoteConnectionId, scope.remoteSshHost, scope.workspaceId); - } catch (_err) { - // Each failed branch exposes its own retry row and retains its cache. - } - }, CONCURRENT_WORKSPACE_LISTINGS); - } - - private async fetchWorkspaceSessions( - scope: WorkspaceDirectoryState, - entry: DeviceDirectoryEntry | undefined, - path: string, - active: boolean - ): Promise { - const binding = this.hooks.credentials(); - const isCurrent = (): boolean => { - const currentBinding = this.hooks.credentials(); - return this.state.isCurrentWorkspaceLoad(scope) && this.state.find(scope.deviceId) === entry && - binding?.session === currentBinding?.session && binding?.relayUrl === currentBinding?.relayUrl && - (!active || (scope.deviceId === this.hooks.activeDeviceId() && this.hooks.activeDeviceConnected())); - }; - scope.status = 'loading'; - // The disclosed row keyed by its ID when the catalog supplied one; the - // legacy triple is only what pre-ID rows have. - const workspace: RemoteWorkspaceIdentity = { - workspaceId: scope.workspaceId.length > 0 ? scope.workspaceId : undefined, - path: path, - remoteConnectionId: scope.remoteConnectionId.length > 0 ? scope.remoteConnectionId : undefined, - remoteSshHost: scope.remoteSshHost.length > 0 ? scope.remoteSshHost : undefined - }; - try { - if (active && this.hooks.loadActiveWorkspaceSessions && this.hooks.onActiveWorkspaceSessions) { - const result = await this.hooks.loadActiveWorkspaceSessions(path, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId); - if (!isCurrent()) return; - this.captureWorkspaceSessions(scope.deviceId, path, result.sessions, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId); - this.hooks.onActiveWorkspaceSessions(path, result, workspace.remoteConnectionId, workspace.remoteSshHost, workspace.workspaceId); - } else { - const source = this.directorySource(); - if (!source || !entry) throw new Error('Account device directory is unavailable.'); - const sessions = await new DeviceDirectoryCoordinator(source).loadWorkspaceSessions(scope.deviceId, workspace); - if (!isCurrent()) return; - entry.sessions = DeviceDirectoryViewModel.replaceWorkspaceSessions(entry.sessions, workspace, sessions, entry.workspaces); - await this.persistDevice(scope.deviceId, entry.workspaces, entry.sessions); - } - if (isCurrent()) { - scope.hasLoadedSessions = true; - scope.status = 'ready'; - } - } catch (err) { - if (isCurrent()) { - scope.status = 'failed'; - throw new Error(err instanceof Error ? err.message : String(err)); - } - } finally { - // A target switch can abandon a live request without replacing this - // device's disclosure object. Do not strand it in `loading` on return. - if (this.state.isCurrentWorkspaceLoad(scope) && scope.status === 'loading') scope.status = 'idle'; - } - } - - /** Replaces one refreshed workspace while preserving every cached sibling. */ - captureWorkspaceSessions(deviceId: string, path: string, sessions: RemoteSession[], remoteConnectionId?: string, remoteSshHost?: string, workspaceId?: string): void { - const entry = this.state.find(deviceId.trim()); - const normalizedPath = path.trim(); - if (!entry || normalizedPath.length === 0) { - return; - } - const workspace: RemoteWorkspaceIdentity = { - workspaceId: workspaceId?.trim() || undefined, - path: normalizedPath, - remoteConnectionId, - remoteSshHost - }; - entry.sessions = DeviceDirectoryViewModel.replaceWorkspaceSessions( - entry.sessions, - workspace, - stampRemoteSessionsDevice(stampRemoteSessionsWorkspace(sessions, workspace), deviceId.trim()), - entry.workspaces - ); - } - - async ensureLoaded(deviceId: string): Promise { - const entry = this.state.find(deviceId); - if (!entry) { - return; - } - if (deviceId === this.hooks.activeDeviceId()) { - return; - } - if (!entry.online) { - return; - } - if (entry.status === 'ready') { - return; - } - await this.loadDevice(deviceId); - } - - private shouldFetch(entry: DeviceDirectoryEntry): boolean { - if (entry.deviceId === this.hooks.activeDeviceId()) { - return false; - } - if (!entry.online) { - return false; - } - return entry.status === 'idle' || entry.status === 'cached' || entry.status === 'failed'; - } - - private async loadDevice(deviceId: string): Promise { - const entry = this.state.find(deviceId); - if (!entry) { - return; - } - if (deviceId === this.hooks.activeDeviceId()) { - return; - } - if (!entry.online) { - return; - } - const binding = this.hooks.credentials(); - const pending = this.inFlight.get(deviceId); - if (pending && pending.entry === entry && pending.session === binding?.session && - pending.relayUrl === binding?.relayUrl) { - return; - } - const source = this.directorySource(); - if (!source) { - entry.status = 'failed'; - entry.errorText = RemoteI18n.t('remote.settings.accountNotSignedIn'); - return; - } - const request: DeviceCatalogRequest = { - entry, session: binding?.session, relayUrl: binding?.relayUrl - }; - this.inFlight.set(deviceId, request); - const isCurrent = (): boolean => { - const currentBinding = this.hooks.credentials(); - return this.inFlight.get(deviceId) === request && this.state.find(deviceId) === entry && - entry.online && request.session === currentBinding?.session && - request.relayUrl === currentBinding?.relayUrl && deviceId !== this.hooks.activeDeviceId(); - }; - entry.status = 'loading'; - entry.errorText = ''; - try { - const coordinator = new DeviceDirectoryCoordinator(source); - const catalog = await coordinator.loadWorkspaceCatalog(deviceId); - if (!isCurrent()) return; - entry.workspaces = catalog.workspaces; - entry.catalogSource = catalog.source; - entry.recentWorkspaces = catalog.recentWorkspaces; - entry.status = 'ready'; - entry.errorText = ''; - await this.persistDevice(deviceId, entry.workspaces, entry.sessions); - } catch (err) { - if (!isCurrent()) return; - // The retry row carries a localized line of its own. What the transport - // throws is English and frequently a stack, so it stays in the log, which - // is the only place it reads as anything but noise. - RemoteLogger.warn(`device directory load failed device=${deviceId}: ${String(err)}`); - entry.status = 'failed'; - entry.errorText = ''; - } finally { - if (this.inFlight.get(deviceId) === request) { - this.inFlight.delete(deviceId); - if (entry.status === 'loading') entry.status = 'idle'; - } - } - } - - private async hydrateDevice(entry: DeviceDirectoryEntry): Promise { - const binding = this.hooks.credentials(); - const previousWorkspaces = entry.workspaces; - const previousSessions = entry.sessions; - const workspaces = this.store ? - await DeviceDirectoryViewModel.safeWorkspaces(this.store, entry.deviceId) : []; - const sessions = this.store ? - await DeviceDirectoryViewModel.safeSessions(this.store, entry.deviceId) : []; - const currentBinding = this.hooks.credentials(); - if (this.state.find(entry.deviceId) !== entry || binding?.session !== currentBinding?.session || - binding?.relayUrl !== currentBinding?.relayUrl) return; - if (workspaces.length === 0 && sessions.length === 0) { - return; - } - if (workspaces.length > 0 && entry.catalogSource.length === 0 && entry.workspaces === previousWorkspaces) { - entry.workspaces = workspaces; - } - if (sessions.length > 0 && entry.sessions === previousSessions) { - entry.sessions = stampRemoteSessionsDevice(sessions, entry.deviceId); - } - if (entry.status === 'idle') { - entry.status = 'cached'; - } - } - - private directorySource(): AccountDeviceDirectorySource | undefined { - if (this.directory) { - return this.directory; - } - const context = this.hooks.credentials(); - return context ? new AccountDeviceDirectory(context) : undefined; - } - - private async persistDevice( - deviceId: string, - workspaces: RecentWorkspaceEntry[], - sessions: RemoteSession[] - ): Promise { - try { - if (this.store) { - await this.store.saveWorkspaces(deviceId, workspaces); - await this.store.saveObservedList(deviceId, sessions, false); - } - } catch (err) { - RemoteLogger.warn(`device directory persist failed device=${deviceId}: ${String(err)}`); - } - } - - private static async safeWorkspaces( - store: RemoteSessionListStore, - deviceId: string - ): Promise { - try { - return await store.loadWorkspaces(deviceId); - } catch (err) { - RemoteLogger.warn(`device workspace cache read failed device=${deviceId}: ${String(err)}`); - return []; - } - } - - private static async safeSessions( - store: RemoteSessionListStore, - deviceId: string - ): Promise { - try { - return (await store.loadList(deviceId)).sessions; - } catch (err) { - RemoteLogger.warn(`device session cache read failed device=${deviceId}: ${String(err)}`); - return []; - } - } - - private static replaceWorkspaceSessions( - current: RemoteSession[], - workspace: RemoteWorkspaceIdentity, - replacement: RemoteSession[], - catalog: RecentWorkspaceEntry[] = [] - ): RemoteSession[] { - const preserved = current.filter((item: RemoteSession): boolean => { - return !remoteSessionBelongsToWorkspace(item, workspace, catalog); - }); - return replacement.concat(preserved); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/FilePreviewController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/FilePreviewController.ets deleted file mode 100644 index 892ebc0d29..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/FilePreviewController.ets +++ /dev/null @@ -1,92 +0,0 @@ -import { FilePreviewRequest, FilePreviewTargetContext } from '../../model/FilePreviewTarget'; -import { SessionSummary } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { FileReferenceKind, FileTargetResolver } from '../policy/FileTargetResolver'; -import { RemoteWorkspaceFileClient } from '../../services/RemoteWorkspaceFileClient'; -import { AppRoute, AppRouteContract } from '../navigation/AppRouteContract'; -import { FilePreviewState } from '../state/FilePreviewState'; -import { RemoteFilePreviewController } from './RemoteFilePreviewController'; - -export interface FilePreviewControllerHooks { - readonly remoteAvailable: () => boolean; - readonly activeSession: () => SessionSummary; - readonly workspacePath: () => string; - readonly openExternalLink: (reference: string) => Promise; - readonly onGeneralStatus: (statusText: string) => void; - readonly onRemoteStatus: (statusText: string) => void; -} - -/** Owns file-preview routing, target validity and the underlying remote file load. */ -export class FilePreviewController { - private readonly state: FilePreviewState; - private readonly hooks: FilePreviewControllerHooks; - private readonly loader: RemoteFilePreviewController; - private controlTargetEpoch: number = 1; - - constructor( - client: RemoteWorkspaceFileClient, - state: FilePreviewState, - hooks: FilePreviewControllerHooks - ) { - this.state = state; - this.hooks = hooks; - this.loader = new RemoteFilePreviewController( - client, - state, - hooks.remoteAvailable, - (): number => this.controlTargetEpoch - ); - } - - open(route: AppRoute, request: FilePreviewRequest): void { - const activeSession = this.hooks.activeSession(); - const context = new FilePreviewTargetContext( - activeSession.sessionId, - activeSession.workspacePath || this.hooks.workspacePath(), - this.controlTargetEpoch - ); - const resolution = FileTargetResolver.resolve(request.reference, request.label, context); - if (resolution.kind === FileReferenceKind.HttpUrl) { - void this.openExternalLink(route, request.reference); - return; - } - if (route !== AppRoute.RemoteChat) { - this.hooks.onGeneralStatus(RemoteI18n.t('generalChat.filePreviewUnavailable')); - return; - } - if (resolution.kind !== FileReferenceKind.RemoteWorkspaceFile || !resolution.target) { - return; - } - void this.loader.open(resolution.target); - } - - close(): void { - this.loader.close(); - } - - refresh(): void { - void this.loader.refresh(); - } - - openLink(reference: string, label: string): void { - this.open(AppRoute.RemoteChat, new FilePreviewRequest(reference, label)); - } - - invalidate(): void { - this.controlTargetEpoch += 1; - this.loader.close(); - } - - private async openExternalLink(route: AppRoute, reference: string): Promise { - const opened = await this.hooks.openExternalLink(reference); - if (opened) { - return; - } - const statusText = RemoteI18n.t('errors.operationFailed'); - if (AppRouteContract.isGeneralComposerRoute(route)) { - this.hooks.onGeneralStatus(statusText); - return; - } - this.hooks.onRemoteStatus(statusText); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/GeneralChatConversationViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/GeneralChatConversationViewModel.ets deleted file mode 100644 index 5fb1304917..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/GeneralChatConversationViewModel.ets +++ /dev/null @@ -1,366 +0,0 @@ -import { - ChatMessage, - ChatMessageItemResponse, - RemoteToolStatusResponse, - SelectedImageAttachment -} from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { Encoding } from '../../services/Encoding'; -import { ConversationViewModel } from './ConversationViewModel'; -import { GeneralChatPageState } from '../state/GeneralChatPageState'; -import { GeneralChatCommandController } from '../../services/general-chat/GeneralChatCommandController'; -import { GeneralChatDraftLifecycleController } from '../../services/general-chat/GeneralChatDraftLifecycleController'; -import { GeneralChatStreamLifecycleController } from '../../services/general-chat/GeneralChatStreamLifecycleController'; -import { - GeneralChatServiceState, - GeneralChatServiceStatus -} from '../../services/general-chat/GeneralChatServiceState'; -import { - GeneralChatSendResult, - GeneralChatStreamCallbacks -} from '../../services/general-chat/GeneralChatPort'; -import { RemoteLogger } from '../../services/RemoteLogger'; - -export interface GeneralChatConversationViewModelHooks { - readonly isVisible: (sessionId: string) => boolean; - readonly currentActiveTurnId: () => string; - readonly latestUserMessageText: () => string; - readonly syncTimeline: () => void; - readonly refreshSessions: () => void; - readonly onTaskStarted?: (sessionId: string, turnId: string) => void; - readonly onTaskCompleted?: (sessionId: string, turnId: string) => void; - readonly onTaskStopped?: (sessionId: string, turnId: string) => void; -} - -/** Owns General Chat stream state and publishes all updates through ConversationViewModel. */ -export class GeneralChatConversationViewModel { - private readonly pageState: GeneralChatPageState; - private readonly command: GeneralChatCommandController; - private readonly drafts: GeneralChatDraftLifecycleController; - private readonly stream: GeneralChatStreamLifecycleController; - private readonly timeline: ConversationViewModel; - private readonly hooks: GeneralChatConversationViewModelHooks; - - constructor( - pageState: GeneralChatPageState, - command: GeneralChatCommandController, - drafts: GeneralChatDraftLifecycleController, - stream: GeneralChatStreamLifecycleController, - timeline: ConversationViewModel, - hooks: GeneralChatConversationViewModelHooks - ) { - this.pageState = pageState; - this.command = command; - this.drafts = drafts; - this.stream = stream; - this.timeline = timeline; - this.hooks = hooks; - } - - async sendMessage(): Promise { - const rawText = this.pageState.chatInput.trim(); - const images = this.pageState.selectedImages.slice(); - const text = rawText.length > 0 ? rawText : - (images.length > 0 ? RemoteI18n.t('chat.analyzeImageDefault') : ''); - const sessionId = this.pageState.activeSession.sessionId || ''; - if ((!text && images.length === 0) || !sessionId || this.pageState.isBusy) { - return; - } - this.pageState.clearComposer(); - this.drafts.clear(sessionId); - const localMessage = this.localUserMessage(text, images); - this.timeline.appendOptimisticMessage(localMessage); - this.hooks.syncTimeline(); - try { - this.pageState.setBusy(true); - this.pageState.setServiceState(GeneralChatServiceState.Sending); - this.pageState.setStatus(RemoteI18n.t('generalChat.generating')); - this.beginStream(sessionId); - const observer = new GeneralChatStreamCallbacks( - async (message: ChatMessage): Promise => { - this.timeline.dispatch({ type: 'user_message', message, persisted: true }); - this.hooks.syncTimeline(); - }, - (delta: string): void => { - this.appendDelta(sessionId, delta); - } - ); - this.stream.setRequestInFlight(true); - const result: GeneralChatSendResult = await this.command.sendMessage( - sessionId, - text, - images, - observer - ); - this.stream.setRequestInFlight(false); - this.flushDelta(sessionId); - this.hooks.refreshSessions(); - if (this.stream.text().length > 0) { - await this.finishStream(sessionId, result); - } else { - const finalMessage = this.messageForActiveTurn(result.assistantMessage); - this.resetStream(); - this.timeline.dispatch({ type: 'user_message', message: result.userMessage, persisted: true }); - this.timeline.dispatch({ - type: 'turn_finished', - sessionId, - turnId: finalMessage.turnId || this.hooks.currentActiveTurnId(), - message: finalMessage - }); - await this.persistAssistantMessage(sessionId, finalMessage); - if (this.hooks.onTaskCompleted) { - this.hooks.onTaskCompleted(sessionId, finalMessage.turnId || ''); - } - this.hooks.syncTimeline(); - this.pageState.setBusy(false); - this.pageState.setServiceState(GeneralChatServiceState.Ready); - this.pageState.setStatus(RemoteI18n.t('generalChat.ready')); - } - } catch (err) { - await this.handleSendFailure(sessionId, rawText, images, err); - } - } - - stop(cancelled: boolean, finalStatus: string = 'cancelled'): void { - const hasStream = this.stream.hasActiveStream(); - if (!this.hooks.isVisible(this.pageState.activeSession.sessionId || '') && !hasStream) { - return; - } - const hadStream = hasStream || this.pageState.activeTurnMessage.id.length > 0; - const currentSessionId = this.stream.currentSessionId(); - const currentTurnId = this.stream.currentTurnId() || this.hooks.currentActiveTurnId(); - const requestInFlight = this.stream.isRequestInFlight(); - if (cancelled && currentSessionId.length > 0) { - this.flushDelta(currentSessionId); - } - if (hasStream) { - this.stream.markRequestCancelled(); - this.command.cancelCurrentRequest(); - } - if (hadStream && this.hooks.onTaskStopped) { - this.hooks.onTaskStopped(currentSessionId || this.pageState.activeSession.sessionId || '', currentTurnId); - } - this.stream.reset(); - if (cancelled && this.pageState.activeTurnMessage.id.length > 0) { - const active = this.pageState.activeTurnMessage; - const stopped: ChatMessage = { - id: Encoding.randomId('assistant'), - turnId: this.hooks.currentActiveTurnId(), - role: 'assistant', - text: active.text || (finalStatus === 'failed' ? - RemoteI18n.t('generalChat.interrupted') : RemoteI18n.t('generalChat.stopped')), - status: finalStatus, - detail: finalStatus === 'failed' ? this.hooks.latestUserMessageText() : '', - timestamp: new Date().toISOString(), - items: this.assistantItems([], active.text || '') - }; - this.timeline.dispatch({ - type: 'turn_finished', - sessionId: this.pageState.activeSession.sessionId || '', - turnId: stopped.turnId || this.hooks.currentActiveTurnId(), - message: stopped - }); - if (requestInFlight) { - this.stream.setPendingFinalMessage(stopped); - } else { - this.persistAssistantMessage(this.pageState.activeSession.sessionId || '', stopped); - } - this.pageState.setStatus(finalStatus === 'failed' ? - RemoteI18n.t('generalChat.interrupted') : RemoteI18n.t('status.stopRequested')); - this.pageState.setServiceState(finalStatus === 'failed' ? - GeneralChatServiceState.Failed : GeneralChatServiceState.Ready); - } - if (this.hooks.isVisible(this.pageState.activeSession.sessionId || '')) { - this.hooks.syncTimeline(); - if (cancelled || hadStream) { - this.pageState.setBusy(false); - } - } - } - - reset(): void { - this.stream.reset(); - } - - private beginStream(sessionId: string): void { - const activeTurn = this.stream.begin(sessionId); - const turnId = activeTurn.turnId || activeTurn.id.replace('active-', ''); - this.timeline.dispatch({ - type: 'turn_started', - sessionId, - turnId - }); - if (this.hooks.onTaskStarted) { - this.hooks.onTaskStarted(sessionId, turnId); - } - this.hooks.syncTimeline(); - } - - private appendDelta(sessionId: string, delta: string): void { - const accepted = this.stream.append( - sessionId, - delta, - (): boolean => this.hooks.isVisible(sessionId), - (activeTurn: ChatMessage): void => { - this.timeline.dispatch({ type: 'active_turn_updated', sessionId, message: activeTurn }); - this.hooks.syncTimeline(); - } - ); - if (accepted) { - this.pageState.setServiceState(GeneralChatServiceState.Streaming); - } - } - - private flushDelta(sessionId: string): void { - const activeTurn = this.stream.flush(sessionId, this.hooks.isVisible(sessionId)); - if (!activeTurn) { - return; - } - this.timeline.dispatch({ type: 'active_turn_updated', sessionId, message: activeTurn }); - this.hooks.syncTimeline(); - } - - private async finishStream(sessionId: string, result: GeneralChatSendResult): Promise { - const currentSessionId = this.stream.currentSessionId(); - const visible = this.hooks.isVisible(sessionId); - RemoteLogger.info(`general chat finish check session=${this.shortId(sessionId)} current=${this.shortId(currentSessionId)} visible=${visible}`); - if (currentSessionId !== sessionId && !visible) { - return; - } - const finalMessage = this.messageForActiveTurn(result.assistantMessage); - this.timeline.dispatch({ type: 'user_message', message: result.userMessage, persisted: true }); - this.timeline.dispatch({ - type: 'turn_finished', - sessionId, - turnId: finalMessage.turnId || this.hooks.currentActiveTurnId(), - message: finalMessage - }); - await this.persistAssistantMessage(sessionId, finalMessage); - if (this.hooks.onTaskCompleted) { - this.hooks.onTaskCompleted(sessionId, finalMessage.turnId || ''); - } - this.hooks.syncTimeline(); - this.resetStream(); - this.pageState.setBusy(false); - this.pageState.setServiceState(GeneralChatServiceState.Ready); - this.pageState.setStatus(RemoteI18n.t('generalChat.ready')); - } - - private messageForActiveTurn(message: ChatMessage): ChatMessage { - const turnId = this.stream.currentTurnId() || message.turnId; - return { - id: message.id, - role: message.role, - text: message.text, - status: message.status, - renderVersion: message.renderVersion, - turnId, - detail: message.detail, - error: message.error, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: message.items, - images: message.images - }; - } - - private async handleSendFailure( - sessionId: string, - rawText: string, - images: SelectedImageAttachment[], - err: Object - ): Promise { - if (this.hooks.onTaskStopped) { - this.hooks.onTaskStopped( - sessionId, - this.stream.currentTurnId() || this.hooks.currentActiveTurnId() - ); - } - this.stream.setRequestInFlight(false); - if (this.stream.takeRequestCancelled()) { - const finalMessage = this.stream.takePendingFinalMessage(); - if (finalMessage) { - await this.persistAssistantMessage(sessionId, finalMessage); - this.pageState.setServiceState(finalMessage.status === 'failed' ? - GeneralChatServiceState.Failed : GeneralChatServiceState.Ready); - } else { - this.pageState.setServiceState(GeneralChatServiceState.Ready); - } - this.resetStream(); - this.pageState.setBusy(false); - return; - } - this.flushDelta(sessionId); - const partialText = this.stream.text(); - const errorText = ConnectionErrorPolicy.errorText(err); - this.pageState.setServiceState(GeneralChatServiceStatus.fromError(errorText)); - this.resetStream(); - this.pageState.setChatInput(rawText); - this.pageState.setSelectedImages(images); - await this.drafts.saveNow(sessionId, rawText); - this.timeline.setPersistedMessages(await this.command.loadMessages(sessionId)); - if (partialText.trim().length > 0) { - const interrupted: ChatMessage = { - id: Encoding.randomId('assistant'), - turnId: this.hooks.currentActiveTurnId(), - role: 'assistant', - text: partialText, - status: 'failed', - detail: rawText, - timestamp: new Date().toISOString(), - items: this.assistantItems([], partialText) - }; - this.timeline.dispatch({ - type: 'turn_finished', - sessionId, - turnId: interrupted.turnId || this.hooks.currentActiveTurnId(), - message: interrupted - }); - await this.persistAssistantMessage(sessionId, interrupted); - } else { - this.timeline.dispatch({ type: 'error', message: errorText }); - } - this.hooks.syncTimeline(); - this.pageState.setStatus(errorText); - this.pageState.setBusy(false); - } - - private resetStream(): void { - this.stream.reset(); - } - - private async persistAssistantMessage(sessionId: string, message: ChatMessage): Promise { - if (sessionId.length > 0) { - await this.command.recordAssistantMessage(sessionId, message); - } - } - - private localUserMessage(text: string, images: SelectedImageAttachment[]): ChatMessage { - return { - id: Encoding.randomId('optimistic-user'), - turnId: '', - role: 'user', - text, - status: 'sent', - detail: '', - timestamp: new Date().toISOString(), - images, - items: [] - }; - } - - private assistantItems(tools: RemoteToolStatusResponse[], text: string): ChatMessageItemResponse[] { - const items: ChatMessageItemResponse[] = []; - tools.forEach((tool: RemoteToolStatusResponse) => items.push({ type: 'tool', tool })); - if (text.trim().length > 0) { - items.push({ type: 'text', content: text }); - } - return items; - } - - private shortId(value: string): string { - return value.length > 8 ? value.slice(0, 8) : value; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/LocaleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/LocaleController.ets deleted file mode 100644 index 0ac7c9b85d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/LocaleController.ets +++ /dev/null @@ -1,43 +0,0 @@ -import { AppLocale } from '../../i18n/AppLocale'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { LocalePreferenceStore } from '../../services/LocalePreferenceStore'; -import { RemoteLogger } from '../../services/RemoteLogger'; - -export interface LocaleControllerHooks { - readonly onLanguageChanged: (language: string) => void; -} - -export class LocaleController { - private readonly store: LocalePreferenceStore; - private readonly hooks: LocaleControllerHooks; - - constructor(store: LocalePreferenceStore, hooks: LocaleControllerHooks) { - this.store = store; - this.hooks = hooks; - } - - async initialize(context: Context): Promise { - try { - const language = await this.store.init(context); - this.hooks.onLanguageChanged(language); - RemoteLogger.info(`app locale ready language=${language}`); - return language; - } catch (err) { - const fallback = RemoteI18n.setLanguage(AppLocale.DEFAULT); - RemoteLogger.warn(`locale init failed, using ${fallback}: ${err instanceof Error ? err.message : String(err)}`); - this.hooks.onLanguageChanged(fallback); - return fallback; - } - } - - async setLanguage(language: string): Promise { - const resolved = await this.store.save(language); - this.hooks.onLanguageChanged(resolved); - RemoteLogger.info(`app locale changed language=${resolved}`); - return resolved; - } - - current(): string { - return this.store.current(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/MiniAppViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/MiniAppViewModel.ets deleted file mode 100644 index e3c1f84f76..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/MiniAppViewModel.ets +++ /dev/null @@ -1,90 +0,0 @@ -import { MiniAppActions, MiniAppBridgeReply, MiniAppBridgeRequest, MiniAppHost } from '../../model/MiniAppModels'; -import { MiniAppDocument } from '../../services/MiniAppDocument'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { MiniAppState } from '../state/MiniAppState'; - -export class MiniAppViewModel { - readonly state: MiniAppState = new MiniAppState(); - private generation: number = 0; - private readonly host: MiniAppHost; - readonly actions: MiniAppActions = { - open: (): void => { void this.open(); }, - close: (): void => this.close(), - back: (): void => { void this.open(); }, - refresh: (): void => { void this.open(); }, - select: (id: string): void => { void this.select(id); }, - request: (raw: string, revision: number): Promise => this.request(raw, revision) - }; - - constructor(host: MiniAppHost) { this.host = host; } - - close(): void { - this.generation += 1; - this.state.visible = false; - this.state.loading = false; - this.state.document = ''; - this.state.appId = ''; - } - - async open(): Promise { - const generation = ++this.generation; - this.state.visible = true; - this.state.document = ''; - this.state.appId = ''; - this.state.name = ''; - this.state.apps = []; - this.state.error = ''; - this.state.loading = true; - try { - const apps = await this.host.list(RemoteI18n.language()); - if (generation === this.generation) this.state.apps = apps; - } catch (error) { - if (generation === this.generation) this.state.error = String(error); - } finally { - if (generation === this.generation) this.state.loading = false; - } - } - - async select(id: string): Promise { - const app = this.state.apps.find((entry) => entry.id === id); - if (!this.state.visible || !app) return; - const generation = ++this.generation; - this.state.loading = true; - this.state.document = ''; - this.state.appId = ''; - this.state.error = ''; - try { - const html = await this.host.document(id); - if (generation !== this.generation) return; - if (!html) throw new Error(RemoteI18n.t('miniapp.invalidPage')); - this.state.appId = id; - this.state.name = app.name; - this.state.document = MiniAppDocument.build(html, RemoteI18n.language()); - this.state.revision += 1; - } catch (error) { - if (generation === this.generation) this.state.error = String(error); - } finally { - if (generation === this.generation) this.state.loading = false; - } - } - - async request(raw: string, revision: number = this.state.revision): Promise { - const generation = this.generation; - let id: string = ''; - try { - const rpc = JSON.parse(raw) as MiniAppBridgeRequest; - id = rpc.id; - if (revision !== this.state.revision || typeof id !== 'string' || !rpc.params || !this.state.visible || !this.state.appId || - !['storage.get', 'storage.set', 'clipboard.writeText'].includes(rpc.method)) { - throw new Error(RemoteI18n.t('miniapp.unsupported')); - } - const result = await this.host.call(this.state.appId, rpc.method, rpc.params); - if (generation !== this.generation) throw new Error(RemoteI18n.t('miniapp.closed')); - const reply: MiniAppBridgeReply = { jsonrpc: '2.0', id, result }; - return JSON.stringify(reply); - } catch (error) { - const reply: MiniAppBridgeReply = { jsonrpc: '2.0', id, error: { message: String(error) } }; - return JSON.stringify(reply); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteActivityViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteActivityViewModel.ets deleted file mode 100644 index 9362e47666..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteActivityViewModel.ets +++ /dev/null @@ -1,193 +0,0 @@ -import { SessionSummary } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { AsyncLifecycleGate } from '../../services/AsyncLifecycleGate'; -import { RemoteActivityLifecycleController } from '../../services/RemoteActivityLifecycleController'; -import { RemoteConnectionCoordinator } from '../../services/RemoteConnectionCoordinator'; -import { RemoteLogger } from '../../services/RemoteLogger'; - -export interface RemoteActivityViewModelHooks { - readonly isConnected: () => boolean; - readonly isReconnecting: () => boolean; - readonly isBusy: () => boolean; - readonly hasRemoteBinding: () => boolean; - readonly isRemoteChat: () => boolean; - readonly activeSession: () => SessionSummary; - readonly onConnectionState: (state: string) => void; - readonly onStatus: (status: string) => void; - readonly onConnectionError: (err: Object) => Promise; - readonly onObserveCatalog?: () => void; - readonly onStopCatalog?: () => void; - readonly onStartPolling: () => void; - readonly onStopPolling: () => void; - readonly onPoll: () => Promise; - readonly onReconnect: () => Promise; - readonly onRestoreSession: (session: SessionSummary) => Promise; -} - -/** Owns foreground recovery, host catalog observation, and idempotent resume cancellation. */ -export class RemoteActivityViewModel { - private readonly activity: RemoteActivityLifecycleController; - private readonly connection: RemoteConnectionCoordinator; - private readonly gate: AsyncLifecycleGate; - private readonly hooks: RemoteActivityViewModelHooks; - private recoveryToken: number = 0; - - constructor( - activity: RemoteActivityLifecycleController, - connection: RemoteConnectionCoordinator, - gate: AsyncLifecycleGate, - hooks: RemoteActivityViewModelHooks - ) { - this.activity = activity; - this.connection = connection; - this.gate = gate; - this.hooks = hooks; - } - - startHeartbeat(): void { - // Relay liveness does not prove that the selected host can answer commands. - this.activity.startHeartbeat(); - this.hooks.onObserveCatalog?.(); - } - - stopHeartbeat(): void { - this.activity.stopHeartbeat(); - this.hooks.onStopCatalog?.(); - } - - /** Bounded host probe used by the foreground heartbeat and explicit recovery. */ - async checkConnectionHealth(): Promise { - if (this.hooks.isBusy() || this.recoveryToken !== 0 || !this.hooks.hasRemoteBinding()) { - return; - } - const wasConnected = this.hooks.isConnected(); - if (!wasConnected && !this.hooks.isReconnecting()) { - return; - } - const token = this.gate.begin(); - this.recoveryToken = token; - try { - await this.connection.ping(); - if (!this.gate.isCurrent(token)) return; - if (!wasConnected) { - this.hooks.onConnectionState('connected'); - this.hooks.onStatus(RemoteI18n.t('connection.connected')); - if (this.hooks.isRemoteChat()) this.hooks.onStartPolling(); - } - } catch (err) { - if (!this.gate.isCurrent(token)) { - return; - } - if (await this.hooks.onConnectionError(err)) { - return; - } - if (!this.gate.isCurrent(token)) { - return; - } - this.hooks.onStatus(ConnectionErrorPolicy.errorText(err)); - if (wasConnected) { - RemoteLogger.info('heartbeat ping failed, waiting for the link to come back'); - this.hooks.onStopPolling(); - this.hooks.onConnectionState('reconnecting'); - } - } finally { - if (this.recoveryToken === token) this.recoveryToken = 0; - } - } - - resume(): void { - if (!this.hooks.hasRemoteBinding()) { - return; - } - this.startHeartbeat(); - if (this.hooks.isRemoteChat() && this.hooks.activeSession().sessionId.length > 0) { - this.hooks.onStartPolling(); - void this.hooks.onPoll(); - } - void this.verifyForeground(); - } - - async verifyForeground(): Promise { - if (this.hooks.isBusy() || !this.hooks.hasRemoteBinding()) { - return; - } - const token = this.gate.begin(); - try { - await this.connection.ping(); - if (!this.gate.isCurrent(token)) { - return; - } - } catch (err) { - if (!this.gate.isCurrent(token)) { - return; - } - if (await this.hooks.onConnectionError(err)) { - return; - } - if (!this.gate.isCurrent(token)) { - return; - } - this.hooks.onStatus(ConnectionErrorPolicy.errorText(err)); - this.hooks.onConnectionState('reconnecting'); - // Only a failed host probe starts recovery; foregrounding a healthy - // connection must not flash a reconnect warning. - this.recoveryToken = token; - try { - await this.reconnect(token); - } catch (reconnectErr) { - if (this.gate.isCurrent(token)) { - this.hooks.onStatus(ConnectionErrorPolicy.errorText(reconnectErr)); - } - } finally { - if (this.recoveryToken === token) { - this.recoveryToken = 0; - } - } - return; - } - this.hooks.onConnectionState('connected'); - this.hooks.onStatus(RemoteI18n.t('connection.connected')); - if (this.hooks.isRemoteChat() && this.hooks.activeSession().sessionId.length > 0) { - try { - await this.hooks.onPoll(); - } catch (err) { - // A transcript refresh error is not evidence that the host ping failed. - if (this.gate.isCurrent(token)) { - this.hooks.onStatus(ConnectionErrorPolicy.errorText(err)); - } - } - } - } - - invalidate(): void { - this.gate.invalidate(); - this.recoveryToken = 0; - this.hooks.onStopPolling(); - this.stopHeartbeat(); - } - - /** Keeps only the active-turn poll alive during a transient background window. */ - suspendKeepingActiveTurnPoll(): void { - this.gate.invalidate(); - this.recoveryToken = 0; - this.stopHeartbeat(); - } - - private async reconnect(token: number): Promise { - const shouldRestore = this.hooks.isRemoteChat() && this.hooks.activeSession().sessionId.length > 0; - const session = this.hooks.activeSession(); - await this.hooks.onReconnect(); - if (!this.gate.isCurrent(token) || !this.hooks.isConnected()) { - return; - } - if (shouldRestore) { - await this.hooks.onRestoreSession(session); - if (!this.gate.isCurrent(token)) { - return; - } - this.hooks.onStartPolling(); - await this.hooks.onPoll(); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteConnectionController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteConnectionController.ets deleted file mode 100644 index 6bec20a67f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteConnectionController.ets +++ /dev/null @@ -1,196 +0,0 @@ -import { - WorkspaceInfo -} from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { Encoding } from '../../services/Encoding'; -import { MobileIdentitySnapshot, MobileIdentityStore } from '../../services/MobileIdentityStore'; -import { RemoteFileDownloadController } from '../../services/RemoteFileDownloadController'; -import { RemoteModelController } from '../../services/RemoteModelController'; -import { RemoteSessionController } from '../../services/RemoteSessionController'; -import { accountDeviceLink } from '../../services/AccountDeviceLink'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { RemoteConnectionCoordinator } from '../../services/RemoteConnectionCoordinator'; -import { RemotePageState } from '../state/RemotePageState'; -import { AppRoute } from '../navigation/AppRouteContract'; -import { RemoteLogger } from '../../services/RemoteLogger'; - -export enum RemoteConnectionState { - Idle = 'idle', - Parsing = 'parsing', - Pairing = 'pairing', - Connected = 'connected', - Reconnecting = 'reconnecting', - Failed = 'failed', - Disconnected = 'disconnected' -} - -export class RemoteConnectionController { - private readonly pageState: RemotePageState; - private readonly identity: MobileIdentityStore; - private readonly connection: RemoteConnectionCoordinator; - private readonly sessions: RemoteSessionController; - private readonly models: RemoteModelController; - private readonly files: RemoteFileDownloadController; - private readonly resetTimeline: (sessionId: string) => void; - private readonly resetKnownState: () => void; - private readonly startHeartbeat: () => void; - private readonly stopHeartbeat: () => void; - private readonly stopPolling: () => void; - private readonly loadRecentWorkspaces: () => Promise; - private readonly clearCachedRemoteData: () => Promise; - private readonly replaceRoute: (route: AppRoute) => void; - private readonly closeConnectSheet: () => void; - private readonly openConnectSheet: () => void; - private deviceId: string = Encoding.randomId('harmony'); - private autoReconnectAttempted: boolean = false; - private failureCount: number = 0; - private lockUntil: number = 0; - private restoredControlTargetType: string = ''; - - constructor( - pageState: RemotePageState, - identity: MobileIdentityStore, - connection: RemoteConnectionCoordinator, - sessions: RemoteSessionController, - models: RemoteModelController, - files: RemoteFileDownloadController, - resetTimeline: (sessionId: string) => void, - resetKnownState: () => void, - startHeartbeat: () => void, - stopHeartbeat: () => void, - stopPolling: () => void, - loadRecentWorkspaces: () => Promise, - clearCachedRemoteData: () => Promise, - replaceRoute: (route: AppRoute) => void, - closeConnectSheet: () => void, - openConnectSheet: () => void - ) { - this.pageState = pageState; - this.identity = identity; - this.connection = connection; - this.sessions = sessions; - this.models = models; - this.files = files; - this.resetTimeline = resetTimeline; - this.resetKnownState = resetKnownState; - this.startHeartbeat = startHeartbeat; - this.stopHeartbeat = stopHeartbeat; - this.stopPolling = stopPolling; - this.loadRecentWorkspaces = loadRecentWorkspaces; - this.clearCachedRemoteData = clearCachedRemoteData; - this.replaceRoute = replaceRoute; - this.closeConnectSheet = closeConnectSheet; - this.openConnectSheet = openConnectSheet; - } - - getDeviceId(): string { - return this.deviceId; - } - - controlTargetPreference(): string { - return this.restoredControlTargetType; - } - - async rememberControlTargetType(controlTargetType: string): Promise { - const normalized = controlTargetType === 'account_device' ? - controlTargetType : ''; - this.restoredControlTargetType = normalized; - try { - await this.identity.saveControlTargetType(normalized); - } catch (err) { - // The live transport is already authoritative. A persistence failure may - // affect the next launch, but must not turn this connection into a failure. - RemoteLogger.warn(`control target preference persistence failed: ${String(err)}`); - } - } - - async restore(context: Context): Promise { - await this.restoreWithReconnectPolicy(context, true); - } - - async restoreWithoutReconnect(context: Context): Promise { - await this.restoreWithReconnectPolicy(context, false); - } - - private async restoreWithReconnectPolicy(context: Context, reconnect: boolean): Promise { - try { - const snapshot: MobileIdentitySnapshot = await this.identity.init(context); - this.deviceId = snapshot.installId; - this.pageState.setUserId(snapshot.userId || snapshot.installId); - this.pageState.setRemoteUrl(snapshot.remoteUrl); - this.restoredControlTargetType = snapshot.controlTargetType === 'account_device' ? snapshot.controlTargetType : ''; - this.models.setPreferredModelId(await this.identity.getLastModelId()); - this.failureCount = snapshot.userIdFailureCount; - this.lockUntil = snapshot.userIdLockUntil > Date.now() ? snapshot.userIdLockUntil : 0; - if (snapshot.userIdLockUntil > 0 && this.lockUntil === 0) { - this.failureCount = 0; - await this.identity.clearUserIdProtection(); - } - this.pageState.setRemoteUrlInputVisible(snapshot.remoteUrl.length > 0); - } catch (err) { - this.pageState.setStatusText(ConnectionErrorPolicy.errorText(err)); - this.setState(RemoteConnectionState.Failed); - } - } - - async disconnect(clearPairing: boolean): Promise { - this.connection.invalidate(); - this.stopPolling(); - this.stopHeartbeat(); - this.connection.reset(); - this.sessions.clearSessions(); - this.pageState.clear(); - this.resetTimeline(''); - this.pageState.setHasMoreMessages(false); - this.models.clearCatalog(); - this.pageState.clearActiveSession(); - this.resetKnownState(); - this.files.clear(); - this.pageState.setWorkspace(RemoteI18n.t('status.notConnected'), '', '', '', 'normal'); - this.pageState.setAuthenticatedUserId(''); - // Same rule as Android and iOS: leaving an account device keeps it as the - // selection, so the settings card can offer it again. Only unpairing ends it. - if (clearPairing || this.pageState.controlTargetType !== 'account_device') { - this.pageState.clearControlTarget(); - } - this.pageState.clearWorkspaceActions(); - this.setState(RemoteConnectionState.Disconnected); - this.pageState.setConnectionFailureKind(''); - this.pageState.setStatusText(clearPairing ? RemoteI18n.t('status.pairingCleared') : RemoteI18n.t('status.disconnected')); - this.replaceRoute(AppRoute.RemoteHome); - if (clearPairing) { - this.pageState.setRemoteUrl(''); - this.pageState.setDesktopIdentity('', ''); - this.pageState.setUserId(this.deviceId); - this.pageState.setAccountPairing(false, ''); - this.pageState.setRemoteUrlInputVisible(false); - await this.identity.clearPairingInput(); - await this.rememberControlTargetType(''); - // Unpairing is the user saying they are done with that desktop. Leaving - // its sessions on disk would put them back on Remote Home at the next - // launch, with nothing behind them to open. - await this.clearCachedRemoteData(); - } else { - this.pageState.setRemoteUrlInputVisible(this.pageState.remoteUrl.trim().length > 0); - } - } - - ensureAvailable(): boolean { - if (RemoteUiState.canUseRemote(this.pageState.connectionState)) { - return true; - } - this.pageState.setStatusText(RemoteI18n.t('status.remoteUnavailable')); - return false; - } - - applyWorkspace(workspace: WorkspaceInfo): void { - this.pageState.setWorkspace(workspace.name, workspace.path, workspace.assistantId || '', workspace.gitBranch, - workspace.workspaceKind || 'normal', workspace.remoteConnectionId || '', workspace.remoteSshHost || '', - workspace.workspaceId || ''); - } - - private setState(state: RemoteConnectionState): void { - this.pageState.setConnectionState(state); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteCreateFlowController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteCreateFlowController.ets deleted file mode 100644 index 74c7005c85..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteCreateFlowController.ets +++ /dev/null @@ -1,137 +0,0 @@ -import { RemoteSession, SessionSummary } from '../../model/RemoteModels'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemotePageState } from '../state/RemotePageState'; -import { - RemoteConversationDependencies, - requireRemoteRuntime, - routeCreatedRemoteSession, - routeRemoteSessionInPlace -} from './ConversationRuntime'; - -/** Creates and opens remote sessions without an intermediate creation page. */ -export class RemoteCreateFlowController { - private readonly remote: RemotePageState; - private readonly remoteRuntime?: RemoteConversationDependencies; - - constructor( - remote: RemotePageState, - remoteRuntime: RemoteConversationDependencies | undefined - ) { - this.remote = remote; - this.remoteRuntime = remoteRuntime; - } - - private navigateCreated(sessionId: string): void { - routeCreatedRemoteSession(sessionId, requireRemoteRuntime(this.remoteRuntime), (dismissed: boolean) => { - this.remote.setConversationDismissed(dismissed); - }); - } - - private navigateInPlace(sessionId: string): void { - routeRemoteSessionInPlace(sessionId, requireRemoteRuntime(this.remoteRuntime), (dismissed: boolean) => { - this.remote.setConversationDismissed(dismissed); - }); - } - - async createRemoteSession(agentType: string, inPlace: boolean = false): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - runtime.filePreview.close(); - await runtime.sessions.createSession( - agentType, - '', - inPlace ? (sessionId: string): void => this.navigateInPlace(sessionId) : - (sessionId: string): void => this.navigateCreated(sessionId) - ); - } - - async ensureRemoteControlTarget(deviceId?: string): Promise { - const target = (deviceId || '').trim(); - if (target.length === 0) { - return; - } - const runtime = requireRemoteRuntime(this.remoteRuntime); - const activeId = this.remote.controlTargetDeviceId || this.remote.desktopId; - if (target === activeId && this.remote.connectionState === 'connected') { - return; - } - this.remote.setStatusText(RemoteI18n.t('remote.settings.deviceConnecting')); - try { - let device = runtime.settings.knownAccountDevice(target); - if (!device) { - device = (await runtime.settings.listCloudAccountDevices()) - .find((item: CloudAccountDevice): boolean => item.deviceId === target); - } - if (!device) { - throw new Error(RemoteI18n.t('remote.settings.deviceUnavailable')); - } - await runtime.settings.selectCloudAccountDevice(device, false); - } catch (err) { - this.remote.setLoadingHome(false); - throw new Error(err instanceof Error ? err.message : String(err)); - } - } - - async createRemoteSessionInWorkspace( - path: string, - agentType: string = 'code', - inPlace: boolean = false, - deviceId: string = '', - remoteConnectionId?: string, - remoteSshHost?: string, - workspaceId?: string - ): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - runtime.filePreview.close(); - await this.ensureRemoteControlTarget(deviceId); - await runtime.sessions.createSessionInWorkspace( - path, - '', - agentType, - inPlace ? (sessionId: string): void => this.navigateInPlace(sessionId) : - (sessionId: string): void => this.navigateCreated(sessionId), - '', true, remoteConnectionId, - remoteSshHost, - workspaceId - ); - } - - async openRemoteSession(item: RemoteSession, inPlace: boolean = false): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - runtime.filePreview.close(); - this.remote.setPendingSessionId(item.id); - try { - await this.ensureRemoteControlTarget(item.deviceId); - await runtime.sessions.openSession( - item, - this.remote.workspacePath, - inPlace ? (sessionId: string): void => this.navigateInPlace(sessionId) : - (sessionId: string): void => this.navigateCreated(sessionId) - ); - } catch (err) { - this.remote.setPendingSessionId(''); - this.remote.setLoadingHome(false); - RemoteLogger.warn(`open remote session failed session=${item.id}: ${String(err)}`); - throw new Error(err instanceof Error ? err.message : String(err)); - } - } - - applyRemoteActiveSession(session: SessionSummary): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const current = this.remote.activeSession; - if (runtime.hooks.isFilePreviewVisible() && - (current.sessionId !== session.sessionId || current.workspacePath !== session.workspacePath)) { - runtime.filePreview.close(); - } - this.remote.setActiveSession(session); - } - - async deleteRemoteSession(item: RemoteSession): Promise { - await requireRemoteRuntime(this.remoteRuntime).sessions.deleteSession(item, this.remote.workspacePath); - } - - routeCreatedRemoteSession(sessionId: string): void { - this.navigateCreated(sessionId); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteFilePreviewController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteFilePreviewController.ets deleted file mode 100644 index b3cd237933..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteFilePreviewController.ets +++ /dev/null @@ -1,266 +0,0 @@ -import { FileInfo, ReadFileChunkResult, ReadFileResult } from '../../model/RemoteModels'; -import { - FilePreviewPhase, - FilePreviewRendererKind, - FilePreviewState -} from '../state/FilePreviewState'; -import { FilePreviewTarget } from '../../model/FilePreviewTarget'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { Encoding } from '../../services/Encoding'; -import { FilePreviewErrorPolicy } from '../../services/FilePreviewErrorPolicy'; -import { FilePreviewPolicy } from '../../services/FilePreviewPolicy'; -import { RemoteWorkspaceFileClient } from '../../services/RemoteWorkspaceFileClient'; - -export class RemoteFilePreviewController { - private readonly client: RemoteWorkspaceFileClient; - private readonly state: FilePreviewState; - private readonly remoteAvailable: () => boolean; - private readonly currentControlTargetEpoch: () => number; - - constructor( - client: RemoteWorkspaceFileClient, - state: FilePreviewState, - remoteAvailable: () => boolean, - currentControlTargetEpoch: () => number - ) { - this.client = client; - this.state = state; - this.remoteAvailable = remoteAvailable; - this.currentControlTargetEpoch = currentControlTargetEpoch; - } - - async open(target: FilePreviewTarget): Promise { - if (!target.isValid() || !this.remoteAvailable() || - target.controlTargetEpoch !== this.currentControlTargetEpoch()) { - return; - } - const version = this.state.begin(target); - try { - const info = await this.client.getFileInfo(target.remotePath, target.sessionId); - if (!this.isCurrentTarget(version, target) || this.failIfUnavailable()) { - return; - } - this.applyMetadata(info); - const renderer = RemoteFilePreviewController.rendererFor(info.name, info.mimeType); - this.state.rendererKind = renderer; - if (renderer === FilePreviewRendererKind.Unsupported || - (renderer === FilePreviewRendererKind.Image && !FilePreviewPolicy.canPreviewImage(info.size))) { - this.state.phase = FilePreviewPhase.Unsupported; - return; - } - if (renderer === FilePreviewRendererKind.Image) { - const image = await this.client.readFile(target.remotePath, target.sessionId, undefined, FilePreviewPolicy.IMAGE_MAX_BYTES); - if (!this.isCurrentTarget(version, target) || this.failIfUnavailable()) { - return; - } - if (!FilePreviewPolicy.canPreviewImage(image.size)) { - this.state.fileName = image.name; - this.state.fileSize = image.size; - this.state.mimeType = image.mimeType; - this.state.phase = FilePreviewPhase.Unsupported; - return; - } - this.applyImage(image); - return; - } - const limit = FilePreviewPolicy.textReadLimit(info.size); - const chunk = await this.client.readFileChunk(target.remotePath, 0, limit, target.sessionId); - if (!this.isCurrentTarget(version, target) || this.failIfUnavailable()) { - return; - } - this.applyText(chunk, info.size > limit); - } catch (err) { - if (!this.isCurrentTarget(version, target)) { - return; - } - this.state.phase = FilePreviewPhase.Error; - if (this.remoteAvailable()) { - const failure = FilePreviewErrorPolicy.resolve(err); - this.state.errorText = failure.text; - this.state.errorRetryable = failure.retryable; - } else { - this.state.errorText = RemoteI18n.t('filePreview.offline'); - this.state.errorRetryable = true; - } - } - } - - async refresh(): Promise { - if (!this.state.visible || !this.state.target.isValid()) { - return; - } - await this.open(this.state.target); - } - - close(): void { - this.state.close(); - } - - private isCurrentTarget(version: number, target: FilePreviewTarget): boolean { - return this.state.isCurrent(version, target) && - target.controlTargetEpoch === this.currentControlTargetEpoch(); - } - - private failIfUnavailable(): boolean { - if (this.remoteAvailable()) { - return false; - } - this.state.phase = FilePreviewPhase.Error; - this.state.errorText = RemoteI18n.t('filePreview.offline'); - this.state.errorRetryable = true; - return true; - } - - private applyMetadata(info: FileInfo): void { - this.state.fileName = info.name; - this.state.fileSize = info.size; - this.state.mimeType = info.mimeType; - } - - private applyText(chunk: ReadFileChunkResult, truncated: boolean): void { - const bytes = Encoding.base64ToBytes(chunk.contentBase64); - if (RemoteFilePreviewController.isBinary(bytes)) { - this.state.phase = FilePreviewPhase.Unsupported; - this.state.rendererKind = FilePreviewRendererKind.Unsupported; - this.state.loadedBytes = bytes.length; - return; - } - const text = Encoding.bytesToUtf8(bytes); - if (RemoteFilePreviewController.isSuspiciousText(bytes, text)) { - this.state.phase = FilePreviewPhase.Unsupported; - this.state.rendererKind = FilePreviewRendererKind.Unsupported; - this.state.loadedBytes = bytes.length; - return; - } - this.state.textContent = text; - this.state.contentBase64 = ''; - this.state.loadedBytes = bytes.length; - this.state.truncated = truncated || chunk.totalSize > bytes.length; - this.state.phase = FilePreviewPhase.Ready; - } - - private applyImage(result: ReadFileResult): void { - this.state.fileName = result.name; - this.state.fileSize = result.size; - this.state.mimeType = result.mimeType; - this.state.contentBase64 = result.contentBase64; - this.state.textContent = ''; - this.state.loadedBytes = result.size; - this.state.truncated = false; - this.state.phase = FilePreviewPhase.Ready; - } - - static rendererFor(name: string, mimeType: string): FilePreviewRendererKind { - const mime = mimeType.toLowerCase(); - const extension = RemoteFilePreviewController.extension(name); - if (mime.indexOf('image/') === 0 && extension !== 'svg') { - return FilePreviewRendererKind.Image; - } - if (mime === 'text/markdown' || extension === 'md' || extension === 'mdx') { - return FilePreviewRendererKind.Markdown; - } - if (mime.indexOf('text/') === 0 || mime === 'application/json' || mime === 'application/xml' || - RemoteFilePreviewController.isTextExtension(extension) || - RemoteFilePreviewController.isTextFileName(name)) { - return FilePreviewRendererKind.Text; - } - return FilePreviewRendererKind.Unsupported; - } - - private static extension(name: string): string { - const fileName = name.replace(/\\/g, '/').split('/').pop() || ''; - const dot = fileName.lastIndexOf('.'); - return dot >= 0 ? fileName.slice(dot + 1).toLowerCase() : ''; - } - - private static isTextExtension(extension: string): boolean { - return '|js|jsx|ts|tsx|mjs|cjs|py|rs|go|java|kt|c|cpp|h|hpp|cs|rb|php|swift|vue|svelte|css|scss|less|json|jsonc|yaml|yml|toml|xml|csv|tsv|txt|log|sh|bash|zsh|fish|ps1|bat|cmd|sql|graphql|gql|proto|lock|env|ini|cfg|conf|ets|gitignore|editorconfig|'.indexOf(`|${extension}|`) >= 0; - } - - private static isTextFileName(name: string): boolean { - const fileName = name.replace(/\\/g, '/').split('/').pop()?.toLowerCase() || ''; - return fileName === 'dockerfile' || fileName === 'makefile' || fileName === 'justfile' || - fileName === 'gemfile' || fileName === 'rakefile' || fileName === 'procfile' || - fileName === 'license' || fileName === 'readme' || fileName === 'changelog'; - } - - private static isBinary(bytes: Uint8Array): boolean { - const limit = Math.min(bytes.length, 4096); - for (let index = 0; index < limit; index++) { - if (bytes[index] === 0) { - return true; - } - } - return false; - } - - private static isSuspiciousText(bytes: Uint8Array, text: string): boolean { - if (!RemoteFilePreviewController.isValidUtf8(bytes)) { - return true; - } - if (text.indexOf('\uFFFD') >= 0) { - return true; - } - const limit = Math.min(bytes.length, 4096); - let controls = 0; - for (let index = 0; index < limit; index++) { - const value = bytes[index]; - if (value < 32 && value !== 9 && value !== 10 && value !== 13) { - controls += 1; - } - } - return limit > 0 && controls / limit > 0.02; - } - - private static isValidUtf8(bytes: Uint8Array): boolean { - let index = 0; - while (index < bytes.length) { - const first = bytes[index]; - if (first <= 0x7F) { - index += 1; - continue; - } - let continuationCount = 0; - let minimumFirst = 0x80; - let maximumFirst = 0xBF; - if (first >= 0xC2 && first <= 0xDF) { - continuationCount = 1; - } else if (first === 0xE0) { - continuationCount = 2; - minimumFirst = 0xA0; - } else if (first >= 0xE1 && first <= 0xEC) { - continuationCount = 2; - } else if (first === 0xED) { - continuationCount = 2; - maximumFirst = 0x9F; - } else if (first >= 0xEE && first <= 0xEF) { - continuationCount = 2; - } else if (first === 0xF0) { - continuationCount = 3; - minimumFirst = 0x90; - } else if (first >= 0xF1 && first <= 0xF3) { - continuationCount = 3; - } else if (first === 0xF4) { - continuationCount = 3; - maximumFirst = 0x8F; - } else { - return false; - } - if (index + continuationCount >= bytes.length) { - return false; - } - const second = bytes[index + 1]; - if (second < minimumFirst || second > maximumFirst) { - return false; - } - for (let offset = 2; offset <= continuationCount; offset++) { - const continuation = bytes[index + offset]; - if (continuation < 0x80 || continuation > 0xBF) { - return false; - } - } - index += continuationCount + 1; - } - return true; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteSessionViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteSessionViewModel.ets deleted file mode 100644 index f54019eefa..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteSessionViewModel.ets +++ /dev/null @@ -1,388 +0,0 @@ -import { RemoteSession, SessionSummary } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteChatCommandController } from '../../services/RemoteChatCommandController'; -import { RemoteModelController } from '../../services/RemoteModelController'; -import { RemoteSessionController } from '../../services/RemoteSessionController'; -import { RemoteFileDownloadController } from '../../services/RemoteFileDownloadController'; -import { DeferredLoadingGate } from '../../services/DeferredLoadingGate'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { MainThreadStallProbe } from '../../services/MainThreadStallProbe'; -import { RemotePageState } from '../state/RemotePageState'; - -export interface RemoteSessionViewModelHooks { - readonly remoteAvailable: () => boolean; - readonly isConnected: () => boolean; - readonly isBusy: () => boolean; - readonly onBusy: (busy: boolean) => void; - readonly onRouteChat: (sessionId: string) => void; - readonly onRouteHome: () => void; - readonly onStopPolling: () => void; - readonly onStartPolling: () => void; - readonly onNudgePolling: () => void; - readonly onResetTimeline: (sessionId: string) => void; - readonly onClearRemoteFiles: () => void; - readonly onKnownStateReset: () => void; - readonly onLoadActiveMessages: () => Promise; - readonly onCreatedSession: (session: SessionSummary) => Promise; - readonly onRefreshSessions: () => Promise; - readonly onSelectWorkspace: (path: string, workspaceId?: string) => Promise; -} - -/** Owns remote session commands and their page lifecycle effects. */ -export class RemoteSessionViewModel { - private readonly pageState: RemotePageState; - private readonly sessions: RemoteSessionController; - private readonly chat: RemoteChatCommandController; - private readonly models: RemoteModelController; - private readonly files: RemoteFileDownloadController; - private readonly hooks: RemoteSessionViewModelHooks; - // Long enough that a cached transcript never flashes a skeleton on its way in, - // short enough that a transcript coming over the relay still says so. The cap - // is the backstop for a session whose records never arrive at all. - private readonly openLoadingGate: DeferredLoadingGate = - new DeferredLoadingGate(140, (visible: boolean): void => this.pageState.setTranscriptLoading(visible), 20000); - // How many opens this view model has started and not yet settled. Opening a - // session raises the busy flag, so without this the flag an open sets would - // read, to the next tap, as a run in progress. - private openInFlight: number = 0; - // Only the latest selection may start polling after a shared or delayed - // transcript request settles. This is separate from the loading gate token: - // the gate owns presentation, while this generation owns lifecycle effects. - private openGeneration: number = 0; - - constructor( - pageState: RemotePageState, - sessions: RemoteSessionController, - chat: RemoteChatCommandController, - models: RemoteModelController, - files: RemoteFileDownloadController, - hooks: RemoteSessionViewModelHooks - ) { - this.pageState = pageState; - this.sessions = sessions; - this.chat = chat; - this.models = models; - this.files = files; - this.hooks = hooks; - } - - private static shortId(value: string): string { - if (value.length <= 10) { - return value; - } - return `${value.slice(0, 6)}...${value.slice(-4)}`; - } - - async refreshSessions(propagateFailure: boolean = false): Promise { - await this.sessions.refresh( - this.pageState.sessionQuery, - this.pageState.sessionFilter, - this.hooks.remoteAvailable(), - this.hooks.isConnected(), - propagateFailure - ); - } - - async loadMoreSessions(): Promise { - await this.sessions.loadMore( - this.pageState.sessionQuery, - this.pageState.sessionFilter, - this.hooks.isBusy(), - this.hooks.remoteAvailable() - ); - } - - async setFilter(filter: string): Promise { - if (this.pageState.sessionFilter === filter) { - return; - } - this.pageState.setFilter(filter); - await this.refreshSessions(); - } - - async createSession( - agentType: string, - instruction: string = '', - onRouteChat: (sessionId: string) => void = this.hooks.onRouteChat, - modelId: string = '', - routeBeforeCreate: boolean = true - ): Promise { - if (this.hooks.isBusy() || !this.hooks.remoteAvailable()) { - return; - } - const previousSession: SessionSummary = this.copySession(this.pageState.activeSession); - this.beginSessionCreation(onRouteChat, routeBeforeCreate); - try { - const created = await this.performCreateSession(agentType, instruction, onRouteChat, modelId); - if (!created && routeBeforeCreate) { - this.restoreAfterFailedCreation(previousSession, onRouteChat); - } - } finally { - this.pageState.setConversationLoading(false); - this.pageState.setPendingSessionId(''); - } - } - - private async performCreateSession( - agentType: string, - instruction: string, - onRouteChat: (sessionId: string) => void, - modelId: string, - workspacePath: string = '', - remoteConnectionId?: string, - remoteSshHost?: string, - workspaceId?: string - ): Promise { - const created = await this.sessions.create( - agentType, - this.hooks.isBusy(), - this.hooks.remoteAvailable(), - async (session: SessionSummary): Promise => { - this.pageState.clearComposer(); - this.pageState.setHasMoreMessages(false); - this.hooks.onKnownStateReset(); - this.hooks.onResetTimeline(session.sessionId); - onRouteChat(session.sessionId); - // The create surface has already handed its optimistic instruction to - // the remote projection. Do not cover it with a loading veil while the - // empty initial transcript and first turn are being synchronized. - this.pageState.setConversationLoading(false); - // Same ordering as openSession: whatever the new session already has to - // show goes up first. The model picker needs no request of its own — - // the poll started here carries the catalog back with it. - await this.hooks.onLoadActiveMessages(); - this.hooks.onStartPolling(); - await this.hooks.onCreatedSession(session); - }, - instruction, - modelId, - workspacePath, - remoteConnectionId, - remoteSshHost, - workspaceId - ); - if (created && (created.initialTurnId || '').length > 0) { - // The first poll may have observed the newly allocated session before - // send_message reached the host and backed off as idle. Wake it as soon - // as the initial turn is accepted instead of hiding up to ten seconds of - // otherwise available streaming output. - this.hooks.onNudgePolling(); - } - return created; - } - - async createSessionInWorkspace( - path: string, - instruction: string = '', - agentType: string = 'code', - onRouteChat: (sessionId: string) => void = this.hooks.onRouteChat, - modelId: string = '', - routeBeforeCreate: boolean = true, - remoteConnectionId?: string, - remoteSshHost?: string, - workspaceId?: string - ): Promise { - if (this.hooks.isBusy() || !this.hooks.remoteAvailable()) { - return; - } - const previousSession: SessionSummary = this.copySession(this.pageState.activeSession); - this.beginSessionCreation(onRouteChat, routeBeforeCreate); - let created: SessionSummary | undefined; - try { - created = await this.performCreateSession(agentType, instruction, onRouteChat, modelId, path, remoteConnectionId, remoteSshHost, workspaceId); - if (!created && routeBeforeCreate) { - this.restoreAfterFailedCreation(previousSession, onRouteChat); - } - } finally { - this.pageState.setConversationLoading(false); - this.pageState.setPendingSessionId(''); - } - } - - private beginSessionCreation( - onRouteChat: (sessionId: string) => void, - routeBeforeCreate: boolean - ): void { - this.hooks.onStopPolling(); - this.pageState.setPendingSessionId(''); - this.pageState.setConversationLoading(true); - if (routeBeforeCreate) { - onRouteChat(''); - } - } - - private restoreAfterFailedCreation( - previousSession: SessionSummary, - onRouteChat: (sessionId: string) => void - ): void { - if (previousSession.sessionId.length === 0) { - this.hooks.onRouteHome(); - return; - } - this.pageState.setActiveSession(previousSession); - onRouteChat(previousSession.sessionId); - this.hooks.onStartPolling(); - } - - private copySession(session: SessionSummary): SessionSummary { - return { - sessionId: session.sessionId, - title: session.title, - workspacePath: session.workspacePath, - remoteConnectionId: session.remoteConnectionId, - remoteSshHost: session.remoteSshHost, - agentType: session.agentType, - initialTurnId: session.initialTurnId - }; - } - - async openSession( - item: RemoteSession, - currentWorkspacePath: string, - onRouteChat: (sessionId: string) => void = this.hooks.onRouteChat - ): Promise { - // A tap that arrives while another open is still in flight is a correction, - // not a mistake: the user has picked a different session and expects that - // one. It used to be swallowed, because `RemoteSessionController.open` - // raises the busy flag for the whole open and this guard read that flag as - // a run in progress — so for the second or so an uncached open takes, every - // row in the list was dead and nothing on screen said why. Opens supersede - // each other instead; only a run this view model did not start blocks. - const isBusy = this.hooks.isBusy() && this.openInFlight === 0; - const remoteAvailable = this.hooks.remoteAvailable(); - if (isBusy || item.id.length === 0 || !remoteAvailable) { - // Dropped taps are invisible from the outside — the row simply does - // nothing — so say which guard swallowed it. - RemoteLogger.info(`session open ignored session=${RemoteSessionViewModel.shortId(item.id)} busy=${isBusy ? '1' : '0'} available=${remoteAvailable ? '1' : '0'}`); - return; - } - if (this.openInFlight > 0 && this.pageState.activeSession.sessionId === item.id) { - RemoteLogger.info( - `session open coalesced session=${RemoteSessionViewModel.shortId(item.id)}` - ); - return; - } - // Bracketing the open: every stage between this line and the transcript - // reaching the screen logs, so the gap that the user feels can be pinned on - // one of them rather than inferred from the two ends. - RemoteLogger.info(`session open tap session=${RemoteSessionViewModel.shortId(item.id)}`); - MainThreadStallProbe.watch('session-open', 6000); - this.pageState.setPendingSessionId(item.id); - // No skeleton yet. The tapped row highlights from the pending id alone, and - // everything the detail pane needs to show the new session empty — title, - // workspace, a cleared timeline — is set synchronously below. If the - // transcript is cached it lands before the gate opens and the pane goes - // straight from one conversation to the next. - const loadingToken = this.openLoadingGate.arm(); - const openGeneration = ++this.openGeneration; - let requested = false; - onRouteChat(item.id); - RemoteLogger.info(`session open routed session=${RemoteSessionViewModel.shortId(item.id)}`); - this.openInFlight += 1; - try { - await this.sessions.open( - item, - item.workspacePath || currentWorkspacePath, - false, - true, - async (session: SessionSummary): Promise => { - this.hooks.onStopPolling(); - this.hooks.onResetTimeline(item.id); - this.hooks.onKnownStateReset(); - this.pageState.setHasMoreMessages(false); - this.files.clear(); - this.pageState.clearComposer(); - // Transcript first: it is the thing the user opened the session to - // see, and a cached one needs no round trip at all. - // - // Nothing fetches the model catalog here. The reset above puts the - // known catalog version back to zero, so the first poll asks for the - // catalog as part of the same request and the desktop sends it. A - // separate `get_model_catalog` would only queue ahead of the - // transcript — the desktop answers device RPCs one at a time, and - // measured against this device it pushed the transcript from ~2.4s - // out to ~5.5s. - await this.hooks.onLoadActiveMessages(); - if (openGeneration === this.openGeneration && - this.pageState.activeSession.sessionId === session.sessionId) { - this.hooks.onStartPolling(); - } - requested = true; - } - ); - } finally { - this.openInFlight -= 1; - // The command returning is not the transcript arriving. `open` hands the - // durable record stream a request for this session's history and comes - // back in a few milliseconds; the records themselves land seconds later, - // and releasing here left that whole gap blank with nothing to read. - // `settleTranscriptLoading` ends the wait when the records do arrive. - // An open that never got as far as asking has nothing to wait for. - if (!requested) { - this.openLoadingGate.release(loadingToken); - } - // Only the tap that still owns the gate owns the highlight: a second tap - // during the first open has already moved both. - if (loadingToken === this.openLoadingGate.currentToken()) { - this.pageState.setPendingSessionId(''); - } - RemoteLogger.info(`session open settled session=${RemoteSessionViewModel.shortId(item.id)}`); - } - } - - /** The transcript reached the pane, so the wait an open started is over. */ - settleTranscriptLoading(): void { - this.openLoadingGate.settle(); - } - - async deleteSession(item: RemoteSession, currentWorkspacePath: string): Promise { - await this.sessions.delete( - item, - this.pageState.activeSession.sessionId, - this.hooks.isBusy(), - this.hooks.remoteAvailable(), - this.pageState.sessionQuery, - this.pageState.sessionFilter, - async (): Promise => { - this.hooks.onStopPolling(); - await this.chat.forgetMessages(item.id); - this.hooks.onResetTimeline(''); - this.pageState.setHasMoreMessages(false); - this.pageState.clearComposer(); - this.models.clearCatalog(); - this.hooks.onKnownStateReset(); - this.pageState.setActiveSession({ - sessionId: '', - title: '', - workspacePath: currentWorkspacePath, - agentType: 'code' - }); - this.pageState.clearActiveSession(); - this.hooks.onRouteHome(); - } - ); - } - - async loadActiveMessages(isChatRoute: (sessionId: string) => boolean): Promise { - const sessionId = this.pageState.activeSession.sessionId || ''; - await this.chat.loadMessages(sessionId, isChatRoute); - } - - async loadOlderMessages(knownPollVersion: number): Promise { - await this.chat.loadOlderMessages( - this.pageState.activeSession.sessionId || '', - knownPollVersion, - this.pageState.hasMoreMessages, - this.hooks.isBusy() - ); - } - - async selectModel(modelId: string): Promise { - await this.models.selectModel( - modelId, - this.pageState.activeSession.sessionId || '', - this.hooks.isBusy(), - this.hooks.remoteAvailable() - ); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteTranscriptController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteTranscriptController.ets deleted file mode 100644 index 371b71ce8f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteTranscriptController.ets +++ /dev/null @@ -1,742 +0,0 @@ -import { - REMOTE_CAPABILITY_DIALOG_STEER_V1, - REMOTE_CAPABILITY_PLAN_BUILD_V1, - RemoteImageContext, - RemoteQuestionAnswerPayload -} from '../../model/RemoteModels'; -import { ChatTimelineItem } from '../../model/ChatTimelineModels'; -import { ChatTimelineState, ChatTimelineStore } from '../../services/ChatTimelineStore'; -import { CommandPalettePolicy } from '../../services/CommandPalettePolicy'; -import { RemoteCommandPaletteScope } from '../../services/RemoteCommandPaletteController'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { Encoding } from '../../services/Encoding'; -import { MarkdownHtmlSerializer } from '../../services/MarkdownHtmlSerializer'; -import { RemoteChatPollingCursor, RemoteChatPollingSnapshot } from '../../services/RemoteChatPollingLifecycleController'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemoteUiState } from '../../services/RemoteUiState'; -import { RollbackFailureKind, RollbackOutcomePolicy } from '../../services/RollbackOutcomePolicy'; -import { MessageCopyScope, CommandPaletteAction, CommandPaletteRequest, SessionRollbackRequest } from '../actions/ConversationIntent'; -import { RollbackPresentationPolicy } from '../policy/RollbackPresentationPolicy'; -import { SessionRollbackEventType } from '../policy/SessionRollbackPolicy'; -import { RemotePageState } from '../state/RemotePageState'; -import { - RemoteConversationDependencies, - requireRemoteRuntime, - shortSessionId -} from './ConversationRuntime'; - -/** Longest a streaming turn's transcript write is held back, in milliseconds. */ -const REMOTE_TRANSCRIPT_CACHE_INTERVAL_MS: number = 400; - -export class RemoteTranscriptController { - private readonly remote: RemotePageState; - private readonly remoteRuntime?: RemoteConversationDependencies; - private readonly notify: (message: string) => void; - private knownPollVersionValue: number = 0; - private knownModelCatalogVersion: number = 0; - private knownRemoteMessageCount: number = 0; - private isSyncingAfterTurn: boolean = false; - private isRebuildingRemoteTranscript: boolean = false; - private pendingTranscriptCache: number = -1; - // True while the transcript changed without a write behind it. A history page - // is read oldest-first, so every record of the burst lands in front of the - // window and nothing already written can be reused: writing during the burst - // rewrites the whole transcript once per record, on the thread that draws the - // screen, for a page nobody has finished reading yet. - private transcriptDirty: boolean = false; - - constructor( - remote: RemotePageState, - remoteRuntime: RemoteConversationDependencies | undefined, - notify: (message: string) => void - ) { - this.remote = remote; - this.remoteRuntime = remoteRuntime; - this.notify = notify; - } - - knownPollVersion(): number { - return this.knownPollVersionValue; - } - - resetKnownRemoteState(): void { - this.knownPollVersionValue = 0; - this.knownModelCatalogVersion = 0; - this.knownRemoteMessageCount = 0; - this.cancelPendingTranscriptCache(); - this.transcriptDirty = false; - } - - updateKnownMessageCount(pollVersion: number, knownMessageCount: number): void { - this.knownRemoteMessageCount = knownMessageCount; - this.updateChatPollingCursor(pollVersion, knownMessageCount); - } - - updateKnownModelCatalogVersion(version: number): void { - this.knownModelCatalogVersion = version; - requireRemoteRuntime(this.remoteRuntime).polling.updateKnownModelCatalogVersion(version); - } - - async loadRemoteMessages(): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const sessionId = this.remote.activeSession.sessionId || ''; - await runtime.chat.loadMessages( - sessionId, - runtime.hooks.isConversationContext - ); - // Read the skill catalog behind the transcript. This is also the palette's - // behavior probe — a host that does not serve the read is what greys the row - // — and it is cached per session, so opening a session pays for it once. - void runtime.commandPalette.loadCatalog( - sessionId, - this.commandPaletteModeId(), - false, - this.commandPaletteScope() - ); - } - - /** - * One tap in the composer's command row. - * - * Everything the palette can do lands here, because this controller owns what - * "the active conversation" means: the session id, the draft, the workspace - * that owns the session, and whether the probe has answered yet. - */ - async dispatchCommandPalette(request: CommandPaletteRequest): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const sessionId = this.remote.activeSession.sessionId || ''; - const palette = this.remote.commandPalette; - if (request.action === CommandPaletteAction.ToggleGoal) { - // Goals are plain message text, so this works on any host that can send. - const toggled = CommandPalettePolicy.toggleGoal(this.remote.chatInput, palette.goalPending); - this.remote.setChatInput(toggled.draft); - palette.setGoalPending(toggled.pending); - return; - } - if (request.action === CommandPaletteAction.SelectSkill) { - palette.setSkill(request.skillId, request.skillLabel); - return; - } - if (request.action === CommandPaletteAction.ClearSkill) { - palette.clearSkill(); - return; - } - const canApply = this.commandPaletteScope(); - if (sessionId.length === 0 || !canApply(sessionId)) { - RemoteLogger.info( - `command palette ignored action=${request.action} session=${shortSessionId(sessionId)}`); - return; - } - const scope = this.commandPaletteCommandScope(sessionId); - if (request.action === CommandPaletteAction.Compact || - request.action === CommandPaletteAction.InitAgentsMd || - request.action === CommandPaletteAction.RetryCommand) { - const wireAction = request.action === CommandPaletteAction.RetryCommand ? request.wireAction : request.action; - if (!CommandPalettePolicy.isRunnable(wireAction)) { - return; - } - await runtime.commandPalette.runCommand(sessionId, wireAction, scope, canApply); - return; - } - if (request.action === CommandPaletteAction.OpenUsage || - request.action === CommandPaletteAction.RetryUsage) { - await runtime.commandPalette.loadUsageReport(sessionId, scope, canApply); - return; - } - if (request.action === CommandPaletteAction.OpenSkills || - request.action === CommandPaletteAction.RefreshCatalog) { - await runtime.commandPalette.loadCatalog( - sessionId, - this.commandPaletteModeId(), - request.action === CommandPaletteAction.RefreshCatalog, - canApply); - } - } - - /** - * The host's mode id for the palette's catalog read. - * - * It is the session's own agent type: the picker must show the skills that - * mode would actually run, and a session that has not named one yet falls back - * to the desktop's default harness rather than an empty mode. - */ - private commandPaletteModeId(): string { - const agentType = (this.remote.activeSession.agentType || '').trim(); - return agentType.length > 0 ? agentType : 'agentic'; - } - - /** The workspace that owns the active session, as the verbs expect it. */ - private commandPaletteCommandScope(sessionId: string): RemoteCommandPaletteScope { - const scope: RemoteCommandPaletteScope = { sessionId }; - if (this.remote.workspaceId.length > 0) { - scope.workspaceId = this.remote.workspaceId; - } - if (this.remote.workspacePath.length > 0) { - scope.workspacePath = this.remote.workspacePath; - } - if (this.remote.workspaceConnectionId.length > 0) { - scope.remoteConnectionId = this.remote.workspaceConnectionId; - } - if (this.remote.workspaceSshHost.length > 0) { - scope.remoteSshHost = this.remote.workspaceSshHost; - } - return scope; - } - - /** Reads stay pinned to the session they were asked for. */ - private commandPaletteScope(): (sessionId: string) => boolean { - return (sessionId: string): boolean => - sessionId.length > 0 && this.remote.activeSession.sessionId === sessionId; - } - - async selectRemoteModel(modelId: string): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.models.selectModel( - modelId, - this.remote.activeSession.sessionId || '', - this.remote.isBusy, - runtime.connection.ensureAvailable() - ); - } - - async loadOlderRemoteMessages(): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.chat.loadOlderMessages( - this.remote.activeSession.sessionId || '', - this.knownPollVersionValue, - this.remote.hasMoreMessages, - this.remote.isBusy - ); - } - - async sendRemoteMessage(): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const sessionId = this.remote.activeSession.sessionId || ''; - const contextRevision = this.remote.sessionContextRevision; - if (this.remote.isVoiceListening) { - await runtime.hooks.stopVoiceInput(); - } - if (this.remote.activeSession.sessionId !== sessionId || - this.remote.sessionContextRevision !== contextRevision) { - return; - } - const rawText = this.remote.chatInput.trim(); - const images = this.remote.selectedImages.slice(); - // A bare `/goal` is a command with its argument still missing, so it is not - // a message yet: the composer already drew it as SendBlocked, and anything - // that reaches the send path another way stops here too. - if (CommandPalettePolicy.blocksSend(rawText)) { - return; - } - // The skill token is a chip beside the field, so this is where it becomes - // message content — once, and only for the draft being sent. It is built from - // the picked skill's name, which is the form the desktop's own picker writes. - const skillLabel = this.remote.commandPalette.skillLabel; - const text = rawText.length > 0 ? CommandPalettePolicy.composeSubmissionText(rawText, skillLabel) : - (images.length > 0 ? RemoteI18n.t('chat.analyzeImageDefault') : ''); - if ((!text && images.length === 0) || !sessionId || this.remote.isBusy || this.remote.connectionState !== 'connected' || - !runtime.connection.ensureAvailable()) { - return; - } - // A new message is the conversation moving on from the point a rollback left - // it at, so the hint row describing that rollback stops being the last thing - // that happened. It is cleared only here and on a session change. - this.remote.clearRollbackNotice(); - const queuedBehindRunningTurn = this.hasRunningRemoteTurn(); - const activeTurnId = this.remoteActiveTurnId(); - const canSteerRunningTurn = queuedBehindRunningTurn && activeTurnId.length > 0 && - this.remote.supportsHostCapability(REMOTE_CAPABILITY_DIALOG_STEER_V1); - const imageContexts: RemoteImageContext[] = images.length > 0 ? - runtime.imagePicker.toRemoteContexts(images) : []; - if (canSteerRunningTurn) { - RemoteLogger.info( - `chat steer requested session=${shortSessionId(sessionId)} turn=${shortSessionId(activeTurnId)}` - ); - this.startRemotePolling(); - runtime.polling.nudge(); - await runtime.chat.steerPreparedMessage( - sessionId, - activeTurnId, - text, - rawText, - images, - imageContexts, - this.remote.isBusy, - true - ); - return; - } - // Older desktop hosts do not advertise steering. Keep their established - // queue behavior so mixed-version Remote Connect sessions remain usable. - const clientTurnId = Encoding.randomId('harmony-turn'); - const localMessage = RemoteUiState.localUserMessage(text, images, clientTurnId); - runtime.timeline.appendOptimisticMessage(localMessage); - const pendingActiveId = runtime.timeline.setPendingActiveTurn(localMessage.id); - this.syncRemoteTimeline(); - RemoteLogger.info(`chat send queued session=${shortSessionId(sessionId)} pending=${pendingActiveId} behindRunningTurn=${queuedBehindRunningTurn ? '1' : '0'}`); - if (queuedBehindRunningTurn) { - this.notify(RemoteI18n.t('chat.queuedAfterRunningTurn')); - } - this.startRemotePolling(); - runtime.polling.nudge(); - await runtime.chat.sendPreparedMessage( - sessionId, - text, - this.remote.activeSession.agentType, - rawText, - images, - imageContexts, - localMessage.id, - pendingActiveId, - this.remote.isBusy, - true, - localMessage.turnId || '' - ); - } - - async buildRemotePlan(planFilePath: string, planName: string): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const sessionId = this.remote.activeSession.sessionId || ''; - if (!this.remote.supportsHostCapability(REMOTE_CAPABILITY_PLAN_BUILD_V1)) { - this.notify(RemoteI18n.t('chat.planBuildUnavailable')); - return; - } - if (this.hasRunningRemoteTurn()) { - this.notify(RemoteI18n.t('chat.planBuildWaitForTurn')); - return; - } - if (planFilePath.trim().length === 0 || sessionId.length === 0 || this.remote.isBusy || this.remote.connectionState !== 'connected' || - !runtime.connection.ensureAvailable()) { - return; - } - const displayName = planName.trim().length > 0 ? planName.trim() : 'Plan'; - const localMessage = RemoteUiState.localUserMessage(`Build Plan: ${displayName}`); - runtime.timeline.appendOptimisticMessage(localMessage); - const pendingActiveId = runtime.timeline.setPendingActiveTurn(localMessage.id); - this.syncRemoteTimeline(); - this.startRemotePolling(); - runtime.polling.nudge(); - await runtime.chat.buildPlan( - sessionId, - planFilePath.trim(), - displayName, - this.remote.activeSession.agentType, - localMessage.id, - pendingActiveId, - this.remote.isBusy, - true - ); - } - - async stopRemoteTask(): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const sessionId = this.remote.activeSession.sessionId || ''; - if (!sessionId) { - return; - } - await runtime.chat.stopTask( - sessionId, - this.remote.activeTurnMessage.id, - this.remoteActiveTurnId(), - this.remote.connectionState === 'connected' && runtime.connection.ensureAvailable() - ); - } - - async renameRemoteSession(title: string): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const nextTitle = title.trim(); - if (!this.remote.activeSession.sessionId || nextTitle.length === 0 || - nextTitle === this.remote.activeSession.title || this.remote.isBusy) { - return; - } - await runtime.chat.renameActiveSession( - this.remote.activeSession, - nextTitle, - this.remote.isBusy, - runtime.connection.ensureAvailable() - ); - } - - /** - * Writes one message body to the clipboard. - * - * `rich` is the only scope that changes the payload shape: the Markdown source - * goes out as the plain flavor and its rendered html as a second record, so a - * rich-text receiver pastes formatted content while everything else still - * pastes the source. The other scopes stay the single plain write that every - * copy caller used before the assistant menu. - */ - async copyRemoteMessage(text: string, scope: MessageCopyScope): Promise { - if (text.trim().length === 0) { - return; - } - try { - const clipboard = requireRemoteRuntime(this.remoteRuntime).clipboard; - if (scope === MessageCopyScope.Rich) { - await clipboard.copyRich(text, MarkdownHtmlSerializer.toHtml(text)); - } else { - await clipboard.writeText(text); - } - this.remote.setStatusText(RemoteI18n.t('status.messageCopied')); - } catch (err) { - this.remote.setStatusText(ConnectionErrorPolicy.errorText(err)); - } - } - - async downloadRemoteFile(path: string): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.files.download( - path, - this.remote.activeSession.sessionId || '', - this.remote.isBusy, - runtime.connection.ensureAvailable() - ); - } - - /** - * Runs one staged rollback, then optionally sends the text it was staged with. - * - * This is the end of the chain the staged preview leaves open: the pane decides - * *that* a rollback happens and leaves staging before the host answers, so the - * answer has to come back somewhere that still exists — here, as an outcome on - * the page state. - * - * The two steps are one call on purpose. `sendText` is the send-while-staging - * exit, and the order between the steps is the contract: the host has to retire - * the turn before a message may be appended to it. A rollback that succeeded and - * a send that failed is recoverable — the draft is left in the composer — so the - * draft is only handed to the send path, never cleared here. - * - * After a success the transcript is refetched. The host answers the poll with - * the rewritten snapshot, but this client reads `historyRewritten` as false and - * only compares message counts, so nothing tells the store its persisted rows - * were replaced; asking for the transcript is what actually removes them. - */ - async rollbackRemoteSession(request: SessionRollbackRequest): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const sessionId = this.remote.activeSession.sessionId || ''; - const contextRevision = this.remote.sessionContextRevision; - const targetTurnId = request.targetTurnId.trim(); - if (sessionId.length === 0 || targetTurnId.length === 0) { - // Nothing addressable reached this layer, so nothing can succeed. Say so - // rather than returning quietly: the pane has already left staging. - RemoteLogger.info(`rollback skipped session=${shortSessionId(sessionId)} target_len=${targetTurnId.length}`); - this.remote.reportRollbackOutcome(SessionRollbackEventType.RollbackFailed); - return; - } - try { - const result = await runtime.chat.rollbackSessionToTurn(sessionId, targetTurnId); - if (!this.isCurrentSessionContext(sessionId, contextRevision)) { - return; - } - RemoteLogger.info( - `rollback projected retired=${result.retiredTurnIds.length} restored=${result.restoredFiles.length} ` + - `changed=${result.changed ? '1' : '0'}` - ); - const notice = RemoteI18n.f2( - RollbackPresentationPolicy.ROLLED_BACK_NOTICE_KEY, - `${result.retiredTurnIds.length}`, - `${result.restoredFiles.length}` - ); - const sendText = request.sendText.trim(); - if (sendText.length > 0) { - // Sending runs the ordinary path, so the message is owned, acknowledged - // and failed exactly like any other one: a send that does not go out - // restores the draft and marks its own row, which is the recoverable - // state the frozen interaction asks for. It also retires any earlier - // notice, so this one is set after it. - this.remote.setChatInput(sendText); - await this.sendRemoteMessage(); - } - if (!this.isCurrentSessionContext(sessionId, contextRevision)) { - return; - } - this.remote.setRollbackNotice(notice); - this.rebuildRemoteTranscript(sessionId); - } catch (err) { - if (!this.isCurrentSessionContext(sessionId, contextRevision)) { - return; - } - const kind = RollbackOutcomePolicy.failureKind(err); - RemoteLogger.info( - `rollback refused session=${shortSessionId(sessionId)} target=${shortSessionId(targetTurnId)} ` + - `kind=${kind} message=${RollbackOutcomePolicy.messageOf(err)}` - ); - this.remote.reportRollbackOutcome( - kind === RollbackFailureKind.StaleView ? - SessionRollbackEventType.StaleViewDetected : SessionRollbackEventType.RollbackFailed - ); - } - } - - private isCurrentSessionContext(sessionId: string, revision: number): boolean { - return this.remote.sessionContextRevision === revision && - this.remote.activeSession.sessionId === sessionId && - requireRemoteRuntime(this.remoteRuntime).hooks.isConversationContext(sessionId); - } - - /** - * Refetches the transcript after a rollback this client could not repair. - * - * A stale or refused rollback leaves the local rows describing history the host - * no longer has, so the authoritative transcript is what the pane returns to. - */ - resyncAfterRollback(): void { - const sessionId = this.remote.activeSession.sessionId || ''; - if (sessionId.length === 0) { - return; - } - this.rebuildRemoteTranscript(sessionId); - } - - retryRemoteMessage(text: string): void { - if (this.remote.isBusy || !requireRemoteRuntime(this.remoteRuntime).connection.ensureAvailable()) { - return; - } - this.remote.setChatInput(text); - this.sendRemoteMessage(); - } - - async approveRemoteTool(toolId: string, updatedInput?: Object): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.tools.approve( - toolId, this.remote.activeSession.sessionId || '', runtime.connection.ensureAvailable(), updatedInput - ); - } - - async rejectRemoteTool(toolId: string): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.tools.reject( - toolId, this.remote.activeSession.sessionId || '', runtime.connection.ensureAvailable() - ); - } - - async cancelRemoteTool(toolId: string): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.tools.cancel( - toolId, this.remote.activeSession.sessionId || '', runtime.connection.ensureAvailable() - ); - } - - async answerRemoteQuestion(toolId: string, answers: RemoteQuestionAnswerPayload): Promise { - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.tools.answer( - toolId, this.remote.activeSession.sessionId || '', runtime.connection.ensureAvailable(), answers - ); - } - - resetRemoteTimeline(sessionId: string): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - if (this.pendingTranscriptCache !== -1) { - clearTimeout(this.pendingTranscriptCache); - this.pendingTranscriptCache = -1; - } - runtime.timeline.reset(sessionId); - this.knownPollVersionValue = 0; - this.syncRemoteTimeline(); - } - - syncRemoteTimeline(): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const state: ChatTimelineState = runtime.timeline.snapshotState(); - this.remote.setTimelineProjection( - state.persistedMessages, - state.optimisticMessages, - state.activeTurn || RemoteUiState.emptyActiveTurn(), - this.remote.hasMoreMessages, - runtime.timeline.viewState(this.remote.hasMoreMessages) - ); - this.remote.setModelCatalog(state.modelCatalog, state.selectedModelId); - } - - startRemotePolling(): void { - requireRemoteRuntime(this.remoteRuntime).polling.startActiveSession({ - sessionId: this.remote.activeSession.sessionId || '', - cursor: this.currentChatPollingCursor(), - activeTurn: this.remote.activeTurnMessage - }); - } - - applyRemoteSnapshot(snapshot: RemoteChatPollingSnapshot): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - if (!runtime.hooks.isConversationContext(snapshot.sessionId)) { - return; - } - if (snapshot.historyRewritten) { - this.cancelPendingTranscriptCache(); - this.transcriptDirty = false; - this.rebuildRemoteTranscript(snapshot.sessionId); - return; - } - runtime.timeline.applySnapshot(snapshot); - this.syncRemoteTimeline(); - this.remote.conversation.promptSuggestion = snapshot.promptSuggestion ?? ''; - if (snapshot.historyLoading === true) { - // A history page publishes once per record it contains, and every one of - // them lands in front of the window, so no row already on disk survives: - // writing during the burst rewrites the whole transcript on the thread - // that draws the screen, for a cache nothing reads before the next open. - this.deferTranscriptCache(); - } else if (this.transcriptDirty) { - // The page settled, and the settle publishes again. - this.cacheTranscriptNow(snapshot.sessionId, true); - } else if (snapshot.messageSnapshot !== undefined) { - // A streaming turn restates the whole transcript on every chunk. Writing - // all of it back each time re-encrypts the session dozens of times a - // second, so during a turn only the last write of a burst is kept. - if (this.hasRunningRemoteTurn()) this.scheduleTranscriptCache(snapshot.sessionId); - else this.cacheTranscriptNow(snapshot.sessionId, true); - } else if (snapshot.newMessages.length > 0) { - this.cacheRemoteTranscript(snapshot.sessionId, false); - } - this.knownPollVersionValue = snapshot.cursor.pollVersion; - this.knownModelCatalogVersion = snapshot.cursor.knownModelCatalogVersion; - this.knownRemoteMessageCount = snapshot.cursor.knownMessageCount; - if (snapshot.title.length > 0) { - this.remote.setActiveSession({ - sessionId: this.remote.activeSession.sessionId, - title: snapshot.title, - workspacePath: this.remote.activeSession.workspacePath, - remoteConnectionId: this.remote.activeSession.remoteConnectionId, - agentType: this.remote.activeSession.agentType - }); - } - if (snapshot.modelCatalog) { - runtime.models.applyCatalog(snapshot.modelCatalog); - } - this.remote.setStatusText(this.hasRunningRemoteTurn() - ? RemoteI18n.t('status.desktopProcessing') - : RemoteI18n.t('status.messagesSynced')); - if (snapshot.shouldSyncAfterTurnEnded) { - this.syncAfterRemoteTurnEnded(); - } - } - - /** - * Writes the transcript now on screen back to disk. - * - * Fire-and-forget on purpose: the snapshot is already rendered, and a cache - * that cannot be written only costs the next open a fetch it used to pay for - * anyway. - */ - private scheduleTranscriptCache(sessionId: string): void { - this.transcriptDirty = true; - if (this.pendingTranscriptCache !== -1) return; - this.pendingTranscriptCache = setTimeout(() => { - this.pendingTranscriptCache = -1; - this.cacheRemoteTranscript(sessionId, true); - this.transcriptDirty = false; - }, REMOTE_TRANSCRIPT_CACHE_INTERVAL_MS); - } - - /** - * Holds the transcript write back for the rest of a history page. - * - * Nothing reads the cache before the next open, and the page publishes again - * when its read settles, which is where the deferred write lands. - */ - private deferTranscriptCache(): void { - this.transcriptDirty = true; - this.cancelPendingTranscriptCache(); - } - - private cancelPendingTranscriptCache(): void { - if (this.pendingTranscriptCache !== -1) { - clearTimeout(this.pendingTranscriptCache); - this.pendingTranscriptCache = -1; - } - } - - private cacheTranscriptNow(sessionId: string, authoritativeSnapshot: boolean): void { - this.cancelPendingTranscriptCache(); - this.cacheRemoteTranscript(sessionId, authoritativeSnapshot); - this.transcriptDirty = false; - } - - private cacheRemoteTranscript(sessionId: string, authoritativeSnapshot: boolean): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - const state: ChatTimelineState = runtime.timeline.snapshotState(); - if (authoritativeSnapshot) { - runtime.chatCache.replaceSnapshot(sessionId, state.persistedMessages); - } else { - runtime.chatCache.syncIncremental(sessionId, state.persistedMessages); - } - } - - /** - * Refetches a transcript the desktop no longer agrees with. - * - * Tails are handed out by index, so once the desktop reports fewer messages - * than this session had counted there is no offset left that means the same - * thing on both ends. Everything stored for the session goes, including the - * poll cursor, which `reloadMessages` resets by way of `onMessageCountKnown`. - */ - private rebuildRemoteTranscript(sessionId: string): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - if (this.isRebuildingRemoteTranscript) { - return; - } - this.isRebuildingRemoteTranscript = true; - RemoteLogger.info(`remote transcript rewritten upstream session=${shortSessionId(sessionId)}`); - runtime.chatCache.forget(sessionId) - .then((): Promise => runtime.chat.reloadMessages(sessionId, runtime.hooks.isConversationContext)) - .then((): void => { - this.isRebuildingRemoteTranscript = false; - }) - .catch((): void => { - this.isRebuildingRemoteTranscript = false; - }); - } - - hasRunningRemoteTurn(): boolean { - return this.remote.activeTurnMessage.id.length > 0 && - (this.remote.activeTurnMessage.status || '').toLowerCase() === 'active'; - } - - remoteActiveTurnId(): string { - return ChatTimelineStore.cancelableTurnId(this.remote.activeTurnMessage); - } - - projectedRemoteTimelineItems(): ChatTimelineItem[] { - return requireRemoteRuntime(this.remoteRuntime).timeline.viewState(this.remote.hasMoreMessages); - } - - private currentChatPollingCursor(): RemoteChatPollingCursor { - return { - pollVersion: this.knownPollVersionValue, - knownMessageCount: this.knownRemoteMessageCount, - knownModelCatalogVersion: this.knownModelCatalogVersion - }; - } - - private updateChatPollingCursor(pollVersion: number, knownMessageCount: number): void { - this.knownPollVersionValue = pollVersion; - this.knownRemoteMessageCount = knownMessageCount; - requireRemoteRuntime(this.remoteRuntime).polling.updateCursor({ - pollVersion, - knownMessageCount, - knownModelCatalogVersion: this.knownModelCatalogVersion - }); - } - - private async syncAfterRemoteTurnEnded(): Promise { - if (this.isSyncingAfterTurn) { - return; - } - this.isSyncingAfterTurn = true; - try { - // Deliberately not the cached path: this exists to pick up whatever the - // desktop settled on after the turn finished, which is exactly what the - // cache does not know yet. - const runtime = requireRemoteRuntime(this.remoteRuntime); - await runtime.chat.reloadMessages( - this.remote.activeSession.sessionId || '', - runtime.hooks.isConversationContext - ); - } finally { - this.isSyncingAfterTurn = false; - } - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteWorkspaceViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteWorkspaceViewModel.ets deleted file mode 100644 index 89541a9635..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/RemoteWorkspaceViewModel.ets +++ /dev/null @@ -1,201 +0,0 @@ -import { RecentWorkspaceEntry, WorkspaceInfo } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemoteWorkspaceCoordinator } from '../../services/RemoteWorkspaceCoordinator'; -import { RemotePageState } from '../state/RemotePageState'; - -export interface RemoteWorkspaceViewModelHooks { - readonly isRemoteAvailable: () => boolean; - /** Stable owner of the current remote catalog; empty while no target owns it. */ - readonly remoteTargetId: () => string; - readonly isBusy: () => boolean; - readonly onBusy: (isBusy: boolean) => void; - readonly onStatus: (statusText: string) => void; - readonly onWorkspaceSelected: (workspace: WorkspaceInfo) => void; - readonly onCatalogLoading: (targetId: string) => void; - readonly onCatalogLoaded: (targetId: string, workspaces: RecentWorkspaceEntry[], source?: string, recentWorkspaces?: RecentWorkspaceEntry[]) => void; - readonly onCatalogFailed: (targetId: string) => void; - readonly onRefreshSessions: () => Promise; - readonly onConnectionFailure: (error: Object) => void; -} - -/** Owns the workspace/assistant picker workflows and their presentation state. */ -export class RemoteWorkspaceViewModel { - private readonly pageState: RemotePageState; - private readonly coordinator: RemoteWorkspaceCoordinator; - private readonly hooks: RemoteWorkspaceViewModelHooks; - private catalogLoadVersion: number = 0; - // Background catalog invalidation must not cancel a foreground picker's - // result/finally, and opening a picker must not abandon sidebar loading. - private pickerLoadVersion: number = 0; - - constructor( - pageState: RemotePageState, - coordinator: RemoteWorkspaceCoordinator, - hooks: RemoteWorkspaceViewModelHooks - ) { - this.pageState = pageState; - this.coordinator = coordinator; - this.hooks = hooks; - } - - async toggleRecentWorkspaces(): Promise { - if (this.pageState.showWorkspacePicker) { - this.pageState.setWorkspacePickerVisible(false); - return; - } - this.pageState.setWorkspacePickerVisible(true); - this.pageState.setAssistantPickerVisible(false); - await this.loadRecentWorkspaces(); - } - - async toggleAssistants(): Promise { - if (this.pageState.showAssistantPicker) { - this.pageState.setAssistantPickerVisible(false); - return; - } - this.pageState.setAssistantPickerVisible(true); - this.pageState.setWorkspacePickerVisible(false); - await this.loadAssistants(); - } - - async selectWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - return await this.select(path, false, connectionId, sshHost, workspaceId); - } - - async selectAssistant(path: string, workspaceId?: string): Promise { - return await this.select(path, true, undefined, undefined, workspaceId); - } - - async loadRecentWorkspacesInBackground(propagateFailure: boolean = false): Promise { - const loadVersion = ++this.catalogLoadVersion; - const targetId = this.hooks.remoteTargetId(); - if (targetId.length === 0) { - return; - } - this.hooks.onCatalogLoading(targetId); - try { - if (this.pageState.savedConnectionsTargetId !== targetId) { - this.pageState.savedConnections = []; - this.pageState.savedConnectionsTargetId = ''; - } - try { - const saved = await this.coordinator.savedConnections(); - if (this.isCurrentCatalogLoad(loadVersion, targetId)) { - this.pageState.savedConnections = saved; - this.pageState.savedConnectionsTargetId = targetId; - } - } catch (error) { - if (this.isCurrentCatalogLoad(loadVersion, targetId)) this.hooks.onConnectionFailure(error); - } - // The coordinator follows the selected runtime. A superseded request - // must not issue its next operation against a newly selected device. - if (!this.isCurrentCatalogLoad(loadVersion, targetId)) return; - const catalog = await this.coordinator.workspaceCatalog(); - if (!this.isCurrentCatalogLoad(loadVersion, targetId)) return; - const allWorkspaces = catalog.workspaces; - this.pageState.setRecentWorkspaces(catalog.recentWorkspaces); - this.hooks.onCatalogLoaded(targetId, allWorkspaces, catalog.source, catalog.recentWorkspaces); - RemoteLogger.info( - `workspace catalog loaded target=${targetId} count=${allWorkspaces.length} first=${allWorkspaces.length > 0 ? allWorkspaces[0].path : ''}` - ); - } catch (err) { - if (this.isCurrentCatalogLoad(loadVersion, targetId)) { - this.hooks.onCatalogFailed(targetId); - } - RemoteLogger.warn(`background recent workspace load failed: ${String(err)}`); - if (propagateFailure && this.isCurrentCatalogLoad(loadVersion, targetId)) throw new Error(String(err)); - } - } - - private async loadRecentWorkspaces(): Promise { - if (!this.hooks.isRemoteAvailable()) { - return; - } - const loadVersion = ++this.pickerLoadVersion; - const targetId = this.hooks.remoteTargetId(); - try { - this.hooks.onBusy(true); - this.hooks.onStatus(RemoteI18n.t('status.loadingRecentWorkspaces')); - const recent = await this.coordinator.recentWorkspaces(); - if (!this.isCurrentPickerLoad(loadVersion, targetId)) { - return; - } - this.pageState.setRecentWorkspaces(recent); - this.hooks.onStatus(recent.length > 0 ? - RemoteI18n.t('status.chooseWorkspace') : RemoteI18n.t('status.noRecentWorkspaces')); - } catch (err) { - if (this.isCurrentPickerLoad(loadVersion, targetId)) { - this.hooks.onConnectionFailure(err); - } - } finally { - if (this.isCurrentPickerLoad(loadVersion, targetId)) { - this.hooks.onBusy(false); - } - } - } - - private isCurrentCatalogLoad(loadVersion: number, targetId: string): boolean { - return targetId.length > 0 && - loadVersion === this.catalogLoadVersion && - targetId === this.hooks.remoteTargetId(); - } - - private isCurrentPickerLoad(loadVersion: number, targetId: string): boolean { - return targetId.length > 0 && loadVersion === this.pickerLoadVersion && targetId === this.hooks.remoteTargetId(); - } - - private async loadAssistants(): Promise { - if (!this.hooks.isRemoteAvailable()) { - return; - } - const loadVersion = ++this.pickerLoadVersion; - const targetId = this.hooks.remoteTargetId(); - try { - this.hooks.onBusy(true); - this.hooks.onStatus(RemoteI18n.t('status.loadingAssistants')); - const assistants = await this.coordinator.assistants(); - if (!this.isCurrentPickerLoad(loadVersion, targetId)) { - return; - } - this.pageState.setAssistants(assistants); - this.hooks.onStatus(assistants.length > 0 ? - RemoteI18n.t('status.chooseAssistant') : RemoteI18n.t('status.noAssistants')); - } catch (err) { - if (this.isCurrentPickerLoad(loadVersion, targetId)) { - this.hooks.onConnectionFailure(err); - } - } finally { - if (this.isCurrentPickerLoad(loadVersion, targetId)) { - this.hooks.onBusy(false); - } - } - } - - private async select(path: string, assistant: boolean, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - // A reference is complete with either its ID or, for pre-ID rows, its path. - const id = workspaceId?.trim() || undefined; - if (this.hooks.isBusy() || (path.trim().length === 0 && id === undefined) || !this.hooks.isRemoteAvailable()) { - return false; - } - try { - this.hooks.onBusy(true); - this.hooks.onStatus(RemoteI18n.t(assistant ? - 'status.switchingAssistant' : 'status.switchingWorkspace')); - const workspace = assistant ? - await this.coordinator.switchAssistant(path, id) : await this.coordinator.switchWorkspace(path, connectionId, sshHost, id); - this.hooks.onWorkspaceSelected(workspace); - this.pageState.closePickers(); - this.pageState.clear(); - this.hooks.onStatus(RemoteI18n.t(assistant ? - 'status.assistantSwitched' : 'status.workspaceSwitched')); - this.hooks.onBusy(false); - await this.hooks.onRefreshSessions(); - return true; - } catch (err) { - this.hooks.onConnectionFailure(err); - this.hooks.onBusy(false); - return false; - } - } -} 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 deleted file mode 100644 index 54c98571bb..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets +++ /dev/null @@ -1,994 +0,0 @@ -import { GitHubAccountProfile, GitHubProfileLoader } from '../../services/GitHubAccountProfile'; -import { normalizeAccountRelayUrl, OFFICIAL_RELAY_URL, sameRelayDeployment } from '../../services/AccountDeviceLink'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { stampRemoteSessionsDevice } from '../../services/RemoteSessionIdentity'; -import { - DEFAULT_CLOUD_RELAY_URL, - CloudAccountBinding, - CloudAccountClient, - CloudAccountDevice, - CloudAccountRequestError, - CloudAccountSession, - accountDeviceDisplayName, - isDeviceControllable -} from '../../services/CloudAccountClient'; -import { CloudAccountSessionStore, PersistedCloudAccountSession } from '../../services/CloudAccountSessionStore'; -import { ConnectionErrorPolicy } from '../../services/ConnectionErrorPolicy'; -import { Encoding } from '../../services/Encoding'; -import { RemoteLogger } from '../../services/RemoteLogger'; -import { RemoteSessionManager } from '../../services/RemoteSessionManager'; -import { WatchProvisionOutcome } from '../../services/WatchProvisionController'; -import { RemoteDefaultModels, RemoteModelCatalog, RemotePermissionMode } from '../../model/RemoteModels'; -import { RemotePageState } from '../state/RemotePageState'; - -export interface CloudAccountSettingsHooks { - readonly deviceId: () => string; - readonly openAuthorization: (url: string) => Promise; - readonly remoteAvailable: () => boolean; - readonly invalidatePreview: () => void; - readonly invalidateRemoteActivity: () => void; - readonly invalidateRemoteConnection: () => void; - readonly stopPolling: () => void; - readonly stopHeartbeat: () => void; - readonly startHeartbeat: () => void; - readonly resetTimeline: () => void; - readonly resetKnownRemoteState: () => void; - /** Cached transcripts and session lists belong to the account that was signed in. */ - readonly clearCachedRemoteData: () => Promise; - readonly closeSettings: () => void; - readonly closeConnectSheet: () => void; - readonly navigateRemoteHome: () => void; - readonly loadRecentWorkspaces: () => Promise; - readonly saveControlTargetType: (controlTargetType: string) => Promise; - readonly onAccountDevices: (devices: CloudAccountDevice[]) => void; - /** Snapshot the outgoing live device before teardown clears its lists. */ - readonly onBeforeControlTargetChange: () => void; - /** The incoming device owns a catalog request from the start of its switch. */ - readonly onControlTargetLoading: (deviceId: string) => void; - readonly onControlTargetChanged: () => void; -} - -export interface CloudAccountSettingsDependencies { - readonly client: CloudAccountClient; - readonly sessionStore: CloudAccountSessionStore; - readonly profileLoader?: GitHubProfileLoader; - readonly sessionManager: RemoteSessionManager; - readonly remoteState: RemotePageState; - readonly hooks: CloudAccountSettingsHooks; -} - -export interface PreferredCloudTarget { - readonly deviceId: string; - readonly deviceName: string; -} - -/** Owns the authenticated account and remote device selection. */ -export class SettingsController { - private readonly cloud?: CloudAccountSettingsDependencies; - private cloudInitialization?: Promise; - private cloudSession?: CloudAccountSession; - private cloudRelayUrl: string = ''; - private selectedRelayUrl: string = DEFAULT_CLOUD_RELAY_URL; - private accountLoginVersion: number = 0; - /** Account login identity; pairing projections must never overwrite it. */ - private cloudAccountUsername: string = ''; - 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; - private targetProbing: boolean = false; - private targetProbeDelay: number = 250; - private restoringControlTarget: boolean = false; - private accountDeviceSelectionVersion: number = 0; - /** Last account device the user successfully controlled, independent of the live QR projection. */ - private preferredTargetDeviceId: string = ''; - private preferredTargetDeviceName: string = ''; - - constructor(cloud: CloudAccountSettingsDependencies) { - this.cloud = cloud; - } - - async initializeCloudAccount(context: Context): Promise { - if (!this.cloudInitialization) { - this.cloudInitialization = this.initializeCloudAccountInternal(context); - } - await this.cloudInitialization; - } - - private async initializeCloudAccountInternal(context: Context): Promise { - const cloud = this.requireCloud(); - await cloud.sessionStore.init(context); - await this.restoreCloudAccountSession(); - void this.refreshCloudAccountProfile(); - } - - hasCloudAccountSession(): boolean { - return this.cloudSession !== undefined; - } - - /** - * Whether this phone might be able to add a device to the account itself. - * - * The relay checks the credential's provisioning scope. A local session - * makes the action available; a server refusal is reported to the caller. - */ - canMintWatchCredential(): boolean { - return this.cloudSession !== undefined && this.cloudRelayUrl.length > 0; - } - - /** - * Mints a watch's own account credential straight from this phone. - * - * Returns `undefined` without a signed-in session and propagates server - * refusals. The watch receives its own newly generated device secret, - * sealed by the provisioning transport; the phone's secret stays local. - */ - async provisionWatchCredential( - deviceId: string, - deviceName: string, - requestId: string, - password: string = '' - ): Promise { - const session = this.cloudSession; - if (!session || this.cloudRelayUrl.length === 0) { - return undefined; - } - const cloud = this.requireCloud(); - // Persist the identity before registration. A timed-out or cancelled - // handoff can then replay registration without rotating the watch's key. - let identity = await cloud.sessionStore.loadWatchProvisionIdentity(this.cloudRelayUrl, session.userId, deviceId); - if (!identity) { - identity = { - relayUrl: this.cloudRelayUrl, userId: session.userId, deviceId, requestId, - privateKeyBase64: Encoding.bytesToBase64(Encoding.randomBytes(32)) - }; - await cloud.sessionStore.saveWatchProvisionIdentity(identity); - } - const secret = Encoding.base64ToBytes(identity.privateKeyBase64); - try { - const provisioned = await cloud.client.provisionDevice( - this.cloudRelayUrl, session, deviceId, deviceName, identity.requestId, secret); - RemoteLogger.info(`watch credential minted from the phone account device=${provisioned.deviceId}`); - const masterKeyBase64 = Encoding.bytesToBase64(provisioned.deviceSecret); - provisioned.deviceSecret.fill(0); - return { - ok: true, - passwordRequired: false, - relayUrl: this.cloudRelayUrl, - token: provisioned.token, - userId: provisioned.userId, - masterKeyBase64, - deviceId: provisioned.deviceId, - failure: '', - desktopReported: false - }; - } catch (err) { - throw err instanceof Error ? err : new Error('Watch credential provisioning failed.'); - } finally { - secret.fill(0); - } - } - - selectAccountRelay(relayUrl: string): void { - const endpoint = normalizeAccountRelayUrl(relayUrl); - if (!endpoint) throw new Error('Invalid Relay URL'); - if (!sameRelayDeployment(this.cloudRelayUrl, endpoint)) { - this.teardownCloudAccountProjection(this.requireCloud()); - this.selectedRelayUrl = endpoint; - } - } - - async loginCloudAccount(): Promise { - const relayUrl = this.selectedRelayUrl; - const generation = ++this.accountLoginVersion; - const cloud = this.requireCloud(); - if (this.cloudInitialization) { - await this.cloudInitialization; - } - RemoteLogger.info('cloud account UI login requested'); - let deviceSecret: Uint8Array; - try { - deviceSecret = await cloud.sessionStore.deviceSecret(); - } catch (err) { - RemoteLogger.error(`cloud account device identity failed: ${err instanceof Error ? err.message : String(err)}`); - throw err instanceof Error ? err : new Error(String(err)); - } - if (generation !== this.accountLoginVersion) { deviceSecret.fill(0); throw new Error('Account login cancelled'); } - let session: CloudAccountSession; - try { - session = await cloud.client.login(relayUrl, cloud.hooks.deviceId(), cloud.hooks.openAuthorization, deviceSecret); - } finally { deviceSecret.fill(0); } - if (generation !== this.accountLoginVersion) { - session.masterKey.fill(0); - throw new Error('Account login cancelled'); - } - const username = session.userId; - this.clearPreferredCloudTarget(); - this.applyCloudAccountSession(session, relayUrl, username); - try { - await cloud.sessionStore.save({ - relayUrl: relayUrl.trim(), username: username.trim(), token: session.token, userId: session.userId, - masterKey: Encoding.bytesToBase64(session.masterKey) - }); - } catch (err) { - RemoteLogger.warn(`cloud account session persistence failed: ${String(err)}`); - } - void this.refreshCloudAccountProfile(); - RemoteLogger.info('cloud account session active, refreshing account devices'); - RemoteLogger.info(`cloud account login success user=${session.userId}`); - return session.userId; - } - - applyCloudAccountSession(session: CloudAccountSession, relayUrl: string, username: string): void { - const remoteState = this.requireCloud().remoteState; - this.cloudSession = session; - this.cloudRelayUrl = relayUrl.trim(); - this.selectedRelayUrl = this.cloudRelayUrl; - this.cloudAccountUsername = username.trim(); - remoteState.setAccountAvatarUrl(''); - remoteState.setAccountUserId(session.userId); - remoteState.setAccountUsername(this.cloudAccountUsername); - this.startPresencePolling(0); - } - - cancelCloudLogin(): void { this.cloud?.client.cancelAuthorization(); } - - /** Keep browser authorization polling aligned with the page lifecycle. */ - setAuthorizationForeground(value: boolean): void { - this.cloud?.client.setAuthorizationForeground(value); - } - - async logoutCloudAccount(): Promise { - this.cancelCloudLogin(); - const cloud = this.requireCloud(); - cloud.hooks.invalidatePreview(); - this.teardownCloudAccountProjection(cloud); - await cloud.sessionStore.clear(); - await cloud.hooks.clearCachedRemoteData(); - cloud.remoteState.clearControlTarget(); - cloud.remoteState.setHostCapabilities([]); - await this.saveControlTargetType(''); - RemoteLogger.info('cloud account logout success'); - } - - activeCloudAccount(): CloudAccountBinding | undefined { - const cloud = this.cloud; - const session = this.cloudSession; - if (!cloud || !session || this.cloudRelayUrl.length === 0) { - return undefined; - } - const binding: CloudAccountBinding = { - client: cloud.client, - relayUrl: this.cloudRelayUrl, - session - }; - return binding; - } - - cloudRelayEndpoint(): string { - return this.cloudRelayUrl; - } - - preferredCloudTarget(): PreferredCloudTarget | undefined { - const deviceId = this.preferredTargetDeviceId.trim(); - if (deviceId.length === 0) { - return undefined; - } - return { - deviceId, - deviceName: this.preferredTargetDeviceName.trim() || deviceId - }; - } - - /** Account Socket.IO owns liveness. Presence snapshots update known rows - * directly; reconnect and unknown devices hydrate metadata once, never idle. */ - startPresencePolling(_maxAgeMs: number): void { - this.stopPresencePolling(); - const binding = this.activeCloudAccount(); - if (!binding) return; - const epoch = this.presenceGeneration; - try { - 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(); - cloud.hooks.onAccountDevices(this.accountDevices); - const target = this.targetReleased() ? '' : cloud.remoteState.controlTargetDeviceId; - if (target && !ids.includes(target)) { - cloud.remoteState.setConnectionState('reconnecting'); - cloud.remoteState.setStatusText(RemoteI18n.t('remote.settings.deviceUnavailable')); - if (this.targetProbeTimer !== -1) clearTimeout(this.targetProbeTimer); - this.targetProbeTimer = -1; - } else if (target && previousTarget?.online !== true) { - this.targetProbeDelay = 250; this.scheduleTargetProbe(epoch); - } - if (ids.some((id: string) => !this.accountDevices.some((device: CloudAccountDevice) => device.deviceId === id))) void this.hydratePresence(epoch); - }, - () => { void this.hydratePresence(epoch); }); - } catch (error) { - // Transport startup failure must not invalidate a restored account identity. - const cloud = this.requireCloud(); - cloud.remoteState.setStatusText(ConnectionErrorPolicy.errorText(error)); - if (cloud.remoteState.controlTargetDeviceId && !this.targetReleased()) cloud.remoteState.setConnectionState('reconnecting'); - RemoteLogger.warn(`account presence observer failed: ${ConnectionErrorPolicy.errorText(error)}`); - } - } - - stopPresencePolling(): void { - this.presenceGeneration++; - this.latestPresence = undefined; - this.stopPresence?.(); this.stopPresence = undefined; - if (this.targetProbeTimer !== -1) clearTimeout(this.targetProbeTimer); - this.targetProbeTimer = -1; - } - - private async hydratePresence(epoch: number): Promise { - if (this.presenceRefreshing || epoch !== this.presenceGeneration) return; - this.presenceRefreshing = true; - try { - await this.refreshAccountDevicesIfStale(0); - if (epoch === this.presenceGeneration) { this.targetProbeDelay = 250; this.scheduleTargetProbe(epoch); } - } - finally { this.presenceRefreshing = false; } - } - - /** - * The user left the selected device: it stays as the selection so it can be - * offered again, but presence churn must not bring the link back on its own. - */ - private targetReleased(): boolean { - const remoteState = this.requireCloud().remoteState; - return remoteState.controlTargetType === 'account_device' && remoteState.connectionState === 'disconnected'; - } - - private scheduleTargetProbe(epoch: number): void { - if (epoch !== this.presenceGeneration || this.targetProbeTimer !== -1 || this.targetProbing || - this.targetReleased()) return; - const cloud = this.requireCloud(); - const target = cloud.remoteState.controlTargetDeviceId; - if (!target || !this.accountDevices.some((device: CloudAccountDevice) => device.deviceId === target && device.online)) return; - this.targetProbeTimer = setTimeout(() => { - this.targetProbeTimer = -1; - void this.probeTarget(epoch, target); - }, this.targetProbeDelay); - } - - private async probeTarget(epoch: number, target: string): Promise { - if (epoch !== this.presenceGeneration || target !== this.requireCloud().remoteState.controlTargetDeviceId || - this.targetReleased()) return; - this.targetProbing = true; - let retry = false; - try { - await this.requireCloud().sessionManager.ping(); - if (epoch !== this.presenceGeneration || target !== this.requireCloud().remoteState.controlTargetDeviceId || - this.targetReleased()) return; - this.requireCloud().remoteState.setConnectionState('connected'); - this.targetProbeDelay = 250; - } catch (error) { - if (epoch === this.presenceGeneration && target === this.requireCloud().remoteState.controlTargetDeviceId && - !this.targetReleased()) { - this.requireCloud().remoteState.setConnectionState('reconnecting'); - this.requireCloud().remoteState.setStatusText(ConnectionErrorPolicy.errorText(error)); - this.targetProbeDelay = Math.min(30000, this.targetProbeDelay * 2); - retry = true; - } - } finally { - this.targetProbing = false; - if (retry) this.scheduleTargetProbe(epoch); - } - } - - /** - * Refetches account device presence when the last answer is older than - * [maxAgeMs]. - * - * The relay owns presence in a live socket registry, so its answer is only - * as current as the last time we asked — and the only ask used to be at - * cold start. A desktop that came online afterwards stayed grey in the - * sidebar until the app was killed and relaunched. - * - * Failure is swallowed on purpose: this runs off returning to the - * foreground, where the user asked for nothing and a thrown error would - * surface as an alert about a request they never made. - */ - async refreshAccountDevicesIfStale(maxAgeMs: number): Promise { - if (!this.hasCloudAccountSession()) { - return; - } - if (Date.now() - this.lastAccountDevicesAt < maxAgeMs) { - return; - } - try { - await this.listCloudAccountDevices(); - } catch (err) { - RemoteLogger.warn(`account device presence refresh failed: ${String(err)}`); - } - } - - /** - * Re-publishes the cached device list so presence can be re-derived. - * - * Presence is not purely the relay's to decide: a device we hold a live link - * to is online whatever the socket registry last projected. That override is - * evaluated when the list is published, so a link going live has to republish - * or the desktop we just connected to keeps whatever the last fetch claimed — - * on a cold start that fetch happens before the reconnect lands, and the - * answer it brought back is "offline". - * - * No request goes out: this is the same list, read again. - */ - resyncAccountDevicePresence(): void { - if (this.accountDevices.length === 0) { - return; - } - this.requireCloud().hooks.onAccountDevices(this.accountDevices); - } - - async listCloudAccountDevices(): Promise { - const cloud = this.requireCloud(); - const session = this.cloudSession; - 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) { - if (this.cloudSession !== session) throw new Error('Account changed while loading devices'); - if (err instanceof CloudAccountRequestError && err.statusCode === 401) { - await this.expireCloudAccountSession(); - throw new Error(RemoteI18n.t('remote.settings.accountExpired')); - } - if (err instanceof CloudAccountRequestError && - (err.statusCode === 404 || err.statusCode === 503 || err.statusCode === 504)) { - throw new Error(RemoteI18n.t('remote.settings.deviceUnavailable')); - } - throw new Error(err instanceof Error ? err.message : RemoteI18n.t('remote.settings.deviceLoadFailed')); - } - } - - knownAccountDevice(deviceId: string): CloudAccountDevice | undefined { - const target = deviceId.trim(); - if (target.length === 0) { - return undefined; - } - return this.accountDevices.find((item: CloudAccountDevice): boolean => item.deviceId === target); - } - - async getRemotePermissionMode(): Promise { - const cloud = this.requireCloud(); - if (!cloud.hooks.remoteAvailable()) { - throw new Error(RemoteI18n.t('remote.permissions.connectionRequired')); - } - return cloud.sessionManager.getPermissionMode(); - } - - async setRemotePermissionMode(mode: RemotePermissionMode): Promise { - const cloud = this.requireCloud(); - if (!cloud.hooks.remoteAvailable()) { - throw new Error(RemoteI18n.t('remote.permissions.connectionRequired')); - } - return cloud.sessionManager.setPermissionMode(mode); - } - - /** - * The connected desktop's own model catalog: no session id, so the read is - * device scope and carries the reconciled default models. - */ - async getDeviceModelCatalog(): Promise { - const cloud = this.requireCloud(); - if (!cloud.hooks.remoteAvailable()) { - throw new Error(RemoteI18n.t('status.remoteUnavailable')); - } - return cloud.sessionManager.getModelCatalog(); - } - - /** - * Writes the three phone-managed model slots as one object and answers with - * the desktop's reconciled values. `null` is a value: the fast model then - * follows the primary one and the others are left unconfigured. - */ - async setDeviceModelDefaults( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise { - const cloud = this.requireCloud(); - if (!cloud.hooks.remoteAvailable()) { - throw new Error(RemoteI18n.t('status.remoteUnavailable')); - } - return cloud.sessionManager.setModelDefaults(primary, fast, imageUnderstanding); - } - - /** - * Puts the account back on the desktop it was last driving. - * - * `navigateHome` is off for the cold-start restore: the launch route is the - * user's business, and reconnecting in the background should not move them - * off the screen the app opened on. A manual reconnect is already on the - * Remote surface, so there it lands where the user expects. - */ - async restoreCloudTarget( - targetDeviceId: string, - targetDeviceName: string, - navigateHome: boolean = true - ): Promise { - const targetId = targetDeviceId.trim(); - if (targetId.length === 0) { - return; - } - this.setPreferredCloudTarget(targetId, targetDeviceName.trim() || targetId); - const remoteState = this.requireCloud().remoteState; - try { - const devices = await this.listCloudAccountDevices(); - const target = devices.find((device: CloudAccountDevice): boolean => device.deviceId === targetId); - if (!target || !target.online) { - const targetName = target ? accountDeviceDisplayName(target) : targetDeviceName || targetId; - remoteState.setControlTarget('account_device', targetId, targetName); - remoteState.setDesktopIdentity(targetName, targetId); - remoteState.setConnectionState('reconnecting'); - remoteState.setStatusText(RemoteI18n.t('remote.settings.deviceUnavailable')); - this.requireCloud().hooks.startHeartbeat(); - return; - } - await this.selectCloudAccountDevice({ - deviceId: target.deviceId, - deviceName: target.deviceName || targetDeviceName || target.deviceId, - deviceAlias: target.deviceAlias, - online: target.online, - lastSeenAt: target.lastSeenAt, - compatible: target.compatible - }, navigateHome); - } catch (err) { - RemoteLogger.warn(`cloud target restore failed: ${err instanceof Error ? err.message : 'unknown error'}`); - if (!this.cloudSession) { - // The account itself went away — an expired token clears it — so there - // is no desktop left to aim at, and the surfaces already say as much. - return; - } - // A failed connect attempt drops the target so a half-open link cannot be - // mistaken for a live one, but a restore that failed is exactly the case - // where the target still matters: without it the reconnect button has - // nothing to retry and falls through to the paired-desktop path. - remoteState.setControlTarget('account_device', targetId, targetDeviceName.trim() || targetId); - remoteState.setConnectionState('reconnecting'); - remoteState.setStatusText(ConnectionErrorPolicy.errorText(err)); - this.requireCloud().hooks.startHeartbeat(); - } - } - - async handleRemoteConnectionError(err: Object): Promise { - const remoteState = this.requireCloud().remoteState; - if (remoteState.controlTargetType !== 'account_device' || - !(err instanceof CloudAccountRequestError) || err.statusCode !== 401) { - return false; - } - await this.expireCloudAccountSession(); - remoteState.setStatusText(RemoteI18n.t('remote.settings.accountExpired')); - return true; - } - - async selectCloudAccountDevice(device: CloudAccountDevice, navigateHome: boolean = true): Promise { - const cloud = this.requireCloud(); - const session = this.cloudSession; - if (!device.online) { - throw new Error(RemoteI18n.t('remote.settings.deviceOffline')); - } - // A confirmed-incompatible device stays listed but is never a target. - if (!isDeviceControllable(device)) { - throw new Error(RemoteI18n.t('remote.settings.deviceIncompatible')); - } - if (!session || this.cloudRelayUrl.length === 0) { - throw new Error(RemoteI18n.t('remote.settings.accountNotSignedIn')); - } - const deviceId = device.deviceId.trim(); - if (deviceId.length === 0 || deviceId === cloud.hooks.deviceId()) { - return; - } - const selectionVersion = ++this.accountDeviceSelectionVersion; - // A QR room and an account-device link can identify the same physical - // desktop. Only short-circuit when the active transport is already the - // account path the user selected; otherwise this tap is an intentional - // room -> account migration and must replace the transport and persist the - // account target for the next launch. - if (cloud.remoteState.controlTargetType === 'account_device' && - deviceId === cloud.remoteState.controlTargetDeviceId && - cloud.remoteState.connectionState === 'connected') { - cloud.hooks.closeConnectSheet(); - if (navigateHome) { - cloud.hooks.navigateRemoteHome(); - } - return; - } - // Taken before the teardown, which is the last moment the outgoing device - // is still readable off the page state. - const previousTarget = this.restorableControlTarget(); - this.prepareAccountDeviceConnection(deviceId); - try { - const initialSync = await cloud.sessionManager.connectAccountDevice( - cloud.client, - this.cloudRelayUrl, - session, - deviceId - ); - if (selectionVersion !== this.accountDeviceSelectionVersion) { - RemoteLogger.info(`stale device switch completion ignored device=${deviceId}`); - return; - } - RemoteLogger.info( - `account device sync device=${deviceId} workspace=${initialSync.workspace.path} sessions=${initialSync.sessions.length}` - ); - 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, - initialSync.workspace.assistantId || '', - initialSync.workspace.gitBranch, - initialSync.workspace.workspaceKind || 'normal', - initialSync.workspace.remoteConnectionId || '', - initialSync.workspace.remoteSshHost || '', - initialSync.workspace.workspaceId || '' - ); - cloud.remoteState.setSessions( - stampRemoteSessionsDevice(initialSync.sessions, deviceId), - initialSync.hasMoreSessions - ); - cloud.hooks.onControlTargetChanged(); - cloud.remoteState.setAuthenticatedUserId(initialSync.authenticatedUserId); - cloud.remoteState.setHostCapabilities(initialSync.capabilities || []); - cloud.remoteState.setConnectionState('connected'); - this.setPreferredCloudTarget(deviceId, displayName); - await this.saveControlTargetType('account_device'); - this.resyncAccountDevicePresence(); - cloud.remoteState.setStatusText(RemoteI18n.t('connection.connected')); - // Dismissing the picker and going home are the same event: the switch the - // user asked for from a sheet is done. A switch nobody asked for — the - // one behind opening a session on another desktop, or the restore after a - // failed one — must not take their place in the UI away from them. - if (navigateHome) { - cloud.hooks.closeSettings(); - cloud.hooks.closeConnectSheet(); - cloud.hooks.navigateRemoteHome(); - } - try { - await this.persistCurrentCloudSessionTarget(deviceId, displayName); - } catch (err) { - RemoteLogger.warn(`account target persistence failed device=${deviceId}: ${String(err)}`); - } - cloud.hooks.startHeartbeat(); - // Same reasoning as the paired-desktop path in RemoteConnectionController: - // the cross-workspace scan runs behind a list that is already usable. - void cloud.hooks.loadRecentWorkspaces(); - } catch (err) { - if (selectionVersion !== this.accountDeviceSelectionVersion) { - RemoteLogger.info(`stale device switch failure ignored device=${deviceId}`); - return; - } - if (err instanceof CloudAccountRequestError && err.statusCode === 401) { - await this.expireCloudAccountSession(); - } - cloud.remoteState.clearControlTarget(); - cloud.remoteState.setConnectionState('failed'); - const message = ConnectionErrorPolicy.errorText(err); - cloud.remoteState.setStatusText(message); - cloud.sessionManager.reset(); - await this.restoreControlTarget(previousTarget); - throw new Error(message); - } finally { - if (selectionVersion === this.accountDeviceSelectionVersion) { - cloud.remoteState.setLoadingHome(false); - cloud.remoteState.setBusy(false); - } - } - } - - /** - * The device to fall back to if the switch about to start fails, or nothing. - * - * Only an account device qualifies. A QR-paired room is re-established by - * `RemoteConnectionController`, not from here, so offering to restore it - * would be a promise this method cannot keep. `online: true` is not a guess: - * it is what the live connection just proved, and it is what - * `selectCloudAccountDevice` refuses to dial without. - */ - private restorableControlTarget(): CloudAccountDevice | undefined { - const state = this.requireCloud().remoteState; - if (state.controlTargetType !== 'account_device' || state.connectionState !== 'connected') { - return undefined; - } - const deviceId = state.controlTargetDeviceId.trim(); - if (deviceId.length === 0) { - return undefined; - } - return { - deviceId, - deviceName: state.controlTargetDeviceName || deviceId, - online: true - }; - } - - /** - * Puts the phone back on the desktop it was talking to before a failed switch. - * - * There is one transport, so `prepareAccountDeviceConnection` has to tear the - * old link down before dialling the new one. When the dial fails, what is - * left is no device at all, with polling and the heartbeat stopped — tapping - * a session on a machine that has gone away costs the user the machine they - * were actually using. The restore is best effort and deliberately silent: - * the original failure is still what gets reported, because the thing the - * user asked for did not happen either way. The re-entry guard is what stops - * a restore that fails from trying to restore itself. - */ - private async restoreControlTarget(previous?: CloudAccountDevice): Promise { - if (!previous || this.restoringControlTarget) { - return; - } - this.restoringControlTarget = true; - try { - await this.selectCloudAccountDevice(previous, false); - RemoteLogger.info(`control target restored device=${previous.deviceId}`); - } catch (err) { - RemoteLogger.warn(`control target restore failed device=${previous.deviceId}: ${String(err)}`); - } finally { - this.restoringControlTarget = false; - } - } - - async refreshCloudAccountProfile(): Promise { - const cloud = this.requireCloud(); - const session = this.cloudSession; - const loader = cloud.profileLoader; - if (!session || !loader) return; - const version = this.accountLoginVersion; - const isCurrent = (): boolean => this.cloudSession === session && this.accountLoginVersion === version; - const apply = (profile: GitHubAccountProfile): void => { - if (!isCurrent() || profile.userId !== session.userId) return; - this.cloudAccountUsername = profile.login; - cloud.remoteState.setAccountUsername(profile.login); - cloud.remoteState.setAccountAvatarUrl(profile.avatarUrl); - }; - try { - const cached = await cloud.sessionStore.loadProfile(session.userId); - if (!isCurrent()) return; - if (cached) { - apply(cached); - const age = Date.now() - cached.fetchedAt; - if (age >= 0 && age < 24 * 60 * 60 * 1000) return; - } - } catch (_err) { RemoteLogger.warn('GitHub profile cache unavailable'); } - if (!isCurrent()) return; - try { - const profile = await loader.load(session.userId); - if (!isCurrent() || profile.userId !== session.userId) return; - apply(profile); - await cloud.sessionStore.saveProfile(profile); - } catch (_err) { - // Optional public metadata must never expire or block the authenticated session. - RemoteLogger.warn('GitHub profile refresh unavailable; keeping account session'); - } - } - - private async restoreCloudAccountSession(): Promise { - const cloud = this.requireCloud(); - try { - const persisted = await cloud.sessionStore.load(); - if (!persisted) { - return; - } - if (/^https:\/\/remote\.openbitfun\.com\/v\/[^/]+\/?$/.test(persisted.relayUrl) - && !sameRelayDeployment(persisted.relayUrl, OFFICIAL_RELAY_URL)) { - // Relay credentials are database-scoped; never replay an older credential at a new endpoint. - this.selectedRelayUrl = OFFICIAL_RELAY_URL; - this.cloudRelayUrl = OFFICIAL_RELAY_URL; - // Saved profile identity is not authentication against the current relay. - // Keep the encrypted record and display name, but expose the sign-in entry. - cloud.remoteState.setAccountUserId(''); - cloud.remoteState.setAccountUsername(persisted.username || persisted.userId); - cloud.remoteState.setStatusText(RemoteI18n.t('remote.settings.relayReauthorizationRequired')); - RemoteLogger.warn('Saved account requires authorization for the current relay'); - return; - } - const session: CloudAccountSession = { - token: persisted.token, - userId: persisted.userId, - masterKey: Encoding.base64ToBytes(persisted.masterKey) - }; - this.applyCloudAccountSession(session, persisted.relayUrl, persisted.username || session.userId); - this.restorePersistedControlTarget(persisted); - } catch (err) { - RemoteLogger.warn(`cloud account restore failed: ${err instanceof Error ? err.message : 'unknown error'}`); - // Retain the encrypted record. A temporary keystore/storage failure must - // not turn into an implicit logout and erase the only resumable session. - cloud.remoteState.setStatusText(ConnectionErrorPolicy.errorText(err)); - } - } - - /** - * Names the desktop this account was last driving, without connecting to it. - * - * The account path has no pairing snapshot on disk the way the scanned-room - * path does — the target rides along in the encrypted account record — so - * without this a cold start could not even say which desktop it used to be - * on, and the restore that follows would have nothing to aim at. - */ - private restorePersistedControlTarget(persisted: PersistedCloudAccountSession): void { - const targetId = (persisted.targetDeviceId || '').trim(); - if (targetId.length === 0) { - return; - } - const targetName = (persisted.targetDeviceName || '').trim() || targetId; - this.setPreferredCloudTarget(targetId, targetName); - this.restorePreferredCloudTargetProjection(); - } - - private async expireCloudAccountSession(): Promise { - const cloud = this.requireCloud(); - cloud.hooks.invalidatePreview(); - // Revocation removes live authority, not the user's encrypted record or - // cached remote sessions. Only explicit logout may erase those records. - this.teardownCloudAccountProjection(cloud); - RemoteLogger.info('cloud account session expired'); - } - - /** Publishes the complete signed-out projection as one synchronous transition. */ - private teardownCloudAccountProjection( - cloud: CloudAccountSettingsDependencies - ): void { - // Invalidate late device-selection completions before touching observable - // state. During an in-flight switch the target is deliberately `none`, but - // its busy/status/session projection still belongs to the account. - cloud.client.closeAccount(); - this.accountDeviceSelectionVersion += 1; - this.resetAccountDeviceConnection(true); - this.clearCloudAccountIdentity(cloud); - } - - private async saveControlTargetType(controlTargetType: string): Promise { - try { - await this.requireCloud().hooks.saveControlTargetType(controlTargetType); - } catch (err) { - RemoteLogger.warn(`control target preference persistence failed: ${String(err)}`); - } - } - - /** Drops the remaining account identity facts after remote teardown. */ - private clearCloudAccountIdentity(cloud: CloudAccountSettingsDependencies): void { - this.stopPresencePolling(); - this.accountLoginVersion += 1; - this.cloudSession?.masterKey.fill(0); - this.cloudSession = undefined; - this.cloudRelayUrl = ''; - this.cloudAccountUsername = ''; - this.clearPreferredCloudTarget(); - this.accountDevices = []; - this.lastAccountDevicesAt = 0; - cloud.hooks.onAccountDevices([]); - cloud.remoteState.setAccountUserId(''); - cloud.remoteState.setAccountUsername(''); - cloud.remoteState.setAccountAvatarUrl(''); - } - - private prepareAccountDeviceConnection(deviceId: string): void { - const cloud = this.requireCloud(); - cloud.hooks.onBeforeControlTargetChange(); - cloud.hooks.invalidatePreview(); - cloud.hooks.invalidateRemoteActivity(); - cloud.hooks.invalidateRemoteConnection(); - cloud.hooks.stopPolling(); - cloud.hooks.stopHeartbeat(); - cloud.remoteState.setConnectionState('reconnecting'); - cloud.remoteState.setLoadingHome(true); - cloud.remoteState.clearControlTarget(); - cloud.remoteState.setWorkspace(RemoteI18n.t('status.notConnected'), '', '', '', 'normal'); - // The workspace catalog belongs to the control target, just like the - // workspace and session projection above. Keeping it alive across this - // boundary makes the outgoing desktop's catalog look like the incoming - // desktop's while the latter is still connecting. - cloud.remoteState.clearWorkspaceActions(); - cloud.hooks.onControlTargetLoading(deviceId); - cloud.remoteState.setBusy(true); - cloud.remoteState.setStatusText(RemoteI18n.t('remote.settings.deviceConnecting')); - cloud.remoteState.clearActiveSession(); - cloud.hooks.resetTimeline(); - cloud.hooks.resetKnownRemoteState(); - cloud.remoteState.setSessions([], false); - } - - private resetAccountDeviceConnection(clearWorkspace: boolean): void { - const cloud = this.requireCloud(); - cloud.hooks.invalidateRemoteActivity(); - cloud.hooks.stopPolling(); - cloud.hooks.stopHeartbeat(); - cloud.sessionManager.reset(); - cloud.remoteState.resetConversationContext(); - cloud.hooks.resetTimeline(); - cloud.hooks.resetKnownRemoteState(); - if (clearWorkspace) { - cloud.remoteState.setWorkspace(RemoteI18n.t('status.notConnected'), '', '', '', 'normal'); - cloud.remoteState.setAuthenticatedUserId(''); - cloud.remoteState.clearWorkspaceActions(); - } - cloud.remoteState.clearControlTarget(); - cloud.remoteState.setConnectionState('disconnected'); - } - - private setPreferredCloudTarget(deviceId: string, deviceName: string): void { - this.preferredTargetDeviceId = deviceId.trim(); - this.preferredTargetDeviceName = deviceName.trim() || this.preferredTargetDeviceId; - } - - private clearPreferredCloudTarget(): void { - this.preferredTargetDeviceId = ''; - this.preferredTargetDeviceName = ''; - } - - private restorePreferredCloudTargetProjection(): void { - const target = this.preferredCloudTarget(); - if (!target) { - return; - } - const remoteState = this.requireCloud().remoteState; - remoteState.setControlTarget('account_device', target.deviceId, target.deviceName); - remoteState.setDesktopIdentity(target.deviceName, target.deviceId); - } - - private async persistCurrentCloudSessionTarget(deviceId: string, deviceName: string): Promise { - const cloud = this.requireCloud(); - const session = this.cloudSession; - if (!session || this.cloudRelayUrl.length === 0) { - return; - } - await cloud.sessionStore.save({ - relayUrl: this.cloudRelayUrl, - username: this.cloudAccountUsername || session.userId, - token: session.token, - userId: session.userId, - masterKey: Encoding.bytesToBase64(session.masterKey), - targetDeviceId: deviceId.trim(), - targetDeviceName: deviceName.trim() || deviceId.trim() - }); - } - - private requireCloud(): CloudAccountSettingsDependencies { - if (!this.cloud) { - throw new Error('Cloud account settings dependencies are not configured.'); - } - return this.cloud; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/VisibleConversationController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/VisibleConversationController.ets deleted file mode 100644 index 9464fecd4c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/VisibleConversationController.ets +++ /dev/null @@ -1,87 +0,0 @@ -import { RemoteSession } from '../../model/RemoteModels'; -import { AppRoute } from '../navigation/AppRouteContract'; -import { RemotePageState } from '../state/RemotePageState'; -import { CommandPaletteRequest } from '../actions/ConversationIntent'; -import { RemoteConversationDependencies, requireRemoteRuntime } from './ConversationRuntime'; -import { RemoteCreateFlowController } from './RemoteCreateFlowController'; -import { RemoteTranscriptController } from './RemoteTranscriptController'; - -/** All visible conversation operations execute on the selected remote host. */ -export class VisibleConversationController { - private readonly remote: RemotePageState; - private readonly remoteRuntime: RemoteConversationDependencies | undefined; - private readonly transcript: RemoteTranscriptController; - private readonly createFlow: RemoteCreateFlowController; - private readonly setChatInputRef: (route: AppRoute, value: string) => void; - private readonly setVisibleStatusTextRef: (text: string) => void; - private readonly notify: (text: string) => void; - - constructor( - remote: RemotePageState, - remoteRuntime: RemoteConversationDependencies | undefined, - transcript: RemoteTranscriptController, - createFlow: RemoteCreateFlowController, - setChatInputRef: (route: AppRoute, value: string) => void, - setVisibleStatusTextRef: (text: string) => void, - notify: (text: string) => void - ) { - this.remote = remote; - this.remoteRuntime = remoteRuntime; - this.transcript = transcript; - this.createFlow = createFlow; - this.setChatInputRef = setChatInputRef; - this.setVisibleStatusTextRef = setVisibleStatusTextRef; - this.notify = notify; - } - - openHomeSession(session: RemoteSession, inPlace: boolean = false): void { - requireRemoteRuntime(this.remoteRuntime).filePreview.close(); - void this.createFlow.openRemoteSession(session, inPlace).catch((err: Object) => { - this.notify(err instanceof Error ? err.message : String(err)); - }); - } - - async deleteHomeSession(session: RemoteSession): Promise { - await this.createFlow.deleteRemoteSession(session); - } - - async sendVisibleMessage(): Promise { await this.transcript.sendRemoteMessage(); } - async stopVisibleTask(): Promise { await this.transcript.stopRemoteTask(); } - async renameVisibleSession(title: string): Promise { await this.transcript.renameRemoteSession(title); } - async retryVisibleMessage(text: string): Promise { this.transcript.retryRemoteMessage(text); } - downloadVisibleFile(path: string): void { void this.transcript.downloadRemoteFile(path); } - async selectVisibleModel(modelId: string): Promise { await this.transcript.selectRemoteModel(modelId); } - - async dispatchCommandPalette(request: CommandPaletteRequest): Promise { - await this.transcript.dispatchCommandPalette(request); - } - - closeActiveChat(): void { - const runtime = requireRemoteRuntime(this.remoteRuntime); - runtime.filePreview.close(); - void runtime.hooks.stopVoiceInput(); - runtime.polling.stop(); - this.remote.setConversationDismissed(true); - runtime.appShell.replaceRouteWithoutAnimation(AppRoute.RemoteHome); - } - - onVisibleChatInputChange(route: AppRoute, value: string): void { - this.setChatInputRef(route, value); - } - - latestUserMessageText(): string { - const candidates = this.remote.persistedMessages.concat(this.remote.optimisticMessages); - for (let index = candidates.length - 1; index >= 0; index--) { - if (candidates[index].role === 'user' && candidates[index].text.trim().length > 0) { - return candidates[index].text; - } - } - return ''; - } - - showHomeToast(message: string): void { - if (!requireRemoteRuntime(this.remoteRuntime).hooks.showToast(message)) { - this.setVisibleStatusTextRef(message); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/WorkspaceToolsViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/WorkspaceToolsViewModel.ets deleted file mode 100644 index a8c44a04de..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/WorkspaceToolsViewModel.ets +++ /dev/null @@ -1,347 +0,0 @@ -import { RemoteFileDownloadController } from '../../services/RemoteFileDownloadController'; -import { WorkspaceFileUploadClient } from '../../services/WorkspaceFileUploadClient'; -import { Encoding } from '../../services/Encoding'; -import { RemoteSessionManager } from '../../services/RemoteSessionManager'; -import { HostSessionStream } from '../../services/HostSessionStream'; -import { WorkspaceToolsState, WorkspaceToolsIntent, WorkspaceFileEntry, WorkspaceTerminalEntry, WorkspaceToolLocation } from '../state/WorkspaceToolsState'; -import { RuntimeFileLocation } from '../../model/RemoteModels'; - -interface RuntimeSystemInfo { homeDir?: string; } -interface DirectoryPage { children: WorkspaceFileEntry[]; hasMore: boolean; } -interface TerminalPage { data: string; nextOffset: number; cursor: number; truncated: boolean; } -interface TerminalCreated { id: string; } -interface FileRequest { sortBy?: string; sortOrder?: string; expectedHash?: string; path?: string; filePath?: string; oldPath?: string; newPath?: string; content?: string; workspacePath?: string; remoteConnectionId?: string; offset?: number; limit?: number; recursive?: boolean; } -interface FileArgs { request: FileRequest; } -interface TerminalRequest { sessionId?: string; workingDirectory?: string; connectionId?: string; cols?: number; rows?: number; source?: string; data?: string; immediate?: boolean; } -interface TerminalArgs { request: TerminalRequest; } -interface TerminalHistoryArgs { sessionId: string; afterOffset: number; } - -/** Files and PTYs always belong to the selected runtime, including saved SSH targets. */ -export class WorkspaceToolsViewModel { - private browseGeneration: number = 0; - private state: WorkspaceToolsState; - private manager: RemoteSessionManager; - private target: () => string; - private location?: RuntimeFileLocation; - private deviceScope: boolean = false; - private download?: RemoteFileDownloadController; - private upload: WorkspaceFileUploadClient; - private owner: string = ''; - private originalContent: string = ''; - private pendingNavigation?: WorkspaceToolsIntent; - private expectedHash: string = ''; - private epoch: number = 0; - private stream?: HostSessionStream; - private terminalCursor: number = 0; - private terminalGeneration: number = 0; - private readingTerminal: boolean = false; - private terminalDirty: boolean = false; - private terminalHistoryError: string = ''; - private inputBuffer: string = ''; - private inputTimer: number = -1; - private inputSending: boolean = false; - private resizeTimer: number = -1; - constructor(state: WorkspaceToolsState, manager: RemoteSessionManager, target: () => string) { - this.state = state; this.manager = manager; this.target = target; - this.upload = new WorkspaceFileUploadClient(manager, target); - } - dispatch(intent: WorkspaceToolsIntent): void { - if (intent.type === 'file-action-cancel') { if (!this.state.busy) this.state.fileAction = ''; return; } - if (intent.type === 'file-action-name') { if (!this.state.busy) this.state.fileActionName = intent.text || ''; return; } - if (intent.type === 'file-action') { - if (this.state.busy) return; - this.state.fileAction = intent.text || ''; this.state.fileActionPath = intent.path || ''; - this.state.fileActionName = this.state.entries.find((entry: WorkspaceFileEntry): boolean => entry.path === intent.path)?.name || ''; - this.state.error = ''; return; - } - if (intent.type === 'panel') { this.state.initialTab = intent.tab || 0; return; } - if (intent.type === 'browse-workspace' || intent.type === 'browse-more') { void this.browseWorkspace(intent); return; } - if (intent.type === 'discard-cancel') { this.pendingNavigation = undefined; this.state.confirmDiscard = false; return; } - if (intent.type === 'discard-confirm') { - const next = this.pendingNavigation; this.pendingNavigation = undefined; this.state.confirmDiscard = false; - this.state.content = this.originalContent; this.state.dirty = false; - if (next) this.dispatch(next); return; - } - if (this.state.dirty && ['close', 'editor-back', 'read', 'read-new', 'directory', 'open', 'open-device'].includes(intent.type)) { - this.pendingNavigation = intent; this.state.confirmDiscard = true; - if (intent.type === 'open' || intent.type === 'open-device') this.state.visible = true; - return; - } - if (intent.type === 'editor-back') { this.state.editorVisible = false; this.state.editing = false; return; } - if (intent.type === 'editor-edit') { this.state.editing = true; return; } - if (intent.type === 'line-numbers') { this.state.lineNumbers = !this.state.lineNumbers; return; } - if (intent.type === 'sort') { this.state.sort = Number(intent.text || '0'); void this.run({ type: 'directory' }); return; } - - if (intent.type === 'terminal-renderer-error' || intent.type === 'file-renderer-error') { this.state.error = intent.text || ''; return; } - if (intent.type === 'terminal-write') { this.queueInput(intent.text || ''); return; } - if (intent.type === 'terminal-resize') { this.queueResize(intent.text || ''); return; } - if (intent.type === 'edit') { this.state.content = intent.text || ''; this.state.dirty = this.state.content !== this.originalContent; return; } - if (intent.type === 'read-new') { this.state.selectedFile = intent.path || ''; this.state.content = ''; this.originalContent = ''; this.expectedHash = ''; this.state.editorVisible = true; this.state.editing = true; this.state.dirty = false; return; } - if (intent.type === 'close') { this.close(); return; } - void this.run(intent); - } - private async browseWorkspace(intent: WorkspaceToolsIntent): Promise { - const generation = ++this.browseGeneration; const target = this.target(); - const path = intent.path || '/'; const append = intent.type === 'browse-more'; - this.state.browseBusy = true; this.state.browseError = ''; - if (!append) { - this.state.browsePath = path; - this.state.browseEntries = []; - this.state.browseHasMore = false; - } - try { - const args: FileArgs = { request: { path: path, remoteConnectionId: intent.text || '', - offset: append ? this.state.browseEntries.length : 0, limit: 100, sortBy: 'name', sortOrder: 'asc' } }; - const page = await this.manager.hostInvoke('get_directory_children_paginated', args); - if (generation !== this.browseGeneration || target !== this.target()) return; - this.state.browsePath = path; - this.state.browseEntries = append ? this.state.browseEntries.concat(page.children) : page.children; - this.state.browseHasMore = page.hasMore; - } catch (error) { if (generation === this.browseGeneration && target === this.target()) this.state.browseError = String(error); } - finally { if (generation === this.browseGeneration) this.state.browseBusy = false; } - } - private queueInput(data: string): void { - if (!this.current(this.epoch) || !this.state.terminalId || (!data && !this.inputBuffer)) return; - this.inputBuffer += data; - if (!this.inputSending && this.inputTimer === -1) { - const epoch = this.epoch; const terminalId = this.state.terminalId; - this.inputTimer = setTimeout(() => { this.inputTimer = -1; void this.flushInput(terminalId, epoch); }, 8); - } - } - private async flushInput(terminalId: string, epoch: number): Promise { - if (this.inputSending) return; - this.inputSending = true; - try { - while (this.inputBuffer && this.current(epoch) && terminalId === this.state.terminalId) { - let end = Math.min(this.inputBuffer.length, 64 * 1024); - const last = this.inputBuffer.charCodeAt(end - 1); - if (end < this.inputBuffer.length && last >= 0xd800 && last <= 0xdbff) end--; - const data = this.inputBuffer.slice(0, end); - this.inputBuffer = this.inputBuffer.slice(data.length); - const args: TerminalArgs = { request: { sessionId: terminalId, data: data } }; - await this.manager.hostInvoke('terminal_write', args); - } - } catch (error) { - // An uncertain write may already have reached the PTY. Never replay it. - if (this.current(epoch) && terminalId === this.state.terminalId) { this.inputBuffer = ''; this.state.error = String(error); } - } finally { this.inputSending = false; if (this.inputBuffer) this.queueInput(''); } - } - private queueResize(value: string): void { - if (this.resizeTimer !== -1) clearTimeout(this.resizeTimer); - const epoch = this.epoch; const terminalId = this.state.terminalId; - this.resizeTimer = setTimeout(() => { - this.resizeTimer = -1; - if (!this.current(epoch) || !terminalId || terminalId !== this.state.terminalId) return; - const values = value.split('x').map((part: string) => Number(part)); - if (values.length !== 2 || values.some((dimension: number) => !Number.isSafeInteger(dimension) || dimension < 1)) return; - const args: TerminalArgs = { request: { sessionId: terminalId, cols: values[0], rows: values[1] } }; - void this.manager.hostInvoke('terminal_resize', args).catch((error: Error) => { if (this.current(epoch)) this.state.error = error.message; }); - }, 80); - } - private clearInput(): void { - this.inputBuffer = ''; - if (this.inputTimer !== -1) clearTimeout(this.inputTimer); - if (this.resizeTimer !== -1) clearTimeout(this.resizeTimer); - this.inputTimer = -1; this.resizeTimer = -1; - } - private close(): void { - this.clearInput(); - this.download?.cancel(); this.download = undefined; - this.epoch++; this.terminalGeneration++; this.stream?.close(); this.stream = undefined; this.state.visible = false; this.state.fileAction = ''; - } - private current(epoch: number): boolean { return epoch === this.epoch && this.owner === this.target() && this.state.visible; } - private async run(intent: WorkspaceToolsIntent): Promise { - const opening = intent.type === 'open' || intent.type === 'open-device'; - if (opening) { - this.close(); this.owner = this.target(); this.state.visible = true; - this.location = undefined; this.state.entries = []; this.state.directory = ''; this.state.terminals = []; - this.state.editorVisible = false; this.state.dirty = false; this.state.confirmDiscard = false; - this.state.selectedFile = ''; this.state.content = ''; this.state.output = ''; this.state.terminalId = ''; this.state.busy = false; - } - const epoch = this.epoch; - if (!this.current(epoch) || this.state.busy) return; - this.state.busy = true; this.state.error = ''; - try { - if (!opening && !this.location) throw new Error('Choose a location on the controlled runtime first'); - if (opening) { - if (intent.deviceId && intent.deviceId !== this.owner) throw new Error('The controlled runtime changed'); - this.deviceScope = intent.type === 'open-device'; - this.state.deviceScope = this.deviceScope; - this.state.connectionId = intent.connectionId || ''; - if (this.deviceScope) { - const emptyArgs: Record = {}; - const locations = await this.manager.hostInvoke('ssh_list_saved_connections', emptyArgs); - if (!this.current(epoch)) return; - this.state.locations = locations; - if (intent.connectionId && !locations.some((item: WorkspaceToolLocation): boolean => item.id === intent.connectionId)) { - throw new Error('Saved connection is unavailable on the controlled runtime'); - } - } - let path = intent.path || ''; - if (this.deviceScope) { - if (intent.connectionId) path = '/'; - else { - const empty: Record = {}; - const system = await this.manager.hostInvoke('get_system_info', empty); - if (!this.current(epoch)) return; - path = system.homeDir || ''; - } - } - if (!path) throw new Error('The runtime did not provide a default directory'); - const workspace: RuntimeFileLocation = { path: path, remoteConnectionId: intent.connectionId }; - this.state.initialTab = intent.tab || 0; - this.location = workspace; this.state.directory = workspace.path; - await this.directory(workspace.path, false, epoch); - if (!this.current(epoch)) return; - const emptyArgs: Record = {}; - const terminals = await this.manager.hostInvoke('terminal_list', emptyArgs); - if (this.current(epoch)) this.state.terminals = terminals.filter((terminal: WorkspaceTerminalEntry): boolean => - (this.deviceScope || (terminal.initialCwd || terminal.cwd) === workspace.path) && (terminal.connectionId || '') === (workspace.remoteConnectionId || '')); - } else if (intent.type === 'directory' || intent.type === 'more') { - await this.directory(intent.path || this.state.directory, intent.type === 'more', epoch); - } else if (intent.type === 'read') { - const path = intent.path || ''; - const content = await this.file('read_file_content', { filePath: path }); - const hash = await Encoding.sha256(content); - if (this.current(epoch)) { this.state.selectedFile = path; this.state.content = content; this.originalContent = content; this.expectedHash = hash; this.state.editorVisible = true; this.state.editing = false; this.state.dirty = false; } - } else if (intent.type === 'download') { - if (!this.location) throw new Error('Select a runtime location first'); - const location: RuntimeFileLocation = { path: this.state.directory, remoteConnectionId: this.location.remoteConnectionId }; - this.download = new RemoteFileDownloadController(this.manager, - (_pending: string, _saved: string, status: string): void => { if (this.current(epoch)) this.state.downloadStatus = status; }, - (): void => {}, (): void => {}, (): void => {}); - await this.download.download(intent.path || this.state.selectedFile, '', false, true, location); - } else if (intent.type === 'save') { - const savedContent = this.state.content; - await this.file('write_file_content', { filePath: intent.path || this.state.selectedFile, content: savedContent, expectedHash: this.expectedHash, workspacePath: this.location?.path }); - const hash = await Encoding.sha256(savedContent); - if (this.current(epoch)) { this.expectedHash = hash; this.originalContent = savedContent; this.state.dirty = this.state.content !== savedContent; } - await this.directory(this.state.directory, false, epoch); - } else if (intent.type === 'upload' || intent.type === 'upload-resume') { - if (intent.type === 'upload') this.state.uploadProgress = 0; - if (intent.type === 'upload') await this.upload.select(intent.path || '', this.location?.remoteConnectionId, intent.path === this.state.selectedFile ? this.expectedHash : '', () => this.current(epoch), this.location?.path || ''); - await this.upload.resume(() => this.current(epoch), (offset: number, total: number) => { if (this.current(epoch)) this.state.uploadProgress = total ? Math.floor(offset * 100 / total) : 100; }); - if (this.current(epoch)) this.state.uploadPending = this.upload.hasPending(); - await this.directory(this.state.directory, false, epoch); - } else if (intent.type === 'upload-cancel') { - await this.upload.cancel(); if (this.current(epoch)) this.state.uploadPending = false; - } else if (intent.type === 'file-action-submit') { - const action = this.state.fileAction; - const name = this.state.fileActionName; - const oldPath = this.state.fileActionPath; - if (action !== 'delete' && !name.trim()) throw new Error('A file name is required'); - const path = name.startsWith('/') ? name : `${this.state.directory.replace(/\/$/, '')}/${name}`; - const entry = this.state.entries.find((item: WorkspaceFileEntry): boolean => item.path === oldPath); - if ((action === 'rename' || action === 'delete') && !entry) throw new Error('File entry is no longer available'); - if (action === 'file') await this.file('write_file_content', { filePath: path, workspacePath: this.location?.path, content: '', expectedHash: '' }); - else if (action === 'folder') await this.file('create_directory', { path: path }); - else if (action === 'rename') await this.file('rename_file', { oldPath: oldPath, newPath: path }); - else if (action === 'delete') await this.file(entry?.isDirectory ? 'delete_directory' : 'delete_file', { path: oldPath, recursive: false }); - else if (action === 'upload') { - await this.upload.select(path, this.location?.remoteConnectionId, '', () => this.current(epoch), this.location?.path || ''); - await this.upload.resume(() => this.current(epoch), (offset: number, total: number) => { if (this.current(epoch)) this.state.uploadProgress = total ? Math.floor(offset * 100 / total) : 100; }); - } else throw new Error('Unknown file action'); - await this.directory(this.state.directory, false, epoch); - if (this.current(epoch)) this.state.fileAction = ''; - } else if (intent.type === 'mkdir') { - await this.file('create_directory', { path: intent.path }); - await this.directory(this.state.directory, false, epoch); - } else if (intent.type === 'rename') { - await this.file('rename_file', { oldPath: this.state.selectedFile, newPath: intent.path }); - if (this.current(epoch)) this.state.selectedFile = intent.path || ''; - await this.directory(this.state.directory, false, epoch); - } else if (intent.type === 'delete' || intent.type === 'rmdir') { - await this.file(intent.type === 'delete' ? 'delete_file' : 'delete_directory', { path: intent.path || this.state.selectedFile, recursive: false }); - if (this.current(epoch)) { this.state.selectedFile = ''; this.state.content = ''; } - await this.directory(this.state.directory, false, epoch); - } else if (intent.type === 'terminal-create') { - const request: TerminalRequest = { workingDirectory: this.location?.path, connectionId: this.location?.remoteConnectionId || '', cols: 80, rows: 24, source: 'user' }; - const args: TerminalArgs = { request: request }; - const terminal = await this.manager.hostInvoke('terminal_create', args); - if (this.current(epoch)) { this.attach(terminal.id); this.state.terminals = this.state.terminals.concat([{ id: terminal.id }]); } - } else if (intent.type === 'terminal-attach') { - this.attach(intent.path || ''); - } else if (intent.type === 'terminal-write') { - const args: TerminalArgs = { request: { sessionId: this.state.terminalId, data: intent.text || '' } }; - await this.manager.hostInvoke('terminal_write', args); - } else if (intent.type === 'terminal-close') { - const args: TerminalArgs = { request: { sessionId: this.state.terminalId, immediate: true } }; - await this.manager.hostInvoke('terminal_close', args); - if (this.current(epoch)) { - this.terminalGeneration++; this.stream?.close(); this.stream = undefined; - this.state.terminals = this.state.terminals.filter((entry: WorkspaceTerminalEntry) => entry.id !== this.state.terminalId); - this.state.terminalId = ''; this.state.output = ''; - } - } else if (intent.type === 'terminal-resize') { - const parts = (intent.text || '').split('x'); - const cols = Number(parts[0]); const rows = Number(parts[1]); - if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 1 || rows < 1) throw new Error('Use columns x rows, for example 80x24'); - const args: TerminalArgs = { request: { sessionId: this.state.terminalId, cols: cols, rows: rows } }; - await this.manager.hostInvoke('terminal_resize', args); - } - } catch (error) { if (this.current(epoch)) this.state.error = String(error); } - finally { if (this.current(epoch)) { this.state.busy = false; this.state.uploadPending = this.upload.hasPending(); } } - } - private file(command: string, request: FileRequest): Promise { - if (this.owner !== this.target()) throw new Error('Controlled runtime changed'); - request.remoteConnectionId = this.location?.remoteConnectionId || ''; - request.workspacePath = this.location?.path; - const args: FileArgs = { request: request }; - return this.manager.hostInvoke(command, args); - } - private async directory(path: string, append: boolean, epoch: number): Promise { - if (!this.current(epoch)) return; - const page = await this.file('get_directory_children_paginated', { path: path, offset: append ? this.state.entries.length : 0, limit: 100, sortBy: this.state.sort < 2 ? 'name' : 'modified', sortOrder: this.state.sort % 2 === 0 ? 'asc' : 'desc' }); - if (!this.current(epoch)) return; - this.state.directory = path; - if (this.deviceScope && this.location) this.location = { path: path, remoteConnectionId: this.location.remoteConnectionId }; - this.state.entries = append ? this.state.entries.concat(page.children) : page.children; - this.state.hasMore = page.hasMore; - } - private attach(id: string): void { - this.clearInput(); - const generation = ++this.terminalGeneration; - this.stream?.close(); this.state.terminalId = id; this.state.output = ''; this.terminalCursor = 0; - const epoch = this.epoch; - this.stream = this.manager.subscribeSession(`terminal-${id}`, { - onEvent: async (): Promise => { if (this.currentTerminal(id, epoch, generation)) this.terminalDirty = true; }, - onCaughtUp: async (): Promise => { - if (!this.currentTerminal(id, epoch, generation)) return; - this.terminalDirty = true; await this.readTerminal(id, epoch, generation); - }, - onError: (error: Error): void => { if (this.currentTerminal(id, epoch, generation)) { this.terminalHistoryError = error.message; this.state.error = error.message; } } - }); - this.terminalDirty = true; - void this.readTerminal(id, epoch, generation); - } - private currentTerminal(id: string, epoch: number, generation: number): boolean { - return this.current(epoch) && generation === this.terminalGeneration && id === this.state.terminalId; - } - private async readTerminal(id: string, epoch: number, generation: number): Promise { - if (!this.currentTerminal(id, epoch, generation)) return; - if (this.readingTerminal) { this.terminalDirty = true; return; } - this.readingTerminal = true; - try { - while (this.terminalDirty && this.currentTerminal(id, epoch, generation)) { - this.terminalDirty = false; - const args: TerminalHistoryArgs = { sessionId: id, afterOffset: this.terminalCursor }; - const page = await this.manager.hostInvoke('terminal_get_history', args); - if (!this.currentTerminal(id, epoch, generation)) return; - if (!Number.isSafeInteger(page.nextOffset) || !Number.isSafeInteger(page.cursor) || page.nextOffset < 0 || page.cursor < page.nextOffset) throw new Error('Invalid terminal history cursor'); - if (page.nextOffset < this.terminalCursor && !page.truncated) throw new Error('Terminal cursor moved backwards'); - if (!(page.nextOffset > this.terminalCursor || (page.truncated && page.nextOffset < this.terminalCursor) || page.nextOffset === page.cursor)) throw new Error('Terminal history made no progress'); - if (this.terminalHistoryError.length > 0 && this.state.error === this.terminalHistoryError) this.state.error = ''; - this.terminalHistoryError = ''; - this.state.output = (page.truncated ? '' : this.state.output) + page.data; - // Match the runtime's retained display history; the durable stream stores notifications only. - if (this.state.output.length > 4 * 1024 * 1024) this.state.output = this.state.output.slice(-4 * 1024 * 1024); - this.terminalCursor = page.nextOffset; - this.terminalDirty = this.terminalDirty || page.nextOffset < page.cursor; - } - } catch (error) { if (this.currentTerminal(id, epoch, generation)) { this.terminalHistoryError = String(error); this.state.error = this.terminalHistoryError; } } - finally { - this.readingTerminal = false; - if (this.terminalDirty && this.state.visible && generation !== this.terminalGeneration) void this.readTerminal(this.state.terminalId, this.epoch, this.terminalGeneration); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceDirectory.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceDirectory.ets deleted file mode 100644 index 7adb8110c4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceDirectory.ets +++ /dev/null @@ -1,110 +0,0 @@ -import { WorkspaceCatalog, projectWorkspaceCatalog } from './WorkspaceCatalog'; -import { - AssistantEntry, - AssistantListResponse, - RecentWorkspaceEntry, - RecentWorkspaceListResponse, - REMOTE_CAPABILITY_WORKSPACE_ID_REFERENCES_V1, - RemoteSession, - RemoteWorkspaceIdentity, - SessionListResponse, - WorkspaceInfoResponse -} from '../model/RemoteModels'; -import { CloudAccountBinding } from './CloudAccountClient'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { - AccountDeviceCommandTransport, - INTERACTIVE_DIRECTORY_TIMEOUT_MS -} from './RemoteCommandTransport'; -import { RemoteCommandFactory } from './RemoteCommandFactory'; -import { RemoteResponseMapper } from './RemoteResponseMapper'; -import { stampRemoteSessionsDevice, stampRemoteSessionsWorkspace } from './RemoteSessionIdentity'; - -export interface AccountDeviceDirectorySource { - listWorkspaceCatalog(deviceId: string): Promise; - listRecentWorkspaces(deviceId: string): Promise; - listAssistants(deviceId: string): Promise; - listSessions(deviceId: string, workspace: RemoteWorkspaceIdentity): Promise; -} - -/** Read-only per-device RPCs that never touch the active conversation transport. */ -export class AccountDeviceDirectory implements AccountDeviceDirectorySource { - private readonly context: CloudAccountBinding; - /** - * Capabilities each directory device advertised, probed once per device. - * - * Directory listings do not go through the handshake of the active - * connection, so a device's capability set is learned here before the first - * command that would carry a `workspace_id` to it. - */ - private readonly deviceCapabilities: Map = new Map(); - - constructor(context: CloudAccountBinding) { - this.context = context; - } - - async listWorkspaceCatalog(deviceId: string): Promise { - const response = await this.transport(deviceId).send(RemoteCommandFactory.listRecentWorkspaces()); - return projectWorkspaceCatalog(response, await this.listAssistants(deviceId)); - } - - async listRecentWorkspaces(deviceId: string): Promise { - const response = await this.transport(deviceId).send( - RemoteCommandFactory.listRecentWorkspaces() - ); - return RemoteResponseMapper.recentWorkspaces(response.workspaces || []); - } - - async listAssistants(deviceId: string): Promise { - const response = await this.transport(deviceId).send( - RemoteCommandFactory.listAssistants() - ); - return response.assistants || []; - } - - async listSessions(deviceId: string, workspace: RemoteWorkspaceIdentity): Promise { - const scope: RemoteWorkspaceIdentity = { - workspaceId: workspace.workspaceId || undefined, - path: workspace.path.trim(), - remoteConnectionId: workspace.remoteConnectionId, - remoteSshHost: workspace.remoteSshHost - }; - if (!scope.workspaceId && scope.path.length === 0) { - return []; - } - if (scope.workspaceId) { - await this.requireWorkspaceIdReferences(deviceId); - } - const response = await this.transport(deviceId).send( - RemoteCommandFactory.listSessions(scope, 50, 0, ''), - INTERACTIVE_DIRECTORY_TIMEOUT_MS - ); - const sessions = stampRemoteSessionsWorkspace(RemoteResponseMapper.sessions(response.sessions || []), scope); - return stampRemoteSessionsDevice(sessions, deviceId); - } - - /** Rejects an ID-carrying listing to a device that never advertised ID references. */ - private async requireWorkspaceIdReferences(deviceId: string): Promise { - let capabilities = this.deviceCapabilities.get(deviceId); - if (capabilities === undefined) { - const response = await this.transport(deviceId).send( - RemoteCommandFactory.getWorkspaceInfo(), - INTERACTIVE_DIRECTORY_TIMEOUT_MS - ); - capabilities = (response.capabilities || []).slice(); - this.deviceCapabilities.set(deviceId, capabilities); - } - if (capabilities.indexOf(REMOTE_CAPABILITY_WORKSPACE_ID_REFERENCES_V1) < 0) { - throw new Error(RemoteI18n.t('errors.workspaceIdUnsupported')); - } - } - - private transport(deviceId: string): AccountDeviceCommandTransport { - return new AccountDeviceCommandTransport( - this.context.client, - this.context.relayUrl, - this.context.session, - deviceId - ); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceLink.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceLink.ets deleted file mode 100644 index 7030e12841..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceLink.ets +++ /dev/null @@ -1,104 +0,0 @@ -/** Hosted Relay service version announced by the official endpoint. */ -export const RELAY_SERVICE_VERSION: string = '1.0.10'; - -const OFFICIAL_RELAY_ORIGIN: string = 'https://remote.openbitfun.com'; - -/** Paths served by the same deployed Relay and the same account database. - * `?v=` replaced the path segment as the client-facing version, but `/v/1.0.2` - * stays live for builds that predate the change: a token, master key, or device - * registration obtained through either path is interchangeable, because both - * reach one process and one database. Any other `/v/` path is a - * different deployment. */ -const LIVE_RELAY_ENDPOINT_PATHS: string[] = ['/relay', '/v/1.0.2']; - -const VERSION_PATTERN: RegExp = /^[A-Za-z0-9.]{1,32}$/; - -/** Identity of the official Relay: no version query, no fragment, no trailing - * slash. Every path join and every deployment comparison uses this value. */ -export const OFFICIAL_RELAY_URL: string = `${OFFICIAL_RELAY_ORIGIN}/relay`; - -/** The same deployment as a user sees and shares it: the service version - * travels as a GET parameter instead of a path segment, so a release no longer - * needs a proxy location of its own. */ -export const OFFICIAL_RELAY_ENDPOINT: string = `${OFFICIAL_RELAY_URL}?v=${RELAY_SERVICE_VERSION}`; - -export interface AccountDeviceLink { relayUrl: string; deviceId: string; } - -/** Strip the version parameter and any trailing slash, or explain why not. - * Exactly one `v=` parameter is accepted; every other query parameter - * is rejected so the query can never carry per-request data, and a fragment - * means the value is a page rather than an endpoint. */ -function endpointBase(value: string): string | undefined { - const text = value.trim(); - if (text === '' || text.indexOf('#') >= 0) return undefined; - const mark = text.indexOf('?'); - const base = (mark >= 0 ? text.substring(0, mark) : text).replace(/\/+$/, ''); - if (mark >= 0) { - const pairs = text.substring(mark + 1).split('&'); - if (pairs.length !== 1 || pairs[0].substring(0, 2) !== 'v=' || - !VERSION_PATTERN.test(pairs[0].substring(2))) return undefined; - } - return base; -} - -function officialPath(value: string): string { - return value.startsWith(OFFICIAL_RELAY_ORIGIN) ? value.substring(OFFICIAL_RELAY_ORIGIN.length) : ''; -} - -export function normalizeAccountRelayUrl(value: string): string { - const base = endpointBase(value); - if (!base) return ''; - // Both live aliases of the official host answer as one deployment, so an - // endpoint stored by an older build still resolves to today's identity. - if (LIVE_RELAY_ENDPOINT_PATHS.indexOf(officialPath(base)) >= 0) return OFFICIAL_RELAY_URL; - const match = /^(https?:\/\/)(localhost|\[[0-9a-fA-F:]+\]|[0-9.]+)(?::([0-9]{1,5}))?$/.exec(base); - if (!match) return ''; - if (match[3] && (Number(match[3]) < 1 || Number(match[3]) > 65535)) return ''; - const host = match[2].toLowerCase(); - const octets = host.split('.').map((part: string): number => Number(part)); - const local = host === 'localhost' || host === '[::1]' || - /^\[(?:f[cd][0-9a-f]{2}|fe[89ab][0-9a-f]):/.test(host) || - (octets.length === 4 && octets.every((part: number): boolean => Number.isInteger(part) && part >= 0 && part <= 255) && - (octets[0] === 10 || octets[0] === 127 || (octets[0] === 192 && octets[1] === 168) || - (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) || (octets[0] === 169 && octets[1] === 254))); - return local ? base : ''; -} - -interface RelayEndpointIdentity { origin: string; path: string; } - -function endpointIdentity(value: string): RelayEndpointIdentity | undefined { - const base = endpointBase(value); - if (!base) return undefined; - const match = /^(https?):\/\/(\[[0-9a-fA-F:]+\]|[^/?#:@]+)(?::([0-9]{1,5}))?([^?#]*)$/.exec(base); - if (!match) return undefined; - const scheme = match[1].toLowerCase(); - const port = match[3] ? Number(match[3]) : (scheme === 'https' ? 443 : 80); - if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined; - return { origin: `${scheme}://${match[2].toLowerCase()}:${port}`, path: match[4] }; -} - -/** Whether two endpoints resolve to the same deployed Relay. - * This is the comparison behind reusing a stored token or master key: both live - * aliases of one host count as one deployment, so a build that moves from - * `/v/1.0.2` to `/relay?v=` keeps its credential, while any other versioned - * path is a different or retired deployment. */ -export function sameRelayDeployment(left: string, right: string): boolean { - const a = endpointIdentity(left); - const b = endpointIdentity(right); - if (!a || !b || a.origin !== b.origin) return false; - return a.path === b.path || - (LIVE_RELAY_ENDPOINT_PATHS.indexOf(a.path) >= 0 && LIVE_RELAY_ENDPOINT_PATHS.indexOf(b.path) >= 0); -} - -/** Endpoint and target are hints; the account directory is the authority. */ -export function accountDeviceLink(value: string): AccountDeviceLink | undefined { - const text = value.trim(); - if (text.length > 8192) return undefined; - const parts = text.split('/#/pair?did='); - if (parts.length !== 2) return undefined; - const relayUrl = normalizeAccountRelayUrl(parts[0]); - let deviceId = ''; - try { deviceId = decodeURIComponent(parts[1]); } catch (_error) { return undefined; } - if (!relayUrl || !/^[A-Za-z0-9_.-]{1,128}$/.test(deviceId) || deviceId === '.' || deviceId === '..') return undefined; - return { relayUrl, deviceId }; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountRealtime.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountRealtime.ets deleted file mode 100644 index 81bd07f8ee..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountRealtime.ets +++ /dev/null @@ -1,232 +0,0 @@ -import { webSocket } from '@kit.NetworkKit'; -import { RpcPayload } from './RpcPayload'; -import { EncryptedPayload } from '../model/RemoteModels'; -import { normalizeAccountRelayUrl } from './AccountDeviceLink'; -import { CLIENT_PROTOCOL_VERSION, clientVersion } from './ClientBuild'; - -interface EphemeralKind { type?: string; } -interface EngineOpen { sid: string; pingInterval: number; pingTimeout: number; } -interface Auth { token: string; clientType: string; clientVersion: string; clientProtocol: number; } -interface RpcCall { method: string; params: Object; timeoutMs: number; } -interface RpcResult { ok: boolean; result?: Object; error?: string; } -interface PendingCall { - resolve: (value: Object) => void; - reject: (error: Error) => void; - timer: number; -} -interface ReadyWaiter { resolve: () => void; reject: (error: Error) => void; timer: number; } - -/** JSON/base64 profile of Happy's Engine.IO v4 / Socket.IO v5 transport. - * Large content uses HTTP, so binary attachments are not part of this profile. - * The account owner, not pages or pollers, owns heartbeat and reconnection. */ -export class AccountRealtime { - private socket?: webSocket.WebSocket; - private epoch: number = 0; - private connected: boolean = false; - peerEncodings: Set = new Set(); - private closed: boolean = false; - private nextAck: number = 0; - private retryDelay: number = 1000; - private reconnectTimer: number = -1; - private idleTimer: number = -1; - private idleMs: number = 15000; - private opened: boolean = false; - private pending: Map = new Map(); - private waiters: Set = new Set(); - private updateListeners: Set<(event: string, data: Object) => void> = new Set(); - private reconnectListeners: Set<() => void> = new Set(); - private relayUrl: string; - private token: string; - private payloads: RpcPayload; - - constructor(relayUrl: string, token: string) { - const base = normalizeAccountRelayUrl(relayUrl); - if (!base) throw new Error('Invalid Relay URL'); - this.relayUrl = base; - this.token = token; - this.payloads = new RpcPayload(base, token); - this.open(); - } - - onUpdate(listener: (event: string, data: Object) => void): () => void { - this.updateListeners.add(listener); - return () => { this.updateListeners.delete(listener); }; - } - onReconnect(listener: () => void): () => void { - this.reconnectListeners.add(listener); - return () => { this.reconnectListeners.delete(listener); }; - } - - async call(target: string, params: EncryptedPayload, timeoutMs: number, expectedEncodings?: Set): Promise { - if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new Error('Invalid RPC timeout'); - if (this.closed) throw new Error('Relay is closed; request was not submitted'); - await this.ready(); - const socket = this.socket; - const epoch = this.epoch; - if (!socket || !this.connected || this.closed) throw new Error('Relay disconnected; request was not submitted'); - this.assertEncodingCurrent(expectedEncodings); - const wireParams = await this.payloads.uploadIfLarge(params); - if (this.closed || !this.connected || this.epoch !== epoch) throw new Error('Relay connection changed; request was not submitted'); - this.assertEncodingCurrent(expectedEncodings); - const id = this.nextAck++; - const call: RpcCall = { method: `${target}:invoke`, params: wireParams, timeoutMs: timeoutMs }; - const data = `42${id}${JSON.stringify(['rpc-call', call])}`; - const reply = await new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.pending.delete(id); - reject(new Error('RPC acknowledgement timed out; delivery outcome is unknown')); - }, timeoutMs); - this.pending.set(id, { resolve: resolve, reject: reject, timer: timer }); - socket.send(data).then((sent: boolean) => { - if (!sent) this.fail(epoch, false); - }).catch(() => { this.fail(epoch, false); }); - }); - const result = await this.payloads.resolve(reply); - if (this.closed || this.epoch !== epoch) throw new Error('Relay connection changed; delivery outcome is unknown'); - return result as EncryptedPayload; - } - - private assertEncodingCurrent(expected?: Set): void { - if (expected && expected !== this.peerEncodings) { - throw new Error('Relay capabilities changed; request was not submitted'); - } - } - - ready(): Promise { - if (this.closed) return Promise.reject(new Error('Relay is closed')); - if (this.connected) return Promise.resolve(); - return new Promise((resolve, reject) => { - const waiter: ReadyWaiter = { resolve: resolve, reject: reject, timer: -1 }; - waiter.timer = setTimeout(() => { - this.waiters.delete(waiter); - reject(new Error('Relay connection timed out; request was not submitted')); - }, 15000); - this.waiters.add(waiter); - }); - } - - private open(): void { - if (this.closed) return; - const socket = webSocket.createWebSocket(); - const epoch = ++this.epoch; - this.socket = socket; - this.opened = false; - this.idleMs = 15000; - this.armIdle(epoch); - socket.on('message', (error, data: string | ArrayBuffer) => { - if (epoch !== this.epoch || this.closed) return; - if (error || typeof data !== 'string' || data.length > 256 * 1024) { this.fail(epoch, false); return; } - try { this.receive(socket, epoch, data); } catch (_) { this.fail(epoch, false); } - }); - socket.on('close', () => { this.fail(epoch, false); }); - socket.on('error', () => { this.fail(epoch, false); }); - const url = this.relayUrl.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:'); - socket.connect(`${url}/v1/updates/?EIO=4&transport=websocket`) - .then((success: boolean) => { if (!success) this.fail(epoch, false); }) - .catch(() => { this.fail(epoch, false); }); - } - - private write(socket: webSocket.WebSocket, epoch: number, frame: string): void { - socket.send(frame).then((sent: boolean) => { if (!sent) this.fail(epoch, false); }) - .catch(() => { this.fail(epoch, false); }); - } - - private receive(socket: webSocket.WebSocket, epoch: number, frame: string): void { - this.armIdle(epoch); - if (frame.startsWith('0')) { - if (this.opened) throw new Error('Duplicate Engine.IO handshake'); - const open = JSON.parse(frame.substring(1)) as EngineOpen; - if (!open.sid || !Number.isFinite(open.pingInterval) || !Number.isFinite(open.pingTimeout) - || open.pingInterval <= 0 || open.pingTimeout <= 0) throw new Error('Invalid Engine.IO heartbeat'); - this.opened = true; - this.idleMs = open.pingInterval + open.pingTimeout; - this.armIdle(epoch); - // The Relay reads this build from the handshake, not from the login row, - // when it gates device RPC between two clients. - const auth: Auth = { - token: this.token, clientType: 'user-scoped', - clientVersion: clientVersion(), clientProtocol: CLIENT_PROTOCOL_VERSION - }; - this.write(socket, epoch, `40${JSON.stringify(auth)}`); - } else if (frame.startsWith('2')) { - this.write(socket, epoch, `3${frame.substring(1)}`); - } else if (frame.startsWith('40')) { - if (!this.opened) throw new Error('Missing Engine.IO handshake'); - } else if (frame.startsWith('44')) { - this.fail(epoch, true); - } else if (frame === '1' || frame === '41') { - this.fail(epoch, false); - } else if (frame.startsWith('43')) { - const bracket = frame.indexOf('[', 2); - const ack = frame.substring(2, bracket); - if (bracket < 3 || !/^\d+$/.test(ack)) throw new Error('Invalid Socket.IO acknowledgement'); - const id = Number(ack); - const result = JSON.parse(frame.substring(bracket)) as RpcResult[]; - if (result.length !== 1) throw new Error('Invalid Socket.IO acknowledgement payload'); - const pending = this.pending.get(id); - if (!pending) return; - this.pending.delete(id); - clearTimeout(pending.timer); - if (result[0].ok && result[0].result) pending.resolve(result[0].result!); - else pending.reject(new Error(result[0].error || 'Relay RPC rejected')); - } else if (frame.startsWith('42[')) { - const parts = JSON.parse(frame.substring(2)) as Object[]; - if (parts.length < 2 || typeof parts[0] !== 'string') throw new Error('Invalid Socket.IO event'); - const name = parts[0] as string; - if (name === 'auth-ok') { - this.connected = true; - this.retryDelay = 1000; - this.waiters.forEach((waiter: ReadyWaiter) => { clearTimeout(waiter.timer); waiter.resolve(); }); - this.waiters.clear(); - this.reconnectListeners.forEach((listener: () => void) => { listener(); }); - } - // Relay-stored session updates ('update') are retired; an older relay may - // still emit them and no listener reads their body. Presence and - // encrypted device events (stream hints) arrive as 'ephemeral'. - if (name === 'ephemeral') { - if ((parts[1] as EphemeralKind).type === 'device-presence') this.peerEncodings = new Set(); - this.updateListeners.forEach((listener: (event: string, data: Object) => void) => { listener(name, parts[1]); }); - } - } else { - throw new Error('Unsupported Socket.IO packet'); - } - } - - private armIdle(epoch: number): void { - if (this.idleTimer >= 0) clearTimeout(this.idleTimer); - this.idleTimer = setTimeout(() => { this.fail(epoch, false); }, this.idleMs); - } - - private fail(epoch: number, fatal: boolean): void { - if (epoch !== this.epoch) return; - this.epoch++; - this.connected = false; - this.peerEncodings = new Set(); - if (this.idleTimer >= 0) clearTimeout(this.idleTimer); - const socket = this.socket; - this.socket = undefined; - if (socket) { socket.off('message'); socket.off('close'); socket.off('error'); socket.close().catch(() => {}); } - this.pending.forEach((call: PendingCall) => { - clearTimeout(call.timer); - call.reject(new Error('Relay connection lost; delivery outcome is unknown')); - }); - this.pending.clear(); - if (fatal) this.closed = true; - if (this.closed) { - this.waiters.forEach((waiter: ReadyWaiter) => { clearTimeout(waiter.timer); waiter.reject(new Error('Relay authentication ended')); }); - this.waiters.clear(); - return; - } - this.reconnectTimer = setTimeout(() => { this.open(); }, this.retryDelay * (0.5 + Math.random())); - this.retryDelay = Math.min(5000, this.retryDelay * 2); - } - - close(): void { - if (this.closed) return; - this.closed = true; - this.payloads.close(); - if (this.reconnectTimer >= 0) clearTimeout(this.reconnectTimer); - this.fail(this.epoch, true); - this.updateListeners.clear(); this.reconnectListeners.clear(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AsyncLifecycleGate.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/AsyncLifecycleGate.ets deleted file mode 100644 index ce1daa021a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/AsyncLifecycleGate.ets +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Invalidates asynchronous work when the owning UI lifecycle changes. - * A token is intentionally cheap to copy and can be checked after every await. - */ -export class AsyncLifecycleGate { - private generation: number = 0; - - begin(): number { - this.generation += 1; - return this.generation; - } - - invalidate(): void { - this.generation += 1; - } - - isCurrent(token: number): boolean { - return token === this.generation; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/BuiltinMiniAppHost.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/BuiltinMiniAppHost.ets deleted file mode 100644 index 1f48e527d0..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/BuiltinMiniAppHost.ets +++ /dev/null @@ -1,86 +0,0 @@ -import { util } from '@kit.ArkTS'; -import { fileIo as fs } from '@kit.CoreFileKit'; -import { MiniAppBridgeParams, MiniAppHost, MiniAppSummary } from '../model/MiniAppModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ClipboardService } from './ClipboardService'; - -interface BuiltinMiniAppLocale { name: string; description: string; } -interface BuiltinMiniAppEntry { id: string; locales: Record; } -interface MiniAppFileError { code?: number; } - -/** Only these product-selected bundles may access the local bridge. */ -export const BUILTIN_MINIAPP_IDS: string[] = ['builtin-gomoku', 'builtin-regex-playground', 'builtin-daily-divination']; - -export class BuiltinMiniAppHost implements MiniAppHost { - private readonly context: () => Context; - // Serialize mutations and reads so close/reopen cannot overtake a pending save. - private storageQueue: Promise = Promise.resolve(null); - - constructor(context: () => Context) { this.context = context; } - - private assertApp(appId: string): void { - if (!BUILTIN_MINIAPP_IDS.includes(appId)) throw new Error(RemoteI18n.t('miniapp.unsupported')); - } - - private async resource(name: string): Promise { - const bytes = await this.context().resourceManager.getRawFileContent(`miniapps/${name}`); - return util.TextDecoder.create('utf-8').decodeWithStream(bytes); - } - - async list(locale: string): Promise { - const catalog = JSON.parse(await this.resource('catalog.json')) as BuiltinMiniAppEntry[]; - return catalog.map((entry: BuiltinMiniAppEntry): MiniAppSummary => { - this.assertApp(entry.id); - const copy = entry.locales[locale] || entry.locales['en-US']; - return { id: entry.id, name: copy.name, description: copy.description }; - }); - } - - async document(appId: string): Promise { - this.assertApp(appId); - return this.resource(`${appId}.html`); - } - - async call(appId: string, method: string, params: MiniAppBridgeParams): Promise { - this.assertApp(appId); - if (method === 'clipboard.writeText' && typeof params.text === 'string') { - await new ClipboardService().writeText(params.text); - return null; - } - if ((method !== 'storage.get' && method !== 'storage.set') || typeof params.key !== 'string' || - !this.allowedKey(appId, params.key)) throw new Error(RemoteI18n.t('miniapp.unsupported')); - const operation = this.storageQueue.then((): Promise => this.storage(appId, method, params)); - this.storageQueue = operation.catch((): null => null); - return operation; - } - - private allowedKey(appId: string, key: string): boolean { - return (appId === 'builtin-gomoku' && key === 'stats') || - (appId === 'builtin-regex-playground' && key === 'regex-state') || - (appId === 'builtin-daily-divination' && key === 'lastReading'); - } - - private async storage(appId: string, method: string, params: MiniAppBridgeParams): Promise { - // Stable path across bundle upgrades. Never remove unreadable records. - const directory = `${this.context().filesDir}/miniapps`; - const path = `${directory}/${appId}-${params.key}.json`; - if (method === 'storage.get') { - try { - return JSON.parse(await fs.readText(path)) as Object | null; - } catch (error) { - if ((error as MiniAppFileError).code === 13900002) return null; // ENOENT only - throw new Error(String(error)); - } - } - await fs.mkdir(directory, true); - const file = await fs.open(`${path}.tmp`, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC); - try { - await fs.write(file.fd, JSON.stringify(params.value === undefined ? null : params.value)); - await fs.fsync(file.fd); - } finally { - await fs.close(file); - } - await fs.rename(`${path}.tmp`, path); - return null; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatComposerPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatComposerPolicy.ets deleted file mode 100644 index 6269eb250f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatComposerPolicy.ets +++ /dev/null @@ -1,136 +0,0 @@ -// Each offered action has a live and a dimmed form, and both are worth keeping -// apart from Idle. SendBlocked means the user has written something the link -// cannot carry yet — drawing that as idle would tell them their draft does not -// exist. VoiceBlocked keeps the microphone on screen through a busy moment, so -// the control does not swap glyphs mid-turn and then swap back. Idle is the one -// state with nothing to offer: no dictation on this surface, and no draft. -export enum ComposerPrimaryAction { - Stop = 'stop', - Send = 'send', - SendBlocked = 'send_blocked', - Voice = 'voice', - VoiceBlocked = 'voice_blocked', - Idle = 'idle' -} - -export class ChatComposerPolicy { - static canStop(isTurnRunning: boolean, requiresRemoteConnection: boolean, connectionState: string): boolean { - return isTurnRunning && (!requiresRemoteConnection || connectionState === 'connected'); - } - - static canSend( - text: string, - attachmentCount: number, - isBusy: boolean, - requiresRemoteConnection: boolean, - connectionState: string - ): boolean { - const hasContent = text.trim().length > 0 || attachmentCount > 0; - const remoteAvailable = !requiresRemoteConnection || - connectionState === 'connected'; - return hasContent && !isBusy && remoteAvailable; - } - - static canUseVoice(text: string, attachmentCount: number, isBusy: boolean): boolean { - return text.trim().length === 0 && attachmentCount === 0 && !isBusy; - } - - /** - * Whether the draft earns the supplemental voice slot beside the primary one. - * - * The primary slot belongs to Send as soon as the draft carries anything, but - * dictation is still an input method at that point, so a draft keeps a second - * way into it. That slot is asked for by the expanded action row alone: the - * collapsed field is one line tall and the draft being composed has the - * stronger claim on that room, so `ComposerBar` does not mount it inside the - * field in any state, and a collapsed draft shows the primary action only. - * Keeping the expanded affordance mounted while busy avoids layout movement; - * the component dims it until recording can start again. - */ - static shouldShowSupplementalVoice( - text: string, - attachmentCount: number, - isVoiceListening: boolean, - showVoiceInput: boolean - ): boolean { - return showVoiceInput && !isVoiceListening && - (text.trim().length > 0 || attachmentCount > 0); - } - - static canUseSupplementalVoice(isBusy: boolean): boolean { - return !isBusy; - } - - // Which of the things the one round button on the right is offering. The - // composer has a single primary slot rather than a row of buttons, so "which - // action" is a decision, not a layout detail — and it is the same decision on - // both clients. Dictation and a running turn used to arrive here folded into - // one flag, but they sit on opposite sides of the draft: dictation outranks - // it because the draft is still being spoken, whereas a running turn only - // outranks it where the draft has nowhere to go — on a surface that can hand - // the message over mid-run, keeping the button on Stop traps what was typed. - static primaryAction( - text: string, - attachmentCount: number, - isBusy: boolean, - isVoiceListening: boolean, - isTurnRunning: boolean, - supportsMidRunSend: boolean, - requiresRemoteConnection: boolean, - connectionState: string, - showVoiceInput: boolean - ): ComposerPrimaryAction { - if (isVoiceListening) { - return ComposerPrimaryAction.Stop; - } - if (isTurnRunning && !supportsMidRunSend) { - return ComposerPrimaryAction.Stop; - } - if (text.trim().length > 0 || attachmentCount > 0) { - const sendable = ChatComposerPolicy.canSend( - text, attachmentCount, isBusy, requiresRemoteConnection, connectionState); - return sendable ? ComposerPrimaryAction.Send : ComposerPrimaryAction.SendBlocked; - } - if (isTurnRunning) { - return ComposerPrimaryAction.Stop; - } - if (!showVoiceInput) { - return ComposerPrimaryAction.Idle; - } - const usable = ChatComposerPolicy.canUseVoice(text, attachmentCount, isBusy); - return usable ? ComposerPrimaryAction.Voice : ComposerPrimaryAction.VoiceBlocked; - } - - // Whether the bar is in its tall form, where the field gets its own row and - // the side controls move to a second one. A newline counts even without - // focus: the collapsed field is one line tall, and text the user cannot see - // is text they cannot check before sending. - static isExpanded( - text: string, - inputFocused: boolean, - modelSelectorOpen: boolean, - continuingEditAfterModelSelection: boolean = false - ): boolean { - return inputFocused || modelSelectorOpen || continuingEditAfterModelSelection || text.indexOf('\n') >= 0; - } - - static shouldShowAddButton(showAddButton: boolean, supportsAttachments: boolean): boolean { - return showAddButton && supportsAttachments; - } - - static primaryActionAccessibilityKey( - action: ComposerPrimaryAction, - isVoiceListening: boolean - ): string { - if (action === ComposerPrimaryAction.Stop) { - return isVoiceListening ? 'chat.stopListening' : 'chat.stop'; - } - if (action === ComposerPrimaryAction.Voice || action === ComposerPrimaryAction.VoiceBlocked) { - return 'chat.voiceInput'; - } - if (action === ComposerPrimaryAction.Send || action === ComposerPrimaryAction.SendBlocked) { - return 'chat.send'; - } - return ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets deleted file mode 100644 index 76a7f11824..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets +++ /dev/null @@ -1,249 +0,0 @@ -import { MessageQueueStore } from './MessageQueueStore'; -import { MessageQueueAction, MessageQueueState } from '../model/MessageQueue'; -import { InteractionMailboxStore } from './InteractionMailboxStore'; -import { InteractionMailboxAction, InteractionMailboxState } from '../model/InteractionMailbox'; -import { DurableSessionReducer } from './DurableSessionReducer'; -import { HostSessionStream, HostSessionEvent } from './HostSessionStream'; -import { SubagentBranchCache, SubagentFollowState, SubagentStreamCoordinator } from './SubagentStreamCoordinator'; -import { - ChatMessage, - RemoteModelCatalog -} from '../model/RemoteModels'; -import { RemoteSessionManager } from './RemoteSessionManager'; - -export interface ChatSessionCursor { - pollVersion: number; - knownMessageCount: number; - knownModelCatalogVersion: number; -} - -export interface ChatSessionSnapshot { - sessionId: string; - cursor: ChatSessionCursor; - changed: boolean; - title: string; - sessionState: string; - newMessages: ChatMessage[]; - /** When present, this and activeTurn form a complete authoritative reducer projection. */ - messageSnapshot?: ChatMessage[]; - activeTurn?: ChatMessage; - modelCatalog?: RemoteModelCatalog; - shouldSyncAfterTurnEnded: boolean; - // The desktop now holds fewer messages than this session had counted, so the - // transcript it was handing out tails of is no longer the one on screen. - // Nothing below can resume from an offset into a list that shrank. - historyRewritten: boolean; - /** Exact completed turn whose terminal assistant is now durable. */ - completedTurnId: string; - hasMoreMessages?: boolean; - historyLoading?: boolean; - historyFailed?: boolean; - /** Empty when no valid hint remains; older hosts simply never emit one. */ - promptSuggestion?: string; -} - -export interface ChatSessionControllerCallbacks { - onSnapshot: (snapshot: ChatSessionSnapshot) => void; - onQueue?: (state: MessageQueueState) => void; - onMailbox?: (state: InteractionMailboxState) => void; - onError: (error: Object) => void; - canPoll: (sessionId: string) => boolean; -} - -export interface ChatSessionControllerOptions { - /** Stabilization window before the first idle poll after selecting a session. */ - initialPollDelayMs: number; - /** - * Where a delegation's child transcripts are kept between app launches. - * - * Absent for a host that has no phone transcript cache to write to: the - * branches then live for as long as the session is open, as they always did. - */ - branchCache?: SubagentBranchCache; -} - - -/** Like Happy's normalized message reducer, history and realtime are one - * stable-id collection. No separately timed transcript snapshot is merged in. */ - -export class ChatSessionController { - private sessionManager: RemoteSessionManager; - private callbacks: ChatSessionControllerCallbacks; - private sessionId: string = ''; - private cursor: ChatSessionCursor = { pollVersion: 0, knownMessageCount: 0, knownModelCatalogVersion: 0 }; - private stream?: HostSessionStream; - private reducer: DurableSessionReducer = new DurableSessionReducer(); - private messageQueue: MessageQueueStore; - private mailbox: InteractionMailboxStore; - private subagents: SubagentStreamCoordinator; - private generation: number = 0; - private stopped: boolean = true; - private caughtUp: boolean = false; - private sessionState: string = 'idle'; - private completedTurnId: string = ''; - private hasMoreMessages: boolean = false; - private historyLoading: boolean = false; - private historyReplaying: boolean = false; - private historyFailed: boolean = false; - private modelReadVersion: number = 0; - private pendingModelCatalog?: RemoteModelCatalog; - - constructor(sessionManager: RemoteSessionManager, callbacks: ChatSessionControllerCallbacks, - options?: ChatSessionControllerOptions) { - this.sessionManager = sessionManager; this.callbacks = callbacks; - this.messageQueue = new MessageQueueStore(sessionManager, (state: MessageQueueState): void => { this.callbacks.onQueue?.(state); }, callbacks.canPoll); - this.mailbox = new InteractionMailboxStore(sessionManager, (state: InteractionMailboxState): void => { this.callbacks.onMailbox?.(state); }); - // A delegation tool's child sessions are streams of their own; they are read - // while this session is open and their records land in the branch of the - // item that launched them. - this.subagents = new SubagentStreamCoordinator(sessionManager, - (): void => { this.publishChildBranch(); }, - (error: Error): void => { if (!this.stopped) this.callbacks.onError(error); }, - options?.branchCache); - } - start(sessionId: string, cursor: ChatSessionCursor, _activeTurn?: ChatMessage): void { - if (!this.stopped && this.sessionId === sessionId && this.stream && !this.stream.isClosed()) { - this.stream.wake(); return; - } - this.stop(); this.sessionId = sessionId; this.cursor = cursor; - this.reducer = new DurableSessionReducer(); this.mailbox.select(sessionId); this.messageQueue.select(sessionId); this.stopped = false; this.caughtUp = false; - this.sessionState = 'idle'; this.completedTurnId = ''; this.hasMoreMessages = false; - this.historyLoading = false; this.historyReplaying = false; this.historyFailed = false; - this.pendingModelCatalog = undefined; - this.subagents.beginSession(sessionId); - const epoch = this.generation; - void this.loadInitialModelCatalog(sessionId, epoch); - try { - this.stream = this.sessionManager.subscribeSession(sessionId, { - onEvent: async (event: HostSessionEvent): Promise => { - if (!this.current(epoch) || event.session_id !== sessionId) return; - // Mailbox RPCs are independently coalesced and generation-fenced. They - // must not delay the serial transcript stream or its durable cursor. - if (event.event === 'session-interaction-changed') { void this.mailbox.refresh(); return; } - if (!this.reducer.apply(event)) return; - // The launch of a child agent is a parent record: it is the only place - // the host names the session its process lives in. - this.subagents.observeParentEvent(event); - if (this.caughtUp && !this.historyReplaying) this.publish(); - }, - onResumed: async (): Promise => { if (this.current(epoch)) void this.mailbox.refresh(); }, - onGap: async (): Promise => { - // The desktop restarted the stream: everything reduced so far came - // from its previous epoch and is replayed from the latest page. - if (!this.current(epoch)) return; - this.historyReplaying = true; - this.reducer = new DurableSessionReducer(); this.hasMoreMessages = false; - if (this.caughtUp) this.publish(); - }, - onCaughtUp: async (): Promise => { - if (!this.current(epoch)) return; - this.caughtUp = true; this.historyReplaying = false; this.publish(); - }, - onHistory: (hasMore: boolean): void => { this.hasMoreMessages = hasMore; }, - onHistoryReplay: (active: boolean): void => { - if (this.current(epoch)) this.historyReplaying = active; - }, - onHistoryState: (loading: boolean, failed: boolean): void => { - if (!this.current(epoch)) return; - this.historyLoading = loading; this.historyFailed = failed; - if (this.caughtUp) this.publish(); - }, - onError: (error: Error): void => { if (this.current(epoch)) this.callbacks.onError(error); } - }); - } catch (error) { this.callbacks.onError(error); } - } - async refreshModelCatalog(): Promise { - if (!this.stopped) await this.loadInitialModelCatalog(this.sessionId, this.generation); - } - private async loadInitialModelCatalog(sessionId: string, epoch: number): Promise { - const version = ++this.modelReadVersion; - try { - const catalog = await this.sessionManager.getModelCatalog(sessionId); - if (!this.current(epoch) || version !== this.modelReadVersion) return; - this.pendingModelCatalog = catalog; - if (this.caughtUp && !this.historyReplaying) this.publish(); - } catch (error) { - if (this.current(epoch) && version === this.modelReadVersion) this.callbacks.onError(error); - } - } - stop(_clearActiveTurn: boolean = true): void { - this.generation++; this.stopped = true; this.mailbox.select(''); this.messageQueue.select(''); this.stream?.close(); this.stream = undefined; - this.subagents.endSession(); - } - loadOlder(): void { this.stream?.loadOlder(); } - nudge(): void { this.stream?.wake(); } - updateCursor(cursor: ChatSessionCursor): void { this.cursor = cursor; } - updateKnownModelCatalogVersion(version: number): void { - this.modelReadVersion++; - this.pendingModelCatalog = undefined; - this.cursor.knownModelCatalogVersion = version; - } - setKnownMessageCount(count: number): void { this.cursor.knownMessageCount = count; } - clearActiveTurn(): void { /* Runtime message/state events own turn lifetime. */ } - async dispatchQueue(action: MessageQueueAction): Promise { if (!this.stopped) await this.messageQueue.dispatch(action); } - async dispatchMailbox(action: InteractionMailboxAction): Promise { - if (!this.stopped && action.sessionId === this.sessionId) await this.mailbox.dispatch(action); - } - private current(epoch: number): boolean { return epoch === this.generation && !this.stopped; } - async pollNow(): Promise { this.stream?.wake(); } - /** - * A child branch grew while the parent's own records did not. - * - * The transcript is republished through the same path a parent record takes, - * so an arriving subagent step and an arriving parent record reach the screen - * the same way. It waits for the parent's own page like any other publish: - * while a history replay is landing, the transcript on screen is a partial - * one and every record of it would repaint the conversation. - */ - private publishChildBranch(): void { - if (!this.caughtUp || this.historyReplaying) return; - this.publish(); - } - /** - * Makes sure one delegation's worker is being followed. - * - * The card asks for this when the reader opens it: the branch may have lost - * its stream to the cap, and an open card has to show the worker's own steps. - */ - ensureBranchSubscribed(ownerToolCallId: string): void { - this.subagents.ensureSubscribed(ownerToolCallId); - } - /** How many of this session's children are followed, for previews and focused tests. */ - subagentFollowState(): SubagentFollowState { - return this.subagents.followState(); - } - private publish(): void { - if (this.stopped || !this.callbacks.canPoll(this.sessionId)) return; - const transcript: ChatMessage[] = this.reducer.messages(); - // The transcript names every child this session launched. Reading the names - // out of it is what keeps a delegation's worker reachable when no parent - // record arrives — a phone that just restarted, or an offline host — because - // the cached launch item still carries the child Session id. - this.subagents.observeParentMessages(transcript); - const persisted: ChatMessage[] = []; - let active: ChatMessage | undefined = undefined; - this.completedTurnId = ''; - this.subagents.decorate(transcript).forEach((message: ChatMessage) => { - if (message.role === 'assistant' && (message.status === 'active' || message.status === 'running')) active = message; - else { - persisted.push(message); - if (message.role === 'assistant') { - this.completedTurnId = message.status === 'completed' ? (message.turnId || '') : ''; - } - } - }); - this.cursor.knownMessageCount = persisted.length; - const catalog = this.pendingModelCatalog; - this.pendingModelCatalog = undefined; - if (catalog) this.cursor.knownModelCatalogVersion = catalog.version || 0; - const suggestion = this.reducer.promptSuggestion(); - this.callbacks.onSnapshot({ - sessionId: this.sessionId, cursor: this.cursor, changed: true, title: '', modelCatalog: catalog, - sessionState: active ? 'active' : this.sessionState, newMessages: [], - activeTurn: active, messageSnapshot: persisted, shouldSyncAfterTurnEnded: false, - historyRewritten: false, completedTurnId: this.completedTurnId, hasMoreMessages: this.hasMoreMessages, - historyLoading: this.historyLoading, historyFailed: this.historyFailed, - promptSuggestion: active ? '' : suggestion - }); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineProjector.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineProjector.ets deleted file mode 100644 index ef68dca26d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineProjector.ets +++ /dev/null @@ -1,231 +0,0 @@ -import { ChatMessage, ChatMessageItemResponse } from '../model/RemoteModels'; -import { ChatTimelineItem, ChatTimelineItemType } from '../model/ChatTimelineModels'; - -export { ChatTimelineItem, ChatTimelineItemType, ChatTimelineRevisionTracker } from '../model/ChatTimelineModels'; - -export class ChatTimelineProjector { - /** - * `activeTurnAnchorId` is the id of the optimistic message the running turn - * is answering. Anything sent after that message is queued behind the turn, - * so it belongs below the reply rather than above it — appending the turn - * last would push a mid-run message up under the previous one instead. - */ - static project( - messages: ChatMessage[], - pendingMessages: ChatMessage[], - activeTurn: ChatMessage, - hasMoreMessages: boolean, - activeTurnAnchorId: string = '' - ): ChatTimelineItem[] { - const persistedMessages = ChatTimelineProjector.realMessages(messages); - const shouldRenderActiveTurn = ChatTimelineProjector.shouldRenderActiveTurn(persistedMessages, activeTurn); - // A running turn can be delivered both as an active snapshot and as a - // persisted assistant stub containing only thinking/tools. They represent - // one visual row and share one stable turn key, so retaining both would - // violate the uniqueness contract required by Repeat.virtualScroll(). - const timelineMessages = shouldRenderActiveTurn ? persistedMessages.filter((message: ChatMessage) => { - return !ChatTimelineProjector.isMatchingAssistantTurn(activeTurn, message); - }) : persistedMessages; - const pendingItems = ChatTimelineProjector.pendingMessagesNotPersisted(pendingMessages, timelineMessages); - const anchorIndex = ChatTimelineProjector.anchorIndex(pendingItems, activeTurnAnchorId); - const items: ChatTimelineItem[] = timelineMessages.map((message: ChatMessage) => { - const item: ChatTimelineItem = { - id: `message-${message.id}`, - type: ChatTimelineProjector.messageItemType(message), - message, - isStreaming: false, - isFinalizing: false, - showRetryAction: false - }; - return item; - }); - - // The message that started the turn has usually been persisted by the time - // the reply streams, so no anchor is left to sit behind: whatever is still - // optimistic was sent later and is waiting its turn. - if (shouldRenderActiveTurn && anchorIndex < 0) { - items.push(ChatTimelineProjector.activeTurnItem(activeTurn)); - } - - pendingItems.forEach((message: ChatMessage, index: number) => { - const item: ChatTimelineItem = { - id: `pending-${message.id}`, - type: 'optimistic_user_message', - message, - isStreaming: false, - isFinalizing: false, - showRetryAction: false - }; - items.push(item); - if (shouldRenderActiveTurn && index === anchorIndex) { - items.push(ChatTimelineProjector.activeTurnItem(activeTurn)); - } - }); - - if (items.length === 0 && !hasMoreMessages) { - const item: ChatTimelineItem = { - id: 'empty-state', - type: 'empty_state', - isStreaming: false, - isFinalizing: false, - showRetryAction: false - }; - items.push(item); - } - - ChatTimelineProjector.markLatestFailedMessageRetryable(items); - return items; - } - - private static anchorIndex(pendingItems: ChatMessage[], activeTurnAnchorId: string): number { - if (activeTurnAnchorId.length === 0) { - return -1; - } - for (let index = 0; index < pendingItems.length; index++) { - if (pendingItems[index].id === activeTurnAnchorId) { - return index; - } - } - return -1; - } - - private static activeTurnItem(activeTurn: ChatMessage): ChatTimelineItem { - const turnKey = ChatTimelineProjector.activeTurnKey(activeTurn); - const item: ChatTimelineItem = { - id: `active-${turnKey}`, - type: 'assistant_live_turn', - message: activeTurn, - isStreaming: (activeTurn.status || '').toLowerCase() === 'active', - isFinalizing: (activeTurn.status || '').toLowerCase() === 'completed', - showRetryAction: false - }; - return item; - } - - private static markLatestFailedMessageRetryable(items: ChatTimelineItem[]): void { - for (let index = items.length - 1; index >= 0; index--) { - const message = items[index].message; - if (!message) { - continue; - } - const failed = (message.status || '').toLowerCase() === 'failed'; - items[index].showRetryAction = failed; - if (failed && message.role === 'assistant') { - const retryText = ChatTimelineProjector.nearestUserText(items, index); - if (retryText.length > 0) { - items[index].message = { - id: message.id, - role: message.role, - text: message.text, - status: message.status, - renderVersion: message.renderVersion, - turnId: message.turnId, - detail: retryText, - error: message.error, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: message.items, - images: message.images - }; - } - } - return; - } - } - - private static nearestUserText(items: ChatTimelineItem[], beforeIndex: number): string { - for (let index = beforeIndex - 1; index >= 0; index--) { - const message = items[index].message; - if (message && message.role === 'user' && (message.text || '').trim().length > 0) { - return message.text; - } - } - return ''; - } - - static pendingMessagesNotPersisted(pendingMessages: ChatMessage[], messages: ChatMessage[]): ChatMessage[] { - return pendingMessages.filter((pending: ChatMessage) => { - return !messages.some((message: ChatMessage) => { - return pending.role === 'user' && message.role === 'user' && pending.id === message.id; - }); - }); - } - - private static realMessages(messages: ChatMessage[]): ChatMessage[] { - return messages.filter((message: ChatMessage) => { - return !ChatTimelineProjector.isSeedMessage(message); - }); - } - - private static shouldRenderActiveTurn(messages: ChatMessage[], activeTurn: ChatMessage): boolean { - if (!activeTurn || activeTurn.id.length === 0) { - return false; - } - return !messages.some((message: ChatMessage) => { - return ChatTimelineProjector.isPersistedAssistantDuplicate(activeTurn, message); - }); - } - - private static isSeedMessage(message: ChatMessage): boolean { - return message.id.indexOf('system-') === 0 && message.role === 'assistant'; - } - - private static messageItemType(message: ChatMessage): ChatTimelineItemType { - return message.role === 'user' ? 'user_message' : 'assistant_message'; - } - - private static isPersistedAssistantDuplicate(activeTurn: ChatMessage, message: ChatMessage): boolean { - if (!ChatTimelineProjector.hasDisplayableAssistantFinal(message)) { - return false; - } - return ChatTimelineProjector.isMatchingAssistantTurn(activeTurn, message); - } - - private static isMatchingAssistantTurn(activeTurn: ChatMessage, message: ChatMessage): boolean { - if (message.role !== 'assistant') { - return false; - } - if (message.id === activeTurn.id) { - return true; - } - if (activeTurn.turnId && activeTurn.turnId.length > 0 && message.id === `${activeTurn.turnId}_assistant`) { - return true; - } - return activeTurn.turnId !== undefined && activeTurn.turnId.length > 0 && - message.turnId !== undefined && message.turnId === activeTurn.turnId; - } - - private static hasDisplayableAssistantFinal(message: ChatMessage): boolean { - if ((message.text || '').trim().length > 0 && (message.text || '').trim() !== (message.thinking || '').trim()) { - return true; - } - return ChatTimelineProjector.lastTopLevelText(message.items || []).length > 0; - } - - private static lastTopLevelText(items: ChatMessageItemResponse[]): string { - for (let index = items.length - 1; index >= 0; index--) { - const item = items[index]; - const type = (item.type || '').toLowerCase(); - if ((item.content || '').trim().length > 0 && - !item.tool && - item.is_subagent !== true && - type !== 'thinking' && - type !== 'user-steering' && - type !== 'tool' && - type !== 'subagent' && - type !== 'agent') { - return (item.content || '').trim(); - } - } - return ''; - } - - private static activeTurnKey(activeTurn: ChatMessage): string { - if (activeTurn.turnId && activeTurn.turnId.length > 0) { - return activeTurn.turnId; - } - return activeTurn.id; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineStore.ets deleted file mode 100644 index 2b0034e64a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatTimelineStore.ets +++ /dev/null @@ -1,1051 +0,0 @@ -import { - ChatMessage, - ChatMessageItemResponse, - ImageAttachment, - RemoteModelCatalog, - RemoteToolStatusResponse -} from '../model/RemoteModels'; -import { ChatSessionCursor, ChatSessionSnapshot } from './ChatSessionController'; -import { ChatTimelineItem, ChatTimelineProjector } from './ChatTimelineProjector'; -import { RemoteUiState } from './RemoteUiState'; -import { ConversationEvent } from './ConversationEvent'; - -// Marks the placeholder turn shown between sending a message and hearing back -// which turn the desktop opened for it. Everything after the prefix is a local -// message id, so it must never be mistaken for a server-issued turn id. -export const PENDING_ACTIVE_TURN_ID_PREFIX: string = 'active-pending-'; - -export type ChatSyncPhase = - | 'idle' - | 'loading' - | 'sending' - | 'streaming' - | 'finalizing' - | 'reconnecting' - | 'error'; - -export interface ChatTimelineState { - sessionId: string; - persistedMessages: ChatMessage[]; - optimisticMessages: ChatMessage[]; - activeTurn?: ChatMessage; - syncPhase: ChatSyncPhase; - cursor: ChatSessionCursor; - modelCatalog: RemoteModelCatalog; - selectedModelId: string; -} - -export class ChatTimelineStore { - private state: ChatTimelineState = ChatTimelineStore.emptyState(''); - // The optimistic message the active turn is replying to. Kept out of - // `ChatTimelineState` because nothing but the projection needs it: it exists - // so a message sent mid-run renders below the running reply instead of - // jumping up beside the message that started it. - private activeTurnAnchor: string = ''; - - reset(sessionId: string = ''): void { - this.state = ChatTimelineStore.emptyState(sessionId); - this.activeTurnAnchor = ''; - } - - snapshot(): ChatTimelineState { - return { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages.slice(), - optimisticMessages: this.state.optimisticMessages.slice(), - activeTurn: this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: { - pollVersion: this.state.cursor.pollVersion, - knownMessageCount: this.state.cursor.knownMessageCount, - knownModelCatalogVersion: this.state.cursor.knownModelCatalogVersion - }, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setSyncPhase(syncPhase: ChatSyncPhase): void { - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: this.state.activeTurn, - syncPhase, - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setCursor(cursor: ChatSessionCursor): void { - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: { - pollVersion: cursor.pollVersion, - knownMessageCount: cursor.knownMessageCount, - knownModelCatalogVersion: cursor.knownModelCatalogVersion - }, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setModelCatalog(modelCatalog: RemoteModelCatalog, selectedModelId: string): void { - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: { - pollVersion: this.state.cursor.pollVersion, - knownMessageCount: this.state.cursor.knownMessageCount, - knownModelCatalogVersion: modelCatalog.version || 0 - }, - modelCatalog, - selectedModelId - }; - } - - setSelectedModelId(selectedModelId: string): void { - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId - }; - } - - /** - * Binds the optimistic user bubble to the host turn acknowledged by the - * send response. New hosts preserve the client turn id, while older hosts - * generate a replacement id. Handling both here also closes the race where - * polling publishes the persisted message before the send response arrives. - */ - acknowledgeOptimisticTurn(localMessageId: string, turnId: string): void { - const normalizedLocalId = localMessageId.trim(); - const normalizedTurnId = turnId.trim(); - if (normalizedLocalId.length === 0 || normalizedTurnId.length === 0) { - return; - } - const persistedAlreadyArrived = this.state.persistedMessages.some((message: ChatMessage) => { - return message.role === 'user' && (message.turnId || '').trim() === normalizedTurnId; - }); - const optimisticMessages = persistedAlreadyArrived ? - this.state.optimisticMessages.filter((message: ChatMessage) => message.id !== normalizedLocalId) : - this.state.optimisticMessages.map((message: ChatMessage) => { - if (message.id !== normalizedLocalId) { - return message; - } - return { - id: message.id, - turnId: normalizedTurnId, - role: message.role, - text: message.text, - status: message.status, - renderVersion: message.renderVersion, - detail: message.detail, - error: message.error, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: message.items, - images: message.images - }; - }); - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages, - activeTurn: this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setPersistedMessages(messages: ChatMessage[]): void { - const persistedMessages = ChatTimelineStore.carrySteeringItems( - this.state.activeTurn, - ChatTimelineStore.realMessages(messages) - ); - const previousIds = new Set(); - this.state.persistedMessages.forEach((message: ChatMessage) => previousIds.add(message.id)); - const newlyPersistedMessages = persistedMessages.filter((message: ChatMessage) => !previousIds.has(message.id)); - const activeTurnCovered = this.coveredByPersistedMessage(this.state.activeTurn, persistedMessages) || - this.coveredByNewAssistantContent(this.state.activeTurn, newlyPersistedMessages); - this.state = { - sessionId: this.state.sessionId, - persistedMessages, - optimisticMessages: ChatTimelineStore.optimisticMessagesNotPersisted( - this.state.optimisticMessages, - newlyPersistedMessages - ), - activeTurn: activeTurnCovered ? undefined : this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - mergePersistedMessages(messages: ChatMessage[]): void { - const incomingMessages = ChatTimelineStore.realMessages(messages); - const previousIds = new Set(); - this.state.persistedMessages.forEach((message: ChatMessage) => previousIds.add(message.id)); - // Only this delivery can acknowledge an optimistic message. Replayed - // history with the same text must not consume a message the user just sent. - const newlyPersistedMessages = incomingMessages.filter((message: ChatMessage) => !previousIds.has(message.id)); - const persistedMessages = ChatTimelineStore.carrySteeringItems( - this.state.activeTurn, - RemoteUiState.mergeMessages(this.state.persistedMessages, incomingMessages) - ); - const activeTurnCovered = this.coveredByPersistedMessage(this.state.activeTurn, persistedMessages) || - this.coveredByNewAssistantContent(this.state.activeTurn, newlyPersistedMessages); - this.state = { - sessionId: this.state.sessionId, - persistedMessages, - optimisticMessages: ChatTimelineStore.optimisticMessagesNotPersisted( - this.state.optimisticMessages, - newlyPersistedMessages - ), - activeTurn: activeTurnCovered ? undefined : this.state.activeTurn, - syncPhase: this.state.syncPhase, - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - appendOptimisticMessage(message: ChatMessage): void { - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages.concat([message]), - activeTurn: this.state.activeTurn, - syncPhase: 'sending', - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - appendSteeringItem( - turnId: string, - steeringId: string, - content: string, - images: ImageAttachment[] - ): boolean { - const active = this.state.activeTurn; - if (!active || ChatTimelineStore.cancelableTurnId(active) !== turnId || steeringId.length === 0) { - return false; - } - const items = active.items ? active.items.slice() : []; - const existingIndex = items.findIndex((item: ChatMessageItemResponse) => { - return (item.type || '').toLowerCase() === 'user-steering' && item.steering_id === steeringId; - }); - const steeringItem: ChatMessageItemResponse = { - type: 'user-steering', - steering_id: steeringId, - content, - images: images.slice() - }; - if (existingIndex >= 0) { - items[existingIndex] = steeringItem; - } else { - items.push(steeringItem); - } - this.setActiveTurn({ - id: active.id, - turnId: active.turnId, - role: active.role, - text: active.text, - status: active.status, - detail: active.detail, - error: active.error, - timestamp: active.timestamp, - thinking: active.thinking, - tools: active.tools, - items, - images: active.images, - renderVersion: (active.renderVersion || 0) + 1 - }); - return true; - } - - markOptimisticMessageFailed(messageId: string): void { - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: RemoteUiState.markMessageFailed(this.state.optimisticMessages, messageId), - activeTurn: this.state.activeTurn, - syncPhase: 'error', - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setLocalActiveTurn(turnId: string): void { - const normalizedTurnId = turnId.trim(); - if (normalizedTurnId.length === 0) { - return; - } - const activeId = `active-${normalizedTurnId}`; - if (this.state.activeTurn && this.state.activeTurn.id === activeId) { - const existing = this.state.activeTurn; - const activeTurn: ChatMessage = { - id: existing.id, - turnId: existing.turnId && existing.turnId.length > 0 ? existing.turnId : normalizedTurnId, - role: existing.role, - text: existing.text, - status: existing.status || 'active', - detail: existing.detail, - error: existing.error, - timestamp: existing.timestamp, - thinking: existing.thinking, - tools: existing.tools, - items: existing.items, - images: existing.images - }; - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn, - syncPhase: ChatTimelineStore.phaseForActiveTurn(activeTurn, 'streaming'), - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - return; - } - if (this.state.activeTurn && this.state.activeTurn.id.length > 0 && - this.state.activeTurn.id !== activeId && - !ChatTimelineStore.isLocalPendingActiveTurn(this.state.activeTurn)) { - return; - } - // Promoting the placeholder keeps the message it was opened for; a turn - // that appears without one belongs to the newest thing the user sent. - if (!this.state.activeTurn || !ChatTimelineStore.isLocalPendingActiveTurn(this.state.activeTurn)) { - this.activeTurnAnchor = this.lastOptimisticMessageId(); - } - const activeTurn: ChatMessage = { - id: activeId, - turnId: normalizedTurnId, - role: 'assistant', - text: '', - status: 'active', - detail: '' - }; - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn, - syncPhase: 'streaming', - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setPendingActiveTurn(localId: string): string { - const normalizedLocalId = localId.trim(); - if (normalizedLocalId.length === 0) { - return ''; - } - const activeId = `${PENDING_ACTIVE_TURN_ID_PREFIX}${normalizedLocalId}`; - if (this.state.activeTurn && this.state.activeTurn.id.length > 0 && - this.state.activeTurn.id !== activeId && - !ChatTimelineStore.isLocalPendingActiveTurn(this.state.activeTurn)) { - return ''; - } - this.activeTurnAnchor = normalizedLocalId; - const activeTurn: ChatMessage = { - id: activeId, - role: 'assistant', - text: '', - status: 'active', - detail: '' - }; - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn, - syncPhase: 'streaming', - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - return activeId; - } - - clearPendingActiveTurn(activeId: string): void { - if (!this.state.activeTurn || this.state.activeTurn.id !== activeId || - !ChatTimelineStore.isLocalPendingActiveTurn(this.state.activeTurn)) { - return; - } - this.activeTurnAnchor = ''; - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: undefined, - syncPhase: 'idle', - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - setActiveTurn(activeTurn?: ChatMessage): void { - const normalized = activeTurn && activeTurn.id.length > 0 ? activeTurn : undefined; - const merged = ChatTimelineStore.activeTurnForUpdate(this.state.activeTurn, normalized); - const nextActiveTurn = this.activeTurnForState(merged); - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: nextActiveTurn, - syncPhase: ChatTimelineStore.phaseForActiveTurn(nextActiveTurn, this.state.syncPhase), - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - clearActiveTurn(): void { - this.activeTurnAnchor = ''; - this.state = { - sessionId: this.state.sessionId, - persistedMessages: this.state.persistedMessages, - optimisticMessages: this.state.optimisticMessages, - activeTurn: undefined, - syncPhase: 'idle', - cursor: this.state.cursor, - modelCatalog: this.state.modelCatalog, - selectedModelId: this.state.selectedModelId - }; - } - - applySnapshot(snapshot: ChatSessionSnapshot): void { - this.setCursor(snapshot.cursor); - if (snapshot.messageSnapshot !== undefined) { - // The durable reducer already resolves identity, ordering, revisions and - // tombstones. Replace its complete projection, as the shared mobile - // session store does, rather than merging it as a legacy partial poll. - // Clear before persisted messages too: stale active/steering blocks must - // not be carried into an authoritative completed turn. Pending user - // messages remain separate until a host record acknowledges them. - this.clearActiveTurn(); - this.setPersistedMessages(snapshot.messageSnapshot); - } else if (snapshot.newMessages.length > 0) { - this.mergePersistedMessages(snapshot.newMessages); - } - this.setActiveTurn(snapshot.activeTurn); - if (snapshot.modelCatalog) { - const selected = RemoteUiState.selectedModelIdForCatalog(snapshot.modelCatalog, this.state.selectedModelId); - this.setModelCatalog(snapshot.modelCatalog, selected); - } - } - - /** Applies transport-neutral conversation events from local or remote adapters. */ - applyEvent(event: ConversationEvent): void { - switch (event.type) { - case 'user_message': - if (event.persisted) { - this.mergePersistedMessages([event.message]); - } else { - this.appendOptimisticMessage(event.message); - } - return; - case 'turn_started': - if (this.acceptsSession(event.sessionId)) { - this.setLocalActiveTurn(event.turnId); - } - return; - case 'assistant_delta': - if (!this.acceptsSession(event.sessionId)) { - return; - } - this.appendAssistantDelta(event.turnId, event.delta); - return; - case 'assistant_message': - this.mergePersistedMessages([event.message]); - this.clearActiveTurn(); - return; - case 'active_turn_updated': - if (this.acceptsSession(event.sessionId)) { - this.setActiveTurn(event.message); - } - return; - case 'tool_started': - if (this.acceptsSession(event.sessionId)) { - this.updateActiveTool(event.turnId, event.tool); - } - return; - case 'tool_finished': - if (this.acceptsSession(event.sessionId)) { - this.updateActiveTool(event.turnId, event.tool); - } - return; - case 'turn_finished': - if (event.message) { - this.mergePersistedMessages([event.message]); - this.clearActiveTurn(); - } else if (this.acceptsSession(event.sessionId)) { - const active = this.state.activeTurn; - if (active && active.turnId === event.turnId) { - this.setActiveTurn({ - id: active.id, - turnId: active.turnId, - role: active.role, - text: active.text, - status: 'completed', - detail: active.detail, - error: active.error, - timestamp: active.timestamp, - thinking: active.thinking, - tools: active.tools, - items: active.items, - images: active.images - }); - } - } - return; - case 'session_updated': - if (this.state.sessionId.length === 0 || this.state.sessionId === event.session.sessionId) { - return; - } - return; - case 'error': - this.setSyncPhase('error'); - return; - } - } - - activeTurnOrEmpty(): ChatMessage { - return this.state.activeTurn || RemoteUiState.emptyActiveTurn(); - } - - project(hasMoreMessages: boolean): ChatTimelineItem[] { - return ChatTimelineProjector.project( - this.state.persistedMessages, - this.state.optimisticMessages, - this.activeTurnOrEmpty(), - hasMoreMessages, - this.activeTurnAnchor - ); - } - - /** The optimistic message the running turn answers, or '' once it persisted. */ - activeTurnAnchorId(): string { - return this.activeTurnAnchor; - } - - private lastOptimisticMessageId(): string { - const messages = this.state.optimisticMessages; - return messages.length > 0 ? messages[messages.length - 1].id : ''; - } - - private acceptsSession(sessionId: string): boolean { - return sessionId.length === 0 || this.state.sessionId.length === 0 || this.state.sessionId === sessionId; - } - - private appendAssistantDelta(turnId: string, delta: string): void { - if (delta.length === 0) { - return; - } - if (!this.state.activeTurn || this.state.activeTurn.turnId !== turnId) { - this.setLocalActiveTurn(turnId); - } - const active = this.state.activeTurn; - if (!active) { - return; - } - this.setActiveTurn({ - id: active.id, - turnId: active.turnId, - role: active.role, - text: `${active.text || ''}${delta}`, - status: 'active', - detail: active.detail, - error: active.error, - timestamp: active.timestamp, - thinking: active.thinking, - tools: active.tools, - items: active.items, - images: active.images, - renderVersion: (active.renderVersion || 0) + delta.length - }); - } - - private updateActiveTool(turnId: string, tool: RemoteToolStatusResponse): void { - if (!this.state.activeTurn || this.state.activeTurn.turnId !== turnId) { - this.setLocalActiveTurn(turnId); - } - const active = this.state.activeTurn; - if (!active) { - return; - } - const tools = (active.tools || []).filter((item: RemoteToolStatusResponse) => item.id !== tool.id); - tools.push(tool); - this.setActiveTurn({ - id: active.id, - turnId: active.turnId, - role: active.role, - text: active.text, - status: 'active', - detail: active.detail, - error: active.error, - timestamp: active.timestamp, - thinking: active.thinking, - tools, - items: active.items, - images: active.images, - renderVersion: (active.renderVersion || 0) + 1 - }); - } - - static optimisticMessagesNotPersisted(optimisticMessages: ChatMessage[], persistedMessages: ChatMessage[]): ChatMessage[] { - // Consume acknowledgements one-to-one so two identical queued sends do not - // both disappear when the first persisted message arrives. - const acknowledgedPersistedIndexes = new Set(); - return optimisticMessages.filter((pending: ChatMessage) => { - const acknowledgedIndex = persistedMessages.findIndex((message: ChatMessage, index: number) => { - return !acknowledgedPersistedIndexes.has(index) && - ChatTimelineStore.isPersistedUserDuplicate(pending, message); - }); - if (acknowledgedIndex < 0) { - return true; - } - acknowledgedPersistedIndexes.add(acknowledgedIndex); - return false; - }); - } - - static isActiveTurnCoveredByMessages(activeTurn: ChatMessage, messages: ChatMessage[]): boolean { - if (activeTurn.id.length === 0) { - return true; - } - return messages.some((message: ChatMessage) => { - return ChatTimelineStore.isPersistedAssistantDuplicate(activeTurn, message); - }); - } - - private coveredByPersistedMessage(activeTurn: ChatMessage | undefined, messages: ChatMessage[]): boolean { - if (!activeTurn || activeTurn.id.length === 0) { - return false; - } - return ChatTimelineStore.isActiveTurnCoveredByMessages(activeTurn, messages); - } - - private coveredByNewAssistantContent(activeTurn: ChatMessage | undefined, messages: ChatMessage[]): boolean { - if (!activeTurn || activeTurn.id.length === 0) { - return false; - } - const activeText = (activeTurn.text || '').trim(); - if (activeText.length === 0) { - return false; - } - return messages.some((message: ChatMessage) => { - return message.role === 'assistant' && ChatTimelineStore.hasDisplayableAssistantFinal(message) && - (message.text || '').trim() === activeText; - }); - } - - private activeTurnForState(activeTurn: ChatMessage | undefined): ChatMessage | undefined { - if (activeTurn && activeTurn.id.length > 0) { - return this.coveredByPersistedMessage(activeTurn, this.state.persistedMessages) ? undefined : activeTurn; - } - if (this.state.activeTurn && ChatTimelineStore.shouldHoldCompletedTurn(this.state.activeTurn) && - !this.coveredByPersistedMessage(this.state.activeTurn, this.state.persistedMessages)) { - return this.state.activeTurn; - } - return undefined; - } - - // The turn id to ask the desktop to cancel, or '' for "whatever is running - // now". A placeholder turn carries a local message id rather than a turn id, - // and offering that as one gets the cancel rejected as stale while the task - // keeps going — so the placeholder window has to fall through to no id. - static cancelableTurnId(activeTurn: ChatMessage): string { - if (activeTurn.turnId && activeTurn.turnId.length > 0) { - return activeTurn.turnId; - } - if (activeTurn.id.indexOf(PENDING_ACTIVE_TURN_ID_PREFIX) === 0) { - return ''; - } - return activeTurn.id.indexOf('active-') === 0 ? activeTurn.id.slice('active-'.length) : ''; - } - - private static isLocalPendingActiveTurn(activeTurn: ChatMessage): boolean { - return activeTurn.id.indexOf(PENDING_ACTIVE_TURN_ID_PREFIX) === 0 && - (!activeTurn.turnId || activeTurn.turnId.length === 0); - } - - private static emptyState(sessionId: string): ChatTimelineState { - return { - sessionId, - persistedMessages: [], - optimisticMessages: [], - syncPhase: 'idle', - cursor: { - pollVersion: 0, - knownMessageCount: 0, - knownModelCatalogVersion: 0 - }, - modelCatalog: RemoteUiState.emptyModelCatalog(), - selectedModelId: '' - }; - } - - private static realMessages(messages: ChatMessage[]): ChatMessage[] { - return messages.filter((message: ChatMessage) => { - return !(message.id.indexOf('system-') === 0 && message.role === 'assistant'); - }); - } - - private static carrySteeringItems( - activeTurn: ChatMessage | undefined, - messages: ChatMessage[] - ): ChatMessage[] { - if (!activeTurn || !(activeTurn.items || []).some((item: ChatMessageItemResponse) => - (item.type || '').toLowerCase() === 'user-steering')) { - return messages; - } - const activeTurnId = ChatTimelineStore.cancelableTurnId(activeTurn); - if (activeTurnId.length === 0) { - return messages; - } - return messages.map((message: ChatMessage) => { - if (message.role !== 'assistant' || (message.turnId || '') !== activeTurnId) { - return message; - } - return { - id: message.id, - turnId: message.turnId, - role: message.role, - text: message.text, - status: message.status, - renderVersion: (message.renderVersion || 0) + 1, - detail: message.detail, - error: message.error, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: ChatTimelineStore.mergeActiveItems(activeTurn.items || [], message.items || []), - images: message.images - }; - }); - } - - private static phaseForActiveTurn(activeTurn: ChatMessage | undefined, fallback: ChatSyncPhase): ChatSyncPhase { - if (!activeTurn || activeTurn.id.length === 0) { - return fallback === 'sending' ? 'sending' : 'idle'; - } - const status = (activeTurn.status || '').toLowerCase(); - if (status === 'active') { - return 'streaming'; - } - if (status === 'completed') { - return 'finalizing'; - } - return fallback; - } - - private static activeTurnForUpdate(previous: ChatMessage | undefined, incoming: ChatMessage | undefined): ChatMessage | undefined { - if (!incoming || incoming.id.length === 0) { - return undefined; - } - if (previous && previous.id.length > 0 && ChatTimelineStore.sameActiveTurn(previous, incoming)) { - return ChatTimelineStore.mergeActiveTurn(previous, incoming); - } - return incoming; - } - - private static sameActiveTurn(previous: ChatMessage, incoming: ChatMessage): boolean { - const previousTurnId = previous.turnId || ''; - const incomingTurnId = incoming.turnId || ''; - if (previousTurnId.length > 0 && incomingTurnId.length > 0 && previousTurnId === incomingTurnId) { - return true; - } - return previous.id === incoming.id && - ChatTimelineStore.isActiveTurnId(previous.id) && - ChatTimelineStore.isActiveTurnId(incoming.id); - } - - private static mergeActiveTurn(previous: ChatMessage, incoming: ChatMessage): ChatMessage { - const text = ChatTimelineStore.monotonicText(previous.text || '', incoming.text || ''); - const thinking = ChatTimelineStore.monotonicText(previous.thinking || '', incoming.thinking || ''); - const items = ChatTimelineStore.mergeActiveItems(previous.items || [], incoming.items || []); - const images = incoming.images && incoming.images.length > 0 ? incoming.images : previous.images; - const tools = incoming.tools !== undefined ? incoming.tools : previous.tools; - const activeTurn: ChatMessage = { - id: incoming.id, - turnId: incoming.turnId || previous.turnId, - role: incoming.role || previous.role, - text, - status: incoming.status || previous.status, - detail: incoming.detail, - error: incoming.error || previous.error, - timestamp: incoming.timestamp || previous.timestamp, - thinking: thinking.length > 0 ? thinking : undefined, - tools, - items, - images, - renderVersion: incoming.renderVersion - }; - return activeTurn; - } - - private static mergeActiveItems( - previousItems: ChatMessageItemResponse[], - incomingItems: ChatMessageItemResponse[] - ): ChatMessageItemResponse[] { - if (incomingItems.length === 0) { - return previousItems; - } - // Poll snapshots can temporarily omit an item while the desktop turn is - // being assembled. Keep the existing order and merge tool rows by their - // stable id instead of treating the array index as identity. - const merged = previousItems.slice(); - const matched = new Set(); - incomingItems.forEach((incoming: ChatMessageItemResponse, incomingIndex: number) => { - let matchIndex = -1; - const incomingToolId = incoming.tool ? (incoming.tool.id || '') : ''; - const incomingSteeringId = incoming.steering_id || ''; - if (incomingSteeringId.length > 0) { - matchIndex = previousItems.findIndex((previous: ChatMessageItemResponse, index: number) => { - return !matched.has(index) && previous.steering_id === incomingSteeringId; - }); - } else if (incomingToolId.length > 0) { - matchIndex = previousItems.findIndex((previous: ChatMessageItemResponse, index: number) => { - return !matched.has(index) && previous.tool !== undefined && - (previous.tool.id || '') === incomingToolId; - }); - } else if (incomingIndex < previousItems.length && - !matched.has(incomingIndex) && - ChatTimelineStore.sameActiveItem(previousItems[incomingIndex], incoming)) { - matchIndex = incomingIndex; - } - if (matchIndex >= 0) { - merged[matchIndex] = ChatTimelineStore.mergeActiveItem(previousItems[matchIndex], incoming); - matched.add(matchIndex); - } else { - merged.push(incoming); - } - }); - return merged; - } - - private static mergeActiveItem( - previous: ChatMessageItemResponse, - incoming: ChatMessageItemResponse - ): ChatMessageItemResponse { - const content = ChatTimelineStore.shouldMergeItemContent(previous, incoming) - ? ChatTimelineStore.monotonicText(previous.content || '', incoming.content || '') - : (incoming.content !== undefined ? incoming.content : previous.content); - const subItems = ChatTimelineStore.mergeActiveItems(previous.subItems || [], incoming.subItems || []); - const item: ChatMessageItemResponse = { - type: incoming.type !== undefined ? incoming.type : previous.type, - steering_id: incoming.steering_id !== undefined ? incoming.steering_id : previous.steering_id, - round_index: incoming.round_index !== undefined ? incoming.round_index : previous.round_index, - content, - tool: incoming.tool !== undefined - ? ChatTimelineStore.mergeTool(previous.tool, incoming.tool) - : previous.tool, - is_subagent: incoming.is_subagent !== undefined ? incoming.is_subagent : previous.is_subagent, - subItems, - images: incoming.images !== undefined ? incoming.images : previous.images - }; - return item; - } - - private static sameActiveItem(previous: ChatMessageItemResponse, incoming: ChatMessageItemResponse): boolean { - const previousType = (previous.type || '').toLowerCase(); - const incomingType = (incoming.type || '').toLowerCase(); - if (previousType !== incomingType) { - return false; - } - const previousSteeringId = previous.steering_id || ''; - const incomingSteeringId = incoming.steering_id || ''; - if (previousSteeringId.length > 0 || incomingSteeringId.length > 0) { - return previousSteeringId === incomingSteeringId; - } - const previousToolId = previous.tool ? (previous.tool.id || '') : ''; - const incomingToolId = incoming.tool ? (incoming.tool.id || '') : ''; - if (previousToolId.length > 0 || incomingToolId.length > 0) { - return previousToolId === incomingToolId; - } - return true; - } - - private static shouldMergeItemContent(previous: ChatMessageItemResponse, incoming: ChatMessageItemResponse): boolean { - return ChatTimelineStore.isTextLikeItem(previous) && ChatTimelineStore.isTextLikeItem(incoming); - } - - private static isTextLikeItem(item: ChatMessageItemResponse): boolean { - const type = (item.type || '').toLowerCase(); - return type === 'text' || type === 'message' || type === 'thinking'; - } - - private static monotonicText(previous: string, incoming: string): string { - if (incoming.length === 0) { - return previous; - } - if (incoming.indexOf(previous) === 0) { - return incoming; - } - if (previous.indexOf(incoming) === 0) { - return previous; - } - if (incoming.length > previous.length && previous.length === 0) { - return incoming; - } - return previous; - } - - private static mergeTool( - previous: RemoteToolStatusResponse | undefined, - incoming: RemoteToolStatusResponse | undefined - ): RemoteToolStatusResponse | undefined { - if (!incoming) { - return previous; - } - if (!previous) { - return incoming; - } - const previousStatus = (previous.status || '').toLowerCase(); - const incomingStatus = (incoming.status || '').toLowerCase(); - const rank = (status: string): number => { - if (status === 'pending_confirmation' || status === 'needs_confirmation' || status === 'pending') { - return 1; - } - if (status === 'running' || status === 'active') { - return 2; - } - if (status === 'completed' || status === 'success' || status === 'finished') { - return 3; - } - if (status === 'rejected' || status === 'cancelled' || status === 'canceled' || status === 'error' || status === 'failed') { - return 4; - } - return 0; - }; - // A delayed poll must not move a completed tool back to running/pending. - if (rank(incomingStatus) < rank(previousStatus)) { - return previous; - } - // Completion snapshots from older desktop builds may carry only status and - // result fields. Preserve the invocation metadata already observed while - // the tool was running so Task/subagent titles do not collapse to "Task". - return { - id: incoming.id !== undefined ? incoming.id : previous.id, - permission_request_id: incoming.permission_request_id, - name: incoming.name !== undefined ? incoming.name : previous.name, - status: incoming.status !== undefined ? incoming.status : previous.status, - duration_ms: incoming.duration_ms !== undefined ? incoming.duration_ms : previous.duration_ms, - start_ms: incoming.start_ms !== undefined ? incoming.start_ms : previous.start_ms, - input_preview: (incoming.input_preview || '').length > 0 ? incoming.input_preview : previous.input_preview, - tool_input: incoming.tool_input !== undefined ? incoming.tool_input : previous.tool_input, - stdout: (incoming.stdout || '').length > 0 ? incoming.stdout : previous.stdout, - stderr: (incoming.stderr || '').length > 0 ? incoming.stderr : previous.stderr, - tool_output: incoming.tool_output !== undefined ? incoming.tool_output : previous.tool_output, - result_preview: (incoming.result_preview || '').length > 0 ? incoming.result_preview : previous.result_preview, - error_preview: (incoming.error_preview || '').length > 0 ? incoming.error_preview : previous.error_preview, - exit_code: incoming.exit_code !== undefined ? incoming.exit_code : previous.exit_code, - plan: incoming.plan !== undefined ? incoming.plan : previous.plan - }; - } - - private static isActiveTurnId(id: string): boolean { - return id.indexOf('active-') === 0; - } - - private static isPersistedAssistantDuplicate(activeTurn: ChatMessage, message: ChatMessage): boolean { - if (message.role !== 'assistant') { - return false; - } - if (!ChatTimelineStore.hasDisplayableAssistantFinal(message)) { - return false; - } - if (message.id === activeTurn.id) { - return true; - } - if (activeTurn.turnId && activeTurn.turnId.length > 0 && message.id === `${activeTurn.turnId}_assistant`) { - return true; - } - return activeTurn.turnId !== undefined && activeTurn.turnId.length > 0 && - message.turnId !== undefined && message.turnId === activeTurn.turnId; - } - - private static shouldHoldCompletedTurn(activeTurn: ChatMessage): boolean { - const status = (activeTurn.status || '').toLowerCase(); - return (status === 'completed' || status === 'done' || status === 'success') && - ChatTimelineStore.hasDisplayableAssistantFinal(activeTurn); - } - - private static hasDisplayableAssistantFinal(message: ChatMessage): boolean { - if ((message.text || '').trim().length > 0 && (message.text || '').trim() !== (message.thinking || '').trim()) { - return true; - } - return ChatTimelineStore.lastTopLevelText(message.items || []).length > 0; - } - - private static lastTopLevelText(items: ChatMessageItemResponse[]): string { - for (let index = items.length - 1; index >= 0; index--) { - const item = items[index]; - const type = (item.type || '').toLowerCase(); - if ((item.content || '').trim().length > 0 && - !item.tool && - item.is_subagent !== true && - type !== 'thinking' && - type !== 'user-steering' && - type !== 'tool' && - type !== 'subagent' && - type !== 'agent') { - return (item.content || '').trim(); - } - } - return ''; - } - - private static isPersistedUserDuplicate(pending: ChatMessage, message: ChatMessage): boolean { - if (pending.role !== 'user' || message.role !== 'user') { - return false; - } - if (pending.id === message.id) { - return true; - } - const pendingTurnId = (pending.turnId || '').trim(); - const messageTurnId = (message.turnId || '').trim(); - if (pendingTurnId.length > 0 && messageTurnId.length > 0) { - return pendingTurnId === messageTurnId; - } - const pendingText = (pending.text || '').trim(); - const messageText = (message.text || '').trim(); - if (pendingText.length === 0 || pendingText !== messageText) { - return false; - } - return ChatTimelineStore.imageSignature(pending.images || []) === ChatTimelineStore.imageSignature(message.images || []); - } - - private static imageSignature(images: ImageAttachment[]): string { - return images.map((image: ImageAttachment) => { - return `${image.name || ''}:${image.data_url || ''}`; - }).sort().join('|'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets deleted file mode 100644 index 3107e7162f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClientBuild.ets +++ /dev/null @@ -1,55 +0,0 @@ -import { bundleManager } from '@kit.AbilityKit'; - -/** - * Identity of THIS client build, reported to the Relay at login and on every - * realtime (re)connect so the Relay can gate remote control between devices. - * - * Compatibility is decided by the Relay alone from the two stored protocol - * numbers; clients read the Relay-computed `compatible` flag on the device - * directory instead of re-deriving the rule. The rule the Relay applies is: - * two devices are mutually controllable only when BOTH report a number AND the - * numbers are equal. - * - * Semantics of CLIENT_PROTOCOL_VERSION: - * - * - legacy clients: report nothing (unreported, so the Relay judges them - * incompatible, never "legacy-compatible"); - * - this build: `2`; - * - increment only on a breaking change to the client control contract. - * - * Kept numerically identical to - * `openbitfun_product_domains::account::CLIENT_PROTOCOL_VERSION` in - * `src/crates/contracts/product-domains/src/account.rs` and to the Kotlin - * `CLIENT_PROTOCOL_VERSION` the other mobile clients share; - * `scripts/mobile-client-build.contract.test.mjs` pins them together so - * one side can never drift. - */ -export const CLIENT_PROTOCOL_VERSION: number = 2; - -/** - * Product build string reported next to CLIENT_PROTOCOL_VERSION for - * diagnostics only; the Relay gates control on the protocol number, never on - * this string. Read from this bundle's own manifest (`AppScope/app.json5` - * `versionName`, which release-please bumps with the workspace version) rather - * than kept as a literal here, so it is never hand-maintained. - * - * Resolved lazily so importing this module never touches the bundle manager; - * the unit runner has none. An unreadable manifest reports an empty string, - * which the Relay stores as "no build string" — the protocol number still - * gates as usual. - */ -export function clientVersion(): string { - if (cachedClientVersion === null) cachedClientVersion = readBundleVersion(); - return cachedClientVersion; -} - -let cachedClientVersion: string | null = null; - -function readBundleVersion(): string { - try { - const info = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT); - return (info.versionName || '').trim(); - } catch (_) { - return ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClipboardService.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClipboardService.ets deleted file mode 100644 index e1aa25433f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ClipboardService.ets +++ /dev/null @@ -1,73 +0,0 @@ -import pasteboard from '@ohos.pasteboard'; -import { OhosError } from './OhosError'; - -/** - * One pasteboard record as it will be written: a MIME flavor and its payload. - * - * The list order is the contract, not an implementation detail — the first - * record is the flavor the pasteboard treats as primary, so plain text has to - * come first for receivers that cannot read html. - */ -export interface ClipboardRecordSpec { - mimeType: string; - value: string; -} - -/** - * Rich clipboard payload construction, kept free of the pasteboard kit so the - * record types and their order stay unit-testable on the host runner. - */ -export class ClipboardRichPayload { - static readonly MIMETYPE_TEXT_PLAIN: string = 'text/plain'; - static readonly MIMETYPE_TEXT_HTML: string = 'text/html'; - - /** - * Markdown source as the plain flavor plus its rendered html as a second - * flavor: html-capable receivers paste formatted content, everything else - * pastes the markdown source. - * - * An empty html adds no record at all, which makes that case identical to a - * plain write. An empty plain keeps its primary slot so the html flavor can - * never become the only thing a receiver can read. - */ - static build(plainText: string, html: string): ClipboardRecordSpec[] { - const specs: ClipboardRecordSpec[] = [ - { mimeType: ClipboardRichPayload.MIMETYPE_TEXT_PLAIN, value: plainText }, - ]; - if (html.length > 0) { - specs.push({ mimeType: ClipboardRichPayload.MIMETYPE_TEXT_HTML, value: html }); - } - return specs; - } -} - -export class ClipboardService { - async writeText(text: string): Promise { - try { - const data = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text); - await pasteboard.getSystemPasteboard().setData(data); - } catch (err) { - throw OhosError.wrap('clipboard write', err); - } - } - - /** - * Writes both flavors in one operation: the markdown source as the primary - * plain record and the rendered html as an additional record. Use `writeText` - * for a plain-only copy. - */ - async copyRich(plainText: string, html: string): Promise { - try { - const specs = ClipboardRichPayload.build(plainText, html); - const primary = specs[0]; - const data = pasteboard.createData(primary.mimeType, primary.value); - for (let index = 1; index < specs.length; index += 1) { - const spec = specs[index]; - data.addRecord(pasteboard.createRecord(spec.mimeType, spec.value)); - } - await pasteboard.getSystemPasteboard().setData(data); - } catch (err) { - throw OhosError.wrap('clipboard rich write', 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 deleted file mode 100644 index 3ea6333871..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets +++ /dev/null @@ -1,649 +0,0 @@ -import { RelayMessageEncoding } from './RelayMessageEncoding'; -import { HostSessionStream, HostSessionCallbacks, HostSessionSource, HostStreamHint, HostStreamPage, HostStreamReadRequest, HostStreamHintPlaintext, parseHostStreamHint } from './HostSessionStream'; -import { AccountRealtime } from './AccountRealtime'; -import { CLIENT_PROTOCOL_VERSION, clientVersion } from './ClientBuild'; -import { normalizeAccountRelayUrl, OFFICIAL_RELAY_URL } from './AccountDeviceLink'; -import { http } from '@kit.NetworkKit'; -import { CloudAccountCrypto } from './CloudAccountCrypto'; -import { X25519 } from './X25519'; -import { Encoding } from './Encoding'; -import { HarmonyRemoteCryptoCipher } from './RemoteCrypto'; -import { OhosError } from './OhosError'; -import { RemoteLogger } from './RemoteLogger'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { CommandStatusResponse, EncryptedPayload, RemoteCommand } from '../model/RemoteModels'; - -interface AccountAuthResponse { token: string; user_id: string; } -interface GitHubStart { - transactionId: string; transactionSecret: string; authorizationUrl: string; - expiresAt: number; pollIntervalSeconds: number; -} -interface GitHubPollRequest { transactionId: string; transactionSecret: string; } -interface GitHubTokens { accessToken: string; } -interface GitHubPoll { status: string; tokens?: GitHubTokens; } -interface LoginRequest { - access_token: string; device_id: string; device_name: string; device_kind: string; - public_key: string; request_id: string; - /** See ClientBuild.ets; the Relay stores both and gates on the protocol. */ - clientVersion: string; clientProtocol: number; -} -interface PeerPublicKey { public_key: string; } -interface RelayErrorResponse { error?: string; } -/** `ephemeral` frame the relay forwards for a host's `DeviceEvent`; the body is ciphertext. */ -interface DeviceEventFrame { type?: string; sourceDeviceId?: string; params?: EncryptedPayload; } - -interface NetworkRequestFailure { code?: number; } - -export class CloudAccountTransportError extends Error { - readonly code: number; - constructor(code: number) { - super(`Account transport failed (code=${code}).`); - this.code = code; - } -} - -export class CloudAccountRequestError extends Error { - readonly statusCode: number; - - constructor(message: string, statusCode: number) { - super(message); - this.name = 'CloudAccountRequestError'; - this.statusCode = statusCode; - } -} - -/** - * Whether a failed sign-in poll should be tried again inside the window. - * - * Retry what the next tick could plausibly get past: a transport failure, and - * a relay that is rate limiting or briefly unavailable. Stop for anything the - * relay meant — a rejected transaction stays rejected however long the phone - * keeps asking. - * - * Kept in step with `shared/core-feature/.../AccountStore.kt`, which carries - * the same decision for the Android and iOS clients. - */ -export function retryableAuthorizationPollError(err: Object): boolean { - if (err instanceof CloudAccountTransportError) return true; - if (err instanceof CloudAccountRequestError) { - const status: number = err.statusCode; - return status === 429 || (status >= 500 && status < 600); - } - return false; -} - -export interface CloudAccountSession { - token: string; - userId: string; - masterKey: Uint8Array; -} - -/** The live account client plus the session it is currently signed in with. */ -export interface CloudAccountBinding { - client: CloudAccountClient; - relayUrl: string; - session: CloudAccountSession; -} - -export interface CloudAccountDevice { - deviceId: string; - deviceName: string; - deviceAlias?: string | null; - deviceKind?: string; - online: boolean; - lastSeenAt?: number; - /** - * Relay-computed mutual-control compatibility of this device with this one. - * - * `false` means confirmed incompatible: either a client build/protocol - * mismatch or a peer that reported no version information (an older client). - * Absent only on an older Relay that does not gate at all, which must be - * treated as "unknown but usable", never as incompatible. - */ - 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; -} - -/** A device credential minted for another device, never for this one. */ -export interface CloudProvisionedDevice { - token: string; - userId: string; - deviceId: string; - deviceSecret: Uint8Array; -} - -interface ProvisionDeviceRequest { - public_key: string; - device_id: string; - device_name: string; - device_kind: string; - request_id: string; -} - -interface ProvisionDeviceWire { - token: string; - user_id: string; - device_id: string; -} - -interface CloudAccountDeviceWire { - device_id: string; - device_name: string; - device_alias?: string | null; - device_kind?: string; - online: boolean; - last_seen_at?: number; - compatible?: boolean; -} - -/** Default OpenBitFun cloud relay used by the desktop account flow. */ -export const DEFAULT_CLOUD_RELAY_URL: string = OFFICIAL_RELAY_URL; - -/** Device kinds the relay accepts; mirrors `relay-service/src/db.rs::DEVICE_KINDS`. */ -const DEVICE_KIND_DESKTOP: string = 'desktop'; -const DEVICE_KIND_CLI: string = 'cli'; -const DEVICE_KIND_MOBILE: string = 'mobile'; -const DEVICE_KIND_WATCH: string = 'watch'; - -/** - * Device names our own non-desktop builds register under, lowercased. - * - * Only labels we hardcode ourselves belong here: the Android client reports - * `Build.MODEL` (`android/.../DeviceInstall.kt:27`), an arbitrary string that - * guessing at would hide desktops as readily as phones. - * - * Kept in step with `shared/core-transport/.../CloudAccountClient.kt`, which - * carries the same list for the Android and iOS clients. - */ -const KNOWN_NON_DESKTOP_DEVICE_NAMES: string[] = ['harmonyos phone', 'harmonyos watch']; - -/** - * Whether a relay device row is a host, and so controllable from a phone. - * - * A row that reports its kind is taken at its word: a desktop and a CLI host run - * the same control plane, so both are targets, while a phone or a watch is only - * ever a controller. A row without one predates the relay learning about kinds, - * and is judged by two weaker signals: this phone's own row is never a host, and - * neither is one carrying a name our own builds register under. Anything else - * stays visible — hiding a real host would strand the user, while a stale phone - * row disappears the next time that phone logs in against a relay that stores - * kinds. - */ -function isHostDeviceRow(device: CloudAccountDeviceWire, selfDeviceId: string): boolean { - const kind = (device.device_kind || '').trim(); - if (kind.length > 0) { - return kind === DEVICE_KIND_DESKTOP || kind === DEVICE_KIND_CLI; - } - if (selfDeviceId.length > 0 && device.device_id === selfDeviceId) { - return false; - } - const name = (device.device_name || '').trim().toLowerCase(); - return KNOWN_NON_DESKTOP_DEVICE_NAMES.indexOf(name) < 0; -} - -/** Client for the current desktop relay account protocol. */ -interface DeviceKeyPair { privateKey: Uint8Array; publicKey: Uint8Array; } - -export class CloudAccountClient { - private realtime?: AccountRealtime; - private realtimeUrl: string = ''; - private realtimeToken: string = ''; - - private connection(relayUrl: string, token: string): AccountRealtime { - const url = normalizeAccountRelayUrl(relayUrl); - if (!url) throw new Error('Invalid Relay URL'); - if (this.realtime && this.realtimeUrl === url && this.realtimeToken === token) return this.realtime; - this.realtime?.close(); - this.realtimeUrl = url; this.realtimeToken = token; - this.realtime = new AccountRealtime(url, token); - return this.realtime; - } - - closeAccount(): void { - this.realtime?.close(); this.realtime = undefined; - this.realtimeUrl = ''; this.realtimeToken = ''; - this.peerKeys.clear(); - } - - /** - * Pairwise message keys by target device, derived from the peer's published - * X25519 key. Stream hints arrive unsolicited, so their key must be at hand; - * a stale entry is dropped when a frame fails to decrypt. - */ - private readonly peerKeys: Map> = new Map(); - - private peerMessageKey(relayUrl: string, session: CloudAccountSession, target: string): Promise { - const cacheKey = `${session.userId}\n${target}`; - const cached = this.peerKeys.get(cacheKey); - if (cached) return cached; - const derived = this.request(relayUrl, - `/api/devices/${encodeURIComponent(target)}/key`, 'GET', undefined, session.token) - .then((peer: PeerPublicKey) => CloudAccountCrypto.deriveDeviceKey(session.masterKey, Encoding.base64ToBytes(peer.public_key))); - this.peerKeys.set(cacheKey, derived); - derived.catch((): void => { this.peerKeys.delete(cacheKey); }); - return derived; - } - - private forgetPeerKey(session: CloudAccountSession, target: string): void { - this.peerKeys.delete(`${session.userId}\n${target}`); - } - - private readonly cipher: HarmonyRemoteCryptoCipher = new HarmonyRemoteCryptoCipher(); - - private authorizationGeneration: number = 0; - private authorizationForeground: boolean = true; - private authorizationForegroundWaiters: Array<() => void> = []; - - cancelAuthorization(): void { - this.authorizationGeneration++; - this.releaseAuthorizationForegroundWaiters(); - } - - /** - * Browser authorization is a foreground interaction. HarmonyOS may suspend - * the page while the external browser is open, so do not start or continue - * relay polling until the page is visible again. - */ - setAuthorizationForeground(value: boolean): void { - if (this.authorizationForeground === value) return; - this.authorizationForeground = value; - this.releaseAuthorizationForegroundWaiters(); - } - - private releaseAuthorizationForegroundWaiters(): void { - const waiters = this.authorizationForegroundWaiters; - this.authorizationForegroundWaiters = []; - waiters.forEach((resolve: () => void): void => resolve()); - } - - private async waitForAuthorizationForeground(generation: number): Promise { - if (generation !== this.authorizationGeneration) return false; - if (this.authorizationForeground) return true; - await new Promise((resolve: () => void): void => { - this.authorizationForegroundWaiters.push(resolve); - }); - return generation === this.authorizationGeneration && this.authorizationForeground; - } - - /** - * Wait for the normal poll interval, but interrupt it when the page is - * backgrounded or foregrounded. A foreground transition therefore performs - * the next poll immediately instead of making the user wait for an old timer. - */ - private async waitForAuthorizationTick(generation: number, delayMs: number): Promise { - if (!await this.waitForAuthorizationForeground(generation)) return false; - let timer: number = -1; - let finish: () => void = (): void => {}; - await new Promise((resolve: () => void): void => { - let settled: boolean = false; - finish = (): void => { - if (settled) return; - settled = true; - if (timer !== -1) clearTimeout(timer); - const index = this.authorizationForegroundWaiters.indexOf(finish); - if (index >= 0) this.authorizationForegroundWaiters.splice(index, 1); - resolve(); - }; - this.authorizationForegroundWaiters.push(finish); - timer = setTimeout(finish, delayMs); - }); - if (generation !== this.authorizationGeneration) return false; - if (!this.authorizationForeground) return this.waitForAuthorizationForeground(generation); - return true; - } - - async login(relayUrl: string, deviceId: string, openAuthorization: (url: string) => Promise, deviceSecret: Uint8Array): Promise { - const generation = ++this.authorizationGeneration; - const startRequest: Record = {}; - const start = await this.post(relayUrl, '/api/auth/github/start?methods=all', startRequest); - if (generation !== this.authorizationGeneration) throw new Error('Sign-in cancelled.'); - if (!start.authorizationUrl.startsWith('https://github.com/login/oauth/authorize?') && !/^https:\/\/auth\.openbitfun\.com\/sign-in#ticket=[A-Za-z0-9_-]+$/.test(start.authorizationUrl)) { - throw new Error('Untrusted account authorization URL.'); - } - const authorizationUrl = start.authorizationUrl.replace( - '/sign-in#', - '/sign-in?returnTo=openbitfun%3A%2F%2Fauth%2Fcallback#' - ); - if (!await openAuthorization(authorizationUrl)) throw new Error('Could not open account sign-in.'); - const deadline = Math.min(start.expiresAt * 1000, Date.now() + 600000); - let lastTransient: Error | undefined = undefined; - let firstPoll = true; - while (Date.now() < deadline && generation === this.authorizationGeneration) { - if (!firstPoll) { - // Keep the return-to-app handoff responsive even when the relay's - // conservative interval is large; the next poll is bounded to 2s. - if (!await this.waitForAuthorizationTick( - generation, - Math.min(2, Math.max(1, start.pollIntervalSeconds)) * 1000, - )) break; - } - firstPoll = false; - if (!await this.waitForAuthorizationForeground(generation)) break; - const request: GitHubPollRequest = { transactionId: start.transactionId, transactionSecret: start.transactionSecret }; - let poll: GitHubPoll; - try { - poll = await this.post(relayUrl, '/api/auth/github/poll', request); - } catch (err) { - // The poll window spans the minutes the user spends in a browser and a - // mail app, which is exactly when a phone drops a connection, hops - // networks, or sleeps its radio. Ending the sign-in on the first hiccup - // would send them back to the start for something the next tick fixes - // by itself, so only a refusal the relay actually means stops the loop. - const failure = err as Error; - if (!retryableAuthorizationPollError(failure)) throw failure; - lastTransient = failure; - RemoteLogger.warn('account authorization poll retrying'); - continue; - } - lastTransient = undefined; - if (!await this.waitForAuthorizationForeground(generation)) break; - if (poll.status === 'authorized' && poll.tokens?.accessToken) { - if (deviceSecret.length !== 32) throw new Error('Invalid device identity.'); - const keys: DeviceKeyPair = { privateKey: new Uint8Array(deviceSecret), publicKey: X25519.scalarMultBase(deviceSecret) }; - const body: LoginRequest = { - access_token: poll.tokens.accessToken, device_id: deviceId, device_name: 'HarmonyOS Phone', - device_kind: DEVICE_KIND_MOBILE, public_key: Encoding.bytesToBase64(keys.publicKey), - request_id: Encoding.randomId('').slice(1), - clientVersion: clientVersion(), clientProtocol: CLIENT_PROTOCOL_VERSION - }; - try { - const auth = await this.post(relayUrl, '/api/auth/login', body); - if (generation !== this.authorizationGeneration) throw new Error('Sign-in cancelled.'); - if (!auth.token || !auth.user_id) throw new Error('Invalid account identity.'); - return { token: auth.token, userId: auth.user_id, masterKey: keys.privateKey }; - } catch (err) { - keys.privateKey.fill(0); - throw OhosError.wrap('GitHub sign-in', err); - } - } - if (poll.status === 'expired' || poll.status === 'denied') break; - } - // A window that ran out while every poll was failing is a network problem, - // not a rejected sign-in: report the one the user can act on. - if (lastTransient !== undefined) throw lastTransient; - throw new Error('GitHub sign-in expired or was cancelled.'); - } - - async provisionDevice( - relayUrl: string, - session: CloudAccountSession, - deviceId: string, - deviceName: string, - requestId: string, - deviceSecret?: Uint8Array - ): Promise { - const privateKey = deviceSecret ? Encoding.copyBytes(deviceSecret) : X25519.generateKeyPair().privateKey; - try { - if (privateKey.length !== 32) throw new Error('Invalid watch device identity.'); - const body: ProvisionDeviceRequest = { - public_key: Encoding.bytesToBase64(X25519.scalarMultBase(privateKey)), - device_id: deviceId, - device_name: deviceName, - device_kind: DEVICE_KIND_WATCH, - request_id: requestId - }; - const wire = await this.request( - relayUrl, '/api/auth/provision-device', 'POST', body, session.token); - const token = (wire.token || '').trim(); - const userId = (wire.user_id || '').trim(); - const provisionedDeviceId = (wire.device_id || '').trim(); - if (token.length === 0 || userId !== session.userId || provisionedDeviceId !== deviceId) { - // A credential naming a different account or device would sign the watch - // in as somebody else. Refuse rather than pass it on. - throw new Error('Relay returned a mismatched provisioned device identity.'); - } - return { token, userId, deviceId: provisionedDeviceId, deviceSecret: privateKey }; - } catch (err) { - privateKey.fill(0); - throw err instanceof Error ? err : new Error('Watch credential provisioning failed.'); - } - } - - /** - * The account's controllable devices — desktops only. - * - * A relay that stores device kinds already filters this list; the client - * repeats the judgement so a phone stops listing itself and its peers before - * that relay is deployed. [selfDeviceId] is this install's own device id. - */ - async listDevices( - relayUrl: string, - session: CloudAccountSession, - selfDeviceId: string = '' - ): Promise { - const devices = await this.request(relayUrl, '/api/devices', 'GET', undefined, session.token); - const hosts = devices.filter((device: CloudAccountDeviceWire): boolean => - isHostDeviceRow(device, selfDeviceId)); - 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, - compatible: device.compatible - })); - } - - /** - * [timeoutMs] defaults to the relay's own patience for a device that is slow - * to answer. A caller with a reason to give up earlier — a handshake, where - * silence means the desktop is gone rather than busy — passes its own. - */ - async deviceRpc( - relayUrl: string, - session: CloudAccountSession, - targetDeviceId: string, - command: RemoteCommand, - timeoutMs: number = 130000 - ): Promise { - const target = targetDeviceId.trim(); - if (target.length === 0) { - throw new Error('Remote target device is required.'); - } - const socket = this.connection(relayUrl, session.token); - const messageKey = await this.peerMessageKey(relayUrl, session, target); - const nonce = Encoding.randomBytes(12); - await socket.ready(); - const encodings = socket.peerEncodings; - const plainCommand = Encoding.utf8ToBytes(JSON.stringify(command)); - const encodedCommand = encodings.has(target) && plainCommand.byteLength > 256 - ? await RelayMessageEncoding.encode(plainCommand) : plainCommand; - const encrypted = await this.cipher.encrypt( - encodedCommand, - messageKey, - nonce - ); - const body: EncryptedPayload = { - encrypted_data: Encoding.bytesToBase64(encrypted), - nonce: Encoding.bytesToBase64(nonce), - accept_encoding: 'zstd-1' - }; - RemoteLogger.info(`device rpc cmd=${command.cmd || 'unknown'} bytes=${body.encrypted_data.length}`); - const response = await socket.call(target, body, timeoutMs, encodedCommand[0] === 0xff ? encodings : undefined); - let plain: Uint8Array; - try { - plain = await this.cipher.decrypt( - Encoding.base64ToBytes(response.encrypted_data), - messageKey, - Encoding.base64ToBytes(response.nonce) - ); - } catch (err) { - // The peer may have re-registered with a new key; the next call re-derives. - this.forgetPeerKey(session, target); - throw OhosError.wrap('device rpc decrypt', err); - } - const parsed = Encoding.parseJsonObject(Encoding.bytesToUtf8(await RelayMessageEncoding.decode(plain))); - if (response.accept_encoding === 'zstd-1') encodings.add(target); - else encodings.delete(target); - if (parsed.resp === 'error') { - throw new Error(parsed.message || 'Remote device command failed.'); - } - return parsed; - } - - observePresence(relayUrl: string, session: CloudAccountSession, - onPresence: (ids: string[]) => void, onReconnect: () => void): () => void { - const socket = this.connection(relayUrl, session.token); - const stopUpdate = socket.onUpdate((event: string, data: Object) => { - const presence = data as AccountPresence; - if (event === 'ephemeral' && presence.type === 'device-presence') { - onPresence((presence.devices || []).map((device: AccountPresenceDevice) => device.device_id)); - } - }); - const stopReconnect = socket.onReconnect(onReconnect); - return () => { stopUpdate(); stopReconnect(); }; - } - - /** - * Opens one host-owned stream (a session transcript, a terminal, or the - * catalog) on the desktop [targetId]. Pages travel as pairwise-encrypted - * `read_stream` RPCs and change hints as `host-stream-changed` device - * events, both forwarded by the relay without being stored. Nothing is - * cached on the phone; an offline desktop has no history to show. - */ - subscribeSession(relayUrl: string, session: CloudAccountSession, targetId: string, - streamId: string, callbacks: HostSessionCallbacks): HostSessionStream { - const target = targetId.trim(); - const socket = this.connection(relayUrl, session.token); - const subscriptionId = Encoding.randomId('stream'); - let scopedSubscription = false; - const source: HostSessionSource = { - target: target, - read: async (request: HostStreamReadRequest): Promise => { - if (this.realtime !== socket) throw new Error('Account changed'); - const command: RemoteCommand = { cmd: 'read_stream', stream_id: streamId, subscribe: true, subscription_id: subscriptionId }; - if (request.after !== undefined) command.after = request.after; - if (request.before !== undefined) command.before = request.before; - if (request.epoch !== undefined) command.epoch = request.epoch; - const page = await this.deviceRpc(relayUrl, session, target, command, 30000); - scopedSubscription = page.subscription_id === subscriptionId; - return page; - }, - unsubscribe: async (): Promise => { - if (this.realtime !== socket || !scopedSubscription) return; - await this.deviceRpc(relayUrl, session, target, - { cmd: 'unsubscribe_stream', stream_id: streamId, subscription_id: subscriptionId }, 15000); - }, - onHint: (listener: (hint: HostStreamHint) => void): (() => void) => - this.observeStreamHints(relayUrl, session, target, listener), - onReconnect: (listener: () => void): (() => void) => socket.onReconnect(listener) - }; - return new HostSessionStream(streamId, source, callbacks); - } - - /** Decrypts `device-event` frames from [target] and forwards the stream hints among them. */ - private observeStreamHints(relayUrl: string, session: CloudAccountSession, target: string, - listener: (hint: HostStreamHint) => void): () => void { - const socket = this.connection(relayUrl, session.token); - return socket.onUpdate((event: string, data: Object) => { - const frame = data as DeviceEventFrame; - if (event !== 'ephemeral' || frame.type !== 'device-event') return; - if (frame.sourceDeviceId !== target || !frame.params) return; - void this.decodeStreamHint(relayUrl, session, target, frame.params, socket.peerEncodings).then((hint?: HostStreamHint) => { - if (hint) listener(hint); - }); - }); - } - - private async decodeStreamHint(relayUrl: string, session: CloudAccountSession, target: string, - params: EncryptedPayload, encodings: Set): Promise { - try { - const key = await this.peerMessageKey(relayUrl, session, target); - const plain = await this.cipher.decrypt(Encoding.base64ToBytes(params.encrypted_data), key, - Encoding.base64ToBytes(params.nonce)); - const body = Encoding.parseJsonObject(Encoding.bytesToUtf8(await RelayMessageEncoding.decode(plain))); - if (params.accept_encoding === 'zstd-1') encodings.add(target); - else encodings.delete(target); - return parseHostStreamHint(target, body); - } catch (err) { - // A frame this key cannot open means the peer re-keyed or the frame was - // not for us; the next RPC re-derives, and the hint is only a nudge. - this.forgetPeerKey(session, target); - RemoteLogger.warn(`device event ignored: ${OhosError.reason(err)}`); - return undefined; - } - } - - private async post(relayUrl: string, path: string, body: Object): Promise { - return this.request(relayUrl, path, 'POST', body); - } - - private async request( - relayUrl: string, - path: string, - method: string, - body?: Object, - token: string = '', - readTimeoutMs: number = 120000 - ): Promise { - const request = http.createHttp(); - const base = normalizeAccountRelayUrl(relayUrl); - if (!base) throw new Error('Invalid Relay URL'); - // Timed so the watch has something to be slow relative to. Phone and watch - // reach the same relay and the same desktop, so a gap between them is the - // client's own cost and a shared floor is the round trip's. - const startedAt = Date.now(); - try { - const headers: Record = { 'Content-Type': 'application/json', 'Accept': 'application/json' }; - if (token.length > 0) headers.Authorization = `Bearer ${token}`; - const requestOptions: http.HttpRequestOptions = { - method: method === 'GET' ? http.RequestMethod.GET : method === 'DELETE' ? http.RequestMethod.DELETE : http.RequestMethod.POST, - header: headers, - expectDataType: http.HttpDataType.STRING, - connectTimeout: 15000, - readTimeout: readTimeoutMs - }; - let bodyBytes = 0; - if (body !== undefined) { - const encoded = JSON.stringify(body); - bodyBytes = encoded.length; - requestOptions.extraData = encoded; - } - const response = await request.request(`${base}${path}`, requestOptions); - const text = typeof response.result === 'string' ? response.result : JSON.stringify(response.result); - // `tls` is cumulative from request start: near zero means the connection - // was reused, and anything large is a handshake this call paid for alone. - const timing = response.performanceTiming; - RemoteLogger.info(`relay ${method} ${path} status=${response.responseCode} elapsed_ms=${Date.now() - startedAt}` + - ` dns=${Math.round(timing.dnsTiming)} tcp=${Math.round(timing.tcpTiming)}` + - ` tls=${Math.round(timing.tlsTiming)} ttfb=${Math.round(timing.firstReceiveTiming)}`); - if (response.responseCode < 200 || response.responseCode >= 300) { - // The size belongs in the log: a body the relay refuses for being too - // big is otherwise indistinguishable from one it refuses for auth. - RemoteLogger.error(`relay request failed ${method} ${path} status=${response.responseCode} bytes=${bodyBytes}`); - let message = response.responseCode === 413 ? RemoteI18n.t('errors.payloadTooLarge') : - `Relay request failed (HTTP ${response.responseCode}).`; - try { - const error = JSON.parse(text) as RelayErrorResponse; - if (error.error) message = error.error; - } catch (_err) { - // Keep the status-based error when the relay did not return JSON. - } - throw new CloudAccountRequestError(message, response.responseCode); - } - return JSON.parse(text) as T; - } catch (err) { - const code = (err as NetworkRequestFailure).code; - if (typeof code === 'number') { - RemoteLogger.warn(`relay transport failed method=${method} path=${path} code=${code}`); - throw new CloudAccountTransportError(code); - } - throw OhosError.wrap('relay request', err); - } finally { - request.destroy(); - } - } -} - -interface AccountPresenceDevice { device_id: string; } -interface AccountPresence { type: string; devices?: AccountPresenceDevice[]; } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountCrypto.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountCrypto.ets deleted file mode 100644 index 9830ad4cce..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountCrypto.ets +++ /dev/null @@ -1,27 +0,0 @@ -import { cryptoFramework } from '@kit.CryptoArchitectureKit'; -import { Encoding } from './Encoding'; -import { X25519 } from './X25519'; - -/** Per-device ECDH and the Relay v1.0.0 domain-separated HKDF contract. */ -export class CloudAccountCrypto { - static async deriveDeviceKey(secret: Uint8Array, peerPublicKey: Uint8Array): Promise { - const shared = X25519.scalarMult(secret, peerPublicKey); - if (shared.every((value: number): boolean => value === 0)) { - throw new Error('Invalid peer public key.'); - } - const own = X25519.scalarMultBase(secret); - let ownFirst = true; - for (let i = 0; i < 32; i++) { - if (own[i] !== peerPublicKey[i]) { ownFirst = own[i] < peerPublicKey[i]; break; } - } - const params: cryptoFramework.HKDFSpec = { - algName: 'HKDF', key: shared, - salt: Encoding.utf8ToBytes('OpenBitFun Relay v1.0.0 device key'), - info: ownFirst ? Encoding.concat(own, peerPublicKey) : Encoding.concat(peerPublicKey, own), - keySize: 32 - }; - try { - return (await cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND').generateSecret(params)).data; - } finally { shared.fill(0); } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets deleted file mode 100644 index 98e8cfaef5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountSessionStore.ets +++ /dev/null @@ -1,235 +0,0 @@ -import { GitHubAccountProfile, readCachedGitHubProfile } from './GitHubAccountProfile'; -import { huks } from '@kit.UniversalKeystoreKit'; -import { preferences } from '@kit.ArkData'; -import { Encoding } from './Encoding'; -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; -import { OhosError } from './OhosError'; -import { RemoteLogger } from './RemoteLogger'; - -const STORE_NAME: string = HarmonyUpgradeIdentityContract.CLOUD_ACCOUNT_STORE; -const CIPHER_KEY: string = 'github_device_session_v1_cipher'; -const IV_KEY: string = 'github_device_session_v1_iv'; -const HUKS_ALIAS: string = HarmonyUpgradeIdentityContract.CLOUD_ACCOUNT_HUKS_ALIAS; - -export interface PersistedCloudAccountSession { - relayUrl: string; - username: string; - token: string; - userId: string; - masterKey: string; - targetDeviceId?: string; - targetDeviceName?: string; -} - -export interface PersistedWatchProvisionIdentity { - relayUrl: string; - userId: string; - deviceId: string; - requestId: string; - privateKeyBase64: string; -} - -/** Persists only an HUKS-encrypted account session, never plaintext secrets. */ -export class CloudAccountSessionStore { - private store?: preferences.Preferences; - private deviceKeyWork?: Promise; - - async init(context: Context): Promise { - try { - this.store = await preferences.getPreferences(context, STORE_NAME); - } catch (err) { - throw OhosError.wrap('cloud account session init', err); - } - } - - async deviceSecret(): Promise { - if (!this.deviceKeyWork) this.deviceKeyWork = this.loadOrCreateDeviceSecret(); - try { return new Uint8Array(await this.deviceKeyWork); } - catch (err) { this.deviceKeyWork = undefined; throw OhosError.wrap('device identity', err); } - } - - private async loadOrCreateDeviceSecret(): Promise { - const value = await this.readSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv'); - if (value) { - const secret = Encoding.base64ToBytes(value); - if (secret.length !== 32) throw new Error('Stored device identity is invalid.'); - return secret; - } - const previous = await this.load(); - const secret = previous ? Encoding.base64ToBytes(previous.masterKey) : Encoding.randomBytes(32); - if (secret.length !== 32) throw new Error('Stored device identity is invalid.'); - try { - await this.writeSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv', Encoding.bytesToBase64(secret)); - } catch (err) { - // A reinstall clears Preferences but HarmonyOS may retain the HUKS alias. - // Only rotate the alias when there is no prior session record: existing - // encrypted account data must never be made unreadable as recovery. - if (previous) throw err instanceof Error ? err : new Error(OhosError.reason(err)); - RemoteLogger.warn('cloud account device identity write failed on fresh install; recreating local key'); - await this.recreateKeyForFreshInstall(); - await this.writeSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv', Encoding.bytesToBase64(secret)); - } - return secret; - } - - private async recreateKeyForFreshInstall(): Promise { - try { - await huks.deleteKeyItem(HUKS_ALIAS, {}); - } catch (err) { - const message = OhosError.reason(err); - if (message.indexOf('12000011') < 0 && message.indexOf('-13') < 0 && - message.toLowerCase().indexOf('does not exist') < 0) { - throw err instanceof Error ? err : new Error(OhosError.reason(err)); - } - } - await this.ensureKey(); - } - - async loadProfile(userId: string): Promise { - const text = await this.readSealed(`github_profile_${userId}_v1_cipher`, `github_profile_${userId}_v1_iv`); - return readCachedGitHubProfile(userId, text || ''); - } - - async saveProfile(profile: GitHubAccountProfile): Promise { - await this.writeSealed(`github_profile_${profile.userId}_v1_cipher`, `github_profile_${profile.userId}_v1_iv`, JSON.stringify(profile)); - } - - async save(session: PersistedCloudAccountSession): Promise { - await this.writeSealed(CIPHER_KEY, IV_KEY, JSON.stringify(session)); - } - - async loadWatchProvisionIdentity(relayUrl: string, userId: string, - deviceId: string): Promise { - const key = this.watchProvisionKey(relayUrl, userId, deviceId); - const text = await this.readSealed(`${key}_cipher`, `${key}_iv`); - if (!text) return undefined; - const identity = JSON.parse(text) as PersistedWatchProvisionIdentity; - if (identity.relayUrl !== relayUrl || identity.userId !== userId || identity.deviceId !== deviceId || - !identity.requestId || Encoding.base64ToBytes(identity.privateKeyBase64).length !== 32) { - throw new Error('Stored watch provisioning identity is invalid.'); - } - return identity; - } - - async saveWatchProvisionIdentity(identity: PersistedWatchProvisionIdentity): Promise { - const key = this.watchProvisionKey(identity.relayUrl, identity.userId, identity.deviceId); - await this.writeSealed(`${key}_cipher`, `${key}_iv`, JSON.stringify(identity)); - } - - private watchProvisionKey(relayUrl: string, userId: string, deviceId: string): string { - return `watch_provision_v1_${encodeURIComponent(relayUrl)}_${encodeURIComponent(userId)}_${deviceId}`; - } - - private async writeSealed(cipherKey: string, ivKey: string, plaintext: string): Promise { - try { - const store = this.requireStore(); - await this.ensureKey(); - const iv = Encoding.randomBytes(16); - const options = this.options(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, iv); - const handle = await huks.initSession(HUKS_ALIAS, options); - const encrypted = await huks.finishSession(handle.handle, { - properties: options.properties, - inData: Encoding.utf8ToBytes(plaintext) - }); - if (!encrypted.outData || encrypted.outData.length === 0) { - throw new Error('Cloud account session encryption failed.'); - } - await store.put(cipherKey, Encoding.bytesToBase64(encrypted.outData)); - await store.put(ivKey, Encoding.bytesToBase64(iv)); - await store.flush(); - } catch (err) { - throw OhosError.wrap('cloud account session save', err); - } - } - - async load(): Promise { - const text = await this.readSealed(CIPHER_KEY, IV_KEY); - return text ? JSON.parse(text) as PersistedCloudAccountSession : undefined; - } - - private async readSealed(cipherKey: string, ivKey: string): Promise { - try { - const store = this.requireStore(); - const cipher = await store.get(cipherKey, ''); - const ivText = await store.get(ivKey, ''); - if (typeof cipher !== 'string' || typeof ivText !== 'string' || cipher.length === 0 || ivText.length === 0) { - return undefined; - } - const iv = Encoding.base64ToBytes(ivText); - const options = this.options(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, iv); - const handle = await huks.initSession(HUKS_ALIAS, options); - const decrypted = await huks.finishSession(handle.handle, { - properties: options.properties, - inData: Encoding.base64ToBytes(cipher) - }); - if (!decrypted.outData) { - return undefined; - } - return Encoding.bytesToUtf8(decrypted.outData); - } catch (err) { - throw OhosError.wrap('cloud account session load', err); - } - } - - async clear(): Promise { - try { - const store = this.requireStore(); - await store.delete(CIPHER_KEY); - await store.delete(IV_KEY); - await store.flush(); - } catch (err) { - throw OhosError.wrap('cloud account session clear', err); - } - } - - private async ensureKey(): Promise { - if (await this.keyItemExists()) { - return; - } - try { - await huks.generateKeyItem(HUKS_ALIAS, { - properties: [ - { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES }, - { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }, - { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }, - { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC }, - { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 } - ] - }); - } catch (err) { - throw OhosError.wrap('cloud account session generate key', err); - } - } - - private async keyItemExists(): Promise { - try { - return await huks.isKeyItemExist(HUKS_ALIAS, {}); - } catch (err) { - const message = err instanceof Error ? err.message : JSON.stringify(err); - if (message.indexOf('12000011') >= 0 || message.indexOf('-13') >= 0 || - message.toLowerCase().indexOf('does not exist') >= 0) { - return false; - } - throw new Error(message || 'HUKS key lookup failed.'); - } - } - - private options(purpose: huks.HuksKeyPurpose, iv: Uint8Array): huks.HuksOptions { - return { - properties: [ - { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES }, - { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: purpose }, - { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC }, - { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }, - { tag: huks.HuksTag.HUKS_TAG_IV, value: iv } - ] - }; - } - - private requireStore(): preferences.Preferences { - if (!this.store) { - throw new Error('Cloud account session store is not initialized.'); - } - return this.store; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CodeSyntaxHighlighter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CodeSyntaxHighlighter.ets deleted file mode 100644 index e04aaa1055..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CodeSyntaxHighlighter.ets +++ /dev/null @@ -1,422 +0,0 @@ -export enum CodeSyntaxTokenKind { - Plain = 'plain', - LineNumber = 'line-number', - Keyword = 'keyword', - String = 'string', - Number = 'number', - Comment = 'comment', - Function = 'function', - Type = 'type', - Constant = 'constant', - Property = 'property' -} - -export class CodeSyntaxToken { - readonly id: string; - readonly text: string; - readonly kind: CodeSyntaxTokenKind; - readonly lineNumber: number; - - constructor(id: string, text: string, kind: CodeSyntaxTokenKind, lineNumber: number = 0) { - this.id = id; - this.text = text; - this.kind = kind; - this.lineNumber = lineNumber; - } -} - -export class CodeSyntaxHighlightCache { - private text: string = ''; - private fileName: string = ''; - private tokens: CodeSyntaxToken[] = []; - private initialized: boolean = false; - - tokensFor(text: string, fileName: string): CodeSyntaxToken[] { - if (this.initialized && this.text === text && this.fileName === fileName) { - return this.tokens; - } - this.text = text; - this.fileName = fileName; - this.tokens = CodeSyntaxHighlighter.tokenize(text, fileName); - this.initialized = true; - return this.tokens; - } -} - -const HIGHLIGHT_MAX_CHARACTERS: number = 256 * 1024; -const HIGHLIGHT_MAX_TOKENS: number = 12000; - -/** - * A bounded lexical colorizer for the native preview surface. It deliberately - * avoids building a full syntax tree and falls back to one plain span for - * large inputs so ArkUI does not have to mount thousands of child spans. - */ -export class CodeSyntaxHighlighter { - static tokenize(text: string, fileName: string): CodeSyntaxToken[] { - const extension = CodeSyntaxHighlighter.extension(fileName); - if (!CodeSyntaxHighlighter.supports(extension) || text.length > HIGHLIGHT_MAX_CHARACTERS) { - return CodeSyntaxHighlighter.plain(text); - } - - const tokens: CodeSyntaxToken[] = []; - const lineCount = CodeSyntaxHighlighter.lineCount(text); - const lineNumberWidth = String(lineCount).length; - let lineNumber = 1; - let index = 0; - let tokenIndex = 0; - let needsLineNumber = true; - - while (index < text.length) { - if (needsLineNumber) { - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, - CodeSyntaxHighlighter.linePrefix(lineNumber, lineNumberWidth), - CodeSyntaxTokenKind.LineNumber, - lineNumber - )); - needsLineNumber = false; - } - - const character = text.charAt(index); - if (character === '\n') { - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, '\n', CodeSyntaxTokenKind.Plain, lineNumber - )); - index += 1; - lineNumber += 1; - needsLineNumber = true; - continue; - } - - const lineComment = CodeSyntaxHighlighter.lineCommentAt(text, index, extension); - if (lineComment.length > 0) { - const end = CodeSyntaxHighlighter.lineEnd(text, index); - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, - text.slice(index, end), - CodeSyntaxTokenKind.Comment, - lineNumber - )); - index = end; - continue; - } - - const blockCommentEnd = CodeSyntaxHighlighter.blockCommentEnd(text, index, extension); - if (blockCommentEnd > index) { - const block = text.slice(index, blockCommentEnd); - CodeSyntaxHighlighter.pushMultilineToken( - tokens, - block, - CodeSyntaxTokenKind.Comment, - lineNumberWidth, - lineNumber, - tokenIndex - ); - const consumedLines = CodeSyntaxHighlighter.newlineCount(block); - tokenIndex = tokens.length; - lineNumber += consumedLines; - needsLineNumber = block.endsWith('\n'); - index = blockCommentEnd; - continue; - } - - if (character === '\'' || character === '"' || character === '`') { - const end = CodeSyntaxHighlighter.stringEnd(text, index, character); - const value = text.slice(index, end); - CodeSyntaxHighlighter.pushMultilineToken( - tokens, - value, - CodeSyntaxTokenKind.String, - lineNumberWidth, - lineNumber, - tokenIndex - ); - const consumedLines = CodeSyntaxHighlighter.newlineCount(value); - tokenIndex = tokens.length; - lineNumber += consumedLines; - needsLineNumber = value.endsWith('\n'); - index = end; - continue; - } - - if (CodeSyntaxHighlighter.isDigit(character)) { - const end = CodeSyntaxHighlighter.numberEnd(text, index); - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, - text.slice(index, end), - CodeSyntaxTokenKind.Number, - lineNumber - )); - index = end; - continue; - } - - if (CodeSyntaxHighlighter.isIdentifierStart(character)) { - const end = CodeSyntaxHighlighter.identifierEnd(text, index); - const word = text.slice(index, end); - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, - word, - CodeSyntaxHighlighter.identifierKind(text, end, word, extension), - lineNumber - )); - index = end; - continue; - } - - const end = CodeSyntaxHighlighter.plainEnd(text, index); - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, - text.slice(index, end), - CodeSyntaxTokenKind.Plain, - lineNumber - )); - index = end; - - if (tokens.length > HIGHLIGHT_MAX_TOKENS) { - return CodeSyntaxHighlighter.plain(text); - } - } - - if (text.length === 0 || needsLineNumber) { - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex}`, - CodeSyntaxHighlighter.linePrefix(lineNumber, lineNumberWidth), - CodeSyntaxTokenKind.LineNumber, - lineNumber - )); - } - return tokens; - } - - private static pushMultilineToken( - tokens: CodeSyntaxToken[], - value: string, - kind: CodeSyntaxTokenKind, - lineNumberWidth: number, - firstLineNumber: number, - firstTokenIndex: number - ): void { - const parts = value.split('\n'); - let lineNumber = firstLineNumber; - let tokenIndex = firstTokenIndex; - parts.forEach((part: string, index: number) => { - if (part.length > 0) { - tokens.push(new CodeSyntaxToken(`syntax-${tokenIndex++}`, part, kind, lineNumber)); - } - if (index < parts.length - 1) { - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, '\n', CodeSyntaxTokenKind.Plain, lineNumber - )); - lineNumber += 1; - if (index < parts.length - 2) { - tokens.push(new CodeSyntaxToken( - `syntax-${tokenIndex++}`, - CodeSyntaxHighlighter.linePrefix(lineNumber, lineNumberWidth), - CodeSyntaxTokenKind.LineNumber, - lineNumber - )); - } - } - }); - } - - private static plain(text: string): CodeSyntaxToken[] { - return [new CodeSyntaxToken('syntax-plain', CodeSyntaxHighlighter.numberedText(text), CodeSyntaxTokenKind.Plain)]; - } - - private static numberedText(text: string): string { - const lines = text.split('\n'); - const width = String(lines.length).length; - return lines.map((line: string, index: number): string => { - return `${CodeSyntaxHighlighter.linePrefix(index + 1, width)}${line}`; - }).join('\n'); - } - - private static linePrefix(lineNumber: number, width: number): string { - let value = String(lineNumber); - while (value.length < width) { - value = ` ${value}`; - } - return `${value} `; - } - - private static identifierKind( - text: string, - end: number, - word: string, - extension: string - ): CodeSyntaxTokenKind { - if (CodeSyntaxHighlighter.isKeyword(word, extension)) { - return CodeSyntaxTokenKind.Keyword; - } - if ('|true|false|null|undefined|none|nil|self|this|super|'.indexOf(`|${word.toLowerCase()}|`) >= 0) { - return CodeSyntaxTokenKind.Constant; - } - const next = CodeSyntaxHighlighter.nextNonWhitespace(text, end); - if (next === '(' || next === '!') { - return CodeSyntaxTokenKind.Function; - } - if (next === ':') { - return CodeSyntaxTokenKind.Property; - } - const first = word.charAt(0); - if (first >= 'A' && first <= 'Z') { - return CodeSyntaxTokenKind.Type; - } - return CodeSyntaxTokenKind.Plain; - } - - private static isKeyword(word: string, extension: string): boolean { - const normalized = word.toLowerCase(); - let keywords = '|if|else|for|while|do|switch|case|break|continue|return|throw|try|catch|finally|new|in|of|'; - if ('|js|jsx|ts|tsx|mjs|cjs|ets|vue|svelte|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'const|let|var|function|class|extends|implements|interface|type|enum|import|export|from|as|async|await|yield|default|delete|instanceof|typeof|void|public|private|protected|readonly|static|get|set|declare|namespace|'; - } else if ('|rs|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'fn|let|mut|struct|enum|impl|trait|use|mod|pub|crate|where|match|move|ref|async|await|dyn|unsafe|extern|const|static|type|loop|'; - } else if ('|py|pyw|pyi|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'def|class|import|from|as|lambda|with|async|await|yield|raise|pass|global|nonlocal|assert|del|elif|except|finally|is|not|and|or|'; - } else if ('|go|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'func|package|import|defer|go|select|chan|map|range|struct|interface|type|var|const|fallthrough|'; - } else if ('|java|kt|kts|scala|groovy|c|cpp|cc|cxx|h|hpp|hxx|hh|cs|swift|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'class|struct|interface|enum|namespace|using|import|package|public|private|protected|static|final|virtual|override|abstract|const|var|val|fun|func|operator|template|typename|extends|implements|throws|'; - } else if ('|sh|bash|zsh|fish|ps1|bat|cmd|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'then|fi|elif|done|function|select|until|export|local|readonly|declare|set|unset|'; - } else if ('|sql|'.indexOf(`|${extension}|`) >= 0) { - keywords += 'select|insert|update|delete|create|alter|drop|from|join|inner|left|right|on|where|group|order|by|having|limit|offset|union|all|distinct|into|values|table|index|view|and|or|not|null|'; - } - return keywords.indexOf(`|${normalized}|`) >= 0; - } - - private static lineCommentAt(text: string, index: number, extension: string): string { - if ('|py|pyw|pyi|rb|sh|bash|zsh|fish|yaml|yml|toml|conf|cfg|ini|'.indexOf(`|${extension}|`) >= 0 && - text.charAt(index) === '#') { - return '#'; - } - if (extension === 'sql' && text.slice(index, index + 2) === '--') { - return '--'; - } - if (text.slice(index, index + 2) === '//') { - return '//'; - } - return ''; - } - - private static blockCommentEnd(text: string, index: number, extension: string): number { - if (text.slice(index, index + 4) === '', index + 4); - return htmlEnd >= 0 ? htmlEnd + 3 : text.length; - } - if (extension !== 'py' && text.slice(index, index + 2) === '/*') { - const end = text.indexOf('*/', index + 2); - return end >= 0 ? end + 2 : text.length; - } - return index; - } - - private static stringEnd(text: string, start: number, quote: string): number { - let index = start + 1; - let escaped = false; - while (index < text.length) { - const character = text.charAt(index); - if (escaped) { - escaped = false; - } else if (character === '\\') { - escaped = true; - } else if (character === quote) { - return index + 1; - } else if (character === '\n' && quote !== '`') { - return index; - } - index += 1; - } - return text.length; - } - - private static numberEnd(text: string, start: number): number { - let index = start + 1; - while (index < text.length) { - const character = text.charAt(index); - if (!CodeSyntaxHighlighter.isDigit(character) && character !== '.' && character !== '_' && - character.toLowerCase() !== 'x' && character.toLowerCase() !== 'b' && - !(character.toLowerCase() >= 'a' && character.toLowerCase() <= 'f')) { - break; - } - index += 1; - } - return index; - } - - private static identifierEnd(text: string, start: number): number { - let index = start + 1; - while (index < text.length && CodeSyntaxHighlighter.isIdentifierPart(text.charAt(index))) { - index += 1; - } - return index; - } - - private static plainEnd(text: string, start: number): number { - let index = start + 1; - while (index < text.length) { - const character = text.charAt(index); - if (character === '\n' || character === '\'' || character === '"' || character === '`' || - CodeSyntaxHighlighter.isDigit(character) || CodeSyntaxHighlighter.isIdentifierStart(character) || - text.slice(index, index + 2) === '//' || text.slice(index, index + 2) === '/*' || - text.slice(index, index + 2) === '--' || character === '#') { - break; - } - index += 1; - } - return index; - } - - private static lineEnd(text: string, start: number): number { - const end = text.indexOf('\n', start); - return end >= 0 ? end : text.length; - } - - private static nextNonWhitespace(text: string, start: number): string { - let index = start; - while (index < text.length && (text.charAt(index) === ' ' || text.charAt(index) === '\t')) { - index += 1; - } - return index < text.length ? text.charAt(index) : ''; - } - - private static lineCount(text: string): number { - return CodeSyntaxHighlighter.newlineCount(text) + 1; - } - - private static newlineCount(text: string): number { - let count = 0; - for (let index = 0; index < text.length; index++) { - if (text.charAt(index) === '\n') { - count += 1; - } - } - return count; - } - - private static isDigit(character: string): boolean { - return character >= '0' && character <= '9'; - } - - private static isIdentifierStart(character: string): boolean { - return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || - character === '_' || character === '$'; - } - - private static isIdentifierPart(character: string): boolean { - return CodeSyntaxHighlighter.isIdentifierStart(character) || CodeSyntaxHighlighter.isDigit(character); - } - - private static extension(fileName: string): string { - const normalized = fileName.replace(/\\/g, '/').split('/').pop() || ''; - const dot = normalized.lastIndexOf('.'); - return dot >= 0 ? normalized.slice(dot + 1).toLowerCase() : ''; - } - - private static supports(extension: string): boolean { - return '|js|jsx|ts|tsx|mjs|cjs|ets|vue|svelte|rs|py|pyw|pyi|rb|go|java|kt|kts|scala|groovy|c|cpp|cc|cxx|h|hpp|hxx|hh|cs|swift|php|css|scss|less|json|jsonc|yaml|yml|toml|xml|html|htm|sh|bash|zsh|fish|ps1|bat|cmd|sql|graphql|gql|proto|'.indexOf(`|${extension}|`) >= 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandCatalogProjection.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandCatalogProjection.ets deleted file mode 100644 index b9ea144e39..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandCatalogProjection.ets +++ /dev/null @@ -1,394 +0,0 @@ -import { - RemoteCommandCatalog, - RemoteSkillCatalogEntry, - REMOTE_SKILL_SOURCE_BUILTIN, - REMOTE_SKILL_SOURCE_PROJECT, - REMOTE_SKILL_SOURCE_USER -} from '../model/RemoteModels'; -import { CommandPalettePolicy } from './CommandPalettePolicy'; - -/** - * Turns the host's skill catalog into the rows the picker sheet renders. - * - * Two shapes meet here. The host sends `get_mode_skill_configs` rows — each a - * `SkillInfo` flattened beside its mode availability flags — and the palette - * wants one entry per invocable skill, with the host's own group taxonomy kept - * for ordering and its availability flags kept as filtering truth. - * - * Pure and host-tolerant: a row is dropped only when it has no id, and the two - * sides of the sheet — the built-in catalog and the skills the user authored — - * never merge, so a user skill that reuses a built-in name stays its own row in - * the custom group instead of shadowing the built-in one. - */ - -export const COMMAND_CATALOG_FILTER_ALL: string = 'all'; -export const COMMAND_CATALOG_FILTER_BUILTIN: string = 'builtin'; -export const COMMAND_CATALOG_FILTER_CUSTOM: string = 'custom'; - -/** - * One raw host row. - * - * Everything but the id is optional so a partially instrumented or older host - * still yields entries instead of failing the whole read. Absent flags read as - * `false` — with `allow_user_invocation` the sole exception, whose contract - * default is `true` — so a host that stops serializing the availability flags - * hides nothing it meant to offer, and offers nothing it meant to hold back. - */ -export interface RemoteModeSkillRow { - key?: string; - name?: string; - description?: string; - groupKey?: string; - group_key?: string; - isBuiltin?: boolean; - is_builtin?: boolean; - level?: string; - isShadowed?: boolean; - is_shadowed?: boolean; - allowUserInvocation?: boolean; - allow_user_invocation?: boolean; - selectedForRuntime?: boolean; - selected_for_runtime?: boolean; - effectiveEnabled?: boolean; - effective_enabled?: boolean; - globallyEnabled?: boolean; - globally_enabled?: boolean; -} - -export class SkillCatalogRow { - readonly id: string; - readonly name: string; - readonly description: string; - readonly group: string; - readonly source: string; - readonly isBuiltin: boolean; - /** - * The exact token the message will carry, e.g. `[$Plan]`. - * - * Built from the skill's name rather than its key, because that is the token - * the desktop's own picker inserts; the key stays the row's identity, which is - * what the picker keys on and what the composer compares against. - */ - readonly insertHint: string; - - constructor(entry: RemoteSkillCatalogEntry, isBuiltin: boolean) { - this.id = entry.id; - this.name = entry.name; - this.description = entry.description; - this.group = entry.group; - this.source = entry.source; - this.isBuiltin = isBuiltin; - this.insertHint = CommandPalettePolicy.skillTokenLabel(entry.name); - } -} - -export class SkillCatalogSection { - readonly id: string; - readonly titleKey: string; - readonly count: number; - readonly rows: SkillCatalogRow[]; - - constructor(id: string, titleKey: string, rows: SkillCatalogRow[]) { - this.id = id; - this.titleKey = titleKey; - this.count = rows.length; - this.rows = rows; - } -} - -export class SkillCatalogFilter { - readonly id: string; - readonly labelKey: string; - readonly count: number; - - constructor(id: string, labelKey: string, count: number) { - this.id = id; - this.labelKey = labelKey; - this.count = count; - } -} - -export class SkillCatalogPresentation { - readonly sections: SkillCatalogSection[]; - readonly filters: SkillCatalogFilter[]; - readonly totalCount: number; - readonly builtinCount: number; - readonly customCount: number; - /** Nothing to show at all: the catalog is empty or the host never sent one. */ - readonly isEmpty: boolean; - readonly hasNoMatches: boolean; - - constructor( - sections: SkillCatalogSection[], - filters: SkillCatalogFilter[], - totalCount: number, - builtinCount: number, - customCount: number, - isEmpty: boolean, - hasNoMatches: boolean - ) { - this.sections = sections; - this.filters = filters; - this.totalCount = totalCount; - this.builtinCount = builtinCount; - this.customCount = customCount; - this.isEmpty = isEmpty; - this.hasNoMatches = hasNoMatches; - } -} - -export class CommandCatalogProjection { - static readonly builtinSectionKey: string = 'commands.skills.sectionBuiltin'; - static readonly customSectionKey: string = 'commands.skills.sectionCustom'; - - /** - * The host's raw rows, as palette entries. - * - * This is the whole of the host-shape translation: the id is the skill key — - * the same string the `[$key]` message token carries — and the availability - * flags are copied through so nothing downstream re-reads the payload. Rows - * without an id are dropped; rows repeating an id collapse onto one entry, - * because a row's key is what the picker lists and keys on and two rows with - * the same key would be the same choice offered twice. - */ - static parseHostCatalog(value?: RemoteModeSkillRow[]): RemoteCommandCatalog { - const parsed: RemoteSkillCatalogEntry[] = []; - if (!value || value.length === 0) { - return { skills: parsed }; - } - for (const row of value) { - const id = CommandCatalogProjection.trimmed(row.key); - if (id.length === 0) { - continue; - } - const builtin = CommandCatalogProjection.flag(row.isBuiltin, row.is_builtin); - parsed.push({ - id, - name: CommandCatalogProjection.rowName(row.name, id), - description: CommandCatalogProjection.trimmed(row.description), - // A user-authored skill has no host group of its own; the picker then - // groups it by source, which is the only taxonomy it actually has. - group: CommandCatalogProjection.trimmed(row.groupKey ?? row.group_key), - source: CommandCatalogProjection.source(builtin, row.level), - shadowed: CommandCatalogProjection.flag(row.isShadowed, row.is_shadowed), - selectedForRuntime: CommandCatalogProjection.flag(row.selectedForRuntime, row.selected_for_runtime), - effectiveEnabled: CommandCatalogProjection.flag(row.effectiveEnabled, row.effective_enabled), - globallyEnabled: CommandCatalogProjection.flag(row.globallyEnabled, row.globally_enabled), - allowUserInvocation: CommandCatalogProjection.defaultTrue(row.allowUserInvocation, row.allow_user_invocation) - }); - } - return { skills: CommandCatalogProjection.collapseById(parsed) }; - } - - /** - * One entry per skill key, in the host's own order. - * - * Which duplicate wins is the part worth being careful about: the host lists - * both the winner and the skill it shadows under the same key, so keeping the - * first row could keep the shadowed one and hide the very skill the user can - * actually invoke. A later row therefore replaces an earlier one when it is - * the invocable of the two, and the position stays the first row's. - */ - private static collapseById(entries: RemoteSkillCatalogEntry[]): RemoteSkillCatalogEntry[] { - const order: string[] = []; - const byId: Map = new Map(); - for (const entry of entries) { - const kept = byId.get(entry.id); - if (kept === undefined) { - order.push(entry.id); - byId.set(entry.id, entry); - continue; - } - if (!CommandCatalogProjection.invocable(kept) && CommandCatalogProjection.invocable(entry)) { - byId.set(entry.id, entry); - } - } - const collapsed: RemoteSkillCatalogEntry[] = []; - for (const id of order) { - const entry = byId.get(id); - if (entry !== undefined) { - collapsed.push(entry); - } - } - return collapsed; - } - - /** - * Whether the host offered this skill to the user in the active mode. - * - * Mirrors the desktop composer's own rule: the host's winner for the name, - * enabled for this mode, enabled globally, and allowed to be invoked by hand. - * A shadowed row is a duplicate of the winner and never a second choice. - */ - static invocable(entry: RemoteSkillCatalogEntry): boolean { - return !entry.shadowed && entry.selectedForRuntime && entry.effectiveEnabled && - entry.globallyEnabled && entry.allowUserInvocation; - } - - /** The invocable catalog as rows, in the host's own order. */ - static rows(catalog?: RemoteCommandCatalog): SkillCatalogRow[] { - const skills = catalog?.skills; - if (!skills || skills.length === 0) { - return []; - } - const rows: SkillCatalogRow[] = []; - for (const skill of skills) { - if (!CommandCatalogProjection.invocable(skill)) { - continue; - } - rows.push(new SkillCatalogRow(skill, CommandCatalogProjection.isBuiltin(skill.source))); - } - return rows; - } - - static builtinCount(rows: SkillCatalogRow[]): number { - return rows.filter((row: SkillCatalogRow): boolean => row.isBuiltin).length; - } - - static customCount(rows: SkillCatalogRow[]): number { - return rows.filter((row: SkillCatalogRow): boolean => !row.isBuiltin).length; - } - - static filters(rows: SkillCatalogRow[]): SkillCatalogFilter[] { - return [ - new SkillCatalogFilter(COMMAND_CATALOG_FILTER_ALL, 'commands.skills.filterAll', rows.length), - new SkillCatalogFilter( - COMMAND_CATALOG_FILTER_BUILTIN, 'commands.skills.filterBuiltin', - CommandCatalogProjection.builtinCount(rows)), - new SkillCatalogFilter( - COMMAND_CATALOG_FILTER_CUSTOM, 'commands.skills.filterCustom', - CommandCatalogProjection.customCount(rows)) - ]; - } - - /** - * The sheet's sections for one query and filter. - * - * Built-in skills are grouped and sorted by their group key, which is the - * catalog's own taxonomy; the custom section always comes last so a user skill - * can never be mistaken for a built-in one. - */ - static present(catalog: RemoteCommandCatalog | undefined, query: string, filterId: string): SkillCatalogPresentation { - const rows = CommandCatalogProjection.rows(catalog); - const filters = CommandCatalogProjection.filters(rows); - if (rows.length === 0) { - return new SkillCatalogPresentation([], filters, 0, 0, 0, true, false); - } - const normalizedQuery = query.trim().toLowerCase(); - const matched = rows.filter((row: SkillCatalogRow): boolean => - CommandCatalogProjection.matches(row, normalizedQuery)); - const sections: SkillCatalogSection[] = []; - if (filterId !== COMMAND_CATALOG_FILTER_CUSTOM) { - const builtin = CommandCatalogProjection.sortBuiltin( - matched.filter((row: SkillCatalogRow): boolean => row.isBuiltin)); - if (builtin.length > 0) { - sections.push(new SkillCatalogSection( - COMMAND_CATALOG_FILTER_BUILTIN, - CommandCatalogProjection.builtinSectionKey, - builtin)); - } - } - if (filterId !== COMMAND_CATALOG_FILTER_BUILTIN) { - const custom = CommandCatalogProjection.sortCustom( - matched.filter((row: SkillCatalogRow): boolean => !row.isBuiltin)); - if (custom.length > 0) { - sections.push(new SkillCatalogSection( - COMMAND_CATALOG_FILTER_CUSTOM, - CommandCatalogProjection.customSectionKey, - custom)); - } - } - return new SkillCatalogPresentation( - sections, - filters, - rows.length, - CommandCatalogProjection.builtinCount(rows), - CommandCatalogProjection.customCount(rows), - false, - sections.length === 0); - } - - static matches(row: SkillCatalogRow, normalizedQuery: string): boolean { - if (normalizedQuery.length === 0) { - return true; - } - return row.name.toLowerCase().indexOf(normalizedQuery) >= 0 || - row.id.toLowerCase().indexOf(normalizedQuery) >= 0 || - row.group.toLowerCase().indexOf(normalizedQuery) >= 0 || - row.description.toLowerCase().indexOf(normalizedQuery) >= 0; - } - - static isBuiltin(source?: string): boolean { - return CommandCatalogProjection.trimmed(source).toLowerCase() === REMOTE_SKILL_SOURCE_BUILTIN; - } - - /** - * Which side of the sheet a row belongs to. - * - * The host says whether the row is a built-in; anything else is user-authored, - * and `level` only decides whether it was written for this project or for the - * user's own directory. - */ - private static source(builtin: boolean, level?: string): string { - if (builtin) { - return REMOTE_SKILL_SOURCE_BUILTIN; - } - return CommandCatalogProjection.trimmed(level).toLowerCase() === REMOTE_SKILL_SOURCE_PROJECT ? - REMOTE_SKILL_SOURCE_PROJECT : REMOTE_SKILL_SOURCE_USER; - } - - /** A flag an older host may omit; absent reads as `false`. */ - private static flag(camel?: boolean, snake?: boolean): boolean { - const value = camel ?? snake; - return value === undefined ? false : value; - } - - /** A flag whose host default is `true`: absent must not read as a refusal. */ - private static defaultTrue(camel?: boolean, snake?: boolean): boolean { - const value = camel ?? snake; - return value === undefined ? true : value; - } - - private static sortBuiltin(rows: SkillCatalogRow[]): SkillCatalogRow[] { - return CommandCatalogProjection.sortRows(rows); - } - - /** The custom section sorts on the same keys; only its place in the sheet differs. */ - private static sortCustom(rows: SkillCatalogRow[]): SkillCatalogRow[] { - return CommandCatalogProjection.sortRows(rows); - } - - private static sortRows(rows: SkillCatalogRow[]): SkillCatalogRow[] { - return rows.slice().sort((left: SkillCatalogRow, right: SkillCatalogRow): number => { - const byGroup = CommandCatalogProjection.compare(left.group, right.group); - if (byGroup !== 0) { - return byGroup; - } - const byName = CommandCatalogProjection.compare(left.name, right.name); - return byName !== 0 ? byName : CommandCatalogProjection.compare(left.id, right.id); - }); - } - - private static compare(left: string, right: string): number { - if (left === right) { - return 0; - } - return left < right ? -1 : 1; - } - - /** - * The row's display name, falling back to its key. - * - * The fallback is the same string the token would carry, so a host row that - * never named its skill still yields a pick that can be sent rather than an - * empty `[$]`. - */ - private static rowName(name: string | undefined, fallback: string): string { - const resolved = CommandCatalogProjection.trimmed(name); - return resolved.length > 0 ? resolved : fallback; - } - - private static trimmed(value?: string): string { - return value === undefined ? '' : value.trim(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandPalettePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandPalettePolicy.ets deleted file mode 100644 index dd61a92904..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CommandPalettePolicy.ets +++ /dev/null @@ -1,565 +0,0 @@ -/** - * The composer command palette's rules, kept pure so they can be exercised - * without ArkUI. - * - * Everything here answers one of three questions: which chip may be tapped - * right now, what a tapped chip does to the draft, and what the draft becomes - * when it is sent. The palette never guesses a session, never opens the picker - * before the host has answered the skill read, and never rewrites a draft the - * user owns. - */ - -/** Lifecycle of the catalog read that doubles as the palette's behavior probe. */ -export enum CommandPaletteCatalogStatus { - /** No read yet: the picker's chip waits rather than acts. */ - Idle = 'idle', - /** The read is in flight. */ - Loading = 'loading', - /** The host answered; the picker has rows to offer. */ - Ready = 'ready', - /** The read failed. The chip still opens the picker, which explains and re-checks. */ - Failed = 'failed' -} - -/** - * Why the skill read failed. - * - * The three cases are not interchangeable to the person holding the phone, and - * only one of them justifies telling them their desktop is out of date. A read - * that reached nothing is a connection to fix; a read the host refused without - * naming a version gap is the host saying no; only a host that reports the gap - * itself is an upgrade. - */ -export enum CommandPaletteProbeFailure { - None = '', - /** The host answered, and its own words name the version gap. */ - VersionGap = 'version_gap', - /** The host answered and refused, for a reason it stated itself. */ - Refused = 'refused', - /** Nothing answered: a transport, timeout or unusable-payload failure. */ - Unreachable = 'unreachable' -} - -/** Whether the probe's answer lets the picker offer rows. */ -export function commandPaletteProbeReady(status: string): boolean { - return status === CommandPaletteCatalogStatus.Ready; -} - -/** - * The host's own wording when it does not have a command in this version. - * - * `PeerRefusal::UnknownToHost` is the peer-host registry's sentence, and it is - * the only thing that names a version. The desktop's command registry answers - * `Command not found: ` for a name it does not carry, which is a refusal - * about the command rather than a statement about the build: it keeps the - * refusal copy and leaves the upgrade claim to the sentence that makes it. - */ -const VERSION_GAP_MARKERS: string[] = [ - 'unknown to this openbitfun', - 'peer host version' -]; - -/** - * The bridge's own wording when it never got to a command handler. - * - * `host_invoke` answers `ok: false` for two unrelated events: a command the host - * declined, and the bridge between the relay and the desktop failing to deliver - * it at all (`peer_host_invoke.rs`: the app handle is not up yet, the request - * could not be emitted, the channel closed, or the whole call timed out). The - * second kind is a connection that did not reach a command, so it must not be - * described as the desktop having answered — the refusal copy asserts an answer, - * and the version claim would be pure invention. - */ -const NON_ANSWER_MARKERS: string[] = [ - 'peer host invoke', - 'peer app handle not ready', - 'failed to emit', - 'channel closed', - 'lock poisoned' -]; - -/** The five chips of the composer command row, in their on-screen order. */ -export enum CommandPaletteChipKind { - Compact = 'compact', - Init = 'init', - Goal = 'goal', - Usage = 'usage', - Skills = 'skills' -} - -export enum CommandPaletteChipState { - Ready = 'ready', - /** The goal chip waiting for its argument; drawn filled. */ - Pending = 'pending', - /** The verb this chip starts is in flight; a spinner replaces its icon. */ - InFlight = 'inflight', - /** Greyed. Still tappable, so the row can explain itself. */ - Dimmed = 'dimmed' -} - -/** - * Why a chip is not ready, and therefore what the row says about it. - * - * A chip's own business is the only thing that holds it back. The skill read is - * the picker's business alone, so a failed read no longer greys the row: the - * verbs exist on every host this app can reach, and a host that refuses one says - * so when it is run. - */ -export enum CommandPaletteDegradeReason { - /** The skill read has not answered, or answered with a failure. */ - Probe = 'probe', - /** Another palette verb is still running. */ - Busy = 'busy', - /** No session is open, so there is nothing to act on. */ - Session = 'session', - None = 'none' -} - -export enum CommandPaletteNoticeKind { - Busy = 'busy', - Done = 'done', - Failed = 'failed' -} - -/** What the row is allowed to do, as a snapshot of the live surface. */ -export class CommandPaletteAvailability { - /** The skill read's lifecycle, which gates the picker's chip and nothing else. */ - readonly probeStatus: string; - /** Why the read failed, when it did; the badge and the copy follow from this. */ - readonly probeFailure: string; - readonly hasSession: boolean; - readonly isBusy: boolean; - /** Wire id of the palette verb currently in flight, or '' when idle. */ - readonly runningCommand: string; - /** The goal chip is prefilled and waiting for its argument. */ - readonly goalPending: boolean; - - constructor( - probeStatus: string, - probeFailure: string, - hasSession: boolean, - isBusy: boolean, - runningCommand: string = '', - goalPending: boolean = false - ) { - this.probeStatus = probeStatus; - this.probeFailure = probeFailure; - this.hasSession = hasSession; - this.isBusy = isBusy; - this.runningCommand = runningCommand; - this.goalPending = goalPending; - } - - get probeReady(): boolean { - return commandPaletteProbeReady(this.probeStatus); - } -} - -/** One rendered chip: its label, its state, and what a tap does. */ -export class CommandPaletteChip { - readonly kind: CommandPaletteChipKind; - readonly state: CommandPaletteChipState; - readonly labelKey: string; - /** Badge shown on the chip's corner, empty when the chip has none. */ - readonly badgeKey: string; - readonly showsChevron: boolean; - /** Empty unless the chip has something to explain. */ - readonly reasonKey: string; - /** False while a tap must not reach the host; the reason line still shows. */ - readonly runsAction: boolean; - - constructor( - kind: CommandPaletteChipKind, - state: CommandPaletteChipState, - labelKey: string, - badgeKey: string, - showsChevron: boolean, - reasonKey: string, - runsAction: boolean - ) { - this.kind = kind; - this.state = state; - this.labelKey = labelKey; - this.badgeKey = badgeKey; - this.showsChevron = showsChevron; - this.reasonKey = reasonKey; - this.runsAction = runsAction; - } -} - -/** The goal chip's two-way toggle result. */ -export class GoalPrefillToggle { - readonly draft: string; - readonly pending: boolean; - - constructor(draft: string, pending: boolean) { - this.draft = draft; - this.pending = pending; - } -} - -const GOAL_COMMAND: string = '/goal'; -const GOAL_PREFILL: string = '/goal '; - -export class CommandPalettePolicy { - static readonly compactLabelKey: string = 'commands.compact'; - static readonly initLabelKey: string = 'commands.init'; - static readonly goalLabelKey: string = 'commands.goal'; - static readonly usageLabelKey: string = 'commands.usage'; - static readonly skillsLabelKey: string = 'commands.skills'; - static readonly upgradeBadgeKey: string = 'commands.upgradeBadge'; - static readonly degradedReasonKey: string = 'commands.degradedReason'; - static readonly busyReasonKey: string = 'commands.busyReason'; - static readonly probeWaitReasonKey: string = 'commands.probeWaitReason'; - static readonly probeRefusedReasonKey: string = 'commands.probeRefusedReason'; - static readonly probeUnreachableReasonKey: string = 'commands.probeUnreachableReason'; - - /** - * The internal ids of the two verbs that run on tap. - * - * They are not wire values: each maps to a desktop command through the - * palette's `host_invoke` client, and they are what the row, the notices and - * the single-flight guard compare against. - */ - static readonly compactWireAction: string = 'compact'; - static readonly initWireAction: string = 'init_agents_md'; - - /** The verb a chip starts, or '' for the chips that only shape the draft. */ - static wireAction(kind: CommandPaletteChipKind): string { - if (kind === CommandPaletteChipKind.Compact) return CommandPalettePolicy.compactWireAction; - if (kind === CommandPaletteChipKind.Init) return CommandPalettePolicy.initWireAction; - return ''; - } - - /** Whether this verb is one the row may start. */ - static isRunnable(wireAction: string): boolean { - return wireAction === CommandPalettePolicy.compactWireAction || - wireAction === CommandPalettePolicy.initWireAction; - } - - /** - * The row, in order. A chip is degraded rather than hidden the moment the host - * cannot serve it: a missing answer has to be visible and explainable, not - * silently absent, and every chip stays tappable so the row can say why. - */ - static chips(availability: CommandPaletteAvailability): CommandPaletteChip[] { - return [ - CommandPalettePolicy.chip(availability, CommandPaletteChipKind.Compact), - CommandPalettePolicy.chip(availability, CommandPaletteChipKind.Init), - CommandPalettePolicy.chip(availability, CommandPaletteChipKind.Goal), - CommandPalettePolicy.chip(availability, CommandPaletteChipKind.Usage), - CommandPalettePolicy.chip(availability, CommandPaletteChipKind.Skills) - ]; - } - - static chip( - availability: CommandPaletteAvailability, - kind: CommandPaletteChipKind - ): CommandPaletteChip { - const labelKey = CommandPalettePolicy.labelKey(kind); - const chevron = kind === CommandPaletteChipKind.Skills; - if (!availability.hasSession) { - return new CommandPaletteChip( - kind, CommandPaletteChipState.Dimmed, labelKey, - '', chevron, CommandPalettePolicy.sessionReasonKey(), false); - } - // Goals are plain message text: the host parses `/goal ` on the - // send path it already has, so this chip is honest about working even when - // the palette's own verbs do not. - if (kind === CommandPaletteChipKind.Goal) { - return new CommandPaletteChip( - kind, - availability.goalPending ? CommandPaletteChipState.Pending : CommandPaletteChipState.Ready, - labelKey, '', false, '', true); - } - // The picker is the one surface whose reach depends on the host's answer, so - // it is the one chip the skill read gates. - if (kind === CommandPaletteChipKind.Skills) { - return CommandPalettePolicy.skillsChip(availability, labelKey); - } - // Compacting, initializing and the usage report exist on every host this app - // can reach, and each one answers for itself when it is run — refusing it is - // the host's message to give, not a verdict this row can reach in advance. - const wireAction = CommandPalettePolicy.wireAction(kind); - if (availability.runningCommand.length > 0 && availability.runningCommand === wireAction) { - return new CommandPaletteChip( - kind, CommandPaletteChipState.InFlight, labelKey, '', false, '', false); - } - if (availability.isBusy || availability.runningCommand.length > 0) { - return new CommandPaletteChip( - kind, CommandPaletteChipState.Dimmed, labelKey, - '', false, CommandPalettePolicy.busyReasonKey, false); - } - return new CommandPaletteChip( - kind, CommandPaletteChipState.Ready, labelKey, '', false, '', true); - } - - /** - * The 技能 chip, which is where the skill read's answer shows. - * - * A read still in flight is neither a refusal nor a promise, so the chip waits - * and says so — no badge, and no sentence about the desktop's version. Only a - * host that reported the version gap itself gets the upgrade badge. - */ - private static skillsChip( - availability: CommandPaletteAvailability, - labelKey: string - ): CommandPaletteChip { - const kind = CommandPaletteChipKind.Skills; - if (availability.probeStatus === CommandPaletteCatalogStatus.Failed) { - // The picker keeps opening: it is where the reason, the host's own text and - // the re-check live, so a dead chip would say strictly less. - return new CommandPaletteChip( - kind, - CommandPaletteChipState.Dimmed, - labelKey, - CommandPalettePolicy.probeBadgeKey(availability.probeFailure), - true, - CommandPalettePolicy.probeReasonKey(availability.probeFailure), - true); - } - if (availability.probeReady) { - return new CommandPaletteChip(kind, CommandPaletteChipState.Ready, labelKey, '', true, '', true); - } - return new CommandPaletteChip( - kind, CommandPaletteChipState.Dimmed, labelKey, '', true, - CommandPalettePolicy.probeWaitReasonKey, false); - } - - /** The corner badge for a failed read: only a version gap is an upgrade. */ - static probeBadgeKey(failure: string): string { - return failure === CommandPaletteProbeFailure.VersionGap ? - CommandPalettePolicy.upgradeBadgeKey : ''; - } - - /** The chip's own sentence for a failed read. */ - static probeReasonKey(failure: string): string { - if (failure === CommandPaletteProbeFailure.VersionGap) { - return CommandPalettePolicy.degradedReasonKey; - } - return failure === CommandPaletteProbeFailure.Refused ? - CommandPalettePolicy.probeRefusedReasonKey : CommandPalettePolicy.probeUnreachableReasonKey; - } - - /** The picker's heading for a failed read. */ - static probeTitleKey(failure: string): string { - if (failure === CommandPaletteProbeFailure.VersionGap) return 'commands.skills.degradedTitle'; - return failure === CommandPaletteProbeFailure.Refused ? - 'commands.skills.refusedTitle' : 'commands.skills.unavailableTitle'; - } - - /** The picker's explanation for a failed read. */ - static probeBodyKey(failure: string): string { - if (failure === CommandPaletteProbeFailure.VersionGap) return 'commands.skills.degradedBody'; - return failure === CommandPaletteProbeFailure.Refused ? - 'commands.skills.refusedBody' : 'commands.skills.unavailableBody'; - } - - /** - * Classifies a failed skill read. - * - * `answered` is what the wire says: the host's bridge replied to this very - * command with a refusal rather than the request never landing. That is still - * not enough to tell the user their desktop is out of date, so the text - * decides — the bridge failing to deliver is a connection problem whatever - * `answered` says, the host's version-gap sentence is the upgrade, and the - * rest is the host declining for a reason of its own. - */ - static probeFailure(answered: boolean, hostText: string): string { - if (!answered) { - return CommandPaletteProbeFailure.Unreachable; - } - const text = hostText.toLowerCase(); - // Checked before the version markers: a bridge that never reached a command - // handler has no opinion about the command set either. - for (const marker of NON_ANSWER_MARKERS) { - if (text.indexOf(marker) >= 0) { - return CommandPaletteProbeFailure.Unreachable; - } - } - for (const marker of VERSION_GAP_MARKERS) { - if (text.indexOf(marker) >= 0) { - return CommandPaletteProbeFailure.VersionGap; - } - } - return CommandPaletteProbeFailure.Refused; - } - - static labelKey(kind: CommandPaletteChipKind): string { - if (kind === CommandPaletteChipKind.Compact) return CommandPalettePolicy.compactLabelKey; - if (kind === CommandPaletteChipKind.Init) return CommandPalettePolicy.initLabelKey; - if (kind === CommandPaletteChipKind.Goal) return CommandPalettePolicy.goalLabelKey; - if (kind === CommandPaletteChipKind.Usage) return CommandPalettePolicy.usageLabelKey; - return CommandPalettePolicy.skillsLabelKey; - } - - static sessionReasonKey(): string { - return 'commands.sessionReason'; - } - - /** - * The row's own line, which is now only ever about the session. - * - * A failed skill read is one chip's business and is explained there and in the - * picker; repeating it under a row of working chips would say the row is broken - * when it is not. - */ - static rowReasonKey(availability: CommandPaletteAvailability): string { - return availability.hasSession ? '' : CommandPalettePolicy.sessionReasonKey(); - } - - /** Whether the palette renders at all: one chip row needs a session to act on. */ - static visible(hasSession: boolean): boolean { - return hasSession; - } - - static canRun(chip: CommandPaletteChip): boolean { - return chip.runsAction; - } - - /** A settled failure is the only notice worth a retry affordance. */ - static canRetry(kind: CommandPaletteNoticeKind, wireAction: string): boolean { - return kind === CommandPaletteNoticeKind.Failed && - CommandPalettePolicy.isRunnable(wireAction); - } - - static busyNoticeKey(wireAction: string): string { - return wireAction === CommandPalettePolicy.initWireAction ? 'commands.initRunning' : 'commands.compactRunning'; - } - - static doneNoticeKey(wireAction: string): string { - return wireAction === CommandPalettePolicy.initWireAction ? 'commands.initDone' : 'commands.compactDone'; - } - - static failedNoticeKey(wireAction: string): string { - return wireAction === CommandPalettePolicy.initWireAction ? 'commands.initFailed' : 'commands.compactFailed'; - } - - /** The prefill the goal chip writes into the draft. */ - static goalPrefillText(): string { - return GOAL_PREFILL; - } - - /** - * Whether `/goal ` may replace what is in the composer. - * - * Only an empty draft may be filled: a prefill that overwrote typed text would - * turn one tap into data loss. - */ - static canPrefillGoal(draft: string): boolean { - return draft.trim().length === 0; - } - - /** Whether the draft is the goal prefill and nothing else. */ - static isGoalPrefill(draft: string): boolean { - return draft === GOAL_PREFILL; - } - - /** - * `true` for a bare `/goal`, which carries no argument and is therefore not a - * message yet. A trailing space is the prefill, not an argument. - */ - static isBareGoalCommand(text: string): boolean { - return text.trim() === GOAL_COMMAND; - } - - /** Whether this draft must not be sent as it stands. */ - static blocksSend(text: string): boolean { - return CommandPalettePolicy.isBareGoalCommand(text); - } - - /** - * Tapping the goal chip. - * - * First tap prefills an empty draft and lights the chip; tapping again takes - * the prefill back off, but only while the draft is still just the prefill — - * once an argument is typed the chip only stops being pending. - */ - static toggleGoal(draft: string, pending: boolean): GoalPrefillToggle { - if (pending) { - if (CommandPalettePolicy.isGoalPrefill(draft)) { - return new GoalPrefillToggle('', false); - } - return new GoalPrefillToggle(draft, false); - } - if (!CommandPalettePolicy.canPrefillGoal(draft)) { - return new GoalPrefillToggle(draft, false); - } - return new GoalPrefillToggle(GOAL_PREFILL, true); - } - - /** - * Picking a skill. - * - * One token at a time: the newest pick replaces the previous one, and picking - * the token that is already there is a no-op rather than a duplicate. The - * comparison is on the skill's key, so re-picking a row whose display name has - * changed is still the same pick. - */ - static applySkillSelection(currentSkillId: string, pickedSkillId: string): string { - const picked = pickedSkillId.trim(); - if (picked.length === 0) { - return currentSkillId; - } - if (picked === currentSkillId) { - return currentSkillId; - } - return picked; - } - - /** - * The token as the composer draws it: the exact text the message will carry. - * - * The label is the skill's own name, which is what the desktop puts in the - * token it inserts (`createSkillPromptReferenceToken(skillName)`), and the - * picker's row hint renders this same string so the two cannot describe - * different things. - */ - static skillTokenLabel(skillLabel: string): string { - const label = skillLabel.trim(); - return label.length === 0 ? '' : `[$${label}]`; - } - - /** Whether the draft opens with a host command rather than free text. */ - static startsWithHostCommand(text: string): boolean { - const trimmed = text.trim(); - return trimmed === GOAL_COMMAND || trimmed.indexOf(`${GOAL_COMMAND} `) === 0; - } - - /** - * The message a skill token sends. - * - * The token is a chip in the composer rather than text in the field, so the - * send path is where it becomes content, built from the same label the chip - * drew. It goes in front of free text, which is the position a reader expects - * and the one the host's skill reference parser accepts anywhere. - * - * A draft that opens with a host command keeps the command first: `/goal` is - * parsed by the desktop from the head of the message (`thread_goal.rs`: - * `goal_objective_from_prompt` refuses anything that does not start with - * `/goal `), so prefixing a token there would silently turn a goal into an - * ordinary message. The token is appended for those drafts instead. - * - * The token is written exactly once: a draft that already carries it keeps it, - * which is what stops a repeated pick from stacking `[$Plan] [$Plan]`. - */ - static composeSubmissionText(draft: string, skillLabel: string): string { - const token = CommandPalettePolicy.skillTokenLabel(skillLabel); - const text = draft.trim(); - if (token.length === 0) { - return draft; - } - if (text.indexOf(token) >= 0) { - return text; - } - if (text.length === 0) { - return token; - } - return CommandPalettePolicy.startsWithHostCommand(text) ? `${text} ${token}` : `${token} ${text}`; - } - - /** Whether a notice is still worth showing after this long, in milliseconds. */ - static noticeDwellMs(kind: CommandPaletteNoticeKind): number { - return kind === CommandPaletteNoticeKind.Done ? 4000 : 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConcurrentWorkspaceListing.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConcurrentWorkspaceListing.ets deleted file mode 100644 index 7ea18daab0..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConcurrentWorkspaceListing.ets +++ /dev/null @@ -1,47 +0,0 @@ -import { RemoteSession } from '../model/RemoteModels'; -import { remoteSessionIdentity } from './RemoteSessionIdentity'; - -/** - * How many workspaces are listed at once during cross-workspace discovery. - * - * Each listing is one round trip to the desktop over the relay, and a phone - * that has been used for a while has twenty-odd recent workspaces: done one - * after another that is five seconds of the session list rearranging itself - * behind the user. Kept small because these run alongside the polling that - * drives an open conversation, and a burst wide enough to crowd it out would - * trade a slow list for a slow chat. - */ -export const CONCURRENT_WORKSPACE_LISTINGS: number = 4; - -export async function mapInConcurrentBatches( - items: T[], - mapper: (item: T) => Promise, - concurrency: number = CONCURRENT_WORKSPACE_LISTINGS -): Promise { - const all: R[] = []; - const width = Math.max(1, concurrency); - for (let start = 0; start < items.length; start += width) { - const batch: T[] = items.slice(start, start + width); - const results: R[] = await Promise.all(batch.map(mapper)); - results.forEach((item: R) => { - all.push(item); - }); - } - return all; -} - -export function mergeUniqueSessions(groups: RemoteSession[][]): RemoteSession[] { - const seen: Set = new Set(); - const all: RemoteSession[] = []; - groups.forEach((sessions: RemoteSession[]) => { - sessions.forEach((item: RemoteSession) => { - const key = remoteSessionIdentity(item); - if (seen.has(key)) { - return; - } - seen.add(key); - all.push(item); - }); - }); - return all; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionErrorPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionErrorPolicy.ets deleted file mode 100644 index 742f36e0b1..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionErrorPolicy.ets +++ /dev/null @@ -1,125 +0,0 @@ -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { MobileIdentityStore } from './MobileIdentityStore'; - -const MAX_FAILED_USER_ID_ATTEMPTS = 3; -const USER_ID_LOCKOUT_MS = 60000; - -export interface UserIdProtectionState { - failureCount: number; - lockUntil: number; -} - -export interface ConnectionErrorResult { - message: string; - failureKind: string; - failureCount: number; - lockUntil: number; - shouldShowRemoteUrlInput: boolean; -} - -export class ConnectionErrorPolicy { - static isLocked(lockUntil: number): boolean { - return lockUntil > Date.now(); - } - - static remainingLockSeconds(lockUntil: number): number { - if (!ConnectionErrorPolicy.isLocked(lockUntil)) { - return 0; - } - return Math.max(1, Math.ceil((lockUntil - Date.now()) / 1000)); - } - - static protectedUserIdError(message: string): boolean { - return message.indexOf('This remote URL is already protected') >= 0 || - message.indexOf('This mobile device must continue using the previously confirmed user ID') >= 0 || - message.indexOf('Invalid username or password') >= 0 || - message.indexOf('Missing password') >= 0 || - message.indexOf('Missing username') >= 0 || - RemoteI18n.textContains('errors.accountPasswordRequired', message) || - RemoteI18n.textContains('errors.accountUsernameRequired', message); - } - - static async connectionErrorResult( - err: Object, - autoReconnect: boolean, - protectionState: UserIdProtectionState, - identityStore: MobileIdentityStore - ): Promise { - const raw = err instanceof Error ? err.message : JSON.stringify(err); - let message = ConnectionErrorPolicy.errorText(err); - let failureCount = protectionState.failureCount; - let lockUntil = protectionState.lockUntil; - - if (!autoReconnect && ConnectionErrorPolicy.protectedUserIdError(raw)) { - failureCount += 1; - const shouldLock = failureCount >= MAX_FAILED_USER_ID_ATTEMPTS; - lockUntil = shouldLock ? Date.now() + USER_ID_LOCKOUT_MS : 0; - await identityStore.saveUserIdProtection(failureCount, lockUntil); - if (shouldLock) { - message = RemoteI18n.f('errors.tooManyAttempts', `${Math.ceil(USER_ID_LOCKOUT_MS / 1000)}`); - } - } - - const failureKind = ConnectionErrorPolicy.failureKindFor(message); - return { - message, - failureKind, - failureCount, - lockUntil, - shouldShowRemoteUrlInput: failureKind === 'expired_room' || failureKind === 'invalid_link' - }; - } - - static failureKindFor(message: string): string { - const text = message.toLowerCase(); - if (ConnectionErrorPolicy.protectedUserIdError(message) || - RemoteI18n.textHasTemplatePrefix('errors.tooManyAttempts', message) || - (message.indexOf('user id') >= 0 && message.indexOf('protected') >= 0)) { - return 'protected_user'; - } - if (RemoteI18n.textEquals('errors.roomNotFound', message) || - RemoteI18n.textEquals('errors.pairRejected', message) || - text.indexOf('room') >= 0 || - text.indexOf('qr') >= 0) { - return 'expired_room'; - } - if (RemoteI18n.textEquals('errors.remoteUrlInvalid', message) || - RemoteI18n.textEquals('errors.remoteUrlMissingParams', message) || - text.indexOf('malformed') >= 0 || - text.indexOf('invalid') >= 0) { - return 'invalid_link'; - } - if (RemoteI18n.textEquals('errors.relayNetwork', message) || - RemoteI18n.textEquals('errors.relayTimeout', message) || - RemoteI18n.textEquals('errors.relayTimeoutDetail', message) || - text.indexOf('network') >= 0 || text.indexOf('dns') >= 0 || text.indexOf('timeout') >= 0) { - return 'network'; - } - return ''; - } - - static errorText(err: Object): string { - const raw = err instanceof Error ? err.message : JSON.stringify(err); - const text = raw.toLowerCase(); - if (RemoteI18n.textEquals('errors.remoteUrlRequired', raw) || - RemoteI18n.textEquals('errors.remoteUrlMissingParams', raw) || - RemoteI18n.textEquals('errors.accountPasswordRequired', raw) || - RemoteI18n.textEquals('errors.accountUsernameRequired', raw) || - RemoteI18n.textEquals('errors.userIdRequired', raw)) { - return raw; - } - if (text.indexOf('uri malformed') >= 0 || text.indexOf('malformed') >= 0 || text.indexOf('invalid') >= 0) { - return RemoteI18n.t('errors.remoteUrlInvalid'); - } - if (text.indexOf('permission') >= 0 || text.indexOf('denied') >= 0) { - return RemoteI18n.t('errors.permissionDenied'); - } - if (text.indexOf('http 401') >= 0 || text.indexOf('unauthorized') >= 0) { - return RemoteI18n.t('remote.settings.accountExpired'); - } - if (text.indexOf('http 404') >= 0 || text.indexOf('http 503') >= 0 || text.indexOf('http 504') >= 0) { - return RemoteI18n.t('remote.settings.deviceUnavailable'); - } - return raw || RemoteI18n.t('errors.operationFailed'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionStatusPresenter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionStatusPresenter.ets deleted file mode 100644 index 6524c811ba..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConnectionStatusPresenter.ets +++ /dev/null @@ -1,58 +0,0 @@ -import { RemoteI18n } from '../i18n/RemoteI18n'; - -export class ConnectionStatusPresenter { - static labelKey(connectionState: string): string { - if (connectionState === 'connected') { - return 'connection.connected'; - } - if (connectionState === 'reconnecting') { - return 'connection.reconnecting'; - } - if (connectionState === 'pairing' || connectionState === 'parsing') { - return 'connection.connecting'; - } - if (connectionState === 'failed') { - return 'connection.error'; - } - if (connectionState === 'disconnected') { - return 'connection.disconnected'; - } - return 'connection.waiting'; - } - - static label(connectionState: string): string { - return RemoteI18n.t(ConnectionStatusPresenter.labelKey(connectionState)); - } - - static detail(connectionState: string, statusText: string, desktopName: string, userId: string): string { - const status = statusText || ConnectionStatusPresenter.label(connectionState); - if (connectionState === 'connected') { - const desktopSuffix = desktopName.length > 0 ? ` · ${desktopName}` : ''; - const userSuffix = userId.length > 0 ? ` · ${RemoteI18n.f('connection.user', userId)}` : ''; - return `${status || RemoteI18n.t('connection.connected')}${desktopSuffix}${userSuffix}`; - } - if (connectionState === 'reconnecting') { - return statusText || RemoteI18n.t('connection.reconnectingDesktop'); - } - if (connectionState === 'failed') { - return statusText || RemoteI18n.t('connection.unavailableReconnect'); - } - if (connectionState === 'disconnected') { - return statusText || RemoteI18n.t('connection.desktopDisconnected'); - } - return status; - } - - static tone(connectionState: string): string { - if (connectionState === 'connected') { - return 'ok'; - } - if (connectionState === 'reconnecting' || connectionState === 'pairing' || connectionState === 'parsing') { - return 'busy'; - } - if (connectionState === 'failed') { - return 'error'; - } - return 'muted'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConversationEvent.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConversationEvent.ets deleted file mode 100644 index 348ef44a8a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ConversationEvent.ets +++ /dev/null @@ -1,71 +0,0 @@ -import { - ChatMessage, - RemoteToolStatusResponse, - SessionSummary -} from '../model/RemoteModels'; - -/** Transport-neutral events consumed by the shared conversation store. */ -export interface ConversationUserMessageEvent { - type: 'user_message'; - message: ChatMessage; - persisted: boolean; -} - -export interface ConversationAssistantDeltaEvent { - type: 'assistant_delta'; - sessionId: string; - turnId: string; - delta: string; -} - -export interface ConversationAssistantMessageEvent { - type: 'assistant_message'; - message: ChatMessage; -} - -export interface ConversationActiveTurnUpdatedEvent { - type: 'active_turn_updated'; - sessionId: string; - message: ChatMessage; -} - -export interface ConversationToolEvent { - type: 'tool_started' | 'tool_finished'; - sessionId: string; - turnId: string; - tool: RemoteToolStatusResponse; -} - -export interface ConversationTurnStartedEvent { - type: 'turn_started'; - sessionId: string; - turnId: string; -} - -export interface ConversationTurnFinishedEvent { - type: 'turn_finished'; - sessionId: string; - turnId: string; - message?: ChatMessage; -} - -export interface ConversationSessionUpdatedEvent { - type: 'session_updated'; - session: SessionSummary; -} - -export interface ConversationErrorEvent { - type: 'error'; - message: string; -} - -export type ConversationEvent = - | ConversationUserMessageEvent - | ConversationAssistantDeltaEvent - | ConversationAssistantMessageEvent - | ConversationActiveTurnUpdatedEvent - | ConversationToolEvent - | ConversationTurnStartedEvent - | ConversationTurnFinishedEvent - | ConversationSessionUpdatedEvent - | ConversationErrorEvent; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeferredLoadingGate.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeferredLoadingGate.ets deleted file mode 100644 index 0cd29dfe0e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeferredLoadingGate.ets +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Holds a loading state back until waiting for it is something the user can - * actually perceive. - * - * Opening a session that is already cached needs one short read off disk, and - * announcing that with a full-pane skeleton costs more than it explains: the - * transcript is replaced by a placeholder and then by itself again, which reads - * as a stall rather than as speed. Below the grace period nothing is shown at - * all; past it the read is slow enough — a fetch over the relay, say — that - * silence would be the worse answer. - * - * Each `arm` supersedes the one before it, so a second tap while the first open - * is still settling cannot have its skeleton dismissed by the first one - * finishing. The token is what enforces that. - * - * `maxVisibleMs` bounds how long the wait may be announced. What ends a wait is - * usually the content arriving, and content that never arrives would otherwise - * leave a skeleton standing for the rest of the session — a placeholder that - * outlives its subject reads as a hang. Past the cap the gate gives up saying - * "loading" and lets whatever the pane does have speak for itself. - */ -export class DeferredLoadingGate { - private readonly delayMs: number; - private readonly maxVisibleMs: number; - private readonly onVisible: (visible: boolean) => void; - private timerId: number = 0; - private holdTimerId: number = 0; - private token: number = 0; - - constructor(delayMs: number, onVisible: (visible: boolean) => void, maxVisibleMs: number = 0) { - this.delayMs = delayMs; - this.onVisible = onVisible; - this.maxVisibleMs = maxVisibleMs; - } - - /** Starts a wait. The returned token is what `release` has to be given. */ - arm(): number { - this.cancelTimer(); - this.cancelHoldTimer(); - this.token += 1; - const armed = this.token; - this.timerId = setTimeout(() => { - this.timerId = 0; - if (armed !== this.token) { - return; - } - this.onVisible(true); - this.startHoldTimer(armed); - }, this.delayMs); - return armed; - } - - /** The token of the most recent `arm`, for callers keeping state beside it. */ - currentToken(): number { - return this.token; - } - - /** Ends the wait started by `token`, if it is still the current one. */ - release(token: number): void { - if (token !== this.token) { - return; - } - this.settle(); - } - - /** - * Ends whatever wait is open because the thing waited for has arrived. - * - * Unlike `release` this takes no token: the arrival is reported by whatever - * carries the content — a transcript snapshot, an error — and that path has - * no memory of which tap asked for it. It is already fenced by the active - * session, so a signal that reaches here is about the wait that is open. - */ - settle(): void { - this.cancelTimer(); - this.cancelHoldTimer(); - this.onVisible(false); - } - - /** Ends whatever wait is open, for teardown. */ - reset(): void { - this.token += 1; - this.settle(); - } - - private startHoldTimer(armed: number): void { - if (this.maxVisibleMs <= 0) { - return; - } - this.holdTimerId = setTimeout(() => { - this.holdTimerId = 0; - if (armed !== this.token) { - return; - } - this.onVisible(false); - }, this.maxVisibleMs); - } - - private cancelTimer(): void { - if (this.timerId !== 0) { - clearTimeout(this.timerId); - this.timerId = 0; - } - } - - private cancelHoldTimer(): void { - if (this.holdTimerId !== 0) { - clearTimeout(this.holdTimerId); - this.holdTimerId = 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceApiLevelService.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceApiLevelService.ets deleted file mode 100644 index 961a7e0daa..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceApiLevelService.ets +++ /dev/null @@ -1,19 +0,0 @@ -import { deviceInfo } from '@kit.BasicServicesKit'; - -/** - * The device's reported API level, for presentation that must not read a - * platform kit itself. - * - * A failed read is reported as 0, which no capability gate treats as a - * supported level, so an unmeasurable device keeps the conservative path - * instead of being assumed capable. - */ -export class DeviceApiLevelService { - static sdkApiVersion(): number { - try { - return deviceInfo.sdkApiVersion; - } catch (_err) { - return 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceDirectoryCoordinator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceDirectoryCoordinator.ets deleted file mode 100644 index 9fd2eb8efd..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DeviceDirectoryCoordinator.ets +++ /dev/null @@ -1,86 +0,0 @@ -import { WorkspaceCatalog, mergeLegacyWorkspaces } from './WorkspaceCatalog'; -import { AssistantEntry, RecentWorkspaceEntry, RemoteSession, RemoteWorkspaceIdentity } from '../model/RemoteModels'; -import { AccountDeviceDirectorySource } from './AccountDeviceDirectory'; -import { - CONCURRENT_WORKSPACE_LISTINGS, - mapInConcurrentBatches, - mergeUniqueSessions -} from './ConcurrentWorkspaceListing'; -import { RemoteLogger } from './RemoteLogger'; -import { stampRemoteSessionsWorkspace } from './RemoteSessionIdentity'; - -export interface DeviceDirectoryCatalog { - workspaces: RecentWorkspaceEntry[]; - sessions: RemoteSession[]; -} - -/** - * Fans a device's recent workspaces out into session lists. - * - * The active conversation transport is not used here: each listing goes through - * the injected directory, which builds a one-shot transport for that device. - */ -export class DeviceDirectoryCoordinator { - private readonly directory: AccountDeviceDirectorySource; - private readonly concurrency: number; - - constructor( - directory: AccountDeviceDirectorySource, - concurrency: number = CONCURRENT_WORKSPACE_LISTINGS - ) { - this.directory = directory; - this.concurrency = concurrency; - } - - async loadDeviceCatalog(deviceId: string): Promise { - const workspaces = await this.loadWorkspaces(deviceId); - return { - workspaces, - sessions: await this.loadSessions(deviceId, workspaces) - }; - } - - async loadWorkspaces(deviceId: string): Promise { - return (await this.loadWorkspaceCatalog(deviceId)).workspaces; - } - - async loadWorkspaceCatalog(deviceId: string): Promise { - return await this.directory.listWorkspaceCatalog(deviceId); - } - - async loadSessions( - deviceId: string, - workspaces: RecentWorkspaceEntry[] - ): Promise { - const groups = await mapInConcurrentBatches( - workspaces, - (entry: RecentWorkspaceEntry): Promise => { - return this.safeSessionsForWorkspace(deviceId, entry); - }, - this.concurrency - ); - return mergeUniqueSessions(groups); - } - - /** One explicit workspace listing; used by the lazy sidebar disclosure. */ - async loadWorkspaceSessions(deviceId: string, workspace: RemoteWorkspaceIdentity): Promise { - return stampRemoteSessionsWorkspace(await this.directory.listSessions(deviceId, workspace), workspace); - } - - private async safeSessionsForWorkspace(deviceId: string, workspace: RemoteWorkspaceIdentity): Promise { - try { - return await this.loadWorkspaceSessions(deviceId, workspace); - } catch (err) { - // One unreadable workspace is not a reason to lose the other twenty. - RemoteLogger.warn(`load workspace sessions failed device=${deviceId} workspace=${workspace.workspaceId || ''} path=${workspace.path}: ${String(err)}`); - return []; - } - } - - static mergeWorkspaces( - recent: RecentWorkspaceEntry[], - assistants: AssistantEntry[] - ): RecentWorkspaceEntry[] { - return mergeLegacyWorkspaces(recent, assistants); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets deleted file mode 100644 index 880f63a4fa..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/DurableSessionReducer.ets +++ /dev/null @@ -1,211 +0,0 @@ -import { ChatMessage, ChatMessageItemResponse, RemoteToolStatusResponse, ImageAttachment } from '../model/RemoteModels'; -import { HostSessionEvent } from './HostSessionStream'; - -interface UserMetadata { original_text?: string; images?: ImageAttachment[]; } -interface UserRecord { id: string; content: string; timestamp: number; metadata?: Object; } -interface TurnRecord { turnId: string; turnIndex: number; sessionId: string; timestamp: number; userMessage: UserRecord; status: string; error?: string; kind?: string; } -interface RoundRecord { id: string; turnId: string; roundIndex: number; timestamp: number; status: string; } -interface ToolCall { id: string; input: Object; } -interface ToolResult { result: Object; success: boolean; error?: string; durationMs?: number; } -interface ItemData { - id: string; content?: string; timestamp?: number; orderIndex?: number; - status?: string; isStreaming?: boolean; isSubagentItem?: boolean; parentTaskToolId?: string; subagentSessionId?: string; - attemptId?: string; attemptIndex?: number; interruptionReason?: string; - toolName?: string; toolCall?: ToolCall; toolResult?: ToolResult; startTime?: number; durationMs?: number; -} -interface ItemRecord { type: string; data: ItemData; } -export interface SessionRecord { sessionId: string; id: string; revision: number; deleted?: boolean; turn?: TurnRecord; round?: RoundRecord; item?: ItemRecord; } -interface StoredTurn { revision: number; data?: TurnRecord; authoritative?: boolean; } -interface StoredRound { revision: number; data?: RoundRecord; } -interface StoredItem { revision: number; turnId: string; roundId: string; data: ItemRecord; } -interface RenderedTurn { generation: number; messages: ChatMessage[]; } -interface PromptSuggestion { sourceTurnId: string; suggestion: string; sessionId?: string; } - -/** Lossless record storage follows Happy's stable-id message reduction. Mobile - * presentation adapts the existing persisted turn schema; it does not define a - * second wire DTO or overwrite newer parent state with an older child record. */ -export class DurableSessionReducer { - private records: Map = new Map(); - private tombstones: Map = new Map(); - private turns: Map = new Map(); - private rounds: Map = new Map(); - private items: Map = new Map(); - // One turn's messages are rebuilt only when something that can change them - // arrived. A record carries no usable "this turn's content changed" flag (a - // round or item record repeats its parent turn header without advancing the - // turn's own revision), so the reducer counts the arrivals itself. - private turnGenerations: Map = new Map(); - private renderedTurns: Map = new Map(); - private generationSeq: number = 0; - private suggestion?: PromptSuggestion; - - /** Optional host hints stay outside durable transcript records. */ - promptSuggestion(): string { - const hint = this.suggestion; - if (!hint) return ''; - const latest = this.latestTurn(); - if (!latest || latest.turnId !== hint.sourceTurnId || latest.status !== 'completed') { - this.suggestion = undefined; - return ''; - } - return hint.suggestion; - } - - private latestTurn(): TurnRecord | undefined { - let latest: TurnRecord | undefined = undefined; - for (const stored of this.turns.values()) { - const turn = stored.data; - if (turn && stored.revision > (this.tombstones.get(`turn/${turn.turnId}`) ?? 0) && - (!latest || turn.turnIndex > latest.turnIndex)) latest = turn; - } - return latest; - } - private touchTurn(turnId: string): void { - this.generationSeq++; - this.turnGenerations.set(turnId, this.generationSeq); - } - /** A tombstone names its turn only when the host repeated the header. */ - private forgetTurnOrAll(record: SessionRecord): void { - const turnId = record.turn?.turnId; - if (turnId) this.touchTurn(turnId); else this.renderedTurns.clear(); - } - apply(event: HostSessionEvent): boolean { - if (event.event === 'agentic://prompt-suggestion') { - const hint = event.payload as PromptSuggestion; - if (!hint || typeof hint.sourceTurnId !== 'string' || !hint.sourceTurnId || - typeof hint.suggestion !== 'string' || !hint.suggestion || - (hint.sessionId !== undefined && hint.sessionId !== event.session_id)) return false; - const latest = this.latestTurn(); - if (latest && latest.turnId !== hint.sourceTurnId) return false; - this.suggestion = hint; - return true; - } - if (event.event !== 'session-record') return false; - const record = event.payload as SessionRecord; - if (record.sessionId !== event.session_id || !record.id || !Number.isSafeInteger(record.revision) || record.revision < 1) throw new Error('Invalid session record identity'); - const previous = this.records.get(record.id); - if (previous && previous.revision >= record.revision) return false; - if (record.deleted) { - if (!/^(turn|round|item)\/.+/.test(record.id)) throw new Error('Invalid session tombstone identity'); - this.records.set(record.id, record); - this.tombstones.set(record.id, record.revision); - if (record.id.startsWith('turn/')) { - const id = record.id.slice(5); const previousTurn = this.turns.get(id); - if (!previousTurn || previousTurn.revision < record.revision) this.turns.set(id, { revision: record.revision }); - this.touchTurn(id); - } else if (record.id.startsWith('round/')) { - const id = record.id.slice(6); const previousRound = this.rounds.get(id); - if (!previousRound || previousRound.revision < record.revision) this.rounds.set(id, { revision: record.revision }); - this.forgetTurnOrAll(record); - } else if (record.id.startsWith('item/')) { - this.items.delete(record.id.slice(5)); - this.forgetTurnOrAll(record); - } else throw new Error('Unknown session tombstone kind'); - return true; - } - const data = record.turn; - if (!data || data.sessionId !== event.session_id) throw new Error('Session turn identity mismatch'); - const expectedId = record.item ? `item/${record.item.data.id}` : record.round ? `round/${record.round.id}` : `turn/${data.turnId}`; - if (record.id !== expectedId) throw new Error('Session record key mismatch'); - if (record.round && record.round.turnId !== data.turnId) throw new Error('Session round parent mismatch'); - if (record.item && !record.round) throw new Error('Session item is missing its round'); - this.records.set(record.id, record); - const turn = this.turns.get(data.turnId); - // A round or item record repeats its parent turn so a partial page still - // reads, but that copy is a header, not the turn's own state: the turn - // record is what the user message and its attachment pixels come from, so a - // header fills a turn it has never seen and never overwrites one. - const header = !!record.round; - if (!turn || (turn.revision < record.revision && !(header && turn.authoritative))) - this.turns.set(data.turnId, { revision: record.revision, data: data, authoritative: !header }); - if (record.round) { - const round = this.rounds.get(record.round.id); - if (!round || round.revision < record.revision) this.rounds.set(record.round.id, { revision: record.revision, data: record.round }); - } - if (record.item && record.round) { - const item = this.items.get(record.item.data.id); - if (!item || item.revision < record.revision) this.items.set(record.item.data.id, - { revision: record.revision, turnId: data.turnId, roundId: record.round.id, data: record.item }); - } - this.touchTurn(data.turnId); - return true; - } - messages(): ChatMessage[] { - const result: ChatMessage[] = []; - const turns = Array.from(this.turns.values()).filter((turn: StoredTurn) => !!turn.data).sort((a: StoredTurn, b: StoredTurn) => (a.data?.turnIndex || 0) - (b.data?.turnIndex || 0)); - // Grouping the items under their turn once keeps a rebuild linear in the - // session's length. Scanning the whole item map again for every turn made a - // long session pay for its own length twice over, on the thread that draws - // it, which is where the scrolling went. - const byTurn: Map = new Map(); - this.items.forEach((item: StoredItem) => { - const bucket = byTurn.get(item.turnId); - if (bucket) bucket.push(item); else byTurn.set(item.turnId, [item]); - }); - for (const stored of turns) { - const turn = stored.data; - if (!turn) continue; - if (turn.kind === 'local_command') continue; - const generation = this.turnGenerations.get(turn.turnId) ?? 0; - const cached = this.renderedTurns.get(turn.turnId); - if (cached && cached.generation === generation) { - for (const message of cached.messages) result.push(message); - continue; - } - const rendered = this.renderTurn(turn, stored, byTurn.get(turn.turnId) ?? []); - this.renderedTurns.set(turn.turnId, { generation: generation, messages: rendered }); - for (const message of rendered) result.push(message); - } - // Dropped turns must not pin their messages, and the cache must not outlive - // the turns it describes. - const live: Set = new Set(); - for (const stored of turns) { const turn = stored.data; if (turn) live.add(turn.turnId); } - for (const key of Array.from(this.renderedTurns.keys())) if (!live.has(key)) this.renderedTurns.delete(key); - return result; - } - private renderTurn(turn: TurnRecord, stored: StoredTurn, entries: StoredItem[]): ChatMessage[] { - const result: ChatMessage[] = []; - const metadata = turn.userMessage.metadata as UserMetadata | undefined; - const userText = metadata?.original_text || turn.userMessage.content; - if (userText.length > 0 || (metadata?.images?.length || 0) > 0) result.push({ id: turn.userMessage.id, turnId: turn.turnId, - role: 'user', text: userText, images: metadata?.images, status: 'sent', timestamp: String(turn.userMessage.timestamp) }); - const turnFence = this.tombstones.get(`turn/${turn.turnId}`) ?? 0; - const visible = entries.filter((item: StoredItem) => { - const round = this.rounds.get(item.roundId); - const roundFence = Math.max(turnFence, this.tombstones.get(`round/${item.roundId}`) ?? 0); - return !!round?.data && round.revision > roundFence && - item.revision > Math.max(roundFence, this.tombstones.get(`item/${item.data.data.id}`) ?? 0); - }) - .sort((a: StoredItem, b: StoredItem) => { - const roundA = this.rounds.get(a.roundId)?.data?.roundIndex || 0; - const roundB = this.rounds.get(b.roundId)?.data?.roundIndex || 0; - return roundA - roundB || (a.data.data.orderIndex ?? a.data.data.timestamp ?? 0) - - (b.data.data.orderIndex ?? b.data.data.timestamp ?? 0) || a.data.data.id.localeCompare(b.data.data.id); - }); - const items: ChatMessageItemResponse[] = []; - const tools: RemoteToolStatusResponse[] = []; - for (const entry of visible) { - const data = entry.data.data; - if (data.status === 'superseded' || data.status === 'retry_superseded') continue; - const round = this.rounds.get(entry.roundId)?.data?.roundIndex || 0; - const item: ChatMessageItemResponse = { type: entry.data.type, content: data.content, round_index: round, is_subagent: data.isSubagentItem === true || !!data.subagentSessionId }; - if (entry.data.type === 'tool') { - const tool: RemoteToolStatusResponse = { id: data.toolCall?.id || data.id, name: data.toolName, status: data.status || (data.toolResult ? (data.toolResult.success ? 'completed' : 'failed') : 'running'), - tool_input: data.toolCall?.input, tool_output: data.toolResult?.result, - duration_ms: data.durationMs ?? data.toolResult?.durationMs, error_preview: data.toolResult?.error, start_ms: data.startTime, - // The child Session this launch started, kept on the projection so a - // transcript that only exists on this phone still says which session a - // delegation drew its worker from. - subagent_session_id: data.subagentSessionId }; - item.tool = tool; tools.push(tool); - } - items.push(item); - } - const status = turn.status === 'inprogress' ? 'active' : turn.status === 'error' ? 'failed' : turn.status; - result.push({ id: `assistant-${turn.turnId}`, turnId: turn.turnId, role: 'assistant', status: status, - text: items.filter((item: ChatMessageItemResponse) => item.type === 'text' && !item.is_subagent).map((item: ChatMessageItemResponse) => item.content || '').join(''), - thinking: items.filter((item: ChatMessageItemResponse) => item.type === 'thinking' && !item.is_subagent).map((item: ChatMessageItemResponse) => item.content || '').join(''), - tools: tools, items: items, timestamp: String(turn.timestamp), error: turn.error, renderVersion: stored.revision }); - return result; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/Encoding.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/Encoding.ets deleted file mode 100644 index 51d81f45a2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/Encoding.ets +++ /dev/null @@ -1,145 +0,0 @@ -import buffer from '@ohos.buffer'; -import { cryptoFramework } from '@kit.CryptoArchitectureKit'; -import util from '@ohos.util'; -import { OhosError } from './OhosError'; - -/** - * Byte/text conversions on the path every relay RPC takes. - * - * These run inline on whichever thread issues the call, which for the device - * RPC is the UI thread, and they run over the whole request and the whole - * response — a transcript-sized `poll_session` reply is hundreds of kilobytes. - * So the cost per byte is what decides whether the frame that should be - * painting a skeleton gets to run at all. Everything here has to stay on a - * native bulk primitive; anything that touches bytes one at a time from ArkTS - * shows up directly as a blocked main thread. - */ -export class Encoding { - static async sha256(text: string): Promise { - const digest = cryptoFramework.createMd('SHA256'); - await digest.update({ data: Encoding.utf8ToBytes(text) }); - const result = await digest.digest(); - return Array.from(result.data).map((value: number) => value.toString(16).padStart(2, '0')).join(''); - } - - static utf8ToBytes(text: string): Uint8Array { - try { - return Encoding.copyBuffer(buffer.from(text, 'utf-8')); - } catch (err) { - throw OhosError.wrap('utf8 encode', err); - } - } - - static bytesToUtf8(bytes: Uint8Array): string { - try { - return buffer.from(bytes).toString('utf-8'); - } catch (err) { - throw OhosError.wrap('utf8 decode', err); - } - } - - static base64ToBytes(text: string): Uint8Array { - try { - return Encoding.copyBuffer(buffer.from(text, 'base64')); - } catch (err) { - throw OhosError.wrap('base64 decode', err); - } - } - - static bytesToBase64(bytes: Uint8Array): string { - try { - return buffer.from(bytes).toString('base64'); - } catch (err) { - throw OhosError.wrap('base64 encode', err); - } - } - - static randomBytes(size: number): Uint8Array { - try { - const random = cryptoFramework.createRandom(); - const data = random.generateRandomSync(size).data; - return Encoding.copyRandomData(data, size); - } catch (err) { - throw OhosError.wrap('random bytes', err); - } - } - - static randomId(prefix: string): string { - try { - return `${prefix}-${util.generateRandomUUID(false)}`; - } catch (err) { - throw OhosError.wrap('random id', err); - } - } - - static concat(left: Uint8Array, right: Uint8Array): Uint8Array { - const out = new Uint8Array(left.length + right.length); - out.set(left, 0); - out.set(right, left.length); - return out; - } - - static copyBytes(bytes: Uint8Array): Uint8Array { - const copy = new Uint8Array(bytes.length); - copy.set(bytes); - return copy; - } - - static parseJsonObject(text: string): T { - return JSON.parse(text) as T; - } - - /** - * Detaches a `Buffer` into a plain `Uint8Array` in one native copy. - * - * This used to read `value[index]` in a loop. On a `Buffer` each of those is - * a proxied property access rather than a typed-array load, so a - * transcript-sized response — hundreds of kilobytes, hundreds of thousands of - * reads — spent about a second of the UI thread here, inside the window where - * the conversation pane was meant to be painting its skeleton. - * - * `value.buffer` is already scoped to this Buffer's own bytes: measured on - * device, a 32-byte Buffer sitting at pool offset 856 reports a 32-byte - * ArrayBuffer, so the offset must not be applied to it. `util.Base64Helper` - * and `util.TextEncoder` would skip the Buffer entirely, but both return - * empty on this runtime. - */ - private static copyBuffer(value: buffer.Buffer): Uint8Array { - return new Uint8Array(value.buffer); - } - - private static copyRandomData(value: Uint8Array | ArrayBuffer, expectedSize: number): Uint8Array { - const bytes = value as Uint8Array; - if (bytes.length === expectedSize) { - return Encoding.copyBytes(bytes); - } - - const rawBuffer = value as ArrayBuffer; - if (rawBuffer.byteLength === expectedSize) { - return Encoding.copyBytes(new Uint8Array(rawBuffer)); - } - - return Encoding.randomBytesFromUuid(expectedSize); - } - - private static randomBytesFromUuid(size: number): Uint8Array { - const out = new Uint8Array(size); - let offset = 0; - while (offset < size) { - let uuid = ''; - try { - uuid = util.generateRandomUUID(false).replace(/-/g, ''); - } catch (err) { - throw OhosError.wrap('random uuid', err); - } - if (uuid.length < 2) { - throw new Error(`Expected ${size} random bytes.`); - } - for (let index = 0; index + 1 < uuid.length && offset < size; index += 2) { - out[offset] = Number.parseInt(uuid.slice(index, index + 2), 16); - offset += 1; - } - } - return out; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewErrorPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewErrorPolicy.ets deleted file mode 100644 index ad377af76d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewErrorPolicy.ets +++ /dev/null @@ -1,42 +0,0 @@ -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; - -export class FilePreviewErrorResult { - readonly text: string; - readonly retryable: boolean; - - constructor(text: string, retryable: boolean) { - this.text = text; - this.retryable = retryable; - } -} - -export class FilePreviewErrorPolicy { - static resolve(err: Object): FilePreviewErrorResult { - const raw = err instanceof Error ? err.message : JSON.stringify(err); - const text = raw.toLowerCase(); - if (text.indexOf('file not found') >= 0 || text.indexOf('file does not exist') >= 0 || - text.indexOf('not a regular file') >= 0 || text.indexOf('no such file') >= 0) { - return new FilePreviewErrorResult(RemoteI18n.t('filePreview.notFound'), true); - } - if (text.indexOf('could not be resolved') >= 0) { - return new FilePreviewErrorResult(RemoteI18n.t('filePreview.unavailable'), true); - } - if (text.indexOf('access denied') >= 0 || text.indexOf('restricted') >= 0 || - text.indexOf('outside') >= 0) { - return new FilePreviewErrorResult(RemoteI18n.t('filePreview.accessDenied'), false); - } - if (text.indexOf('file too large') >= 0 || text.indexOf('too large') >= 0) { - return new FilePreviewErrorResult(RemoteI18n.t('filePreview.tooLarge'), false); - } - const connectionText = ConnectionErrorPolicy.errorText(err); - if (connectionText !== raw || /[\u3400-\u9fff]/.test(raw)) { - return new FilePreviewErrorResult(connectionText, true); - } - return new FilePreviewErrorResult(RemoteI18n.t('filePreview.loadFailed'), true); - } - - static errorText(err: Object): string { - return FilePreviewErrorPolicy.resolve(err).text; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewPolicy.ets deleted file mode 100644 index 540d347c70..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/FilePreviewPolicy.ets +++ /dev/null @@ -1,13 +0,0 @@ -export class FilePreviewPolicy { - static readonly TEXT_MAX_BYTES: number = 2 * 1024 * 1024; - static readonly IMAGE_MAX_BYTES: number = 12 * 1024 * 1024; - - static textReadLimit(fileSize: number): number { - return fileSize > 0 ? Math.min(fileSize, FilePreviewPolicy.TEXT_MAX_BYTES) : - FilePreviewPolicy.TEXT_MAX_BYTES; - } - - static canPreviewImage(fileSize: number): boolean { - return fileSize <= FilePreviewPolicy.IMAGE_MAX_BYTES; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/GitHubAccountProfile.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/GitHubAccountProfile.ets deleted file mode 100644 index 9a76f50b64..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/GitHubAccountProfile.ets +++ /dev/null @@ -1,65 +0,0 @@ -import { http } from '@kit.NetworkKit'; - -/** Public presentation data only. The relay's immutable user ID still owns authorization. */ -export interface GitHubAccountProfile { - userId: string; - login: string; - avatarUrl: string; - fetchedAt: number; -} - -export interface GitHubPublicUser { - id: number; - login: string; - avatar_url?: string; -} - -export interface GitHubProfileLoader { - load(userId: string): Promise; -} - -export function normalizeGitHubProfile(userId: string, user: GitHubPublicUser): GitHubAccountProfile { - if (!/^[1-9][0-9]*$/.test(userId) || !Number.isSafeInteger(user.id) || String(user.id) !== userId || - typeof user.login !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}$/.test(user.login)) { - throw new Error('Invalid GitHub profile identity.'); - } - const avatar = typeof user.avatar_url === 'string' ? user.avatar_url : ''; - return { - userId, login: user.login, - avatarUrl: avatar.startsWith('https://avatars.githubusercontent.com/') ? avatar : '', - fetchedAt: Date.now() - }; -} - -export function readCachedGitHubProfile(userId: string, text: string): GitHubAccountProfile | undefined { - if (!text) return undefined; - try { - const profile = JSON.parse(text) as GitHubAccountProfile; - if (profile.userId !== userId || typeof profile.fetchedAt !== 'number' || !Number.isFinite(profile.fetchedAt)) return undefined; - const normalized = normalizeGitHubProfile(userId, { - id: Number(profile.userId), login: profile.login, avatar_url: profile.avatarUrl - }); - normalized.fetchedAt = profile.fetchedAt; - return normalized; - } catch (_err) { return undefined; } -} - -/** Works for already-signed-in controllers without sending any OpenBitFun token to GitHub. */ -export class GitHubAccountProfileClient implements GitHubProfileLoader { - async load(userId: string): Promise { - if (!/^[1-9][0-9]*$/.test(userId)) throw new Error('Invalid GitHub account ID.'); - const request = http.createHttp(); - try { - const response = await request.request(`https://api.github.com/user/${userId}`, { - method: http.RequestMethod.GET, - header: { 'Accept': 'application/vnd.github+json', 'User-Agent': 'OpenBitFun-Mobile' }, - expectDataType: http.HttpDataType.STRING, - connectTimeout: 5000, readTimeout: 5000 - }); - if (response.responseCode !== 200 || typeof response.result !== 'string') { - throw new Error(`GitHub profile unavailable (HTTP ${response.responseCode}).`); - } - return normalizeGitHubProfile(userId, JSON.parse(response.result) as GitHubPublicUser); - } finally { request.destroy(); } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyTaskCompletionNotificationPort.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyTaskCompletionNotificationPort.ets deleted file mode 100644 index 5466dcb827..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyTaskCompletionNotificationPort.ets +++ /dev/null @@ -1,133 +0,0 @@ -import { preferences } from '@kit.ArkData'; -import { common, wantAgent } from '@kit.AbilityKit'; -import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; -import { notificationManager } from '@kit.NotificationKit'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { RemoteLogger } from './RemoteLogger'; -import { - TaskCompletionNotificationPort, - TaskCompletionObservation -} from './TaskCompletionNotificationController'; - -const BACKGROUND_REASON: string = 'Waiting for an active OpenBitFun task to finish'; - -/** HarmonyOS platform leaf for task-completion notifications. */ -export class HarmonyTaskCompletionNotificationPort implements TaskCompletionNotificationPort { - private readonly contextProvider: () => Context; - private permissionPrepared: boolean = false; - private suspendRequestId: number = 0; - - constructor(contextProvider: () => Context) { - this.contextProvider = contextProvider; - } - - async offerOnboarding(offer: () => Promise): Promise { - if (this.permissionPrepared) { - return; - } - this.permissionPrepared = true; - try { - const store = await preferences.getPreferences(this.contextProvider(), 'notification_onboarding'); - if (await store.get('completed_v1', false) === true) { - return; - } - if (notificationManager.isNotificationEnabledSync()) { - await store.put('completed_v1', true); - await store.flush(); - return; - } - const enable = await offer(); - await store.put('completed_v1', true); - await store.flush(); - if (enable) { - await notificationManager.requestEnableNotification(this.uiAbilityContext()); - } - } catch (err) { - RemoteLogger.warn(`task completion notification permission unavailable: ${HarmonyTaskCompletionNotificationPort.errorText(err)}`); - } - } - - keepAlive(onExpired: () => void): boolean { - this.releaseKeepAlive(); - try { - const info = backgroundTaskManager.requestSuspendDelay(BACKGROUND_REASON, (): void => { - this.suspendRequestId = 0; - RemoteLogger.info('task completion background observation expired'); - onExpired(); - }); - this.suspendRequestId = info.requestId; - RemoteLogger.info(`task completion background observation started delayMs=${info.actualDelayTime}`); - return true; - } catch (err) { - RemoteLogger.warn(`task completion background observation unavailable: ${HarmonyTaskCompletionNotificationPort.errorText(err)}`); - return false; - } - } - - releaseKeepAlive(): void { - if (this.suspendRequestId === 0) { - return; - } - const requestId = this.suspendRequestId; - this.suspendRequestId = 0; - try { - backgroundTaskManager.cancelSuspendDelay(requestId); - } catch (err) { - RemoteLogger.warn(`task completion background observation release failed: ${HarmonyTaskCompletionNotificationPort.errorText(err)}`); - } - } - - async publish(observation: TaskCompletionObservation): Promise { - try { - if (!notificationManager.isNotificationEnabledSync()) { - RemoteLogger.info('task completion notification skipped: notifications disabled'); - return; - } - const context = this.uiAbilityContext(); - const notificationId = HarmonyTaskCompletionNotificationPort.notificationId(observation); - const launchAgent = await wantAgent.getWantAgent({ - wants: [{ - bundleName: context.abilityInfo.bundleName, - abilityName: context.abilityInfo.name - }], - actionType: wantAgent.OperationType.START_ABILITY, - requestCode: notificationId, - actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }); - await notificationManager.publish({ - id: notificationId, - appMessageId: `openbitfun-task-completed:${observation.source}:${observation.sessionId}:${observation.turnId}`, - notificationSlotType: notificationManager.SlotType.SERVICE_INFORMATION, - tapDismissed: true, - wantAgent: launchAgent, - content: { - notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: RemoteI18n.t('notification.taskCompletedTitle'), - text: RemoteI18n.t('notification.taskCompletedBody') - } - } - }); - RemoteLogger.info(`task completion notification published source=${observation.source}`); - } catch (err) { - RemoteLogger.warn(`task completion notification publish failed: ${HarmonyTaskCompletionNotificationPort.errorText(err)}`); - } - } - - private uiAbilityContext(): common.UIAbilityContext { - return this.contextProvider() as common.UIAbilityContext; - } - - private static notificationId(observation: TaskCompletionObservation): number { - const value = `${observation.source}:${observation.sessionId}:${observation.turnId}`; - let hash = 17; - for (let index = 0; index < value.length; index += 1) { - hash = ((hash * 31) + value.charCodeAt(index)) & 0x7FFFFFFF; - } - return hash === 0 ? 1 : hash; - } - - private static errorText(err: Object): string { - return err instanceof Error ? err.message : JSON.stringify(err); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyUpgradeIdentityContract.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyUpgradeIdentityContract.ets deleted file mode 100644 index f4f13f4a8d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HarmonyUpgradeIdentityContract.ets +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Stable HarmonyOS package and storage identifiers retained across the - * product-name change. - * - * These values are not display branding. Changing any of them strands data - * written by an installed release (and changing the bundle id prevents an - * in-place upgrade altogether), so all compatibility-only identifiers live at - * this single boundary instead of leaking through product code. - */ -export class HarmonyUpgradeIdentityContract { - static readonly APP_BUNDLE: string = 'com.bitfun.app'; - static readonly REMOTE_IDENTITY_STORE: string = 'bitfun_remote_identity'; - static readonly CLOUD_ACCOUNT_STORE: string = 'bitfun_cloud_account'; - static readonly CLOUD_ACCOUNT_HUKS_ALIAS: string = 'bitfun_cloud_account_session'; - static readonly APP_LOCALE_STORE: string = 'bitfun_app_locale'; - static readonly REMOTE_CHAT_DATABASE: string = 'bitfun_remote_chat.db'; - static readonly REMOTE_SESSIONS_DATABASE: string = 'bitfun_remote_sessions.db'; - static readonly GENERAL_CHAT_CONFIG_STORE: string = 'bitfun_general_chat_config'; - static readonly GENERAL_CHAT_HUKS_ALIAS: string = 'bitfun_general_chat_api_key'; - static readonly GENERAL_CHAT_DATABASE: string = 'bitfun_general_chat.db'; - static readonly WATCH_HANDOFF_STORE: string = 'bitfun_harmony_handoff_s1'; - static readonly WATCH_PROVISION_REQUEST_KEY: string = 'bitfun.account.provision.request'; - static readonly WATCH_PROVISION_RESPONSE_KEY: string = 'bitfun.account.provision.response'; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostCatalogObserver.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostCatalogObserver.ets deleted file mode 100644 index 4f4210d38a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostCatalogObserver.ets +++ /dev/null @@ -1,114 +0,0 @@ -import { RemoteSessionManager } from './RemoteSessionManager'; -import { HOST_CATALOG_ID, HostSessionEvent, HostSessionStream } from './HostSessionStream'; - -export interface HostCatalogChange { - sessionsRevision?: number; - workspacesRevision?: number; - initial?: boolean; -} - -const HOST_CATALOG_NOTICE_MIN_INTERVAL_MS: number = 3000; - -/** One host invalidation stream; directory contents remain owned by the runtime. */ -export class HostCatalogObserver { - private stream?: HostSessionStream; - private target: string = ''; - private generation: number = 0; - private dirty: boolean = false; - private runningGeneration?: number; - private pendingChange: HostCatalogChange = {}; - private lastSessionsRevision?: number; - private lastWorkspacesRevision?: number; - private lastRefreshAt: number = 0; - private manager: RemoteSessionManager; - private refresh: (change: HostCatalogChange) => Promise; - private onError: (error: Error) => void; - constructor(manager: RemoteSessionManager, refresh: (change: HostCatalogChange) => Promise, onError: (error: Error) => void) { - this.manager = manager; this.refresh = refresh; this.onError = onError; - } - start(target: string): void { - if (!target) { this.stop(); return; } - if (this.target === target && this.stream && !this.stream.isClosed()) { - // Successful session reads also ensure observation is active. Treating - // that as an invalidation makes refresh -> start -> refresh a loop. - this.stream.wake(); - return; - } - this.stop(); this.target = target; - const generation = this.generation; - this.dirty = true; - try { - this.stream = this.manager.subscribeSession(HOST_CATALOG_ID, { - onEvent: async (event: HostSessionEvent): Promise => { - if (generation === this.generation && event.event === 'host-catalog-changed') { - const payload = (event.payload || {}) as Record; - const sessionsRevision = Number(payload.sessionsRevision); - const workspacesRevision = Number(payload.workspacesRevision); - const hasRevisions = Number.isSafeInteger(sessionsRevision) || Number.isSafeInteger(workspacesRevision); - let revisionChanged = false; - if (Number.isSafeInteger(sessionsRevision) && sessionsRevision !== this.lastSessionsRevision) { - this.pendingChange.sessionsRevision = sessionsRevision; - this.lastSessionsRevision = sessionsRevision; - revisionChanged = true; - } - if (Number.isSafeInteger(workspacesRevision) && workspacesRevision !== this.lastWorkspacesRevision) { - this.pendingChange.workspacesRevision = workspacesRevision; - this.lastWorkspacesRevision = workspacesRevision; - revisionChanged = true; - } - // A revision-bearing event with no revision change is only a - // duplicate hint. Legacy hosts omit both values and remain - // conservatively invalidating everything. - if (!hasRevisions) this.pendingChange.initial = true; - if (!hasRevisions || revisionChanged) this.dirty = true; - } - }, - onResumed: async (): Promise => { - if (generation === this.generation) { this.pendingChange.initial = true; this.dirty = true; } - }, - onGap: async (): Promise => { - if (generation === this.generation) { this.pendingChange.initial = true; this.dirty = true; } - }, - onCaughtUp: async (): Promise => { await this.flush(generation); }, - onError: (error: Error): void => { if (generation === this.generation) this.onError(error); } - }); - } catch (error) { this.onError(error as Error); } - } - stop(): void { - this.generation++; this.stream?.close(); this.stream = undefined; - this.target = ''; this.dirty = false; this.pendingChange = {}; - this.lastSessionsRevision = undefined; this.lastWorkspacesRevision = undefined; this.lastRefreshAt = 0; - } - private async flush(generation: number): Promise { - if (this.runningGeneration === generation || generation !== this.generation) return; - // A disconnected target may still have an RPC pending. The new stream - // owns its own refresh and must receive its errors to drive backoff. - this.runningGeneration = generation; - try { - while (this.dirty && generation === this.generation) { - this.dirty = false; - const change = this.pendingChange; - if (this.lastRefreshAt === 0) change.initial = true; - this.pendingChange = {}; - const waitMs = Math.max(0, HOST_CATALOG_NOTICE_MIN_INTERVAL_MS - (Date.now() - this.lastRefreshAt)); - if (this.lastRefreshAt > 0 && waitMs > 0) { - await new Promise((resolve) => setTimeout(resolve, waitMs)); - if (generation !== this.generation) return; - } - await this.refresh(change); - if (generation !== this.generation) return; - this.lastRefreshAt = Date.now(); - } - } catch (error) { - if (generation === this.generation) { - this.pendingChange.initial = true; - this.dirty = true; - this.lastRefreshAt = Date.now(); - // Let the stream's existing backoff retry even if no more hints arrive. - throw new Error(String(error)); - } - } finally { - if (this.runningGeneration === generation) this.runningGeneration = undefined; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostInvokeRefusal.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostInvokeRefusal.ets deleted file mode 100644 index 80f955fbb6..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostInvokeRefusal.ets +++ /dev/null @@ -1,44 +0,0 @@ -/** - * The one failure mode `host_invoke` distinguishes: the host answered. - * - * A bridge answers every invoke with `{ok, value, error}`, and `ok: false` means - * the host received the command and declined it — an unknown name, a retired - * command, a mode it does not have. Everything else that can go wrong on this - * wire (no connection, an expired room, a timeout, a payload that decodes to - * nothing) never reached a host at all, and the two must not be described to the - * user as the same event. - * - * This module owns only that distinction, so the palette can ask whether the host - * spoke without knowing which transport carried the question. - */ - -export class HostInvokeRefusal extends Error { - /** The host's own words for the refusal, exactly as it sent them. */ - readonly hostText: string; - /** The command the host declined. */ - readonly command: string; - - constructor(command: string, hostText: string) { - super(hostText.length > 0 ? hostText : `Remote host refused ${command}`); - this.name = 'HostInvokeRefusal'; - this.command = command; - this.hostText = hostText; - } -} - -/** Whether this failure is the host declining a command rather than the wire breaking. */ -export function isHostInvokeRefusal(err: Object): boolean { - return err instanceof HostInvokeRefusal; -} - -/** - * The host's own account of a refusal. - * - * Kept separate from the shared connection-error wording on purpose: a refused - * command is about the command, and the shared policy rewrites text that looks - * like a URL or a permission problem — which is exactly the kind of sentence a - * refusal needs to keep. - */ -export function hostInvokeRefusalText(err: Object): string { - return isHostInvokeRefusal(err) ? (err as HostInvokeRefusal).hostText : ''; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets deleted file mode 100644 index 084504fcdd..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets +++ /dev/null @@ -1,335 +0,0 @@ -import { RemoteLogger } from './RemoteLogger'; -import { CommandStatusResponse } from '../model/RemoteModels'; - -/** Stream id of the host's workspace/session catalog. */ -export const HOST_CATALOG_ID: string = '@host/catalog'; -export const HOST_STREAM_CHANGED_EVENT: string = 'host-stream-changed'; -export const REMOTE_CAPABILITY_HOST_STREAM_V1: string = 'host_stream_v1'; -/** Hosts keep hint subscriptions alive for 10 minutes; renew well before. */ -const HOST_STREAM_KEEPALIVE_MS: number = 4 * 60 * 1000; - -/** - * How many pages one history request may read while it has not yet shown the - * reader anything it did not already have. - * - * Host pages are cut by sequence, and a record's sequence is the moment it was - * last updated, so one long turn owns every record it produced: a page of - * history can be nothing but more records of the turn that is already on - * screen. Reading exactly one page per request then looks like "history loaded" - * while the transcript above stayed the same. The budget keeps that walk bounded - * (a request is a user gesture, not an unbounded download); the next request - * continues from where this one stopped. Mirrors `MAX_HISTORY_PAGES_PER_REQUEST` - * in the shared core transport. - */ -export const MAX_HISTORY_PAGES_PER_REQUEST: number = 4; - -/** One record as consumed by reducers; `session_id` is the stream id. */ -export interface HostSessionEvent { session_id: string; event: string; payload: Object; } - -export interface HostStreamEventWire { seq: number; event: string; payload: Object; } -/** `RemoteResponse::StreamPage`, flattened, as answered to `read_stream`. */ -export interface HostStreamPage extends CommandStatusResponse { - subscription_id?: string; - stream_id: string; - epoch: number; - events: HostStreamEventWire[]; - has_more: boolean; - cursor: number; - oldest_seq: number; - truncated?: boolean; -} -export interface HostStreamReadRequest { after?: number; before?: number; epoch?: number; } -/** A decrypted `host-stream-changed` device event. */ -export interface HostStreamHint { sourceDeviceId: string; streamId: string; epoch: number; cursor: number; } - -/** Host-facing calls of one stream; production is pairwise-encrypted device RPC. */ -export interface HostSessionSource { - /** Device id of the host whose hints apply to this stream. */ - target: string; - read: (request: HostStreamReadRequest) => Promise; - unsubscribe: () => Promise; - onHint: (listener: (hint: HostStreamHint) => void) => (() => void); - onReconnect: (listener: () => void) => (() => void); -} -export interface HostSessionCallbacks { - onEvent: (event: HostSessionEvent) => Promise; - onCaughtUp: () => Promise; - onResumed?: () => Promise; - onError: (error: Error) => void; - onHistory?: (hasMore: boolean) => void; - /** Local reducer boundary; separate from time spent awaiting the history RPC. */ - onHistoryReplay?: (active: boolean) => void; - onHistoryState?: (loading: boolean, failed: boolean) => void; - /** The host restarted the stream; drop derived state before the latest page is replayed. */ - onGap?: (reason: string) => Promise; -} - -/** Decrypted body of a `device_event` RPC frame. */ -export interface HostStreamHintPlaintext { cmd?: string; event?: string; payload?: HostStreamHintPayload; } -export interface HostStreamHintPayload { stream_id?: string; epoch?: number; cursor?: number; } - -/** Text an older host answers `read_stream` with; there is no capability bit on that path. */ -export function isUnknownStreamCommandRejection(message: string): boolean { - return message.indexOf('invalid RPC command') >= 0 || message.indexOf('unknown variant') >= 0 || - message.indexOf('Could not parse device command') >= 0; -} - -export class HostStreamUnsupportedError extends Error { - constructor(message: string) { super(message); this.name = 'HostStreamUnsupportedError'; } -} - -/** Parses a decrypted `device_event` plaintext; undefined for anything that is not a stream hint. */ -export function parseHostStreamHint(sourceDeviceId: string, plaintext: HostStreamHintPlaintext): HostStreamHint | undefined { - if (plaintext.cmd !== 'device_event' || plaintext.event !== HOST_STREAM_CHANGED_EVENT) return undefined; - const payload = plaintext.payload; - if (!payload || typeof payload.stream_id !== 'string' || typeof payload.epoch !== 'number' || - typeof payload.cursor !== 'number') return undefined; - return { sourceDeviceId: sourceDeviceId, streamId: payload.stream_id, epoch: payload.epoch, cursor: payload.cursor }; -} - -/** The part of a host record this reader needs: the turn it belongs to. */ -interface HostStreamTurnHeader { turnId?: string; } -interface HostStreamRecordTurn { turn?: HostStreamTurnHeader; } - -/** - * The turn a stream event belongs to, for the reader's "is this older than what - * the caller already has" check. `session-record` payloads always carry - * `turn.turnId`; control events belong to no turn and are ignored. - */ -export function hostStreamEventTurnId(event: HostStreamEventWire): string | undefined { - if (event.event !== 'session-record') return undefined; - const turnId = (event.payload as HostStreamRecordTurn).turn?.turnId; - return typeof turnId === 'string' ? turnId : undefined; -} - -/** Rejects a page the host did not accept and asserts it answers this stream. */ -export function checkHostStreamPage(streamId: string, page: HostStreamPage): HostStreamPage { - if (page.resp === 'error') { - const message = page.message || 'Remote device command failed.'; - if (isUnknownStreamCommandRejection(message)) throw new HostStreamUnsupportedError(message); - throw new Error(message); - } - if (page.resp !== undefined && page.resp !== 'stream_page') throw new Error(`Unexpected stream response: ${page.resp}`); - if (page.stream_id !== streamId || !Number.isSafeInteger(page.epoch) || !Number.isSafeInteger(page.cursor) || - !Array.isArray(page.events) || typeof page.has_more !== 'boolean') throw new Error('Invalid stream page'); - for (const event of page.events) { - if (!Number.isSafeInteger(event.seq) || typeof event.event !== 'string') throw new Error('Invalid stream event'); - } - return page; -} - -/** - * Controller-side reader of one host-owned stream. - * - * Wire contract shared with `remote_connect/host_stream.rs` and the Web - * `HostStream.ts`: every page is read from the online desktop (`read_stream`), - * and the desktop pushes `host-stream-changed` hints naming only the stream, - * its epoch and newest sequence. The relay forwards ciphertext and stores - * nothing; this stream keeps no cache either, so closing it forgets the - * transcript. One reader runs at a time; hints, reconnects, the keepalive and - * history requests share that lane so pages never interleave. - */ -export class HostSessionStream { - private stopped: boolean = false; - private running: boolean = false; - private dirty: boolean = true; - private resumed: boolean = true; - private initialized: boolean = false; - private epoch: number = 0; - private cursor: number = 0; - private oldest: number = 1; - private hasOlder: boolean = false; - private truncated: boolean = false; - /** Turns already emitted to the caller, i.e. already part of the transcript. */ - private emittedTurns: Set = new Set(); - private historyRequested: boolean = false; - private retryTimer: number = -1; - private keepaliveTimer: number = -1; - private retryMs: number = 1000; - private unsubscribeHint: () => void; - private unsubscribeReconnect: () => void; - - private streamId: string; - private source: HostSessionSource; - private callbacks: HostSessionCallbacks; - - constructor(streamId: string, source: HostSessionSource, callbacks: HostSessionCallbacks) { - this.streamId = streamId; - this.source = source; - this.callbacks = callbacks; - this.unsubscribeHint = source.onHint((hint: HostStreamHint) => { - if (hint.sourceDeviceId !== this.source.target || hint.streamId !== this.streamId) return; - if (this.initialized && hint.epoch === this.epoch && hint.cursor <= this.cursor) return; - this.wake(); - }); - this.unsubscribeReconnect = source.onReconnect(() => { this.resumed = true; this.wake(); }); - this.keepaliveTimer = setInterval(() => { this.wake(); }, HOST_STREAM_KEEPALIVE_MS); - this.wake(); - } - - isClosed(): boolean { return this.stopped; } - - close(): void { - if (this.stopped) return; - this.stopped = true; - this.unsubscribeHint(); - this.unsubscribeReconnect(); - if (this.retryTimer !== -1) clearTimeout(this.retryTimer); - if (this.keepaliveTimer !== -1) clearInterval(this.keepaliveTimer); - this.retryTimer = -1; - this.keepaliveTimer = -1; - // Best effort: the host also drops idle subscriptions on its own. - if (this.initialized) this.source.unsubscribe().catch((): void => {}); - } - - loadOlder(): void { - if (this.stopped || !this.hasOlder || this.historyRequested) return; - this.historyRequested = true; - this.callbacks.onHistoryState?.(true, false); - if (!this.running) void this.catchUp(); - } - - wake(): void { - if (this.stopped) return; - this.dirty = true; - if (this.retryTimer !== -1) { clearTimeout(this.retryTimer); this.retryTimer = -1; } - if (!this.running) void this.catchUp(); - } - - private async read(request: HostStreamReadRequest): Promise { - let page: HostStreamPage; - try { - page = await this.source.read(request); - } catch (error) { - // The transport surfaces the host's `resp: 'error'` as a thrown Error; - // an older host rejects `read_stream` as an unknown command there. - const failure = error instanceof Error ? error : new Error(String(error)); - if (isUnknownStreamCommandRejection(failure.message)) throw new HostStreamUnsupportedError(failure.message); - throw failure; - } - return checkHostStreamPage(this.streamId, page); - } - - private async emitPage(page: HostStreamPage): Promise { - for (const event of page.events) { - if (this.stopped) return; - await this.callbacks.onEvent({ session_id: this.streamId, event: event.event, payload: event.payload }); - const turnId = hostStreamEventTurnId(event); - if (turnId !== undefined) this.emittedTurns.add(turnId); - } - } - - /** Latest page first, like opening a chat at its bottom. */ - private async resync(): Promise { - const page = await this.read({}); - if (this.stopped) return; - this.epoch = page.epoch; - this.cursor = page.cursor; - this.oldest = page.events.length > 0 ? page.events[0].seq : page.cursor + 1; - this.hasOlder = page.has_more; - this.truncated = page.truncated === true; - this.initialized = true; - await this.emitPage(page); - this.callbacks.onHistory?.(this.hasOlder); - } - - /** False when the host restarted the stream and a resync is required. */ - private async forward(): Promise { - while (!this.stopped) { - const page = await this.read({ after: this.cursor, epoch: this.epoch }); - if (this.stopped) return true; - if (page.epoch !== this.epoch) return false; - await this.emitPage(page); - if (page.events.length > 0) this.cursor = Math.max(this.cursor, page.events[page.events.length - 1].seq); - if (!page.has_more) { - // The newest sequence may belong to an evicted control event; adopt it - // so the next hint compares against the host's view. - this.cursor = Math.max(this.cursor, page.cursor); - return true; - } - } - return true; - } - - private async gap(): Promise { - await this.callbacks.onGap?.('host stream restarted'); - } - - private async older(): Promise { - let pages = 0; - try { - while (this.hasOlder && pages < MAX_HISTORY_PAGES_PER_REQUEST && !this.stopped) { - const before = this.oldest; - RemoteLogger.info(`history page request stream=${this.streamId} before=${before} epoch=${this.epoch}`); - const page = await this.read({ before: before, epoch: this.epoch }); - RemoteLogger.info(`history page received stream=${this.streamId} before=${before} events=${page.events.length} first=${page.events[0]?.seq} hasMore=${page.has_more} epoch=${page.epoch}`); - if (this.stopped) return; - if (page.epoch !== this.epoch) { - await this.gap(); - await this.resync(); - throw new Error('Session history restarted on the host; reloaded from its latest page'); - } - // A page that only repeats turns the transcript already has is not - // progress: keep reading until the caller gets an older turn, the host - // runs out of history, or this request's budget is spent. - const showsAnOlderTurn = page.events.some((event) => { - const turnId = hostStreamEventTurnId(event); - return turnId !== undefined && !this.emittedTurns.has(turnId); - }); - if (pages === 0) this.callbacks.onHistoryReplay?.(true); - await this.emitPage(page); - if (page.events.length > 0) this.oldest = page.events[0].seq; - this.hasOlder = page.has_more; - this.truncated = page.truncated === true; - pages++; - if (showsAnOlderTurn) break; - } - } finally { - if (pages > 0) this.callbacks.onHistory?.(this.hasOlder); - this.callbacks.onHistoryReplay?.(false); - } - } - - private async catchUp(): Promise { - this.running = true; - try { - while ((this.dirty || this.historyRequested) && !this.stopped) { - if (this.dirty) { - this.dirty = false; - if (this.resumed && this.initialized) { await this.callbacks.onResumed?.(); } - if (!this.initialized) { - await this.resync(); - } else if (!(await this.forward())) { - await this.gap(); - await this.resync(); - } - if (this.stopped) return; - this.resumed = false; - await this.callbacks.onCaughtUp(); - } - if (this.historyRequested && !this.stopped) { - await this.older(); this.historyRequested = false; - this.callbacks.onHistoryState?.(false, false); - } - this.retryMs = 1000; - } - } catch (error) { - if (this.stopped) return; - if (this.historyRequested) { this.historyRequested = false; this.callbacks.onHistoryState?.(false, true); } - if (error instanceof HostStreamUnsupportedError) { - // Nothing on this side can make an older host answer; stop instead of - // polling it every 30 seconds. - this.callbacks.onError(error as Error); - this.close(); - return; - } - this.dirty = true; - this.callbacks.onError(error as Error); - this.retryTimer = setTimeout(() => { this.retryTimer = -1; this.wake(); }, this.retryMs); - this.retryMs = Math.min(this.retryMs * 2, 30000); - } finally { - this.running = false; - if ((this.dirty || this.historyRequested) && !this.stopped && this.retryTimer === -1) void this.catchUp(); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ImagePickerService.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ImagePickerService.ets deleted file mode 100644 index 137b1f7be7..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ImagePickerService.ets +++ /dev/null @@ -1,268 +0,0 @@ -import fs from '@ohos.file.fs'; -import image from '@ohos.multimedia.image'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -import util from '@ohos.util'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { OhosError } from './OhosError'; -import { RemoteLogger } from './RemoteLogger'; -import { RemoteImageContext, SelectedImageAttachment } from '../model/RemoteModels'; - -interface ImageMetadata { - name: string; - size: number; - source_uri: string; -} - -interface EncodedImage { - bytes: Uint8Array; - mimeType: string; - compressed: boolean; -} - -interface ImageSize { - width: number; - height: number; -} - -export class ImagePickerService { - private readonly maxImageBytes: number = 4 * 1024 * 1024; - /** - * What an image is allowed to weigh on the wire. A picture travels as base64 - * inside an encrypted, base64-wrapped command, so it reaches the relay at - * roughly 1.8× its byte size — a budget in the hundreds of KB is what keeps a - * phone photo inside a request the relay will accept. - */ - private readonly transportImageBudgetBytes: number = 800 * 1024; - private readonly maxImageDimension: number = 1600; - private readonly compressionQualities: number[] = [82, 72, 62, 50]; - - async pickImages(maxCount: number, existingCount: number): Promise { - const remaining = Math.max(0, maxCount - existingCount); - if (remaining === 0) { - return []; - } - - const options = new photoAccessHelper.PhotoSelectOptions(); - options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; - options.maxSelectNumber = remaining; - options.isOriginalSupported = false; - - const picker = new photoAccessHelper.PhotoViewPicker(); - let result: photoAccessHelper.PhotoSelectResult; - try { - result = await picker.select(options); - } catch (err) { - throw OhosError.wrap('image picker select', err); - } - const uris = result.photoUris || []; - const selected: SelectedImageAttachment[] = []; - for (let index = 0; index < uris.length; index += 1) { - selected.push(await this.readImage(uris[index], index)); - } - return selected; - } - - toRemoteContexts(images: SelectedImageAttachment[]): RemoteImageContext[] { - return images.map((attachment: SelectedImageAttachment) => { - const metadata: ImageMetadata = { - name: attachment.name, - size: attachment.size, - source_uri: attachment.uri - }; - const context: RemoteImageContext = { - id: attachment.id, - data_url: attachment.data_url, - mime_type: attachment.mime_type, - metadata - }; - return context; - }); - } - - private async readImage(uri: string, index: number): Promise { - let originalSize = 0; - try { - originalSize = fs.statSync(uri).size; - } catch (err) { - throw OhosError.wrap('image stat', err); - } - const encoded = await this.encodeImage(uri, originalSize); - if (encoded.bytes.length > this.maxImageBytes) { - throw new Error(RemoteI18n.f('errors.imageTooLargeAfterCompression', `${Math.round(this.maxImageBytes / 1024 / 1024)}`)); - } - - let base64 = ''; - try { - base64 = new util.Base64Helper().encodeToStringSync(encoded.bytes); - } catch (err) { - throw OhosError.wrap('image base64 encode', err); - } - const name = this.imageName(uri, index); - RemoteLogger.info(`image picked original=${originalSize} encoded=${encoded.bytes.length} compressed=${encoded.compressed ? '1' : '0'} mime=${encoded.mimeType}`); - return { - id: `harmony-image-${Date.now()}-${index}`, - uri, - name, - data_url: `data:${encoded.mimeType};base64,${base64}`, - mime_type: encoded.mimeType, - size: encoded.bytes.length, - original_size: originalSize, - compressed: encoded.compressed - }; - } - - private async encodeImage(uri: string, originalSize: number): Promise { - // Photo picker URIs do not reliably carry a file extension or MIME type. - // Decode on the device so HEIC and other camera formats become actual JPEG. - if (originalSize <= this.transportImageBudgetBytes && /\.(png|jpe?g|gif|webp)(\?|$)/i.test(uri)) { - return this.readOriginalImage(uri, originalSize); - } - - try { - return await this.compressImage(uri, originalSize); - } catch (_err) { - throw new Error(RemoteI18n.t('errors.imageCompressionFailed')); - } - } - - private readOriginalImage(uri: string, originalSize: number): EncodedImage { - let file: fs.File | undefined = undefined; - try { - file = fs.openSync(uri); - const buffer = new ArrayBuffer(originalSize); - const readSize = fs.readSync(file.fd, buffer, { length: originalSize }); - const bytes = new Uint8Array(buffer); - const payload = readSize === bytes.length ? bytes : bytes.slice(0, readSize); - return { - bytes: payload, - mimeType: this.inferMimeType(uri), - compressed: false - }; - } catch (err) { - throw OhosError.wrap('image read original', err); - } finally { - if (file) { - try { - fs.closeSync(file); - } catch (closeErr) { - throw OhosError.wrap('image close original', closeErr); - } - } - } - } - - private async compressImage(uri: string, originalSize: number): Promise { - let file: fs.File | undefined = undefined; - let source: image.ImageSource | undefined = undefined; - let pixelMap: image.PixelMap | undefined = undefined; - let packer: image.ImagePacker | undefined = undefined; - - try { - file = fs.openSync(uri); - source = image.createImageSource(file.fd); - const info = await source.getImageInfo(); - const targetSize = this.targetSize(info.size.width, info.size.height); - pixelMap = await source.createPixelMap({ desiredSize: targetSize }); - - packer = image.createImagePacker(); - for (let index = 0; index < this.compressionQualities.length; index += 1) { - const packed = await packer.packToData(pixelMap, { - format: 'image/jpeg', - quality: this.compressionQualities[index], - bufferSize: this.maxImageBytes + 1024 * 1024 - }); - const bytes = new Uint8Array(packed); - if (bytes.length <= this.transportImageBudgetBytes) { - return { - bytes, - mimeType: 'image/jpeg', - compressed: true - }; - } - } - - throw new Error(RemoteI18n.t('errors.imageCompressionFailed')); - } catch (err) { - throw OhosError.wrap('image compress', err); - } finally { - await this.releasePacker(packer); - await this.releasePixelMap(pixelMap); - await this.releaseSource(source); - if (file) { - try { - fs.closeSync(file); - } catch (closeErr) { - throw OhosError.wrap('image close compressed', closeErr); - } - } - } - } - - private targetSize(width: number, height: number): ImageSize { - const longest = Math.max(width, height); - if (longest <= this.maxImageDimension || longest <= 0) { - return { width, height }; - } - - const ratio = this.maxImageDimension / longest; - return { - width: Math.max(1, Math.round(width * ratio)), - height: Math.max(1, Math.round(height * ratio)) - }; - } - - private async releaseSource(source: image.ImageSource | undefined): Promise { - if (!source) { - return; - } - try { - await source.release(); - } catch (_err) { - } - } - - private async releasePixelMap(pixelMap: image.PixelMap | undefined): Promise { - if (!pixelMap) { - return; - } - try { - await pixelMap.release(); - } catch (_err) { - } - } - - private async releasePacker(packer: image.ImagePacker | undefined): Promise { - if (!packer) { - return; - } - try { - await packer.release(); - } catch (_err) { - } - } - - private inferMimeType(uri: string): string { - const lower = uri.toLowerCase(); - if (lower.indexOf('.png') >= 0) { - return 'image/png'; - } - if (lower.indexOf('.webp') >= 0) { - return 'image/webp'; - } - if (lower.indexOf('.gif') >= 0) { - return 'image/gif'; - } - return 'image/jpeg'; - } - - private imageName(uri: string, index: number): string { - const cleanUri = uri.split('?')[0]; - const parts = cleanUri.replace(/\\/g, '/').split('/'); - const raw = parts[parts.length - 1] || `image-${index + 1}`; - try { - return decodeURIComponent(raw); - } catch (_err) { - return raw; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/InteractionMailboxStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/InteractionMailboxStore.ets deleted file mode 100644 index 235211a06c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/InteractionMailboxStore.ets +++ /dev/null @@ -1,121 +0,0 @@ -import { - InteractionMailboxAction, InteractionMailboxActionType, InteractionMailboxState, - PendingPermission, PendingQuestion, SessionInteractionMailbox -} from '../model/InteractionMailbox'; -import { RemoteSessionManager } from './RemoteSessionManager'; - -interface MailboxRequest { sessionId: string; } -interface MailboxArgs { request: MailboxRequest; } -interface PermissionReply { requestId: string; reply: string; updatedInput?: Object; } -interface PermissionReplyArgs { request: PermissionReply; } - -/** The runtime mailbox owns approval and question state, never transcript events. */ -export class InteractionMailboxStore { - private client: RemoteSessionManager; - private onChange: (state: InteractionMailboxState) => void; - private state: InteractionMailboxState = new InteractionMailboxState(); - private epoch: number = 0; - private version: number = 0; - private read?: Promise; - private interacting: Set = new Set(); - - constructor(client: RemoteSessionManager, onChange: (state: InteractionMailboxState) => void) { - this.client = client; this.onChange = onChange; - } - - select(sessionId: string): void { - this.epoch++; this.version++; this.read = undefined; this.interacting.clear(); - this.state = new InteractionMailboxState(); this.state.sessionId = sessionId; - this.publish(); - } - - refresh(): Promise { - if (!this.state.sessionId) return Promise.resolve(); - this.version++; - if (this.read) return this.read; - const epoch = this.epoch; - const read = this.load(epoch).finally(() => { if (this.read === read) this.read = undefined; }); - this.read = read; - return read; - } - - private async load(epoch: number): Promise { - const sessionId = this.state.sessionId; - try { - while (epoch === this.epoch) { - const version = this.version; - const args: MailboxArgs = { request: { sessionId } }; - let snapshot: SessionInteractionMailbox; - try { - snapshot = await this.client.hostInvoke('get_session_interaction_mailbox', args); - } catch (error) { - if (epoch !== this.epoch) return; - // A newer invalidation owns the next read even if this request fails. - if (version !== this.version) continue; - throw error as Error; - } - if (epoch !== this.epoch) return; - if (version !== this.version) continue; - if (snapshot.sessionId !== sessionId || !Array.isArray(snapshot.permissions?.requests) || - !Array.isArray(snapshot.userQuestions?.questions)) throw new Error('Interaction mailbox session or payload mismatch'); - this.state.requests = snapshot.permissions.requests.filter((request: PendingPermission): boolean => request.sessionId === sessionId); - this.state.questions = snapshot.userQuestions.questions.filter((question: PendingQuestion): boolean => question.sessionId === sessionId); - const owned = new Set(this.state.ownedToolIds); - this.state.questions.forEach((question: PendingQuestion): void => { owned.add(question.toolId); }); - this.state.requests.forEach((request: PendingPermission): void => { if (request.toolCallId) owned.add(request.toolCallId); }); - this.state.ownedToolIds = Array.from(owned); - this.state.failure = ''; this.publish(); return; - } - } catch (_error) { - if (epoch === this.epoch) { this.state.failure = 'load'; this.publish(); } - } - } - - async dispatch(action: InteractionMailboxAction): Promise { - if (!action.sessionId || action.sessionId !== this.state.sessionId) return; - if (action.type === InteractionMailboxActionType.Refresh) { await this.refresh(); return; } - const id = action.id || ''; - const permission = action.type === InteractionMailboxActionType.Approve || action.type === InteractionMailboxActionType.Reject; - if (permission ? !this.state.requests.some((item: PendingPermission): boolean => item.requestId === id) : - !this.state.questions.some((item: PendingQuestion): boolean => item.toolId === id)) return; - const epoch = this.epoch; - if (action.type === InteractionMailboxActionType.StartQuestion) { - if (this.interacting.has(id)) return; - this.interacting.add(id); - try { await this.client.startQuestionInteraction(action.sessionId, id); } - catch (_error) { if (epoch === this.epoch) { this.interacting.delete(id); this.state.failure = 'reply'; this.publish(); } } - return; - } - if (this.state.busy) return; - this.state.busy = true; this.state.failure = ''; this.publish(); - try { - if (permission) { - // Rejection never consumes an approval draft, including an invalid one. - const input = action.type === InteractionMailboxActionType.Approve ? action.updatedInput : undefined; - if (input !== undefined && (input === null || typeof input !== 'object' || Array.isArray(input))) { - throw new Error('Permission input must be a JSON object'); - } - const args: PermissionReplyArgs = { request: { requestId: id, - reply: action.type === InteractionMailboxActionType.Approve ? 'once' : 'reject', - updatedInput: action.type === InteractionMailboxActionType.Approve ? input : undefined } }; - await this.client.hostInvoke('respond_permission', args); - } else if (action.type === InteractionMailboxActionType.Answer && action.answers) { - await this.client.answerQuestion(id, action.answers); - } else return; - if (epoch === this.epoch) await this.refresh(); - } catch (_error) { - if (epoch === this.epoch) { this.state.failure = 'reply'; this.publish(); } - } finally { - if (epoch === this.epoch) { this.state.busy = false; this.publish(); } - } - } - - private publish(): void { - const snapshot = new InteractionMailboxState(); - snapshot.sessionId = this.state.sessionId; - snapshot.requests = this.state.requests.slice(); snapshot.questions = this.state.questions.slice(); - snapshot.ownedToolIds = this.state.ownedToolIds.slice(); - snapshot.busy = this.state.busy; snapshot.failure = this.state.failure; - this.onChange(snapshot); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/KeyboardReleaseService.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/KeyboardReleaseService.ets deleted file mode 100644 index adea20ea0e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/KeyboardReleaseService.ets +++ /dev/null @@ -1,45 +0,0 @@ -import { Context } from '@kit.AbilityKit'; -import { inputMethod } from '@kit.IMEKit'; -import { window } from '@kit.ArkUI'; - -/** Platform adapter for dismissing the IME without leaving callers waiting forever. */ -export class KeyboardReleaseService { - static async release(context: Context, timeoutMs: number = 500): Promise { - try { - const appWindow = await window.getLastWindow(context); - const keyboardArea = appWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD); - if (!keyboardArea.visible) { - return; - } - - await new Promise((resolve) => { - let completed = false; - let timeoutId: number = -1; - let onKeyboardDidHide: (keyboardInfo: window.KeyboardInfo) => void = - (_keyboardInfo: window.KeyboardInfo): void => {}; - const finish = (): void => { - if (completed) { - return; - } - completed = true; - appWindow.off('keyboardDidHide', onKeyboardDidHide); - if (timeoutId >= 0) { - clearTimeout(timeoutId); - } - resolve(); - }; - onKeyboardDidHide = (_keyboardInfo: window.KeyboardInfo): void => { - finish(); - }; - - appWindow.on('keyboardDidHide', onKeyboardDidHide); - timeoutId = setTimeout(finish, timeoutMs); - inputMethod.getController().hideTextInput().catch((_err: Object) => { - finish(); - }); - }); - } catch (_err) { - // Releasing the keyboard is best effort and must never block message submission. - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/LegacyWorkspaceCompatibility.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/LegacyWorkspaceCompatibility.ets deleted file mode 100644 index d38f9f01e4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/LegacyWorkspaceCompatibility.ets +++ /dev/null @@ -1,55 +0,0 @@ -import { RemoteWorkspaceIdentity } from '../model/RemoteModels'; - -/** - * Upgrade-only conversion for pre-ID caches and host projections. - * - * Paths are not workspace keys. New state and commands retain `workspaceId`; - * this is the single place where a reference without one may be attributed to - * a catalog record. Mirrors the Kotlin `LegacyWorkspaceCompatibility.resolve` - * and the Rust `resolve_legacy_workspace_reference`: - * - an explicit ID is authoritative and never falls back to a path; - * - a unique path match adopts the record; - * - an ambiguous path stays unresolved; - * - `localhost` without a saved connection is a 1.0.0 local marker, not a host. - * - * Remove when all supported caches have migrated and every peer negotiates - * `workspace_id_references_v1`. - */ -export class LegacyWorkspaceCompatibility { - static resolve( - reference: RemoteWorkspaceIdentity, - catalog: RemoteWorkspaceIdentity[] - ): RemoteWorkspaceIdentity | undefined { - const workspaceId = (reference.workspaceId || '').trim(); - if (workspaceId.length > 0) { - // Two catalog rows sharing an ID is a corrupt catalog; refusing is the only safe answer. - const byId = catalog.filter((candidate: RemoteWorkspaceIdentity): boolean => - candidate.workspaceId === workspaceId); - return byId.length === 1 ? byId[0] : undefined; - } - const root = LegacyWorkspaceCompatibility.normalizeRoot(reference.path); - const connectionId = (reference.remoteConnectionId || '').trim(); - const sshHost = (reference.remoteSshHost || '').trim(); - const localMarker = connectionId.length === 0 && sshHost === 'localhost'; - const matches = catalog.filter((candidate: RemoteWorkspaceIdentity): boolean => { - if (LegacyWorkspaceCompatibility.normalizeRoot(candidate.path) !== root) { - return false; - } - if (connectionId.length > 0 && (candidate.remoteConnectionId || '').trim() !== connectionId) { - return false; - } - if (sshHost.length > 0 && !localMarker && (candidate.remoteSshHost || '').trim() !== sshHost) { - return false; - } - return true; - }); - return matches.length === 1 ? matches[0] : undefined; - } - - /** Trailing separators are not identity; a bare root keeps its slash. */ - private static normalizeRoot(path: string): string { - const trimmed = path.trim(); - const normalized = trimmed.replace(/\/+$/, ''); - return normalized.length > 0 ? normalized : trimmed; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/LocalePreferenceStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/LocalePreferenceStore.ets deleted file mode 100644 index 0ef7cbb43f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/LocalePreferenceStore.ets +++ /dev/null @@ -1,104 +0,0 @@ -import { preferences } from '@kit.ArkData'; -import { i18n } from '@kit.LocalizationKit'; -import { AppLocale } from '../i18n/AppLocale'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; -import { OhosError } from './OhosError'; -import { RemoteLogger } from './RemoteLogger'; - -const STORE_NAME = HarmonyUpgradeIdentityContract.APP_LOCALE_STORE; -const LANGUAGE_KEY = 'language'; - -export interface LocaleSystemHost { - readSystemLanguage(): string; - applyPreferredLanguage(language: string): void; -} - -export class DefaultLocaleSystemHost implements LocaleSystemHost { - readSystemLanguage(): string { - try { - const preferred = i18n.System.getAppPreferredLanguage(); - if (preferred && preferred.length > 0 && preferred !== 'default') { - return preferred; - } - } catch (_err) { - // Fall through to the system language. - } - try { - return i18n.System.getSystemLanguage() || ''; - } catch (_err) { - return ''; - } - } - - applyPreferredLanguage(language: string): void { - try { - i18n.System.setAppPreferredLanguage(AppLocale.systemLanguageTag(language)); - } catch (err) { - RemoteLogger.warn(`app preferred language update failed: ${err instanceof Error ? err.message : String(err)}`); - } - } -} - -export class LocalePreferenceStore { - private store?: preferences.Preferences; - private readonly systemHost: LocaleSystemHost; - - constructor(systemHost: LocaleSystemHost = new DefaultLocaleSystemHost()) { - this.systemHost = systemHost; - } - - async init(context: Context): Promise { - try { - this.store = await preferences.getPreferences(context, STORE_NAME); - } catch (err) { - throw OhosError.wrap('locale preference init', err); - } - const stored = await this.getString(LANGUAGE_KEY); - const detected = AppLocale.initial(stored, this.systemHost.readSystemLanguage()); - return this.apply(detected, AppLocale.resolve(stored).length === 0); - } - - async save(language: string): Promise { - return this.apply(AppLocale.resolve(language) || AppLocale.DEFAULT, true); - } - - current(): string { - return RemoteI18n.language(); - } - - private async apply(language: string, persist: boolean): Promise { - const resolved = RemoteI18n.setLanguage(language); - this.systemHost.applyPreferredLanguage(resolved); - if (persist) { - await this.putString(LANGUAGE_KEY, resolved); - } - return resolved; - } - - private async getString(key: string): Promise { - const store = this.store; - if (!store) { - return ''; - } - try { - const value = await store.get(key, ''); - return typeof value === 'string' ? value : ''; - } catch (err) { - throw OhosError.wrap('locale preference read', err); - } - } - - private async putString(key: string, value: string): Promise { - const store = this.store; - if (!store) { - throw new Error('Locale preference store is not initialized.'); - } - try { - await store.put(key, value); - await store.flush(); - } catch (err) { - throw OhosError.wrap('locale preference write', err); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MainThreadStallProbe.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MainThreadStallProbe.ets deleted file mode 100644 index c0c5a6f66f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MainThreadStallProbe.ets +++ /dev/null @@ -1,58 +0,0 @@ -import { RemoteLogger } from './RemoteLogger'; - -const TICK_MS = 250; -const REPORT_THRESHOLD_MS = 400; - -/** - * Tells a blocked main thread apart from a deferred frame. - * - * A fixed-interval timer whose own lateness is the measurement: the tick is - * trivial, so anything it arrives late by was spent by somebody else holding - * the JS thread. Without this, a log line that lands 1.6s after the state - * write behind it reads the same either way — the thread was busy, or ArkUI - * simply had not painted yet — and those two want opposite fixes. - * - * Armed for a window rather than left running, so nothing pays 4Hz for a - * measurement that only matters around an event someone asked about. - */ -export class MainThreadStallProbe { - private static timerId: number = 0; - private static deadline: number = 0; - private static expectedAt: number = 0; - private static reason: string = ''; - - /** Watches for `windowMs`, restarting the window if one is already open. */ - static watch(reason: string, windowMs: number): void { - MainThreadStallProbe.reason = reason; - MainThreadStallProbe.deadline = Date.now() + windowMs; - if (MainThreadStallProbe.timerId !== 0) { - return; - } - MainThreadStallProbe.arm(); - } - - static stop(): void { - if (MainThreadStallProbe.timerId !== 0) { - clearTimeout(MainThreadStallProbe.timerId); - MainThreadStallProbe.timerId = 0; - } - MainThreadStallProbe.deadline = 0; - } - - private static arm(): void { - MainThreadStallProbe.expectedAt = Date.now() + TICK_MS; - MainThreadStallProbe.timerId = setTimeout(() => { - MainThreadStallProbe.timerId = 0; - const now = Date.now(); - const late = now - MainThreadStallProbe.expectedAt; - if (late >= REPORT_THRESHOLD_MS) { - RemoteLogger.info(`main thread stall reason=${MainThreadStallProbe.reason} blocked_ms=${late}`); - } - if (now >= MainThreadStallProbe.deadline) { - MainThreadStallProbe.deadline = 0; - return; - } - MainThreadStallProbe.arm(); - }, TICK_MS); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownHtmlSerializer.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownHtmlSerializer.ets deleted file mode 100644 index 94b2f86647..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownHtmlSerializer.ets +++ /dev/null @@ -1,262 +0,0 @@ -import { - MarkdownParser, - ParsedMarkdownBlock, - ParsedMarkdownInline, - ParsedMarkdownListItem, - ParsedMarkdownTableCell, - ParsedMarkdownTableRow -} from './MarkdownParser'; - -const SAFE_LINK_SCHEME: RegExp = /^(https?:|computer:|file:)/i; -const ORDERED_MARKER: RegExp = /^\d+\.$/; -const CHECKED_PREFIX: string = ' '; -const UNCHECKED_PREFIX: string = ' '; - -/** One open list element while a parsed list block is being serialized. */ -class HtmlListLevel { - depth: number = 0; - ordered: boolean = false; - itemOpen: boolean = false; - - constructor(depth: number, ordered: boolean) { - this.depth = depth; - this.ordered = ordered; - } -} - -/** - * Renders the parsed Markdown tree as the HTML flavor of a rich clipboard - * payload. Pure string work over `ParsedMarkdownBlock[]`: it never touches the - * UI, the pasteboard, or a platform kit, so the host runner can exercise the - * real source and the clipboard owner only has to move the string. - * - * Every text node and attribute value is escaped, and links are limited to an - * allowlisted scheme so a hostile document cannot smuggle markup or a script - * URL into whatever receives the paste. - */ -export class MarkdownHtmlSerializer { - /** Parses `text` and serializes it. Blank input produces an empty payload. */ - static toHtml(text: string): string { - if (text.trim().length === 0) { - return ''; - } - return MarkdownHtmlSerializer.blocksToHtml(MarkdownParser.parse(text)); - } - - static blocksToHtml(blocks: ParsedMarkdownBlock[]): string { - let html = ''; - for (let index = 0; index < blocks.length; index += 1) { - html += MarkdownHtmlSerializer.blockHtml(blocks[index]); - } - return html; - } - - private static blockHtml(block: ParsedMarkdownBlock): string { - if (block.type === 'heading') { - return MarkdownHtmlSerializer.headingHtml(block); - } - if (block.type === 'quote') { - return MarkdownHtmlSerializer.quoteHtml(block); - } - if (block.type === 'list') { - return MarkdownHtmlSerializer.listHtml(block); - } - if (block.type === 'table') { - return MarkdownHtmlSerializer.tableHtml(block); - } - if (block.type === 'code') { - return MarkdownHtmlSerializer.codeHtml(block); - } - if (block.type === 'divider') { - return '
'; - } - if (block.type === 'frontmatter') { - return `
${MarkdownHtmlSerializer.escape(block.text)}
`; - } - return MarkdownHtmlSerializer.paragraphHtml(block); - } - - private static headingHtml(block: ParsedMarkdownBlock): string { - const level = block.level < 1 ? 1 : (block.level > 6 ? 6 : block.level); - const content = MarkdownHtmlSerializer.inlineHtml(block.inlines, block.text); - return `${content}`; - } - - private static paragraphHtml(block: ParsedMarkdownBlock): string { - const content = MarkdownHtmlSerializer.inlineHtml(block.inlines, block.text); - if (content.length === 0) { - return ''; - } - return `

${content}

`; - } - - /** - * The parser reports the quote depth it consumed, so a nested quote becomes a - * nested element rather than a repeated sibling. - */ - private static quoteHtml(block: ParsedMarkdownBlock): string { - const level = block.level < 1 ? 1 : block.level; - const content = MarkdownHtmlSerializer.inlineHtml(block.inlines, block.text); - return '
'.repeat(level) + content + '
'.repeat(level); - } - - private static codeHtml(block: ParsedMarkdownBlock): string { - const body = MarkdownHtmlSerializer.escape(block.text); - if (block.language.length === 0) { - return `
${body}
`; - } - const language = MarkdownHtmlSerializer.escape(block.language); - return `
${body}
`; - } - - /** - * List items carry their own depth and marker, so one flat sequence still - * renders as nested `ul`/`ol` and swings between both list elements when the - * source mixes markers at the same level. - */ - private static listHtml(block: ParsedMarkdownBlock): string { - const items = block.items; - if (items.length === 0) { - return ''; - } - const levels: HtmlListLevel[] = []; - let html = ''; - for (let index = 0; index < items.length; index += 1) { - const item = items[index]; - const depth = item.depth > 0 ? item.depth : 0; - const ordered = ORDERED_MARKER.test(item.marker); - - while (levels.length > depth + 1) { - html += MarkdownHtmlSerializer.closeLevel(levels); - } - if (levels.length === 0) { - html += MarkdownHtmlSerializer.openLevel(levels, depth, ordered); - } else if (levels[levels.length - 1].depth < depth) { - while (levels.length < depth + 1) { - html += MarkdownHtmlSerializer.openLevel(levels, levels.length, ordered); - } - } else if (levels[levels.length - 1].ordered !== ordered) { - html += MarkdownHtmlSerializer.closeLevel(levels); - html += MarkdownHtmlSerializer.openLevel(levels, depth, ordered); - } - - const level = levels[levels.length - 1]; - if (level.itemOpen) { - html += ''; - level.itemOpen = false; - } - level.itemOpen = true; - html += '
  • '; - html += MarkdownHtmlSerializer.listItemContent(item); - } - while (levels.length > 0) { - html += MarkdownHtmlSerializer.closeLevel(levels); - } - return html; - } - - private static listItemContent(item: ParsedMarkdownListItem): string { - const content = MarkdownHtmlSerializer.inlineHtml(item.inlines, item.text); - if (item.checked === 1) { - return CHECKED_PREFIX + content; - } - if (item.checked === 0) { - return UNCHECKED_PREFIX + content; - } - return content; - } - - private static openLevel(levels: HtmlListLevel[], depth: number, ordered: boolean): string { - levels[levels.length] = new HtmlListLevel(depth, ordered); - return ordered ? '
      ' : '
        '; - } - - private static closeLevel(levels: HtmlListLevel[]): string { - const level = levels[levels.length - 1]; - let html = ''; - if (level.itemOpen) { - html += ''; - level.itemOpen = false; - } - html += level.ordered ? '
    ' : ''; - levels.splice(levels.length - 1, 1); - return html; - } - - private static tableHtml(block: ParsedMarkdownBlock): string { - const rows = block.tableRows; - let head = ''; - let body = ''; - for (let index = 0; index < rows.length; index += 1) { - const row = rows[index]; - if (row.header) { - head += MarkdownHtmlSerializer.tableRowHtml(row); - } else { - body += MarkdownHtmlSerializer.tableRowHtml(row); - } - } - return `${head}${body}
    `; - } - - private static tableRowHtml(row: ParsedMarkdownTableRow): string { - const tag = row.header ? 'th' : 'td'; - let cells = ''; - for (let index = 0; index < row.cells.length; index += 1) { - const cell: ParsedMarkdownTableCell = row.cells[index]; - const style = MarkdownHtmlSerializer.alignmentStyle(cell.alignment); - const content = MarkdownHtmlSerializer.inlineHtml(cell.inlines, cell.text); - cells += `<${tag}${style}>${content}`; - } - return `${cells}`; - } - - private static alignmentStyle(alignment: string): string { - if (alignment === 'center' || alignment === 'right') { - return ` style="text-align: ${alignment}"`; - } - return ''; - } - - private static inlineHtml(inlines: ParsedMarkdownInline[], fallback: string): string { - if (inlines.length === 0) { - return MarkdownHtmlSerializer.escape(fallback); - } - let html = ''; - for (let index = 0; index < inlines.length; index += 1) { - html += MarkdownHtmlSerializer.inlineNodeHtml(inlines[index]); - } - return html; - } - - private static inlineNodeHtml(inline: ParsedMarkdownInline): string { - const text = MarkdownHtmlSerializer.escape(inline.text); - if (inline.type === 'strong') { - return `${text}`; - } - if (inline.type === 'emphasis') { - return `${text}`; - } - if (inline.type === 'code') { - return `${text}`; - } - if (inline.type === 'delete') { - return `${text}`; - } - if (inline.type === 'link') { - if (!SAFE_LINK_SCHEME.test(inline.url)) { - return text; - } - return `${text}`; - } - return text; - } - - /** Escapes `&`, `<`, `>` and `"` for both text nodes and attribute values. */ - private static escape(value: string): string { - return value - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets deleted file mode 100644 index 52a39ad200..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MarkdownParser.ets +++ /dev/null @@ -1,789 +0,0 @@ -export interface ParsedMarkdownInline { - id: string; - type: string; - text: string; - url: string; -} - -export interface ParsedMarkdownListItem { - id: string; - marker: string; - text: string; - inlines: ParsedMarkdownInline[]; - depth: number; - checked: number; -} - -export interface ParsedMarkdownTableCell { - id: string; - text: string; - inlines: ParsedMarkdownInline[]; - alignment: string; -} - -export interface ParsedMarkdownTableRow { - id: string; - header: boolean; - cells: ParsedMarkdownTableCell[]; -} - -export interface ParsedMarkdownBlock { - id: string; - renderKey: string; - type: string; - level: number; - language: string; - text: string; - items: ParsedMarkdownListItem[]; - inlines: ParsedMarkdownInline[]; - tableRows: ParsedMarkdownTableRow[]; -} - -export class MarkdownParseCache { - private text: string = ''; - private blocks: ParsedMarkdownBlock[] = []; - private initialized: boolean = false; - - blocksFor(text: string): ParsedMarkdownBlock[] { - if (this.initialized && this.text === text) { - return this.blocks; - } - this.text = text; - this.blocks = MarkdownParser.parse(text); - this.initialized = true; - return this.blocks; - } -} - -export class MarkdownParser { - static parse(text: string): ParsedMarkdownBlock[] { - const lines = text.replace(/\r\n/g, '\n').split('\n'); - const blocks: ParsedMarkdownBlock[] = []; - let index = 0; - const frontmatterEnd = MarkdownParser.frontmatterEnd(lines); - if (frontmatterEnd > 0) { - MarkdownParser.pushBlock( - blocks, - 'frontmatter', - 0, - '', - lines.slice(1, frontmatterEnd).join('\n').replace(/\s+$/, ''), - [] - ); - index = frontmatterEnd + 1; - } - - while (index < lines.length) { - const raw = lines[index]; - const trimmed = raw.trim(); - if (trimmed.length === 0) { - index += 1; - continue; - } - - if (MarkdownParser.isFence(trimmed)) { - index = MarkdownParser.readCodeBlock(lines, index, blocks); - } else if (MarkdownParser.isSetextHeading(lines, index)) { - const level = /^=+\s*$/.test(lines[index + 1].trim()) ? 1 : 2; - MarkdownParser.pushBlock(blocks, 'heading', level, '', trimmed, []); - index += 2; - } else if (MarkdownParser.isDivider(trimmed)) { - MarkdownParser.pushBlock(blocks, 'divider', 0, '', '', []); - index += 1; - } else if (MarkdownParser.isHeading(trimmed)) { - const level = MarkdownParser.headingLevel(trimmed); - const headingText = trimmed.slice(level).trim().replace(/\s+#+\s*$/, ''); - MarkdownParser.pushBlock(blocks, 'heading', level, '', headingText, []); - index += 1; - } else if (MarkdownParser.isQuote(trimmed)) { - index = MarkdownParser.readQuoteBlock(lines, index, blocks); - } else if (MarkdownParser.isListLine(trimmed)) { - index = MarkdownParser.readListBlock(lines, index, blocks); - } else if (MarkdownParser.isTableStart(lines, index)) { - index = MarkdownParser.readTableBlock(lines, index, blocks); - } else { - index = MarkdownParser.readParagraphBlock(lines, index, blocks); - } - } - - if (blocks.length > 0) { - return blocks; - } - MarkdownParser.pushBlock(blocks, 'paragraph', 0, '', text, []); - return blocks; - } - - static formatInlineText(value: string): string { - return MarkdownParser.plainInlineText(MarkdownParser.parseInlineText(value)); - } - - private static plainInlineText(inlines: ParsedMarkdownInline[]): string { - return inlines.map((inline: ParsedMarkdownInline) => { - return inline.type === 'link' && inline.text !== inline.url ? `${inline.text} (${inline.url})` : inline.text; - }).join(''); - } - - private static readCodeBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number { - const opening = lines[start].trim(); - const fence = MarkdownParser.fenceMarker(opening); - const info = opening.slice(fence.length).trim(); - const language = info.split(/\s+/)[0] || ''; - const body: string[] = []; - let index = start + 1; - while (index < lines.length) { - const trimmed = lines[index].trim(); - if (MarkdownParser.isClosingFence(trimmed, fence)) { - index += 1; - break; - } - body.push(lines[index]); - index += 1; - } - MarkdownParser.pushBlock(blocks, 'code', 0, language, body.join('\n'), []); - return index; - } - - private static readQuoteBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number { - const body: string[] = []; - let index = start; - let level = 0; - while (index < lines.length) { - const trimmed = lines[index].trim(); - if (!MarkdownParser.isQuote(trimmed)) { - break; - } - const currentLevel = MarkdownParser.quoteDepth(trimmed); - if (level === 0) { - level = currentLevel; - } - if (currentLevel !== level) { - MarkdownParser.pushBlock(blocks, 'quote', level, '', MarkdownParser.joinFlowLines(body), []); - body.length = 0; - level = currentLevel; - } - body.push(MarkdownParser.quoteText(trimmed, currentLevel)); - index += 1; - } - if (body.length > 0) { - MarkdownParser.pushBlock(blocks, 'quote', level, '', MarkdownParser.joinFlowLines(body), []); - } - return index; - } - - private static readListBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number { - const items: ParsedMarkdownListItem[] = []; - let index = start; - while (index < lines.length) { - const raw = lines[index]; - const trimmed = raw.trim(); - if (!MarkdownParser.isListLine(trimmed)) { - break; - } - const marker = MarkdownParser.listMarker(trimmed); - const firstLineText = MarkdownParser.listText(trimmed); - const taskMatch = firstLineText.match(/^\[([ xX])\]\s+(.*)$/); - let text = taskMatch ? taskMatch[2] : firstLineText; - let nextIndex = index + 1; - const currentIndent = MarkdownParser.leadingIndentWidth(raw); - while (nextIndex < lines.length) { - const continuation = lines[nextIndex]; - const continuationTrimmed = continuation.trim(); - if (continuationTrimmed.length === 0 || MarkdownParser.isListLine(continuationTrimmed) || - MarkdownParser.leadingIndentWidth(continuation) <= currentIndent) { - break; - } - text += ' ' + continuationTrimmed; - nextIndex += 1; - } - const inlines = MarkdownParser.parseInlineText(text, `li-${start}-${items.length}`); - const item: ParsedMarkdownListItem = { - id: `li-${start}-${items.length}`, - marker, - text: MarkdownParser.plainInlineText(inlines), - inlines, - depth: MarkdownParser.listDepth(raw), - checked: taskMatch ? (taskMatch[1].toLowerCase() === 'x' ? 1 : 0) : -1 - }; - items.push(item); - index = nextIndex; - } - MarkdownParser.pushBlock(blocks, 'list', 0, '', '', items); - return index; - } - - private static readTableBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number { - const sourceRows: string[] = [lines[start].trim(), lines[start + 1].trim()]; - const headerCells = MarkdownParser.splitTableRow(lines[start]); - const separatorCells = MarkdownParser.splitTableRow(lines[start + 1]); - const alignments: string[] = separatorCells.map((cell: string) => MarkdownParser.tableAlignment(cell)); - const rows: ParsedMarkdownTableRow[] = []; - rows.push(MarkdownParser.buildTableRow(headerCells, alignments, true, start, 0)); - let index = start + 2; - while (index < lines.length) { - const trimmed = lines[index].trim(); - if (!MarkdownParser.hasTablePipes(trimmed)) { - break; - } - sourceRows.push(trimmed); - rows.push(MarkdownParser.buildTableRow( - MarkdownParser.splitTableRow(lines[index]), alignments, false, start, rows.length - )); - index += 1; - } - MarkdownParser.pushBlock(blocks, 'table', 0, '', sourceRows.join('\n'), [], rows); - return index; - } - - private static readParagraphBlock(lines: string[], start: number, blocks: ParsedMarkdownBlock[]): number { - const body: string[] = []; - let index = start; - while (index < lines.length) { - const trimmed = lines[index].trim(); - if (trimmed.length === 0 || - MarkdownParser.isFence(trimmed) || - MarkdownParser.isSetextHeading(lines, index) || - MarkdownParser.isDivider(trimmed) || - MarkdownParser.isHeading(trimmed) || - MarkdownParser.isQuote(trimmed) || - MarkdownParser.isListLine(trimmed) || - MarkdownParser.isTableStart(lines, index)) { - break; - } - body.push(lines[index].replace(/^\s+/, '')); - index += 1; - } - MarkdownParser.pushBlock(blocks, 'paragraph', 0, '', MarkdownParser.joinFlowLines(body), []); - return index; - } - - private static pushBlock( - blocks: ParsedMarkdownBlock[], - type: string, - level: number, - language: string, - text: string, - items: ParsedMarkdownListItem[], - tableRows: ParsedMarkdownTableRow[] = [] - ): void { - const id = `md-${blocks.length}-${type}`; - const inlines = MarkdownParser.shouldParseInline(type) ? MarkdownParser.parseInlineText(text, id) : []; - const normalizedText = MarkdownParser.shouldParseInline(type) ? MarkdownParser.plainInlineText(inlines) : text; - const block: ParsedMarkdownBlock = { - id, - renderKey: '', - type, - level, - language, - text: normalizedText, - items, - inlines, - tableRows - }; - block.renderKey = `${id}-${MarkdownParser.blockContentRevision(block)}`; - blocks.push(block); - } - - private static blockContentRevision(block: ParsedMarkdownBlock): string { - let source = MarkdownParser.revisionPart(block.type) + - MarkdownParser.revisionPart(block.level.toString()) + - MarkdownParser.revisionPart(block.language) + - MarkdownParser.revisionPart(block.text); - block.inlines.forEach((inline: ParsedMarkdownInline) => { - source += MarkdownParser.inlineRevisionSource(inline); - }); - block.items.forEach((item: ParsedMarkdownListItem) => { - source += MarkdownParser.revisionPart(item.marker) + - MarkdownParser.revisionPart(item.text) + - MarkdownParser.revisionPart(item.depth.toString()) + - MarkdownParser.revisionPart(item.checked.toString()); - item.inlines.forEach((inline: ParsedMarkdownInline) => { - source += MarkdownParser.inlineRevisionSource(inline); - }); - }); - block.tableRows.forEach((row: ParsedMarkdownTableRow) => { - source += MarkdownParser.revisionPart(row.header ? '1' : '0'); - row.cells.forEach((cell: ParsedMarkdownTableCell) => { - source += MarkdownParser.revisionPart(cell.text) + MarkdownParser.revisionPart(cell.alignment); - cell.inlines.forEach((inline: ParsedMarkdownInline) => { - source += MarkdownParser.inlineRevisionSource(inline); - }); - }); - }); - return MarkdownParser.revisionHash(source); - } - - private static inlineRevisionSource(inline: ParsedMarkdownInline): string { - return MarkdownParser.revisionPart(inline.type) + - MarkdownParser.revisionPart(inline.text) + - MarkdownParser.revisionPart(inline.url); - } - - private static revisionPart(value: string): string { - return `${value.length}:${value}`; - } - - private static revisionHash(value: string): string { - let primary = 7; - let secondary = 11; - for (let index = 0; index < value.length; index += 1) { - const code = value.charCodeAt(index); - primary = (primary * 31 + code) % 2147483647; - secondary = (secondary * 131 + code) % 2147483629; - } - return `${value.length}-${primary}-${secondary}`; - } - - static parseInlineText(value: string, prefix: string = 'inline'): ParsedMarkdownInline[] { - const inlines: ParsedMarkdownInline[] = []; - let index = 0; - while (index < value.length) { - const next = MarkdownParser.nextInlineMarker(value, index); - if (next < 0) { - MarkdownParser.pushTextWithAutoLinks(inlines, prefix, value.slice(index)); - break; - } - if (next > index) { - MarkdownParser.pushTextWithAutoLinks(inlines, prefix, value.slice(index, next)); - } - const consumed = MarkdownParser.readInlineAt(value, next, prefix, inlines); - if (consumed <= next) { - MarkdownParser.pushInline(inlines, prefix, 'text', value.charAt(next), ''); - index = next + 1; - } else { - index = consumed; - } - } - return inlines.filter((inline: ParsedMarkdownInline) => inline.text.length > 0); - } - - private static readInlineAt(value: string, start: number, prefix: string, inlines: ParsedMarkdownInline[]): number { - if (value.charAt(start) === '`') { - let markerLength = 1; - while (value.charAt(start + markerLength) === '`') { - markerLength += 1; - } - const marker = '`'.repeat(markerLength); - const end = value.indexOf(marker, start + markerLength); - if (end > start + markerLength) { - let code = value.slice(start + markerLength, end).replace(/\s+/g, ' '); - if (code.startsWith(' ') && code.endsWith(' ') && code.trim().length > 0) { - code = code.slice(1, -1); - } - MarkdownParser.pushInline(inlines, prefix, 'code', code, ''); - return end + markerLength; - } - } - if (value.slice(start, start + 2) === '**') { - const end = value.indexOf('**', start + 2); - if (end > start + 2) { - MarkdownParser.pushInline(inlines, prefix, 'strong', value.slice(start + 2, end), ''); - return end + 2; - } - } - if (value.slice(start, start + 2) === '__') { - const end = value.indexOf('__', start + 2); - if (end > start + 2) { - MarkdownParser.pushInline(inlines, prefix, 'strong', value.slice(start + 2, end), ''); - return end + 2; - } - } - if (MarkdownParser.isStrikeDelimiter(value, start, false)) { - let end = value.indexOf('~~', start + 2); - while (end >= 0 && !MarkdownParser.isStrikeDelimiter(value, end, true)) { - end = value.indexOf('~~', end + 2); - } - if (end > start + 2) { - MarkdownParser.pushInline(inlines, prefix, 'delete', MarkdownParser.unescapeText(value.slice(start + 2, end)), ''); - return end + 2; - } - } - if (value.charAt(start) === '[') { - const labelEnd = value.indexOf(']', start + 1); - if (labelEnd > start + 1 && value.charAt(labelEnd + 1) === '(') { - const urlEnd = value.indexOf(')', labelEnd + 2); - if (urlEnd > labelEnd + 2) { - MarkdownParser.pushInline(inlines, prefix, 'link', value.slice(start + 1, labelEnd), value.slice(labelEnd + 2, urlEnd)); - return urlEnd + 1; - } - } - } - if (value.charAt(start) === '<') { - const end = value.indexOf('>', start + 1); - if (end > start + 1) { - const url = value.slice(start + 1, end); - if (/^(https?:\/\/|computer:\/\/|file:\/\/)[^\s<>]+$/.test(url)) { - MarkdownParser.pushInline(inlines, prefix, 'link', url, url); - return end + 1; - } - } - } - if (value.charAt(start) === '*') { - const end = value.indexOf('*', start + 1); - if (end > start + 1) { - MarkdownParser.pushInline(inlines, prefix, 'emphasis', value.slice(start + 1, end), ''); - return end + 1; - } - } - if (value.charAt(start) === '_') { - const end = value.indexOf('_', start + 1); - if (end > start + 1) { - MarkdownParser.pushInline(inlines, prefix, 'emphasis', value.slice(start + 1, end), ''); - return end + 1; - } - } - return start; - } - - private static nextInlineMarker(value: string, start: number): number { - const markers: string[] = ['`', '**', '__', '~~', '[', '<', '*', '_']; - let next = -1; - markers.forEach((marker: string) => { - let markerIndex = value.indexOf(marker, start); - while (markerIndex >= 0 && MarkdownParser.isEscaped(value, markerIndex)) { - markerIndex = value.indexOf(marker, markerIndex + marker.length); - } - if (markerIndex >= 0 && (next < 0 || markerIndex < next)) { - next = markerIndex; - } - }); - return next; - } - - private static isStrikeDelimiter(value: string, index: number, closing: boolean): boolean { - // Single tildes are chat ranges; runs longer than two are literal inlines. - if (value.slice(index, index + 2) !== '~~' || value.charAt(index - 1) === '~' || - value.charAt(index + 2) === '~' || MarkdownParser.isEscaped(value, index)) { - return false; - } - const before = value.charAt(index - 1); - const after = value.charAt(index + 2); - const beforeSpace = before.length === 0 || /\s/.test(before); - const afterSpace = after.length === 0 || /\s/.test(after); - const beforePunctuation = /[\p{P}\p{S}]/u.test(before); - const afterPunctuation = /[\p{P}\p{S}]/u.test(after); - return closing ? !beforeSpace && (!beforePunctuation || afterSpace || afterPunctuation) : - !afterSpace && (!afterPunctuation || beforeSpace || beforePunctuation); - } - - private static pushInline( - inlines: ParsedMarkdownInline[], - prefix: string, - type: string, - text: string, - url: string - ): void { - const inline: ParsedMarkdownInline = { - id: `${prefix}-inline-${inlines.length}`, - type, - text, - url - }; - inlines.push(inline); - } - - private static pushTextWithAutoLinks( - inlines: ParsedMarkdownInline[], - prefix: string, - text: string - ): void { - const pattern = /(https?:\/\/|computer:\/\/|file:\/\/)[^\s<>]+/g; - let cursor = 0; - let match: RegExpExecArray | null = pattern.exec(text); - while (match) { - if (match.index > cursor) { - MarkdownParser.pushInline( - inlines, prefix, 'text', MarkdownParser.unescapeText(text.slice(cursor, match.index)), '' - ); - } - let url = match[0]; - let suffix = ''; - while (url.length > 0 && /[.,;:!?]$/.test(url)) { - suffix = url.slice(-1) + suffix; - url = url.slice(0, -1); - } - MarkdownParser.pushInline(inlines, prefix, 'link', url, url); - if (suffix.length > 0) { - MarkdownParser.pushInline(inlines, prefix, 'text', suffix, ''); - } - cursor = match.index + match[0].length; - match = pattern.exec(text); - } - if (cursor < text.length) { - MarkdownParser.pushInline(inlines, prefix, 'text', MarkdownParser.unescapeText(text.slice(cursor)), ''); - } - } - - private static unescapeText(value: string): string { - const escapable = '\\`*{}[]()#+-.!_>~|'; - let result = ''; - let index = 0; - while (index < value.length) { - if (value.charAt(index) === '\\' && index + 1 < value.length && - escapable.indexOf(value.charAt(index + 1)) >= 0) { - result += value.charAt(index + 1); - index += 2; - } else { - result += value.charAt(index); - index += 1; - } - } - return result; - } - - private static isEscaped(value: string, index: number): boolean { - let slashCount = 0; - let cursor = index - 1; - while (cursor >= 0 && value.charAt(cursor) === '\\') { - slashCount += 1; - cursor -= 1; - } - return slashCount % 2 === 1; - } - - private static shouldParseInline(type: string): boolean { - return type === 'paragraph' || type === 'heading' || type === 'quote'; - } - - private static frontmatterEnd(lines: string[]): number { - if (lines.length < 3 || lines[0].trim() !== '---') { - return -1; - } - for (let index = 1; index < lines.length; index += 1) { - const marker = lines[index].trim(); - if (marker === '---' || marker === '...') { - return index > 1 ? index : -1; - } - } - return -1; - } - - private static isHeading(line: string): boolean { - return /^#{1,6}\s+/.test(line); - } - - private static headingLevel(line: string): number { - const match = line.match(/^#{1,6}/); - return match ? match[0].length : 1; - } - - private static isDivider(line: string): boolean { - return /^(?:\*\s*){3,}$/.test(line) || /^(?:_\s*){3,}$/.test(line) || /^(?:-\s*){3,}$/.test(line); - } - - private static isQuote(line: string): boolean { - return line.indexOf('>') === 0; - } - - private static quoteDepth(line: string): number { - let depth = 0; - let index = 0; - while (index < line.length) { - if (line.charAt(index) !== '>') { - break; - } - depth += 1; - index += 1; - if (line.charAt(index) === ' ') { - index += 1; - } - } - return Math.max(1, depth); - } - - private static quoteText(line: string, depth: number): string { - let index = 0; - let consumed = 0; - while (index < line.length && consumed < depth) { - if (line.charAt(index) === '>') { - consumed += 1; - index += 1; - if (line.charAt(index) === ' ') { - index += 1; - } - } else { - break; - } - } - return line.slice(index); - } - - private static isListLine(line: string): boolean { - return /^[-*+]\s+/.test(line) || /^\d+[.)]\s+/.test(line); - } - - private static listMarker(line: string): string { - const ordered = line.match(/^(\d+)[.)]\s+/); - if (ordered) { - return `${ordered[1]}.`; - } - return '•'; - } - - private static listText(line: string): string { - return line.replace(/^[-*+]\s+/, '').replace(/^\d+[.)]\s+/, ''); - } - - private static listDepth(line: string): number { - const width = MarkdownParser.leadingIndentWidth(line); - return width > 0 ? Math.ceil(width / 4) : 0; - } - - private static leadingIndentWidth(line: string): number { - let width = 0; - let index = 0; - while (index < line.length) { - const character = line.charAt(index); - if (character === ' ') { - width += 1; - } else if (character === '\t') { - width += 4; - } else { - break; - } - index += 1; - } - return width; - } - - private static isFence(line: string): boolean { - return /^`{3,}[^`]*$/.test(line) || /^~{3,}.*$/.test(line); - } - - private static fenceMarker(line: string): string { - const match = line.match(/^(`{3,}|~{3,})/); - return match ? match[1] : '```'; - } - - private static isClosingFence(line: string, opening: string): boolean { - if (line.length < opening.length || line.charAt(0) !== opening.charAt(0)) { - return false; - } - let count = 0; - while (count < line.length && line.charAt(count) === opening.charAt(0)) { - count += 1; - } - return count >= opening.length && line.slice(count).trim().length === 0; - } - - private static isSetextHeading(lines: string[], index: number): boolean { - if (index + 1 >= lines.length || lines[index].trim().length === 0) { - return false; - } - return /^(=+|-+)\s*$/.test(lines[index + 1].trim()); - } - - private static joinFlowLines(lines: string[]): string { - let result = ''; - lines.forEach((line: string, index: number) => { - if (index === 0) { - result = line; - return; - } - if (/ {2,}$/.test(result)) { - result = result.replace(/ {2,}$/, '') + '\n' + line; - } else if (result.endsWith('\\')) { - result = result.slice(0, -1) + '\n' + line; - } else { - result += ' ' + line; - } - }); - return result.replace(/\s+$/, ''); - } - - private static isTableStart(lines: string[], index: number): boolean { - if (index + 1 >= lines.length) { - return false; - } - const current = lines[index].trim(); - const next = lines[index + 1].trim(); - return MarkdownParser.hasTablePipes(current) && /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/.test(next); - } - - private static hasTablePipes(line: string): boolean { - let inCode = false; - for (let index = 0; index < line.length; index += 1) { - const character = line.charAt(index); - if (character === '`' && !MarkdownParser.isEscaped(line, index)) { - inCode = !inCode; - } else if (character === '|' && !inCode && !MarkdownParser.isEscaped(line, index)) { - return true; - } - } - return false; - } - - private static splitTableRow(line: string): string[] { - let source = line.trim(); - if (source.startsWith('|')) { - source = source.slice(1); - } - if (source.endsWith('|') && !MarkdownParser.isEscaped(source, source.length - 1)) { - source = source.slice(0, -1); - } - const cells: string[] = []; - let current = ''; - let inCode = false; - let index = 0; - while (index < source.length) { - const character = source.charAt(index); - if (character === '\\' && source.charAt(index + 1) === '|') { - current += '|'; - index += 2; - continue; - } - if (character === '`') { - inCode = !inCode; - current += character; - index += 1; - continue; - } - if (character === '|' && !inCode) { - cells.push(current.trim()); - current = ''; - } else { - current += character; - } - index += 1; - } - cells.push(current.trim()); - return cells; - } - - private static tableAlignment(separator: string): string { - const value = separator.trim(); - if (value.startsWith(':') && value.endsWith(':')) { - return 'center'; - } - if (value.endsWith(':')) { - return 'right'; - } - return 'left'; - } - - private static buildTableRow( - values: string[], - alignments: string[], - header: boolean, - start: number, - rowIndex: number - ): ParsedMarkdownTableRow { - const cells: ParsedMarkdownTableCell[] = []; - const columnCount = Math.max(values.length, alignments.length); - for (let column = 0; column < columnCount; column += 1) { - const text = column < values.length ? values[column] : ''; - const id = `table-${start}-${rowIndex}-${column}`; - const inlines = MarkdownParser.parseInlineText(text, id); - cells.push({ - id, - text: MarkdownParser.plainInlineText(inlines), - inlines, - alignment: column < alignments.length ? alignments[column] : 'left' - }); - } - return { - id: `table-${start}-row-${rowIndex}`, - header, - cells - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets deleted file mode 100644 index b84478c72b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets +++ /dev/null @@ -1,87 +0,0 @@ -import { MessageQueueAction, MessageQueueItem, MessageQueueRequest, MessageQueueSnapshot, MessageQueueState } from '../model/MessageQueue'; -import { RemoteSessionManager } from './RemoteSessionManager'; -import { Encoding } from './Encoding'; - -/** A controller replica; the execution host owns both receipts and dispatch order. */ -export class MessageQueueStore { - private client: RemoteSessionManager; - private onChange: (state: MessageQueueState) => void; - private canPoll: (sessionId: string) => boolean; - private state: MessageQueueState = new MessageQueueState(); - private snapshot?: MessageQueueSnapshot; - private generation: number = 0; - private timer: number = -1; - private reading: boolean = false; - private readVersion: number = 0; - constructor(client: RemoteSessionManager, onChange: (state: MessageQueueState) => void, canPoll: (sessionId: string) => boolean) { - this.client = client; this.onChange = onChange; this.canPoll = canPoll; - } - select(sessionId: string): void { - this.generation++; - if (this.timer >= 0) clearTimeout(this.timer); - this.timer = -1; this.reading = false; this.snapshot = undefined; - this.state = new MessageQueueState(); this.state.sessionId = sessionId; this.publish(); - if (sessionId) void this.refresh(); - } - private accept(value: MessageQueueSnapshot): void { - if (value.sessionId !== this.state.sessionId || !value.queueEpoch || !Array.isArray(value.items)) throw new Error('Invalid queue snapshot'); - if (this.snapshot?.queueEpoch === value.queueEpoch && this.snapshot.revision > value.revision) return; - this.snapshot = value; this.state.revisionKey = `${value.queueEpoch}:${value.revision}`; this.state.items = value.items.slice(); this.state.supportsReorder = value.supportsReorder === true; - this.state.failure = ''; this.publish(); - } - async refresh(): Promise { - if (this.reading || this.state.busy || !this.state.sessionId) return; - if (this.timer >= 0) clearTimeout(this.timer); - const ticket = this.generation; - const version = this.readVersion; - this.reading = true; - try { - if (!this.canPoll(this.state.sessionId)) { - this.state.failure = 'offline'; this.publish(); - } else if (!this.client.supportsMessageQueue()) { - if (this.state.items.length > 0) { this.state.failure = 'unsupported'; this.state.supportsReorder = false; this.publish(); } - } else { - const value = await this.client.manageMessageQueue({ sessionId: this.state.sessionId, action: 'list' }); - if (ticket === this.generation && version === this.readVersion) this.accept(value); - } - } catch (_error) { if (ticket === this.generation && version === this.readVersion) { this.state.failure = 'load'; this.publish(); } } - finally { - if (ticket === this.generation) { - this.reading = false; - this.timer = setTimeout((): void => { void this.refresh(); }, this.state.items.length > 0 ? 2000 : 10000); - } - } - } - async dispatch(action: MessageQueueAction): Promise { - if (action.sessionId !== this.state.sessionId) return; - if (action.action === 'list') { await this.refresh(); return; } - const observed = this.snapshot; - if (!observed || this.state.busy || this.state.failure) return; - if (!this.canPoll(action.sessionId)) { this.state.failure = 'offline'; this.publish(); return; } - const item = this.state.items.find((value: MessageQueueItem): boolean => value.turnId === action.turnId); - if (!item || (item.status !== 'queued' && item.status !== 'blocked')) return; - if (action.action === 'reorder' && (!observed.supportsReorder || item.status !== 'queued')) { - this.state.failure = 'unsupported'; this.publish(); return; - } - const ticket = this.generation; - this.readVersion++; - this.state.busy = true; this.publish(); - const request: MessageQueueRequest = { sessionId: action.sessionId, action: action.action, queueEpoch: observed.queueEpoch, - turnId: item.turnId, operationId: Encoding.randomId('queue'), beforeTurnId: action.beforeTurnId, - expectedRevision: observed.revision, expectedActiveTurnId: observed.activeTurnId }; - try { - const value = await this.client.manageMessageQueue(request); - if (ticket !== this.generation) return; - if (value.queueEpoch !== observed.queueEpoch) throw new Error('Queue owner changed'); - this.accept(value); - } catch (_error) { if (ticket === this.generation) { this.state.failure = 'unknown'; this.publish(); } } - finally { - if (ticket === this.generation) { this.state.busy = false; this.publish(); void this.refresh(); } - } - } - private publish(): void { - const next = new MessageQueueState(); - next.sessionId = this.state.sessionId; next.items = this.state.items.slice(); next.supportsReorder = this.state.supportsReorder; - next.revisionKey = this.state.revisionKey; next.busy = this.state.busy; next.failure = this.state.failure; this.onChange(next); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppDocument.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppDocument.ets deleted file mode 100644 index 56817895d2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MiniAppDocument.ets +++ /dev/null @@ -1,39 +0,0 @@ -import { RemoteI18n } from '../i18n/RemoteI18n'; - -/** Trusted wrapper and untrusted H5 are separate browsing contexts. */ -export class MiniAppDocument { - static build(html: string, locale: string): string { - const language = JSON.stringify(locale).replace(/', ``); - const source = JSON.stringify(localized).replace(/ - - -`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MobileIdentityStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MobileIdentityStore.ets deleted file mode 100644 index e31e136b03..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MobileIdentityStore.ets +++ /dev/null @@ -1,165 +0,0 @@ -import { preferences } from '@kit.ArkData'; -import { Encoding } from './Encoding'; -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; -import { OhosError } from './OhosError'; -import { accountDeviceLink } from './AccountDeviceLink'; -import { RemoteLogger } from './RemoteLogger'; -import { RemoteModelPreferenceStore } from './RemoteModelController'; - -// Persisted identifiers are compatibility contracts; the product rename must -// not strand an installed phone's pairing snapshot in a second store. -const STORE_NAME = HarmonyUpgradeIdentityContract.REMOTE_IDENTITY_STORE; -const INSTALL_ID_KEY = 'mobile_install_id'; -const USER_ID_KEY = 'user_id'; -const REMOTE_URL_KEY = 'remote_url'; -const PAIRING_SAVED_AT_KEY = 'pairing_saved_at'; -const CONTROL_TARGET_TYPE_KEY = 'control_target_type'; -const LAST_MODEL_ID_KEY = 'last_model_id'; -const USER_ID_LOCK_UNTIL_KEY = 'user_id_lock_until'; -const USER_ID_FAILURE_COUNT_KEY = 'user_id_failure_count'; - -export interface MobileIdentitySnapshot { - installId: string; - userId: string; - remoteUrl: string; - pairingSavedAt: number; - controlTargetType: string; - userIdFailureCount: number; - userIdLockUntil: number; -} - -export class MobileIdentityStore implements RemoteModelPreferenceStore { - private preferences?: preferences.Preferences; - - async init(context: Context): Promise { - try { - this.preferences = await preferences.getPreferences(context, STORE_NAME); - } catch (err) { - throw OhosError.wrap('mobile identity init', err); - } - const existingInstallId = await this.getString(INSTALL_ID_KEY); - const installId = existingInstallId || Encoding.randomId('harmony'); - if (!existingInstallId) { - await this.putString(INSTALL_ID_KEY, installId); - } - const snapshot: MobileIdentitySnapshot = { - installId, - userId: await this.getString(USER_ID_KEY), - remoteUrl: await this.getString(REMOTE_URL_KEY), - pairingSavedAt: await this.getNumber(PAIRING_SAVED_AT_KEY), - controlTargetType: await this.getString(CONTROL_TARGET_TYPE_KEY), - userIdFailureCount: await this.getNumber(USER_ID_FAILURE_COUNT_KEY), - userIdLockUntil: await this.getNumber(USER_ID_LOCK_UNTIL_KEY) - }; - if (snapshot.remoteUrl.length > 0) { - RemoteLogger.info( - `pairing snapshot restored device=${this.deviceReference(snapshot.remoteUrl)} saved_at=${snapshot.pairingSavedAt}` - ); - } - return snapshot; - } - - async savePairingInput(userId: string, remoteUrl: string): Promise { - if (!this.preferences) { - throw new Error('Mobile identity store is not initialized.'); - } - const normalizedUrl = remoteUrl.trim(); - const savedAt = Date.now(); - try { - await this.preferences.put(USER_ID_KEY, userId.trim()); - await this.preferences.put(REMOTE_URL_KEY, normalizedUrl); - await this.preferences.put(PAIRING_SAVED_AT_KEY, savedAt); - await this.preferences.flush(); - } catch (err) { - throw OhosError.wrap('mobile identity save pairing snapshot', err); - } - RemoteLogger.info(`pairing snapshot saved device=${this.deviceReference(normalizedUrl)} saved_at=${savedAt}`); - } - - async clearPairingInput(): Promise { - await this.putString(USER_ID_KEY, ''); - await this.putString(REMOTE_URL_KEY, ''); - await this.putNumber(PAIRING_SAVED_AT_KEY, 0); - await this.clearUserIdProtection(); - } - - async saveControlTargetType(controlTargetType: string): Promise { - const normalized = controlTargetType === 'room' || controlTargetType === 'account_device' ? - controlTargetType : ''; - await this.putString(CONTROL_TARGET_TYPE_KEY, normalized); - } - - async saveUserIdProtection(failureCount: number, lockUntil: number): Promise { - await this.putNumber(USER_ID_FAILURE_COUNT_KEY, failureCount); - await this.putNumber(USER_ID_LOCK_UNTIL_KEY, lockUntil); - } - - async clearUserIdProtection(): Promise { - await this.putNumber(USER_ID_FAILURE_COUNT_KEY, 0); - await this.putNumber(USER_ID_LOCK_UNTIL_KEY, 0); - } - - async getLastModelId(): Promise { - return this.getString(LAST_MODEL_ID_KEY); - } - - async saveLastModelId(modelId: string): Promise { - await this.putString(LAST_MODEL_ID_KEY, modelId.trim()); - } - - private async getString(key: string): Promise { - if (!this.preferences) { - return ''; - } - try { - const value = await this.preferences.get(key, ''); - return typeof value === 'string' ? value : ''; - } catch (err) { - throw OhosError.wrap('mobile identity get string', err); - } - } - - private async getNumber(key: string): Promise { - if (!this.preferences) { - return 0; - } - try { - const value = await this.preferences.get(key, 0); - return typeof value === 'number' ? value : Number(value || 0); - } catch (err) { - throw OhosError.wrap('mobile identity get number', err); - } - } - - private async putString(key: string, value: string): Promise { - if (!this.preferences) { - return; - } - try { - await this.preferences.put(key, value); - await this.preferences.flush(); - } catch (err) { - throw OhosError.wrap('mobile identity put string', err); - } - } - - private async putNumber(key: string, value: number): Promise { - if (!this.preferences) { - return; - } - try { - await this.preferences.put(key, value); - await this.preferences.flush(); - } catch (err) { - throw OhosError.wrap('mobile identity put number', err); - } - } - - private deviceReference(remoteUrl: string): string { - try { - return accountDeviceLink(remoteUrl)?.deviceId.slice(0, 8) || 'unavailable'; - } catch (_err) { - return 'invalid'; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MotionPreference.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MotionPreference.ets deleted file mode 100644 index bdafe42009..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MotionPreference.ets +++ /dev/null @@ -1,13 +0,0 @@ -import accessibility from '@ohos.accessibility'; -import deviceInfo from '@ohos.deviceInfo'; - -/** Optional on older phones; never let a presentation preference block startup. */ -export class MotionPreference { - static reduceMotion(): boolean { - try { - return deviceInfo.sdkApiVersion >= 23 && accessibility.isAnimationReduceEnabledSync(); - } catch (_err) { - return false; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/OhosError.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/OhosError.ets deleted file mode 100644 index 0742c7e1ee..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/OhosError.ets +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Converts SDK `BusinessError` values into `Error` so ArkTS sees the throw as - * handled at the call site, while callers still get a real failure. - */ -export class OhosError { - static wrap(operation: string, err: Object): Error { - if (err instanceof Error) { - return err; - } - return new Error(`${operation} failed: ${OhosError.reason(err)}`); - } - - static reason(err: Object): string { - if (err instanceof Error && err.message.length > 0) { - return err.message; - } - try { - const text = JSON.stringify(err); - return text.length > 0 && text !== '{}' ? text : 'unknown error'; - } catch (_jsonErr) { - return `${err}`; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RelayMessageEncoding.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RelayMessageEncoding.ets deleted file mode 100644 index 477408fd3c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RelayMessageEncoding.ets +++ /dev/null @@ -1,25 +0,0 @@ -import relayCodec from 'libopenbitfun_crypto.so'; - -/** Native codec work runs off the ArkTS thread. Bound the wait for a stuck worker. */ -export class RelayMessageEncoding { - static encode(plain: Uint8Array): Promise { - return RelayMessageEncoding.wait(relayCodec.encodeRelayMessage(plain)); - } - - static decode(bytes: Uint8Array): Promise { - return RelayMessageEncoding.wait(relayCodec.decodeRelayMessage(bytes)); - } - - private static wait(work: Promise): Promise { - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { reject(new Error('Relay codec timed out')); }, 15000); - work.then((result: Uint8Array) => { - clearTimeout(timer); - resolve(result); - }, (error: Error) => { - clearTimeout(timer); - reject(error); - }); - }); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteActivityLifecycleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteActivityLifecycleController.ets deleted file mode 100644 index d26fb88e5e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteActivityLifecycleController.ets +++ /dev/null @@ -1,29 +0,0 @@ -import { RemoteHeartbeatController, RemoteHeartbeatScheduler } from './RemoteHeartbeatController'; - -export class RemoteActivityLifecycleController { - private readonly heartbeatController: RemoteHeartbeatController; - - constructor( - onHeartbeatTick: () => Promise, - heartbeatIntervalMs: number = 15000, - heartbeatScheduler?: RemoteHeartbeatScheduler - ) { - this.heartbeatController = new RemoteHeartbeatController( - onHeartbeatTick, - heartbeatIntervalMs, - heartbeatScheduler - ); - } - - startHeartbeat(): void { - this.heartbeatController.start(); - } - - stopHeartbeat(): void { - this.heartbeatController.stop(); - } - - isHeartbeatRunning(): boolean { - return this.heartbeatController.isRunning(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatBranchCache.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatBranchCache.ets deleted file mode 100644 index 209ba1963b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatBranchCache.ets +++ /dev/null @@ -1,36 +0,0 @@ -import { ChatMessage } from '../model/RemoteModels'; -import { RemoteChatCache } from './RemoteChatCache'; -import { SubagentBranchCache } from './SubagentStreamCoordinator'; - -/** - * Child-branch transcripts in the phone's own transcript cache. - * - * This is the storage the parent session's transcript already uses: transcripts - * scoped per controlled desktop and session id, every failure swallowed because - * a cache is reconstructible from the desktop, and one clear on sign-out. A - * child session is an ordinary session on its own stream id, so it is stored - * under its own id — which is also the id the parent's launching item names, and - * therefore the key that maps a stored child back to the parent and the branch - * that owns it. No second store, no second schema, and no second lifecycle to - * keep in step with the parent's. - */ -export class RemoteChatBranchCache implements SubagentBranchCache { - private readonly cache: RemoteChatCache; - - constructor(cache: RemoteChatCache) { - this.cache = cache; - } - - async loadBranch(sessionId: string): Promise { - return await this.cache.load(sessionId); - } - - /** - * A child's transcript is authoritative for the child, the same way the parent - * transcript is: the reducer's projection is complete at every change, so it - * replaces the stored rows rather than appending to them. - */ - async saveBranch(sessionId: string, messages: ChatMessage[]): Promise { - await this.cache.replaceSnapshot(sessionId, messages); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCache.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCache.ets deleted file mode 100644 index e76b30ae7b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCache.ets +++ /dev/null @@ -1,314 +0,0 @@ -import { ChatMessage } from '../model/RemoteModels'; -import { RemoteLogger } from './RemoteLogger'; - -/** - * One session's cached transcript, as it was last written. - * - * `lastMessageId` is what makes an append safe: the desktop hands out message - * tails by index (`poll_session` skips `known_msg_count` entries), so a cached - * prefix that no longer matches the desktop's would silently splice two - * different transcripts together. - */ -export interface RemoteChatCacheSlice { - messages: ChatMessage[]; - lastMessageId: string; -} - -/** Storage behind [RemoteChatCache]; see `RemoteChatLocalRdbStore`. */ -export interface RemoteChatCacheStore { - init(context: Context): Promise; - loadSlice(deviceKey: string, sessionId: string): Promise; - appendMessages( - deviceKey: string, - sessionId: string, - startSeq: number, - messages: ChatMessage[], - lastMessageId: string - ): Promise; - replaceMessages( - deviceKey: string, - sessionId: string, - messages: ChatMessage[], - lastMessageId: string - ): Promise; - deleteSession(deviceKey: string, sessionId: string): Promise; - pruneSessions(deviceKey: string, keepMostRecent: number): Promise; - clearAll(): Promise; -} - -/** - * How many sessions per desktop keep a cached transcript. - * - * The list a phone actually revisits is short, and every session past that is - * disk spent on a transcript the user will re-fetch anyway. Past the budget the - * least recently opened transcript goes first, and opening counts as reading — - * so a session the user keeps coming back to outlives any number of one-off - * ones opened around it. - */ -const CACHED_SESSIONS_PER_DEVICE: number = 20; - -/** - * How many transcripts stay in memory in front of the disk ones. - * - * Three covers what the phone actually alternates between — the session being - * worked in, the one before it, and whatever was glanced at in between — and - * costs nothing on disk. Past that the read off disk is already fast enough - * that holding more would be spending memory to save nothing. - */ -const RESIDENT_SESSIONS: number = 3; - -/** - * On-disk transcripts, so reopening a session renders before the network answers. - * - * Everything here is reconstructible from the desktop, which is what lets every - * method swallow its own failures: a cache that cannot be read or written makes - * the app as slow as it was before the cache existed, and nothing worse. The - * one thing it must never do is serve a transcript that is missing messages out - * of the middle, so any doubt about a stored prefix is resolved by reporting a - * miss. - * - * Entries are scoped per desktop: `session_id` is issued by the desktop that - * owns the session, so two desktops on one account can hand out the same id for - * different conversations. - */ -export class RemoteChatCache { - private readonly store: RemoteChatCacheStore; - private readonly deviceKeyProvider: () => string; - private ready: boolean = false; - // Write cursor for the session on screen, so a poll tick costs one append - // rather than a read followed by an append. - private trackedScope: string = ''; - private trackedCount: number = 0; - private trackedLastMessageId: string = ''; - // Transcripts held in memory, most recently used last. - // - // Only ever populated from a disk read that succeeded or a disk write that - // succeeded, so a resident copy can never claim more messages than the store - // actually holds — which is what lets a resident hit set the append cursor - // instead of forcing the next sync to rewrite the session. - private readonly resident: Map = new Map(); - private residentOrder: string[] = []; - - constructor(store: RemoteChatCacheStore, deviceKeyProvider: () => string) { - this.store = store; - this.deviceKeyProvider = deviceKeyProvider; - } - - async init(context: Context): Promise { - try { - await this.store.init(context); - this.ready = true; - } catch (err) { - RemoteLogger.error(`remote chat cache unavailable: ${RemoteChatCache.reason(err)}`); - } - } - - /** The cached transcript for [sessionId], or an empty list on any miss. */ - async load(sessionId: string): Promise { - const scope = this.scope(sessionId); - if (scope.length === 0) { - return []; - } - const resident = this.resident.get(scope); - if (resident !== undefined) { - this.touchResident(scope); - this.track(scope, resident.messages.length, resident.lastMessageId); - RemoteLogger.info(`remote chat cache resident hit count=${resident.messages.length}`); - return resident.messages.slice(); - } - try { - const slice = await this.store.loadSlice(this.deviceKeyProvider(), sessionId); - this.track(scope, slice.messages.length, slice.lastMessageId); - if (slice.messages.length > 0) { - this.remember(scope, slice.messages, slice.lastMessageId); - } - return slice.messages; - } catch (err) { - this.forgetCursor(); - this.evictResident(scope); - RemoteLogger.error(`remote chat cache read failed: ${RemoteChatCache.reason(err)}`); - return []; - } - } - - /** - * Persists an authoritative transcript returned by `get_session_messages` or - * `message_snapshot`. - * - * Message ids and counts are ordering facts, not content revisions: a turn - * keeps the same assistant id while its final text, status and tool results - * become durable. Therefore a full snapshot always replaces the cached rows, - * even when its ids and length match what is already stored. - */ - async replaceSnapshot(sessionId: string, persistedMessages: ChatMessage[]): Promise { - const scope = this.scope(sessionId); - if (scope.length === 0) { - return; - } - const lastMessageId = persistedMessages.length > 0 - ? persistedMessages[persistedMessages.length - 1].id - : ''; - try { - await this.store.replaceMessages( - this.deviceKeyProvider(), - sessionId, - persistedMessages, - lastMessageId - ); - await this.store.pruneSessions(this.deviceKeyProvider(), CACHED_SESSIONS_PER_DEVICE); - this.track(scope, persistedMessages.length, lastMessageId); - if (persistedMessages.length > 0) { - this.remember(scope, persistedMessages, lastMessageId); - } else { - this.evictResident(scope); - } - } catch (err) { - this.handleWriteFailure(scope, err); - } - } - - /** - * Persists the timeline after an additive poll delta was merged into it. - * - * This path may append because the caller did not receive an authoritative - * replacement. A prefix mismatch still rewrites the session to avoid splicing - * two different histories together. - */ - async syncIncremental(sessionId: string, persistedMessages: ChatMessage[]): Promise { - const scope = this.scope(sessionId); - if (scope.length === 0 || persistedMessages.length === 0) { - return; - } - const lastMessageId = persistedMessages[persistedMessages.length - 1].id; - try { - if (this.canAppendTo(scope, persistedMessages)) { - if (persistedMessages.length === this.trackedCount) { - return; - } - await this.store.appendMessages( - this.deviceKeyProvider(), - sessionId, - this.trackedCount, - persistedMessages.slice(this.trackedCount), - lastMessageId - ); - } else { - await this.store.replaceMessages( - this.deviceKeyProvider(), - sessionId, - persistedMessages, - lastMessageId - ); - // Only a rewrite can bring a session into the cache that was not - // already there, so this is the one branch eviction has anything to do: - // a poll tick appending to a stored session leaves the count where it - // was, and paying for a prune on every tick would be pure overhead. - await this.store.pruneSessions(this.deviceKeyProvider(), CACHED_SESSIONS_PER_DEVICE); - } - this.track(scope, persistedMessages.length, lastMessageId); - this.remember(scope, persistedMessages, lastMessageId); - } catch (err) { - this.handleWriteFailure(scope, err); - } - } - - /** Drops one session, for a delete or a transcript the desktop rewrote. */ - async forget(sessionId: string): Promise { - const scope = this.scope(sessionId); - if (scope.length === 0) { - return; - } - if (scope === this.trackedScope) { - this.forgetCursor(); - } - this.evictResident(scope); - try { - await this.store.deleteSession(this.deviceKeyProvider(), sessionId); - } catch (err) { - RemoteLogger.error(`remote chat cache evict failed: ${RemoteChatCache.reason(err)}`); - } - } - - /** - * Drops every cached transcript, for signing out. - * - * Transcripts belong to the account that was signed in; leaving them on disk - * for the next account to read is the one failure mode worth being loud about. - */ - async clear(): Promise { - this.forgetCursor(); - this.resident.clear(); - this.residentOrder = []; - if (!this.ready) { - return; - } - try { - await this.store.clearAll(); - } catch (err) { - RemoteLogger.error(`remote chat cache clear failed: ${RemoteChatCache.reason(err)}`); - } - } - - private canAppendTo(scope: string, persistedMessages: ChatMessage[]): boolean { - return this.trackedScope === scope && - this.trackedCount > 0 && - this.trackedCount <= persistedMessages.length && - persistedMessages[this.trackedCount - 1].id === this.trackedLastMessageId; - } - - private track(scope: string, count: number, lastMessageId: string): void { - this.trackedScope = scope; - this.trackedCount = count; - this.trackedLastMessageId = lastMessageId; - } - - private forgetCursor(): void { - this.trackedScope = ''; - this.trackedCount = 0; - this.trackedLastMessageId = ''; - } - - /** Takes a copy: the caller's array outlives this call and the timeline edits it. */ - private remember(scope: string, messages: ChatMessage[], lastMessageId: string): void { - this.resident.set(scope, { messages: messages.slice(), lastMessageId }); - this.touchResident(scope); - while (this.residentOrder.length > RESIDENT_SESSIONS) { - const oldest = this.residentOrder.shift(); - if (oldest !== undefined) { - this.resident.delete(oldest); - } - } - } - - private touchResident(scope: string): void { - this.residentOrder = this.residentOrder.filter((entry: string): boolean => entry !== scope); - this.residentOrder.push(scope); - } - - private evictResident(scope: string): void { - this.resident.delete(scope); - this.residentOrder = this.residentOrder.filter((entry: string): boolean => entry !== scope); - } - - private handleWriteFailure(scope: string, err: Object): void { - // Dropping the cursor turns the next incremental sync into a rewrite, which - // is the only safe assumption once a write outcome is unknown. The resident - // copy goes with it because the store may have changed underneath it. - this.forgetCursor(); - this.evictResident(scope); - RemoteLogger.error(`remote chat cache write failed: ${RemoteChatCache.reason(err)}`); - } - - /** Cache key for a session, or '' when there is nothing safe to key on. */ - private scope(sessionId: string): string { - const deviceKey = this.deviceKeyProvider().trim(); - if (!this.ready || deviceKey.length === 0 || sessionId.length === 0) { - return ''; - } - return `${deviceKey}::${sessionId}`; - } - - private static reason(err: Object): string { - return err instanceof Error ? err.message : `${err}`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCommandController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCommandController.ets deleted file mode 100644 index 7406708e9c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatCommandController.ets +++ /dev/null @@ -1,316 +0,0 @@ -import { ComposerSubmission } from '../model/ComposerSubmission'; -import { - ChatMessage, - RemoteImageContext, - SelectedImageAttachment, - SessionRolledBackResult, - SteerTurnResult, - SessionSummary -} from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { RemoteChatCache } from './RemoteChatCache'; -import { RemoteLogger } from './RemoteLogger'; - -export interface RemoteChatCommandClient { - sendMessage(sessionId: string, text: string, agentType?: string, turnId?: string): Promise; - sendMessageWithImages( - sessionId: string, - text: string, - agentType: string, - imageContexts: RemoteImageContext[], - turnId?: string - ): Promise; - steerTurn( - sessionId: string, - turnId: string, - text: string, - displayContent: string, - imageContexts: RemoteImageContext[] - ): Promise; - buildPlan(sessionId: string, planFilePath: string, planName: string, agentType: string): Promise; - cancelTask(sessionId: string, turnId?: string): Promise; - renameSession(sessionId: string, title: string): Promise; - rollbackSessionToTurn(sessionId: string, targetTurnId: string): Promise; -} - -export interface RemoteChatCommandCallbacks { - onMessagesLoaded: (messages: ChatMessage[], hasMoreMessages: boolean) => void; - onMessageCountKnown: (pollVersion: number, knownMessageCount: number) => void; - // Raised once the transcript is on screen, which for a cached session is - // before any request has been sent. Without it the loading skeleton would - // outlive the messages it is standing in for. - onTimelineReady: () => void; - // Draft ownership is captured before the RPC; the owner guards commits and rollback. - onComposerPrepared?: (sessionId: string, text: string, images: SelectedImageAttachment[]) => ComposerSubmission; - onSendSucceeded: (turnId: string, pendingActiveId: string, localMessageId: string) => void; - onSteerSucceeded?: ( - steeringId: string, - turnId: string, - displayText: string, - images: SelectedImageAttachment[] - ) => void; - onSendFailed: ( - rawText: string, - images: SelectedImageAttachment[], - localMessageId: string, - pendingActiveId: string - ) => void; - onActiveSession: (session: SessionSummary) => void; - onSessionTitleChanged: (sessionId: string, title: string) => void; - onStatusText: (statusText: string) => void; - // The status line is only rendered while the link is down, so anything the - // user asked for and did not get has to be said out loud instead. - onToast: (message: string) => void; - onBusy: (isBusy: boolean) => void; - onPollRequested: () => void; - onHistoryRequested?: (sessionId: string, older: boolean) => void; -} - -export class RemoteChatCommandController { - private readonly client: RemoteChatCommandClient; - private readonly callbacks: RemoteChatCommandCallbacks; - private readonly cache: RemoteChatCache; - constructor( - client: RemoteChatCommandClient, - callbacks: RemoteChatCommandCallbacks, - cache: RemoteChatCache - ) { - this.client = client; - this.callbacks = callbacks; - this.cache = cache; - } - - private static shortId(value: string): string { - if (value.length <= 10) return value; - return `${value.slice(0, 6)}...${value.slice(-4)}`; - } - - /** All history reads share the durable record collection and its cursor. */ - async loadMessages(sessionId: string, canApply: (sessionId: string) => boolean): Promise { - if (!sessionId || !canApply(sessionId)) return; - this.requestHistory(sessionId, false); - } - - async reloadMessages(sessionId: string, canApply: (sessionId: string) => boolean): Promise { - if (!sessionId || !canApply(sessionId)) return; - this.requestHistory(sessionId, false); - } - - async forgetMessages(sessionId: string): Promise { await this.cache.forget(sessionId); } - - async loadOlderMessages(sessionId: string, _currentPollVersion: number, - hasMoreMessages: boolean, _isBusy: boolean): Promise { - // Active generation does not prevent reading earlier durable records. - if (!sessionId || !hasMoreMessages) return; - this.requestHistory(sessionId, true); - } - - private requestHistory(sessionId: string, older: boolean): void { - if (!this.callbacks.onHistoryRequested) throw new Error('Durable session history provider is unavailable'); - this.callbacks.onHistoryRequested(sessionId, older); - } - - async sendPreparedMessage( - sessionId: string, - text: string, - agentType: string, - rawText: string, - images: SelectedImageAttachment[], - imageContexts: RemoteImageContext[], - localMessageId: string, - pendingActiveId: string, - isBusy: boolean, - remoteAvailable: boolean, - clientTurnId: string = '' - ): Promise { - if ((text.length === 0 && images.length === 0) || sessionId.length === 0 || isBusy || !remoteAvailable) { - return; - } - let submission: ComposerSubmission | undefined; - try { - this.callbacks.onBusy(true); - this.callbacks.onStatusText(images.length > 0 ? RemoteI18n.t('status.sendImage') : RemoteI18n.t('status.sendCommand')); - // The optimistic user bubble is already published. Consume its draft in - // the same synchronous submission, not after the remote acknowledgment. - submission = this.callbacks.onComposerPrepared?.(sessionId, rawText, images); - submission?.commit(); - const requestedTurnId = clientTurnId.trim().length > 0 ? clientTurnId : localMessageId; - const turnId = images.length > 0 ? - await this.client.sendMessageWithImages(sessionId, text, agentType, imageContexts, requestedTurnId) : - await this.client.sendMessage(sessionId, text, agentType, requestedTurnId); - submission = undefined; - this.callbacks.onSendSucceeded(turnId, pendingActiveId, localMessageId); - this.callbacks.onStatusText(RemoteI18n.t('status.sentWaiting')); - } catch (err) { - submission?.rollback(); - this.callbacks.onSendFailed(rawText, images, localMessageId, pendingActiveId); - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } - - async steerPreparedMessage( - sessionId: string, - turnId: string, - text: string, - displayText: string, - images: SelectedImageAttachment[], - imageContexts: RemoteImageContext[], - isBusy: boolean, - remoteAvailable: boolean - ): Promise { - if ((text.length === 0 && images.length === 0) || sessionId.length === 0 || turnId.length === 0 || - isBusy || !remoteAvailable) { - return; - } - let submission: ComposerSubmission | undefined; - try { - this.callbacks.onBusy(true); - submission = this.callbacks.onComposerPrepared?.(sessionId, displayText, images); - const result = await this.client.steerTurn( - sessionId, - turnId, - text, - displayText, - imageContexts - ); - // Steering has no optimistic bubble: consume its captured draft only - // when the host accepts it, alongside the accepted steering item. - submission?.commit(); - submission = undefined; - if (this.callbacks.onSteerSucceeded) { - this.callbacks.onSteerSucceeded(result.steeringId, result.turnId, displayText, images); - } - this.callbacks.onStatusText(RemoteI18n.t('status.sentWaiting')); - this.callbacks.onPollRequested(); - } catch (err) { - submission?.rollback(); - this.callbacks.onSendFailed(displayText, images, '', ''); - const errorText = ConnectionErrorPolicy.errorText(err); - this.callbacks.onStatusText(errorText); - this.callbacks.onToast(errorText); - } finally { - this.callbacks.onBusy(false); - } - } - - async buildPlan( - sessionId: string, - planFilePath: string, - planName: string, - agentType: string, - localMessageId: string, - pendingActiveId: string, - isBusy: boolean, - remoteAvailable: boolean - ): Promise { - if (sessionId.length === 0 || planFilePath.length === 0 || isBusy || !remoteAvailable) { - return; - } - try { - this.callbacks.onBusy(true); - const turnId = await this.client.buildPlan(sessionId, planFilePath, planName, agentType); - this.callbacks.onSendSucceeded(turnId, pendingActiveId, localMessageId); - this.callbacks.onStatusText(RemoteI18n.t('status.sentWaiting')); - this.callbacks.onPollRequested(); - } catch (err) { - this.callbacks.onSendFailed('', [], localMessageId, pendingActiveId); - const errorText = ConnectionErrorPolicy.errorText(err); - this.callbacks.onStatusText(errorText); - this.callbacks.onToast(errorText); - } finally { - this.callbacks.onBusy(false); - } - } - - async stopTask( - sessionId: string, - activeTurnMessageId: string, - activeTurnId: string, - remoteAvailable: boolean - ): Promise { - RemoteLogger.info(`stop task requested session=${RemoteChatCommandController.shortId(sessionId)} turn=${RemoteChatCommandController.shortId(activeTurnId)} active=${activeTurnMessageId.length > 0 ? '1' : '0'}`); - if (sessionId.length === 0 || !remoteAvailable) { - return; - } - if (activeTurnMessageId.length === 0) { - const nothingRunning = RemoteI18n.t('status.noRunningTask'); - this.callbacks.onStatusText(nothingRunning); - this.callbacks.onToast(nothingRunning); - return; - } - try { - this.callbacks.onStatusText(RemoteI18n.t('status.stoppingTask')); - await this.client.cancelTask(sessionId, activeTurnId); - RemoteLogger.info(`stop task accepted session=${RemoteChatCommandController.shortId(sessionId)} turn=${RemoteChatCommandController.shortId(activeTurnId)}`); - this.callbacks.onStatusText(RemoteI18n.t('status.stopRequested')); - this.callbacks.onPollRequested(); - } catch (err) { - // A rejected cancel leaves the task running, so failing quietly here is - // indistinguishable from the stop having worked. - const errorText = ConnectionErrorPolicy.errorText(err); - RemoteLogger.info(`stop task failed session=${RemoteChatCommandController.shortId(sessionId)} turn=${RemoteChatCommandController.shortId(activeTurnId)}`); - this.callbacks.onStatusText(errorText); - this.callbacks.onToast(errorText); - } - } - - /** - * Runs one rollback and hands the decoded answer back to its caller. - * - * Deliberately thin, and deliberately not swallowing anything: unlike a stop or - * a rename, a refused rollback is not the end of the interaction. The caller - * owns the staged preview, so it is the one that knows whether a refusal means - * "this view moved on, resync quietly" or "say it failed", and it can only make - * that call if the refusal arrives as a thrown error instead of a status line. - */ - async rollbackSessionToTurn(sessionId: string, targetTurnId: string): Promise { - const startedAt = Date.now(); - RemoteLogger.info( - `rollback request session=${RemoteChatCommandController.shortId(sessionId)} ` + - `target=${RemoteChatCommandController.shortId(targetTurnId)}` - ); - const result = await this.client.rollbackSessionToTurn(sessionId, targetTurnId); - RemoteLogger.info( - `rollback accepted session=${RemoteChatCommandController.shortId(sessionId)} ` + - `retired=${result.retiredTurnIds.length} restored=${result.restoredFiles.length} ` + - `changed=${result.changed ? '1' : '0'} ms=${Date.now() - startedAt}` - ); - return result; - } - - async renameActiveSession( - session: SessionSummary, - title: string, - isBusy: boolean, - remoteAvailable: boolean - ): Promise { - const sessionId = session.sessionId || ''; - const nextTitle = title.trim(); - if (sessionId.length === 0 || nextTitle.length === 0 || nextTitle === session.title || isBusy || !remoteAvailable) { - return; - } - try { - this.callbacks.onBusy(true); - this.callbacks.onStatusText(RemoteI18n.t('status.updatingTitle')); - await this.client.renameSession(sessionId, nextTitle); - const updatedSession: SessionSummary = { - sessionId, - title: nextTitle, - workspacePath: session.workspacePath, - remoteConnectionId: session.remoteConnectionId, - agentType: session.agentType, - initialTurnId: session.initialTurnId - }; - this.callbacks.onActiveSession(updatedSession); - this.callbacks.onSessionTitleChanged(sessionId, nextTitle); - this.callbacks.onStatusText(RemoteI18n.t('status.titleUpdated')); - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatLocalRdbStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatLocalRdbStore.ets deleted file mode 100644 index ca23b8271c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatLocalRdbStore.ets +++ /dev/null @@ -1,296 +0,0 @@ -import { relationalStore } from '@kit.ArkData'; -import { ChatMessage } from '../model/RemoteModels'; -import { Encoding } from './Encoding'; -import { OhosError } from './OhosError'; -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; -import { RemoteChatCacheSlice, RemoteChatCacheStore } from './RemoteChatCache'; - -const STORE_CONFIG: relationalStore.StoreConfig = { - name: HarmonyUpgradeIdentityContract.REMOTE_CHAT_DATABASE, - // A step above the S1 the general-chat store uses: these transcripts carry - // the user's source, file paths and terminal output from a machine they own. - securityLevel: relationalStore.SecurityLevel.S2 -}; - -/** - * Bumped whenever a stored row stops meaning what it used to. - * - * A cache is reconstructible by definition, so a mismatch drops the tables and - * refills them from the desktop instead of paying for a migration. - */ -// Version 1 could retain an assistant row whose id was stable while its final -// body became durable. The cache is reconstructible, so invalidate those rows -// once instead of carrying potentially hollow completed replies forward. -const SCHEMA_VERSION: number = 2; -const SCHEMA_VERSION_KEY: string = 'schema_version'; - -const CREATE_META_SQL = - 'CREATE TABLE IF NOT EXISTS remote_chat_meta (' + - 'key TEXT PRIMARY KEY, value TEXT NOT NULL)'; -const CREATE_SESSIONS_SQL = - 'CREATE TABLE IF NOT EXISTS remote_chat_sessions (' + - 'device_key TEXT NOT NULL, session_id TEXT NOT NULL, message_count INTEGER NOT NULL, ' + - 'last_message_id TEXT NOT NULL, updated_at INTEGER NOT NULL, ' + - 'PRIMARY KEY (device_key, session_id))'; -// `seq` is the message's index in the desktop's own list, not an arbitrary sort -// key: `poll_session` returns the tail after `known_msg_count` entries, so the -// two have to count the same things in the same order. -const CREATE_MESSAGES_SQL = - 'CREATE TABLE IF NOT EXISTS remote_chat_messages (' + - 'device_key TEXT NOT NULL, session_id TEXT NOT NULL, seq INTEGER NOT NULL, payload TEXT NOT NULL, ' + - 'PRIMARY KEY (device_key, session_id, seq))'; - -/** Remote transcripts on disk, keyed by the desktop that owns the session. */ -export class RemoteChatLocalRdbStore implements RemoteChatCacheStore { - private store?: relationalStore.RdbStore; - - async init(context: Context): Promise { - try { - const store = await relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_META_SQL); - if (await RemoteChatLocalRdbStore.storedSchemaVersion(store) !== SCHEMA_VERSION) { - await store.executeSql('DROP TABLE IF EXISTS remote_chat_messages'); - await store.executeSql('DROP TABLE IF EXISTS remote_chat_sessions'); - await store.executeSql( - 'INSERT OR REPLACE INTO remote_chat_meta (key, value) VALUES (?, ?)', - [SCHEMA_VERSION_KEY, `${SCHEMA_VERSION}`] - ); - } - await store.executeSql(CREATE_SESSIONS_SQL); - await store.executeSql(CREATE_MESSAGES_SQL); - this.store = store; - } catch (err) { - throw OhosError.wrap('remote chat store init', err); - } - } - - async loadSlice(deviceKey: string, sessionId: string): Promise { - try { - const store = this.requireStore(); - let expectedCount = 0; - let lastMessageId = ''; - const header = await store.querySql( - 'SELECT message_count, last_message_id FROM remote_chat_sessions ' + - 'WHERE device_key = ? AND session_id = ?', - [deviceKey, sessionId] - ); - try { - if (header.goToNextRow()) { - expectedCount = header.getLong(header.getColumnIndex('message_count')); - lastMessageId = header.getString(header.getColumnIndex('last_message_id')); - } - } finally { - RemoteChatLocalRdbStore.closeResult(header); - } - if (expectedCount <= 0) { - return { messages: [], lastMessageId: '' }; - } - - const messages: ChatMessage[] = []; - const rows = await store.querySql( - 'SELECT payload FROM remote_chat_messages ' + - 'WHERE device_key = ? AND session_id = ? AND seq < ? ORDER BY seq ASC', - [deviceKey, sessionId, expectedCount] - ); - try { - const payloadColumn = rows.getColumnIndex('payload'); - while (rows.goToNextRow()) { - messages.push(Encoding.parseJsonObject(rows.getString(payloadColumn))); - } - } finally { - RemoteChatLocalRdbStore.closeResult(rows); - } - // Fewer rows than the header claims means a write was interrupted partway. - // Reporting a miss costs one fetch; reporting the rows would show the user - // a transcript with messages missing out of the middle. - if (messages.length !== expectedCount) { - return { messages: [], lastMessageId: '' }; - } - await this.touchSession(deviceKey, sessionId); - return { messages, lastMessageId }; - } catch (err) { - throw OhosError.wrap('remote chat load slice', err); - } - } - - async appendMessages( - deviceKey: string, - sessionId: string, - startSeq: number, - messages: ChatMessage[], - lastMessageId: string - ): Promise { - if (messages.length === 0) { - return; - } - try { - const store = this.requireStore(); - // Clearing the range first makes a retried append idempotent, which is what - // lets the write run without a transaction around it. - await store.executeSql( - 'DELETE FROM remote_chat_messages WHERE device_key = ? AND session_id = ? AND seq >= ?', - [deviceKey, sessionId, startSeq] - ); - await store.batchInsert( - 'remote_chat_messages', - RemoteChatLocalRdbStore.rows(deviceKey, sessionId, startSeq, messages) - ); - await this.writeHeader(deviceKey, sessionId, startSeq + messages.length, lastMessageId); - } catch (err) { - throw OhosError.wrap('remote chat append messages', err); - } - } - - async replaceMessages( - deviceKey: string, - sessionId: string, - messages: ChatMessage[], - lastMessageId: string - ): Promise { - try { - const store = this.requireStore(); - await store.executeSql( - 'DELETE FROM remote_chat_messages WHERE device_key = ? AND session_id = ?', - [deviceKey, sessionId] - ); - if (messages.length > 0) { - await store.batchInsert( - 'remote_chat_messages', - RemoteChatLocalRdbStore.rows(deviceKey, sessionId, 0, messages) - ); - } - await this.writeHeader(deviceKey, sessionId, messages.length, lastMessageId); - } catch (err) { - throw OhosError.wrap('remote chat replace messages', err); - } - } - - async deleteSession(deviceKey: string, sessionId: string): Promise { - try { - const store = this.requireStore(); - await store.executeSql( - 'DELETE FROM remote_chat_messages WHERE device_key = ? AND session_id = ?', - [deviceKey, sessionId] - ); - await store.executeSql( - 'DELETE FROM remote_chat_sessions WHERE device_key = ? AND session_id = ?', - [deviceKey, sessionId] - ); - } catch (err) { - throw OhosError.wrap('remote chat delete session', err); - } - } - - async pruneSessions(deviceKey: string, keepMostRecent: number): Promise { - try { - const store = this.requireStore(); - const stale = - 'SELECT session_id FROM remote_chat_sessions WHERE device_key = ? ' + - 'ORDER BY updated_at DESC LIMIT -1 OFFSET ?'; - await store.executeSql( - `DELETE FROM remote_chat_messages WHERE device_key = ? AND session_id IN (${stale})`, - [deviceKey, deviceKey, keepMostRecent] - ); - await store.executeSql( - `DELETE FROM remote_chat_sessions WHERE device_key = ? AND session_id IN (${stale})`, - [deviceKey, deviceKey, keepMostRecent] - ); - } catch (err) { - throw OhosError.wrap('remote chat prune sessions', err); - } - } - - async clearAll(): Promise { - try { - const store = this.requireStore(); - await store.executeSql('DELETE FROM remote_chat_messages'); - await store.executeSql('DELETE FROM remote_chat_sessions'); - } catch (err) { - throw OhosError.wrap('remote chat clear all', err); - } - } - - /** Keeps [pruneSessions] evicting the sessions the user stopped opening. */ - private async touchSession(deviceKey: string, sessionId: string): Promise { - try { - await this.requireStore().executeSql( - 'UPDATE remote_chat_sessions SET updated_at = ? WHERE device_key = ? AND session_id = ?', - [Date.now(), deviceKey, sessionId] - ); - } catch (err) { - throw OhosError.wrap('remote chat touch session', err); - } - } - - private async writeHeader( - deviceKey: string, - sessionId: string, - messageCount: number, - lastMessageId: string - ): Promise { - const values: relationalStore.ValuesBucket = { - device_key: deviceKey, - session_id: sessionId, - message_count: messageCount, - last_message_id: lastMessageId, - updated_at: Date.now() - }; - try { - await this.requireStore().insert( - 'remote_chat_sessions', - values, - relationalStore.ConflictResolution.ON_CONFLICT_REPLACE - ); - } catch (err) { - throw OhosError.wrap('remote chat write header', err); - } - } - - private static rows( - deviceKey: string, - sessionId: string, - startSeq: number, - messages: ChatMessage[] - ): relationalStore.ValuesBucket[] { - return messages.map((message: ChatMessage, index: number): relationalStore.ValuesBucket => ({ - device_key: deviceKey, - session_id: sessionId, - seq: startSeq + index, - payload: JSON.stringify(message) - })); - } - - private static async storedSchemaVersion(store: relationalStore.RdbStore): Promise { - try { - const result = await store.querySql( - 'SELECT value FROM remote_chat_meta WHERE key = ?', - [SCHEMA_VERSION_KEY] - ); - try { - if (!result.goToNextRow()) { - return 0; - } - return Number.parseInt(result.getString(result.getColumnIndex('value')), 10) || 0; - } finally { - RemoteChatLocalRdbStore.closeResult(result); - } - } catch (err) { - throw OhosError.wrap('remote chat schema version', err); - } - } - - private static closeResult(result: relationalStore.ResultSet): void { - try { - result.close(); - } catch (err) { - throw OhosError.wrap('remote chat close cursor', err); - } - } - - private requireStore(): relationalStore.RdbStore { - if (!this.store) { - throw new Error('Remote chat local store is not initialized.'); - } - return this.store; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets deleted file mode 100644 index daaf72f1e4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets +++ /dev/null @@ -1,72 +0,0 @@ -import { MessageQueueAction } from '../model/MessageQueue'; -import { InteractionMailboxAction } from '../model/InteractionMailbox'; -import { ChatMessage } from '../model/RemoteModels'; -import { - ChatSessionController, - ChatSessionControllerCallbacks, - ChatSessionCursor, - ChatSessionSnapshot -} from './ChatSessionController'; -import { SubagentBranchCache } from './SubagentStreamCoordinator'; -import { RemoteSessionManager } from './RemoteSessionManager'; - -export type RemoteChatPollingCursor = ChatSessionCursor; -export type RemoteChatPollingSnapshot = ChatSessionSnapshot; - -export interface RemoteChatPollingStartSnapshot { - sessionId: string; - cursor: RemoteChatPollingCursor; - activeTurn?: ChatMessage; -} - -export type RemoteChatPollingLifecycleCallbacks = ChatSessionControllerCallbacks; - -export class RemoteChatPollingLifecycleController { - private readonly controller: ChatSessionController; - - constructor(sessionManager: RemoteSessionManager, callbacks: ChatSessionControllerCallbacks, - branchCache?: SubagentBranchCache) { - this.controller = new ChatSessionController(sessionManager, callbacks, { - initialPollDelayMs: 400, - branchCache: branchCache - }); - } - - startActiveSession(snapshot: RemoteChatPollingStartSnapshot): void { - if (snapshot.sessionId.length === 0) { - return; - } - this.controller.start(snapshot.sessionId, snapshot.cursor, snapshot.activeTurn); - } - - stop(): void { - this.controller.stop(); - } - - async dispatchQueue(action: MessageQueueAction): Promise { await this.controller.dispatchQueue(action); } - async dispatchMailbox(action: InteractionMailboxAction): Promise { await this.controller.dispatchMailbox(action); } - - async refreshModelCatalog(): Promise { await this.controller.refreshModelCatalog(); } - - loadOlder(): void { this.controller.loadOlder(); } - - ensureBranchSubscribed(ownerToolCallId: string): void { - this.controller.ensureBranchSubscribed(ownerToolCallId); - } - - nudge(): void { - this.controller.nudge(); - } - - async pollNow(): Promise { - await this.controller.pollNow(); - } - - updateCursor(cursor: RemoteChatPollingCursor): void { - this.controller.updateCursor(cursor); - } - - updateKnownModelCatalogVersion(version: number): void { - this.controller.updateKnownModelCatalogVersion(version); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandFactory.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandFactory.ets deleted file mode 100644 index b7f28da500..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandFactory.ets +++ /dev/null @@ -1,344 +0,0 @@ -import { - CreateSessionOptions, - RemoteCommand, - RemoteImageContext, - RemotePermissionMode, - RemoteQuestionAnswerPayload, - RemoteWorkspaceIdentity -} from '../model/RemoteModels'; - -/** - * Builds the RemoteCommand wire shapes. - * - * Workspace references follow one rule: when the caller knows the - * `workspaceId`, the command carries only `workspace_id`, so an ID-aware host - * can never silently fall back to a path. The legacy `(path, connection, - * ssh host)` projection is sent only for references that never had an ID. - */ -export class RemoteCommandFactory { - static getWorkspaceInfo(): RemoteCommand { - return { cmd: 'get_workspace_info' }; - } - - static listRecentWorkspaces(): RemoteCommand { - return { cmd: 'list_recent_workspaces' }; - } - - static setWorkspace(path: string, workspaceId?: string, remoteConnectionId?: string, remoteSshHost?: string): RemoteCommand { - if (workspaceId) { - return { cmd: 'set_workspace', workspace_id: workspaceId }; - } - // Upgrade-only command for pre-ID references: the host resolves the path - // through its legacy resolver and rejects unknown or ambiguous roots. - const command: RemoteCommand = { - cmd: 'set_workspace', - path - }; - if (remoteConnectionId !== undefined) { - command.remote_connection_id = remoteConnectionId; - } - if (remoteSshHost !== undefined) { - command.remote_ssh_host = remoteSshHost; - } - return command; - } - - static listAssistants(): RemoteCommand { - return { cmd: 'list_assistants' }; - } - - static setAssistant(path: string, workspaceId?: string): RemoteCommand { - if (workspaceId) { - return { cmd: 'set_assistant', workspace_id: workspaceId }; - } - return { - cmd: 'set_assistant', - path - }; - } - - static listSessions(workspace: RemoteWorkspaceIdentity, limit: number, offset: number, query: string): RemoteCommand { - const command: RemoteCommand = { cmd: 'list_sessions' }; - if (workspace.workspaceId) { - command.workspace_id = workspace.workspaceId; - } else { - command.workspace_path = workspace.path; - } - command.limit = limit; - command.offset = offset; - if (query.trim().length > 0) { - command.query = query.trim(); - } - if (!workspace.workspaceId) { - if (workspace.remoteConnectionId !== undefined) { - command.remote_connection_id = workspace.remoteConnectionId; - } - if (workspace.remoteSshHost !== undefined) { - command.remote_ssh_host = workspace.remoteSshHost; - } - } - return command; - } - - static createSession(options: CreateSessionOptions, workspacePath: string): RemoteCommand { - const command: RemoteCommand = { - cmd: 'create_session', - agent_type: options.agentType, - session_name: options.title.trim() - }; - if (options.workspaceId) { - command.workspace_id = options.workspaceId; - return command; - } - if (workspacePath) { - command.workspace_path = workspacePath; - command.remote_connection_id = options.remoteConnectionId || ''; - command.remote_ssh_host = options.remoteSshHost; - } - return command; - } - - static sendMessage( - sessionId: string, - text: string, - agentType?: string, - imageContexts?: RemoteImageContext[], - turnId?: string - ): RemoteCommand { - const command: RemoteCommand = { - cmd: 'send_message', - session_id: sessionId, - content: text - }; - if (agentType && agentType.length > 0) { - command.agent_type = agentType; - } - if (imageContexts && imageContexts.length > 0) { - command.image_contexts = imageContexts; - } - if (turnId && turnId.length > 0) { - command.turn_id = turnId; - } - return command; - } - - static steerTurn( - sessionId: string, - turnId: string, - text: string, - displayContent: string, - imageContexts?: RemoteImageContext[] - ): RemoteCommand { - const command: RemoteCommand = { - cmd: 'steer_turn', - session_id: sessionId, - turn_id: turnId, - content: text, - display_content: displayContent - }; - if (imageContexts && imageContexts.length > 0) { - command.image_contexts = imageContexts; - } - return command; - } - - static buildPlan(sessionId: string, planFilePath: string, planName: string, agentType?: string): RemoteCommand { - const command: RemoteCommand = { - cmd: 'build_plan', - session_id: sessionId, - plan_file_path: planFilePath, - plan_name: planName - }; - if (agentType && agentType.length > 0) { - command.agent_type = agentType; - } - return command; - } - - static getSessionMessages(sessionId: string): RemoteCommand { - return { - cmd: 'get_session_messages', - session_id: sessionId - }; - } - - static getModelCatalog(sessionId?: string): RemoteCommand { - const command: RemoteCommand = { cmd: 'get_model_catalog' }; - if (sessionId && sessionId.length > 0) { - command.session_id = sessionId; - } - return command; - } - - static setSessionModel(sessionId: string, modelId: string): RemoteCommand { - return { - cmd: 'set_session_model', - session_id: sessionId, - model_id: modelId - }; - } - - /** - * Writes the three phone-managed device model slots as one object. - * - * `null` is a value, not an omission: fast follows the primary model and the - * other two are left unconfigured. The host reads an absent key as "leave - * unchanged", so only an explicit `null` clears a slot. - */ - static setModelDefaults(primary: string | null, fast: string | null, imageUnderstanding: string | null): RemoteCommand { - return { - cmd: 'set_model_defaults', - primary, - fast, - image_understanding: imageUnderstanding - }; - } - - static pollSession( - sessionId: string, - sinceVersion: number, - knownMessageCount: number, - knownModelCatalogVersion: number - ): RemoteCommand { - return { - cmd: 'poll_session', - session_id: sessionId, - since_version: sinceVersion, - known_msg_count: knownMessageCount, - known_model_catalog_version: knownModelCatalogVersion - }; - } - - static cancelTask(sessionId: string, turnId?: string): RemoteCommand { - const command: RemoteCommand = { - cmd: 'cancel_task', - session_id: sessionId - }; - if (turnId && turnId.length > 0) { - command.turn_id = turnId; - } - return command; - } - - static renameSession(sessionId: string, title: string): RemoteCommand { - return { - cmd: 'update_session_title', - session_id: sessionId, - title - }; - } - - static deleteSession(sessionId: string): RemoteCommand { - return { - cmd: 'delete_session', - session_id: sessionId - }; - } - - /** - * Withdraw `targetTurnId` and every turn after it, then restore the files - * those turns touched. The target turn is withdrawn too, and its prompt comes - * back in the reply's `composer_text`. - * - * `expectedStorageTurnIndex` is the stale-view guard: the host refuses the - * rollback when the turn it would address is no longer the one the caller - * saw. Omitting it — which is what the phone does today, because no projected - * message carries a storage index — only widens the race window and never - * changes which turn is addressed, so it is omitted rather than sent as an - * empty value. - */ - static rollbackSessionToTurn(sessionId: string, targetTurnId: string, expectedStorageTurnIndex?: number): RemoteCommand { - const command: RemoteCommand = { - cmd: 'rollback_session_to_turn', - session_id: sessionId, - target_turn_id: targetTurnId - }; - if (expectedStorageTurnIndex !== undefined) { - command.expected_storage_turn_index = expectedStorageTurnIndex; - } - return command; - } - - static confirmTool(toolId: string, updatedInput?: Object): RemoteCommand { - return { - cmd: 'confirm_tool', - tool_id: toolId, - updated_input: updatedInput - }; - } - - static rejectTool(toolId: string, reason: string): RemoteCommand { - return { - cmd: 'reject_tool', - tool_id: toolId, - reason - }; - } - - static cancelTool(toolId: string, reason: string): RemoteCommand { - return { - cmd: 'cancel_tool', - tool_id: toolId, - reason - }; - } - - static getPermissionMode(): RemoteCommand { - return { cmd: 'get_permission_mode' }; - } - - static setPermissionMode(mode: RemotePermissionMode): RemoteCommand { - return { cmd: 'set_permission_mode', mode }; - } - - static answerQuestion(toolId: string, answers: RemoteQuestionAnswerPayload): RemoteCommand { - return { - cmd: 'answer_question', - tool_id: toolId, - answers - }; - } - - static getFileInfo(path: string, sessionId?: string): RemoteCommand { - const command: RemoteCommand = { - cmd: 'get_file_info', - path - }; - if (sessionId && sessionId.length > 0) { - command.session_id = sessionId; - } - return command; - } - - static readFileChunk(path: string, offset: number, limit: number, sessionId?: string): RemoteCommand { - const command: RemoteCommand = { - cmd: 'read_file_chunk', - path, - offset, - limit - }; - if (sessionId && sessionId.length > 0) { - command.session_id = sessionId; - } - return command; - } - - static ping(): RemoteCommand { - return { cmd: 'ping' }; - } - - /** - * Ask the paired desktop to register a keyboard-less device on the account. - * `requestId` comes from that device rather than from here, so a retry - * anywhere along the watch → phone → desktop chain replays one idempotent - * relay request instead of registering a second device. - */ - static provisionPeerDevice(deviceId: string, deviceName: string, requestId: string): RemoteCommand { - return { - cmd: 'provision_peer_device', - device_id: deviceId, - device_name: deviceName, - request_id: requestId - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandPaletteController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandPaletteController.ets deleted file mode 100644 index 231fe000cb..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandPaletteController.ets +++ /dev/null @@ -1,329 +0,0 @@ -import { - RemoteCommandCatalog, - RemoteSessionUsageReport -} from '../model/RemoteModels'; -import { CommandPaletteNoticeKind, CommandPalettePolicy, CommandPaletteProbeFailure } from './CommandPalettePolicy'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { hostInvokeRefusalText, isHostInvokeRefusal } from './HostInvokeRefusal'; -import { RemoteLogger } from './RemoteLogger'; - -/** - * The wire side of the composer command palette. - * - * Four desktop verbs — one read (the skill catalog) and three actions (compact, - * init, usage) — travel as `host_invoke` calls over the connection the phone - * already has. Nothing here needs a capability handshake: the first catalog read - * *is* the probe, and its answer decides whether the row may run anything. A - * host that predates one of these commands refuses it with its own error text, - * which the row shows instead of pretending the tap did nothing. - * - * The catalog is cached per session; it is read on entry, never on render. - */ -export interface RemoteCommandPaletteScope { - sessionId: string; - /** Owning workspace record ID; the paths below are its IO projection. */ - workspaceId?: string; - workspacePath?: string; - remoteConnectionId?: string; - remoteSshHost?: string; -} - -export interface RemoteSkillCatalogQuery extends RemoteCommandPaletteScope { - /** The active session's agent type, which is the host's mode id. */ - modeId: string; - forceRefresh: boolean; -} - -export interface RemoteCommandPaletteClient { - /** Resolves with the host's answer; rejects when the host cannot serve it. */ - skillCatalog(query: RemoteSkillCatalogQuery): Promise; - compactSession(query: RemoteCommandPaletteScope): Promise; - runInitAgentsMd(query: RemoteCommandPaletteScope): Promise; - sessionUsageReport(query: RemoteCommandPaletteScope): Promise; -} - -export interface RemoteCommandPaletteCallbacks { - onCatalogLoading: (sessionId: string) => void; - onCatalogReady: (sessionId: string, catalog: RemoteCommandCatalog) => void; - /** - * The read failed. `failure` is how it failed — a host that refused, or a - * connection that never reached one — and it is what decides whether the row - * may tell the user their desktop is out of date. - */ - onCatalogFailed: (sessionId: string, errorText: string, failure: string) => void; - onCommandStarted: (sessionId: string, wireAction: string) => void; - /** A settled verb. `errorText` is empty on success, and the host's message is. */ - onCommandSettled: (sessionId: string, wireAction: string, errorText: string, message: string) => void; - /** The completion line has been up for its dwell time and may fade out. */ - onCommandNoticeExpired: (sessionId: string, wireAction: string) => void; - onUsageLoading: (sessionId: string) => void; - onUsageReady: (sessionId: string, report: RemoteSessionUsageReport | undefined) => void; - onUsageFailed: (sessionId: string, errorText: string) => void; -} - -/** - * How far the palette's behavior probe has got for the active session. - * - * There is no capability handshake to consult, so the picker reads this instead: - * `Probed` is the state whose rows may be listed, `Unprobed` is where every - * session starts (and reads like a waiting chip for one round trip), and - * `Failed` is a read that did not answer — which is a reason to re-check, and - * only sometimes a reason to upgrade. - */ -export enum CommandPaletteProbe { - Unprobed = 'unprobed', - Probed = 'probed', - Failed = 'failed' -} - -export class RemoteCommandPaletteController { - private readonly client: RemoteCommandPaletteClient; - private readonly callbacks: RemoteCommandPaletteCallbacks; - private catalogSessionId: string = ''; - private catalog?: RemoteCommandCatalog; - /** The probe's answer for `catalogSessionId`. */ - private catalogProbe: string = CommandPaletteProbe.Unprobed; - /** How the read failed, for `catalogSessionId`. */ - private catalogFailure: string = CommandPaletteProbeFailure.None; - /** The host's own text for a failed probe, shown where the row explains itself. */ - private catalogErrorText: string = ''; - /** Wire id of the palette verb in flight, or '' when the row is idle. */ - private runningAction: string = ''; - private noticeTimerId: number = -1; - - constructor(client: RemoteCommandPaletteClient, callbacks: RemoteCommandPaletteCallbacks) { - this.client = client; - this.callbacks = callbacks; - } - - runningCommand(): string { - return this.runningAction; - } - - isRunning(): boolean { - return this.runningAction.length > 0; - } - - catalogFor(sessionId: string): RemoteCommandCatalog | undefined { - return this.catalogSessionId === sessionId ? this.catalog : undefined; - } - - /** Whether a read for this session has already answered for this session. */ - catalogProbeFor(sessionId: string): string { - return this.catalogSessionId === sessionId ? this.catalogProbe : CommandPaletteProbe.Unprobed; - } - - /** How this session's failed read failed, or `None` when it did not. */ - catalogFailureFor(sessionId: string): string { - return this.catalogSessionId === sessionId ? this.catalogFailure : CommandPaletteProbeFailure.None; - } - - /** The host's refusal text for this session's failed probe, or ''. */ - catalogErrorFor(sessionId: string): string { - return this.catalogSessionId === sessionId ? this.catalogErrorText : ''; - } - - /** Drops the cached catalog and pending notice when the conversation ends. */ - reset(): void { - this.cancelNoticeTimer(); - this.catalogSessionId = ''; - this.catalog = undefined; - this.catalogProbe = CommandPaletteProbe.Unprobed; - this.catalogFailure = CommandPaletteProbeFailure.None; - this.catalogErrorText = ''; - this.runningAction = ''; - } - - private static shortSessionId(sessionId: string): string { - return sessionId.length <= 8 ? sessionId : - `${sessionId.slice(0, 4)}...${sessionId.slice(sessionId.length - 4)}`; - } - - /** - * Reads the skill catalog for one session — the palette's behavior probe. - * - * `force` is the user's 「重新检查」: it replays a read that failed, so a - * desktop upgraded since the last attempt is picked up without restarting the - * app. A non-forced call with an answer already in hand does not read again — - * that is what keeps this off the render path — but it does hand the answer - * back, because the cache outlives the state it was painted into. Re-entering a - * session drops the page's palette state while this controller keeps the - * answer, so a silent early return would draw a row that waits for an answer - * this controller already has. - */ - async loadCatalog( - sessionId: string, - modeId: string, - force: boolean, - canApply: (sessionId: string) => boolean - ): Promise { - if (sessionId.length === 0 || !canApply(sessionId)) { - return; - } - if (!force && this.catalogSessionId === sessionId && - this.catalogProbe !== CommandPaletteProbe.Unprobed) { - this.republishProbeAnswer(sessionId); - return; - } - this.catalogSessionId = sessionId; - this.catalogProbe = CommandPaletteProbe.Unprobed; - this.catalogFailure = CommandPaletteProbeFailure.None; - this.catalogErrorText = ''; - if (force) { - this.catalog = undefined; - } - this.callbacks.onCatalogLoading(sessionId); - try { - const catalog = await this.client.skillCatalog({ - sessionId, - modeId, - forceRefresh: force - }); - if (!canApply(sessionId)) { - return; - } - this.catalog = catalog; - this.catalogProbe = CommandPaletteProbe.Probed; - this.callbacks.onCatalogReady(sessionId, catalog); - RemoteLogger.info( - `command catalog loaded session=${RemoteCommandPaletteController.shortSessionId(sessionId)} ` + - `mode=${modeId} skills=${catalog.skills.length} refreshed=${force ? '1' : '0'}`); - } catch (err) { - if (!canApply(sessionId)) { - return; - } - // A read that did not answer leaves the picker's chip waiting for a - // re-check, and only a host that named the version gap gets the upgrade - // badge: "your desktop is too old" is not a thing to say about a timeout. - const answered = isHostInvokeRefusal(err); - const errorText = answered ? hostInvokeRefusalText(err) : ConnectionErrorPolicy.errorText(err); - this.catalog = undefined; - this.catalogProbe = CommandPaletteProbe.Failed; - this.catalogErrorText = errorText; - this.catalogFailure = CommandPalettePolicy.probeFailure(answered, errorText); - RemoteLogger.warn( - `command catalog failed session=${RemoteCommandPaletteController.shortSessionId(sessionId)} ` + - `failure=${this.catalogFailure}: ${String(err)}`); - this.callbacks.onCatalogFailed(sessionId, this.catalogErrorText, this.catalogFailure); - } - } - - /** - * Hands the cached answer back to whoever is painting the row now. - * - * The controller owns the probe's answer and the page owns its presentation; - * re-publishing keeps one owner of the truth instead of letting the two drift - * apart across a session that is left and re-entered. - */ - private republishProbeAnswer(sessionId: string): void { - if (this.catalogProbe === CommandPaletteProbe.Probed && this.catalog !== undefined) { - this.callbacks.onCatalogReady(sessionId, this.catalog); - return; - } - if (this.catalogProbe === CommandPaletteProbe.Failed) { - this.callbacks.onCatalogFailed(sessionId, this.catalogErrorText, this.catalogFailure); - } - } - - /** - * Runs one of the two verbs that execute immediately. - * - * Single-shot: a second tap while the first is still out is dropped rather - * than queued, because the host would either refuse it or act on a context the - * user has not seen the result of yet. - */ - async runCommand( - sessionId: string, - wireAction: string, - query: RemoteCommandPaletteScope, - canApply: (sessionId: string) => boolean - ): Promise { - if (sessionId.length === 0 || wireAction.length === 0 || this.isRunning() || !canApply(sessionId)) { - return; - } - this.cancelNoticeTimer(); - this.runningAction = wireAction; - this.callbacks.onCommandStarted(sessionId, wireAction); - const startedAt = Date.now(); - try { - const message = wireAction === CommandPalettePolicy.initWireAction ? - await this.client.runInitAgentsMd(query) : - await this.client.compactSession(query); - if (!canApply(sessionId)) { - this.runningAction = ''; - return; - } - this.runningAction = ''; - RemoteLogger.info( - `command palette accepted session=${RemoteCommandPaletteController.shortSessionId(sessionId)} ` + - `action=${wireAction} ms=${Date.now() - startedAt}`); - this.callbacks.onCommandSettled(sessionId, wireAction, '', message); - this.scheduleNoticeExpiry(sessionId, wireAction); - } catch (err) { - this.runningAction = ''; - if (!canApply(sessionId)) { - return; - } - const errorText = ConnectionErrorPolicy.errorText(err); - RemoteLogger.warn( - `command palette failed session=${RemoteCommandPaletteController.shortSessionId(sessionId)} ` + - `action=${wireAction}: ${String(err)}`); - this.callbacks.onCommandSettled(sessionId, wireAction, errorText, ''); - } - } - - /** - * The session usage report, read on every open. - * - * Usage is a snapshot by nature, so unlike the catalog it is never served from - * a cache: the numbers the user asked for are the ones measured when they - * asked. - */ - async loadUsageReport( - sessionId: string, - query: RemoteCommandPaletteScope, - canApply: (sessionId: string) => boolean - ): Promise { - if (sessionId.length === 0 || !canApply(sessionId)) { - return; - } - this.callbacks.onUsageLoading(sessionId); - const startedAt = Date.now(); - try { - const report = await this.client.sessionUsageReport(query); - if (!canApply(sessionId)) { - return; - } - RemoteLogger.info( - `session usage report loaded session=${RemoteCommandPaletteController.shortSessionId(sessionId)} ` + - `present=${report ? '1' : '0'} ms=${Date.now() - startedAt}`); - this.callbacks.onUsageReady(sessionId, report); - } catch (err) { - if (!canApply(sessionId)) { - return; - } - RemoteLogger.warn( - `session usage report failed session=${RemoteCommandPaletteController.shortSessionId(sessionId)}: ${String(err)}`); - this.callbacks.onUsageFailed(sessionId, ConnectionErrorPolicy.errorText(err)); - } - } - - private scheduleNoticeExpiry(sessionId: string, wireAction: string): void { - const dwell = CommandPalettePolicy.noticeDwellMs(CommandPaletteNoticeKind.Done); - if (dwell <= 0) { - return; - } - this.cancelNoticeTimer(); - this.noticeTimerId = setTimeout((): void => { - this.noticeTimerId = -1; - this.callbacks.onCommandNoticeExpired(sessionId, wireAction); - }, dwell); - } - - private cancelNoticeTimer(): void { - if (this.noticeTimerId !== -1) { - clearTimeout(this.noticeTimerId); - this.noticeTimerId = -1; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandTransport.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandTransport.ets deleted file mode 100644 index 963e3082b5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCommandTransport.ets +++ /dev/null @@ -1,56 +0,0 @@ -import { HostSessionCallbacks, HostSessionStream } from './HostSessionStream'; -import { CloudAccountClient, CloudAccountSession } from './CloudAccountClient'; -import { CommandStatusResponse, RemoteCommand } from '../model/RemoteModels'; - -/** Interactive directory rows must fail fast enough to leave a usable retry. */ -export const INTERACTIVE_DIRECTORY_TIMEOUT_MS: number = 15000; - -export interface RemoteCommandTransport { - send(command: RemoteCommand, timeoutMs?: number): Promise; - subscribeSession?(logicalId: string, callbacks: HostSessionCallbacks): HostSessionStream; - reset(): void; -} - -export class AccountDeviceCommandTransport implements RemoteCommandTransport { - private streams: Set = new Set(); - private readonly client: CloudAccountClient; - private readonly relayUrl: string; - private readonly session: CloudAccountSession; - private readonly targetDeviceId: string; - - constructor( - client: CloudAccountClient, - relayUrl: string, - session: CloudAccountSession, - targetDeviceId: string - ) { - this.client = client; - this.relayUrl = relayUrl; - this.session = session; - this.targetDeviceId = targetDeviceId; - } - - /** - * The default is the relay's read timeout, not the room transport's 30 s: an - * account command crosses one more hop and the desktop may be waking a cold - * process. It was previously ignored outright, so a caller asking for a - * shorter deadline silently got two minutes — which is the whole wait a - * failed device switch used to cost. - */ - async send(command: RemoteCommand, timeoutMs: number = 130000): Promise { - return this.client.deviceRpc(this.relayUrl, this.session, this.targetDeviceId, command, timeoutMs); - } - - subscribeSession(logicalId: string, callbacks: HostSessionCallbacks): HostSessionStream { - this.streams.forEach((existing: HostSessionStream) => { if (existing.isClosed()) this.streams.delete(existing); }); - const stream = this.client.subscribeSession(this.relayUrl, this.session, this.targetDeviceId, logicalId, callbacks); - this.streams.add(stream); - return stream; - } - - reset(): void { - this.streams.forEach((stream: HostSessionStream) => stream.close()); - this.streams.clear(); - // Account credentials are owned by CloudAccountSessionStore, not by this transport. - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteConnectionCoordinator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteConnectionCoordinator.ets deleted file mode 100644 index ecf36d3296..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteConnectionCoordinator.ets +++ /dev/null @@ -1,20 +0,0 @@ -import { RemoteSessionManager } from './RemoteSessionManager'; -import { AsyncLifecycleGate } from './AsyncLifecycleGate'; - -/** Connection lifetime shared by account selection and the activity monitor. */ -export class RemoteConnectionCoordinator { - private readonly sessionManager: RemoteSessionManager; - private readonly lifecycleGate: AsyncLifecycleGate; - - constructor(sessionManager: RemoteSessionManager, lifecycleGate: AsyncLifecycleGate) { - this.sessionManager = sessionManager; - this.lifecycleGate = lifecycleGate; - } - - invalidate(): void { this.lifecycleGate.invalidate(); } - async ping(): Promise { await this.sessionManager.ping(); } - reset(): void { - this.invalidate(); - this.sessionManager.reset(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCrypto.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCrypto.ets deleted file mode 100644 index 5f10f5f449..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteCrypto.ets +++ /dev/null @@ -1,120 +0,0 @@ -import { cryptoFramework } from '@kit.CryptoArchitectureKit'; -import { Encoding } from './Encoding'; -import { OhosError } from './OhosError'; -import { X25519, X25519KeyPair } from './X25519'; -import { EncryptedPayload } from '../model/RemoteModels'; - -export interface RemoteCryptoCipher { - encrypt(plainBytes: Uint8Array, key: Uint8Array, nonce: Uint8Array): Promise; - decrypt(encryptedBytes: Uint8Array, key: Uint8Array, nonce: Uint8Array): Promise; -} - -export interface RemoteCryptoOptions { - cipher?: RemoteCryptoCipher; - keyPair?: X25519KeyPair; - randomBytes?: (size: number) => Uint8Array; -} - -export class HarmonyRemoteCryptoCipher implements RemoteCryptoCipher { - async encrypt(plainBytes: Uint8Array, key: Uint8Array, nonce: Uint8Array): Promise { - try { - const symKey = await cryptoFramework.createSymKeyGenerator('AES256').convertKey({ data: key }); - const cipher = cryptoFramework.createCipher('AES256|GCM|NoPadding'); - const params: cryptoFramework.GcmParamsSpec = { - algName: 'GcmParamsSpec', - iv: { data: nonce }, - aad: { data: new Uint8Array(0) }, - authTag: { data: new Uint8Array(0) } - }; - await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, params); - const out = await cipher.doFinal({ data: plainBytes }); - const data = out.data; - if (data.length > plainBytes.length) { - return data; - } - return Encoding.concat(data, params.authTag.data); - } catch (err) { - throw OhosError.wrap('remote encrypt', err); - } - } - - async decrypt(encryptedBytes: Uint8Array, key: Uint8Array, nonce: Uint8Array): Promise { - if (encryptedBytes.length < 16) { - throw new Error('Encrypted payload is too short.'); - } - const cipherText = encryptedBytes.slice(0, encryptedBytes.length - 16); - const authTag = encryptedBytes.slice(encryptedBytes.length - 16); - try { - const symKey = await cryptoFramework.createSymKeyGenerator('AES256').convertKey({ data: key }); - const cipher = cryptoFramework.createCipher('AES256|GCM|NoPadding'); - const params: cryptoFramework.GcmParamsSpec = { - algName: 'GcmParamsSpec', - iv: { data: nonce }, - aad: { data: new Uint8Array(0) }, - authTag: { data: authTag } - }; - await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, params); - const out = await cipher.doFinal({ data: cipherText }); - return out.data; - } catch (err) { - throw OhosError.wrap('remote decrypt', err); - } - } -} - -export class RemoteCrypto { - readonly keyPair: X25519KeyPair; - private sharedKey?: Uint8Array; - private readonly cipher: RemoteCryptoCipher; - private readonly randomBytes: (size: number) => Uint8Array; - - constructor(options: RemoteCryptoOptions = {}) { - this.keyPair = options.keyPair || X25519.generateKeyPair(); - this.cipher = options.cipher || new HarmonyRemoteCryptoCipher(); - this.randomBytes = options.randomBytes || Encoding.randomBytes; - } - - getPublicKeyBase64(): string { - return Encoding.bytesToBase64(this.keyPair.publicKey); - } - - deriveSharedKey(peerPublicKeyBase64: string): void { - const peerPublicKey = Encoding.base64ToBytes(peerPublicKeyBase64); - this.sharedKey = X25519.scalarMult(this.keyPair.privateKey, peerPublicKey); - } - - async encryptJson(payload: Object): Promise { - const json = JSON.stringify(payload); - const plainBytes = Encoding.utf8ToBytes(json); - const nonce = this.randomBytes(12); - const encrypted = await this.encryptBytes(plainBytes, nonce); - const result = new EncryptedPayload(); - result.encrypted_data = Encoding.bytesToBase64(encrypted); - result.nonce = Encoding.bytesToBase64(nonce); - return result; - } - - async decryptJson(payload: EncryptedPayload): Promise { - const encrypted = Encoding.base64ToBytes(payload.encrypted_data); - const nonce = Encoding.base64ToBytes(payload.nonce); - const plainBytes = await this.decryptBytes(encrypted, nonce); - return Encoding.parseJsonObject(Encoding.bytesToUtf8(plainBytes)); - } - - private async encryptBytes(plainBytes: Uint8Array, nonce: Uint8Array): Promise { - const key = this.requireSharedKey(); - return this.cipher.encrypt(plainBytes, key, nonce); - } - - private async decryptBytes(encryptedBytes: Uint8Array, nonce: Uint8Array): Promise { - const key = this.requireSharedKey(); - return this.cipher.decrypt(encryptedBytes, key, nonce); - } - - private requireSharedKey(): Uint8Array { - if (!this.sharedKey) { - throw new Error('Remote encryption has not been initialized.'); - } - return this.sharedKey; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteFileDownloadController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteFileDownloadController.ets deleted file mode 100644 index fb65099096..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteFileDownloadController.ets +++ /dev/null @@ -1,189 +0,0 @@ -import fs from '@ohos.file.fs'; -import picker from '@ohos.file.picker'; -import { FileInfo, RuntimeFileLocation } from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { RemoteWorkspaceFileClient } from './RemoteWorkspaceFileClient'; -import { RemoteUiState } from './RemoteUiState'; -import { RemoteLogger } from './RemoteLogger'; - -export interface RemoteFileDownloadClient extends RemoteWorkspaceFileClient {} - -export interface RemoteFileDownloadScheduler { - setTimeout(callback: () => void, delayMs: number): number; - clearTimeout(timerId: number): void; -} - -export interface RemoteFileSaver { - begin(name: string): Promise; - write(bytes: Uint8Array): Promise; - finish(): Promise; - abort(): Promise; -} - -class SystemRemoteFileDownloadScheduler implements RemoteFileDownloadScheduler { - setTimeout(callback: () => void, delayMs: number): number { - return setTimeout(callback, delayMs); - } - - clearTimeout(timerId: number): void { - clearTimeout(timerId); - } -} - -class SystemRemoteFileSaver implements RemoteFileSaver { - private file?: fs.File; - private uri: string = ''; - async begin(name: string): Promise { - const options = new picker.DocumentSaveOptions(); options.newFileNames = [name]; - const uris = await new picker.DocumentViewPicker().save(options); - if (!uris.length) throw new Error('No destination file was selected.'); - const file = await fs.open(uris[0], fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE); - let size = 0; - try { size = (await fs.stat(file.fd)).size; } catch (error) { await fs.close(file); throw error as Error; } - // Document providers do not promise atomic replace. Preserve existing user - // content and only stream into the empty new destination chosen by picker. - if (size !== 0) { await fs.close(file); throw new Error('Choose a new destination file to preserve existing content.'); } - this.file = file; this.uri = uris[0]; - } - async write(bytes: Uint8Array): Promise { - if (!this.file) throw new Error('Download destination is not open.'); - let offset = 0; - while (offset < bytes.length) { - const buffer = bytes.slice(offset).buffer; - const count = await fs.write(this.file.fd, buffer); - if (count <= 0) throw new Error('Download destination write was incomplete.'); - offset += count; - } - } - async finish(): Promise { - if (!this.file) throw new Error('Download destination is not open.'); - await fs.fsync(this.file.fd); await fs.close(this.file); this.file = undefined; - const uri = this.uri; this.uri = ''; return uri; - } - async abort(): Promise { - const file = this.file; const uri = this.uri; this.file = undefined; this.uri = ''; - try { if (file) await fs.close(file); } finally { if (uri) await fs.unlink(uri); } - } -} - -export class RemoteFileDownloadController { - private readonly client: RemoteFileDownloadClient; - private readonly onDownloadStatus: (downloadingFilePath: string, downloadedFilePath: string, fileDownloadStatus: string) => void; - private readonly onClearDownloadingFilePath: () => void; - private readonly onStatusText: (statusText: string) => void; - private readonly onBusy: (isBusy: boolean) => void; - private readonly clearDelayMs: number; - private readonly scheduler: RemoteFileDownloadScheduler; - private readonly fileSaver: RemoteFileSaver; - private downloadingFilePath: string = ''; - private downloadedFilePath: string = ''; - private fileDownloadStatus: string = ''; - private clearTimerId: number = 0; - private generation: number = 0; - private running: boolean = false; - - constructor( - client: RemoteFileDownloadClient, - onDownloadStatus: (downloadingFilePath: string, downloadedFilePath: string, fileDownloadStatus: string) => void, - onClearDownloadingFilePath: () => void, - onStatusText: (statusText: string) => void, - onBusy: (isBusy: boolean) => void, - clearDelayMs: number = 2500, - scheduler: RemoteFileDownloadScheduler = new SystemRemoteFileDownloadScheduler(), - fileSaver: RemoteFileSaver = new SystemRemoteFileSaver() - ) { - this.client = client; - this.onDownloadStatus = onDownloadStatus; - this.onClearDownloadingFilePath = onClearDownloadingFilePath; - this.onStatusText = onStatusText; - this.onBusy = onBusy; - this.clearDelayMs = clearDelayMs; - this.scheduler = scheduler; - this.fileSaver = fileSaver; - } - - async download(path: string, sessionId: string, isBusy: boolean, remoteAvailable: boolean, location?: RuntimeFileLocation): Promise { - const remotePath = RemoteUiState.normalizeRemoteFilePath(path); - if ((!sessionId && !location?.path) || remotePath.length === 0 || isBusy || this.running || !remoteAvailable) { - return; - } - this.cancelClearTimer(); - const generation = ++this.generation; - this.running = true; - try { - RemoteLogger.info(`file_download start session=${sessionId.length > 0 ? 'set' : 'none'}`); - this.onBusy(true); - this.setDownloadStatus(path, '', RemoteI18n.t('status.fileInfo')); - let opened = false; - const result = await this.client.streamFile(remotePath, sessionId || undefined, async (bytes: Uint8Array, info: FileInfo): Promise => { - if (generation !== this.generation) throw new Error('File download cancelled.'); - if (!opened) { await this.fileSaver.begin(info.name); opened = true; } - if (generation !== this.generation) throw new Error('File download cancelled.'); - await this.fileSaver.write(bytes); - }, (downloaded: number, total: number) => { - this.setDownloadStatus(path, '', `${RemoteUiState.formatBytes(downloaded)} / ${RemoteUiState.formatBytes(total)}`); - }, location); - if (generation !== this.generation) throw new Error('File download cancelled.'); - await this.fileSaver.finish(); - this.setDownloadStatus( - path, - path, - RemoteI18n.f2('status.downloadDone', result.name, RemoteUiState.formatBytes(result.size)) - ); - this.onStatusText(this.fileDownloadStatus); - } catch (err) { - try { await this.fileSaver.abort(); } catch (cleanupError) { RemoteLogger.error(`file_download cleanup_failed message=${String(cleanupError)}`); } - const errorText = ConnectionErrorPolicy.errorText(err); - RemoteLogger.error(`file_download failed message=${errorText}`); - this.setDownloadStatus(this.downloadingFilePath, this.downloadedFilePath, errorText); - this.onStatusText(this.fileDownloadStatus); - } finally { - this.running = false; - this.onBusy(false); - this.scheduleClearDownloadingFilePath(); - } - } - - clear(): void { - this.generation++; - this.cancelClearTimer(); - this.setDownloadStatus('', '', ''); - } - - cancel(): void { - this.generation++; - this.cancelClearTimer(); - } - - isClearPending(): boolean { - return this.clearTimerId !== 0; - } - - currentStatusText(): string { - return this.fileDownloadStatus; - } - - private setDownloadStatus(downloadingFilePath: string, downloadedFilePath: string, fileDownloadStatus: string): void { - this.downloadingFilePath = downloadingFilePath; - this.downloadedFilePath = downloadedFilePath; - this.fileDownloadStatus = fileDownloadStatus; - this.onDownloadStatus(downloadingFilePath, downloadedFilePath, fileDownloadStatus); - } - - private scheduleClearDownloadingFilePath(): void { - this.cancelClearTimer(); - this.clearTimerId = this.scheduler.setTimeout(() => { - this.clearTimerId = 0; - this.downloadingFilePath = ''; - this.onClearDownloadingFilePath(); - }, this.clearDelayMs); - } - - private cancelClearTimer(): void { - if (this.clearTimerId !== 0) { - this.scheduler.clearTimeout(this.clearTimerId); - this.clearTimerId = 0; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteHeartbeatController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteHeartbeatController.ets deleted file mode 100644 index 4c306c83af..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteHeartbeatController.ets +++ /dev/null @@ -1,70 +0,0 @@ -export interface RemoteHeartbeatScheduler { - setInterval(callback: () => void, intervalMs: number): number; - clearInterval(timerId: number): void; -} - -class SystemRemoteHeartbeatScheduler implements RemoteHeartbeatScheduler { - setInterval(callback: () => void, intervalMs: number): number { - return setInterval(callback, intervalMs); - } - - clearInterval(timerId: number): void { - clearInterval(timerId); - } -} - -export class RemoteHeartbeatController { - private readonly onTick: () => Promise; - private readonly intervalMs: number; - private readonly scheduler: RemoteHeartbeatScheduler; - private timerId: number = 0; - private inFlight: boolean = false; - - constructor( - onTick: () => Promise, - intervalMs: number = 15000, - scheduler: RemoteHeartbeatScheduler = new SystemRemoteHeartbeatScheduler() - ) { - this.onTick = onTick; - this.intervalMs = intervalMs; - this.scheduler = scheduler; - } - - start(): void { - this.stop(); - this.timerId = this.scheduler.setInterval(() => { - void this.runTick(); - }, this.intervalMs); - } - - /** - * A tick that arrives while the previous one is still out is dropped, not - * queued. The interval counts wall-clock time, but a heartbeat can outlive - * many intervals: a desktop that has stopped answering holds every request - * until the relay's own timeout, two minutes later. Starting one more each - * interval turns a single unanswered request into a pile of them aimed at the - * desktop that is already not answering. - */ - private async runTick(): Promise { - if (this.inFlight) { - return; - } - this.inFlight = true; - try { - await this.onTick(); - } finally { - this.inFlight = false; - } - } - - stop(): void { - if (this.timerId !== 0) { - this.scheduler.clearInterval(this.timerId); - this.timerId = 0; - } - } - - isRunning(): boolean { - return this.timerId !== 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteLogger.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteLogger.ets deleted file mode 100644 index 2c27f9314b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteLogger.ets +++ /dev/null @@ -1,18 +0,0 @@ -import { hilog } from '@kit.PerformanceAnalysisKit'; - -const DOMAIN = 0x0000; -const TAG = 'OpenBitFunStream'; - -export class RemoteLogger { - static info(message: string): void { - hilog.info(DOMAIN, TAG, '%{public}s', message); - } - - static warn(message: string): void { - hilog.warn(DOMAIN, TAG, '%{public}s', message); - } - - static error(message: string): void { - hilog.error(DOMAIN, TAG, '%{public}s', message); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelController.ets deleted file mode 100644 index bf89698d57..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelController.ets +++ /dev/null @@ -1,121 +0,0 @@ -import { RemoteModelCatalog } from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { RemoteUiState } from './RemoteUiState'; - -export interface RemoteModelClient { - getModelCatalog(sessionId?: string): Promise; - setSessionModel(sessionId: string, modelId: string): Promise; -} - -export interface RemoteModelPreferenceStore { - saveLastModelId(modelId: string): Promise; -} - -export class RemoteModelController { - private readonly client: RemoteModelClient; - private readonly preferenceStore: RemoteModelPreferenceStore; - private readonly onCatalogReset: ( - modelCatalog: RemoteModelCatalog, - selectedModelId: string, - knownModelCatalogVersion: number - ) => void; - private readonly onCatalogApplied: ( - modelCatalog: RemoteModelCatalog, - selectedModelId: string, - knownModelCatalogVersion: number - ) => void; - private readonly onStatusText: (statusText: string) => void; - private readonly onBusy: (isBusy: boolean) => void; - private modelCatalog: RemoteModelCatalog = RemoteUiState.emptyModelCatalog(); - private selectedModelId: string = ''; - - constructor( - client: RemoteModelClient, - preferenceStore: RemoteModelPreferenceStore, - onCatalogReset: ( - modelCatalog: RemoteModelCatalog, - selectedModelId: string, - knownModelCatalogVersion: number - ) => void, - onCatalogApplied: ( - modelCatalog: RemoteModelCatalog, - selectedModelId: string, - knownModelCatalogVersion: number - ) => void, - onStatusText: (statusText: string) => void, - onBusy: (isBusy: boolean) => void - ) { - this.client = client; - this.preferenceStore = preferenceStore; - this.onCatalogReset = onCatalogReset; - this.onCatalogApplied = onCatalogApplied; - this.onStatusText = onStatusText; - this.onBusy = onBusy; - } - - setPreferredModelId(modelId: string): void { - this.selectedModelId = modelId.trim(); - } - - clearCatalog(): void { - this.modelCatalog = RemoteUiState.emptyModelCatalog(); - this.onCatalogReset(this.modelCatalog, '', 0); - } - - async loadCatalog( - sessionId: string, - remoteAvailable: boolean, - canApply: (sessionId: string) => boolean - ): Promise { - if (sessionId.length === 0 || !remoteAvailable) { - return; - } - this.clearCatalog(); - try { - const catalog = await this.client.getModelCatalog(sessionId); - if (!canApply(sessionId)) { - return; - } - this.applyCatalog(catalog); - } catch (err) { - this.onStatusText(ConnectionErrorPolicy.errorText(err)); - } - } - - async selectModel( - modelId: string, - sessionId: string, - isBusy: boolean, - remoteAvailable: boolean - ): Promise { - if (sessionId.length === 0 || modelId.length === 0 || modelId === this.selectedModelId || isBusy || !remoteAvailable) { - return; - } - try { - this.onBusy(true); - this.onStatusText(RemoteI18n.t('status.switchingModel')); - const selected = await this.client.setSessionModel(sessionId, modelId); - this.selectedModelId = selected; - await this.preferenceStore.saveLastModelId(selected); - this.modelCatalog = { - version: this.modelCatalog.version, - models: this.modelCatalog.models, - default_models: this.modelCatalog.default_models, - session_model_id: selected - }; - this.onCatalogApplied(this.modelCatalog, selected, this.modelCatalog.version || 0); - this.onStatusText(RemoteI18n.t('status.modelSwitched')); - } catch (err) { - this.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.onBusy(false); - } - } - - applyCatalog(catalog: RemoteModelCatalog): void { - this.modelCatalog = catalog; - this.selectedModelId = RemoteUiState.selectedModelIdForCatalog(catalog, this.selectedModelId); - this.onCatalogApplied(catalog, this.selectedModelId, catalog.version || 0); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelDefaultsController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelDefaultsController.ets deleted file mode 100644 index 1c9bd27f57..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteModelDefaultsController.ets +++ /dev/null @@ -1,388 +0,0 @@ -import { RemoteDefaultModels, RemoteModelCatalog } from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { RemoteUiState } from './RemoteUiState'; - -/** - * The three model slots a phone may write on the controlled desktop. - * - * `null` is a value: the fast model then follows the primary model, and the - * other two are left unconfigured. The slots the phone does not manage - * (`search`, `image_generation`, `speech_recognition`) are never sent. - */ -export interface RemoteModelDefaultsRoles { - primary: string | null; - fast: string | null; - image_understanding: string | null; -} - -/** Roles the sheet can edit, in sheet order. */ -export type RemoteModelDefaultsRole = 'primary' | 'fast' | 'image_understanding'; - -/** - * Device-level model client. - * - * `getModelCatalog()` is called without a session id on purpose: the defaults - * belong to the desktop, not to whichever session happens to be open. - */ -export interface RemoteModelDefaultsClient { - getModelCatalog(sessionId?: string): Promise; - setModelDefaults( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise; -} - -/** Which operation failed, so a retry can offer the matching one. */ -export type RemoteModelDefaultsFailure = '' | 'load' | 'write'; - -/** - * Everything that has to hold before the device page is answerable: the host - * advertises `device_model_defaults_v1`, the link is up, and the desktop it - * points at is the one the values belong to. - */ -export interface RemoteModelDefaultsGate { - supported: boolean; - connected: boolean; - deviceId: string; -} - -/** Everything the device model settings pages render. */ -export interface RemoteModelDefaultsState { - /** The gate allows a read and a write. */ - available: boolean; - /** A device catalog read is in flight. */ - loading: boolean; - /** A write is in flight; the sheet is locked while it is true. */ - busy: boolean; - /** Device catalog: models with their `capabilities`, in host order. */ - catalog: RemoteModelCatalog; - /** Current values. Only ever replaced by a read, never by a write's intent. */ - roles: RemoteModelDefaultsRoles; - /** Raw failure text; empty when the last operation succeeded. */ - error: string; - /** Which operation produced `error`. */ - failure: RemoteModelDefaultsFailure; - /** Transient i18n status line: reading, saving, updated. */ - statusText: string; - /** True once a read has applied values for the current gate. */ - loaded: boolean; -} - -export interface RemoteModelDefaultsCallbacks { - onStateChanged: (state: RemoteModelDefaultsState) => void; -} - -/** - * Device model role defaults for the connected desktop. - * - * Reads and writes go to the desktop's own catalog, so this controller never - * guesses: a write is followed by an explicit re-read and the values on screen - * change only when that read returns. The host repairs an impossible selection - * while persisting it, and showing the intent instead of the result would - * report a configuration that was never stored. - */ -export class RemoteModelDefaultsController { - /** The reason an older desktop cannot serve the device model settings page. */ - private static readonly UNSUPPORTED_REASON_KEY: string = 'settings.model.unsupported'; - - private readonly client: RemoteModelDefaultsClient; - private readonly callbacks: RemoteModelDefaultsCallbacks; - private state: RemoteModelDefaultsState = RemoteModelDefaultsController.unavailableState(); - private gate: RemoteModelDefaultsGate = RemoteModelDefaultsController.closedGate(); - /** - * Bumped when the gate changes or the controller is reset. A result that - * lands after that belongs to a desktop the sheet no longer shows. - */ - private generation: number = 0; - - constructor(client: RemoteModelDefaultsClient, callbacks: RemoteModelDefaultsCallbacks) { - this.client = client; - this.callbacks = callbacks; - } - - getState(): RemoteModelDefaultsState { - return this.state; - } - - /** - * Re-gates the page. Any change of capability, link or desktop drops what is - * on screen (values from one desktop must never render against another) and - * returns true, so the caller knows it has to read again. - */ - setGate(gate: RemoteModelDefaultsGate): boolean { - if (RemoteModelDefaultsController.sameGate(this.gate, gate)) { - return false; - } - this.generation += 1; - this.gate = gate; - const available = gate.supported && gate.connected; - const next: RemoteModelDefaultsState = RemoteModelDefaultsController.unavailableState(); - next.available = available; - if (available) { - next.statusText = RemoteI18n.t('status.loadingModelDefaults'); - } else { - next.error = gate.supported ? - RemoteI18n.t('status.remoteUnavailable') : - RemoteI18n.t(RemoteModelDefaultsController.UNSUPPORTED_REASON_KEY); - } - this.publish(next); - return true; - } - - /** - * Reads the desktop catalog and the defaults that belong to it. - * - * Skips while a read or a write is already running so opening the page during - * a reconnect cannot queue a second read behind the first. - */ - async load(): Promise { - if (!this.state.available || this.state.loading || this.state.busy) { - return; - } - const generation = this.generation; - this.publish(RemoteModelDefaultsController.workingState(this.state, true, false, - RemoteI18n.t('status.loadingModelDefaults'))); - try { - const catalog = await this.readCatalog(generation); - if (!catalog) { - return; - } - this.publish(RemoteModelDefaultsController.readState(this.state, catalog)); - } catch (err) { - if (!this.isCurrent(generation)) { - return; - } - this.publish(RemoteModelDefaultsController.failedState(this.state, err, 'load', - RemoteI18n.t('status.modelDefaultsLoadFailed'))); - } - } - - /** - * Writes one role by sending the whole object, then reads the result back. - * - * The verb replaces all three slots, so the other two come from a fresh read: - * the snapshot from when this page opened could revert a newer desktop save. - * - * Selecting the value a role already has writes nothing: the host reconciles - * on every write, and there is no intent to persist. - */ - async applyRoleSelection(role: RemoteModelDefaultsRole, modelId: string | null): Promise { - if (!this.state.available || this.state.busy || this.state.loading) { - return; - } - if (RemoteModelDefaultsController.sameRoles( - RemoteModelDefaultsController.rolesWithSelection(this.state.roles, role, modelId), this.state.roles)) { - return; - } - const generation = this.generation; - this.publish(RemoteModelDefaultsController.workingState(this.state, false, true, - RemoteI18n.t('status.updatingModelDefaults'))); - try { - const latest = await this.readCatalog(generation); - if (!latest) { - return; - } - const currentRoles = RemoteModelDefaultsController.rolesFromDefaults(latest.default_models); - const nextRoles = RemoteModelDefaultsController.rolesWithSelection(currentRoles, role, modelId); - if (RemoteModelDefaultsController.sameRoles(nextRoles, currentRoles)) { - const unchanged = RemoteModelDefaultsController.readState(this.state, latest); - unchanged.busy = true; - this.publish(unchanged); - return; - } - await this.client.setModelDefaults( - nextRoles.primary, - nextRoles.fast, - nextRoles.image_understanding - ); - if (!this.isCurrent(generation)) { - return; - } - // The acknowledgement says what was written, not what is now stored: the - // desktop may have repaired the selection, so the read decides. - try { - const catalog = await this.readCatalog(generation); - if (!catalog) { - return; - } - const readState = RemoteModelDefaultsController.readState(this.state, catalog); - readState.busy = true; - readState.statusText = RemoteI18n.t('status.modelDefaultsUpdated'); - this.publish(readState); - } catch (err) { - if (!this.isCurrent(generation)) { - return; - } - const failed = RemoteModelDefaultsController.failedState(this.state, err, 'load', - RemoteI18n.t('status.modelDefaultsLoadFailed')); - failed.busy = true; - this.publish(failed); - } - } catch (err) { - if (!this.isCurrent(generation)) { - return; - } - this.publish(RemoteModelDefaultsController.failedState(this.state, err, 'write', - RemoteI18n.t('status.modelDefaultsUpdateFailed'))); - } finally { - if (this.isCurrent(generation)) { - const done = RemoteModelDefaultsController.copyState(this.state); - done.busy = false; - this.publish(done); - } - } - } - - /** Clears the page while it is closed. */ - reset(): void { - this.generation += 1; - this.gate = RemoteModelDefaultsController.closedGate(); - this.publish(RemoteModelDefaultsController.unavailableState()); - } - - /** The i18n key of the reason an old desktop cannot serve this page. */ - static unsupportedReasonKey(): string { - return RemoteModelDefaultsController.UNSUPPORTED_REASON_KEY; - } - - /** The values for one role, mapped from the wire shape (`undefined` = null). */ - static rolesFromDefaults(defaults: RemoteDefaultModels): RemoteModelDefaultsRoles { - return { - primary: RemoteModelDefaultsController.slotValue(defaults.primary), - fast: RemoteModelDefaultsController.slotValue(defaults.fast), - image_understanding: RemoteModelDefaultsController.slotValue(defaults.image_understanding) - }; - } - - private async readCatalog(generation: number): Promise { - const catalog = await this.client.getModelCatalog(); - return this.isCurrent(generation) ? catalog : undefined; - } - - private isCurrent(generation: number): boolean { - return generation === this.generation; - } - - private publish(state: RemoteModelDefaultsState): void { - this.state = state; - this.callbacks.onStateChanged(state); - } - - private static slotValue(value: string | null | undefined): string | null { - return value === undefined || value === null || value.length === 0 ? null : value; - } - - private static rolesWithSelection( - roles: RemoteModelDefaultsRoles, - role: RemoteModelDefaultsRole, - modelId: string | null - ): RemoteModelDefaultsRoles { - if (role === 'primary') { - return { primary: modelId, fast: roles.fast, image_understanding: roles.image_understanding }; - } - if (role === 'fast') { - return { primary: roles.primary, fast: modelId, image_understanding: roles.image_understanding }; - } - if (role === 'image_understanding') { - return { primary: roles.primary, fast: roles.fast, image_understanding: modelId }; - } - return RemoteModelDefaultsController.copyRoles(roles); - } - - private static sameRoles(first: RemoteModelDefaultsRoles, second: RemoteModelDefaultsRoles): boolean { - return first.primary === second.primary && - first.fast === second.fast && - first.image_understanding === second.image_understanding; - } - - private static sameGate(first: RemoteModelDefaultsGate, second: RemoteModelDefaultsGate): boolean { - return first.supported === second.supported && - first.connected === second.connected && - first.deviceId === second.deviceId; - } - - private static copyRoles(roles: RemoteModelDefaultsRoles): RemoteModelDefaultsRoles { - return { - primary: roles.primary, - fast: roles.fast, - image_understanding: roles.image_understanding - }; - } - - private static copyState(state: RemoteModelDefaultsState): RemoteModelDefaultsState { - return { - available: state.available, - loading: state.loading, - busy: state.busy, - catalog: state.catalog, - roles: RemoteModelDefaultsController.copyRoles(state.roles), - error: state.error, - failure: state.failure, - statusText: state.statusText, - loaded: state.loaded - }; - } - - private static workingState( - state: RemoteModelDefaultsState, - loading: boolean, - busy: boolean, - statusText: string - ): RemoteModelDefaultsState { - const next = RemoteModelDefaultsController.copyState(state); - next.loading = loading; - next.busy = busy; - next.error = ''; - next.failure = ''; - next.statusText = statusText; - return next; - } - - /** Applies a read: the only path that may change the values on screen. */ - private static readState(state: RemoteModelDefaultsState, catalog: RemoteModelCatalog): RemoteModelDefaultsState { - const next = RemoteModelDefaultsController.copyState(state); - next.catalog = catalog; - next.roles = RemoteModelDefaultsController.rolesFromDefaults(catalog.default_models || {}); - next.loading = false; - next.error = ''; - next.failure = ''; - next.statusText = ''; - next.loaded = true; - return next; - } - - private static failedState( - state: RemoteModelDefaultsState, - err: Object, - failure: RemoteModelDefaultsFailure, - fallbackText: string - ): RemoteModelDefaultsState { - const next = RemoteModelDefaultsController.copyState(state); - // The host's own rejection (an unknown model id, for example) is kept as it - // arrived: replacing it with a generic line would hide what to fix. - next.error = err instanceof Error && err.message.length > 0 ? err.message : fallbackText; - next.failure = failure; - next.loading = false; - next.statusText = ''; - return next; - } - - private static unavailableState(): RemoteModelDefaultsState { - return { - available: false, - loading: false, - busy: false, - catalog: RemoteUiState.emptyModelCatalog(), - roles: { primary: null, fast: null, image_understanding: null }, - error: '', - failure: '', - statusText: '', - loaded: false - }; - } - - private static closedGate(): RemoteModelDefaultsGate { - return { supported: false, connected: false, deviceId: '' }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteResponseMapper.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteResponseMapper.ets deleted file mode 100644 index 10d1709edc..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteResponseMapper.ets +++ /dev/null @@ -1,368 +0,0 @@ -import { - ActiveTurnSnapshotResponse, - ChatMessage, - ChatMessageItemResponse, - ChatMessageResponse, - InitialSyncResponse, - RecentWorkspaceEntry, - RecentWorkspaceEntryResponse, - RemoteSession, - RemoteToolStatusResponse, - SessionItemResponse, - SessionRolledBackResponse, - SessionRolledBackResult, - WorkspaceInfo, - WorkspaceInfoResponse -} from '../model/RemoteModels'; - -export class RemoteResponseMapper { - static workspaceFromInitialSync(response: InitialSyncResponse): WorkspaceInfo { - const workspacePath = response.path || ''; - const workspaceName = RemoteResponseMapper.workspaceDisplayName( - response.project_name, - workspacePath, - response.remote_ssh_host, - response.remote_connection_id - ); - return { - workspaceId: response.workspace_id, - path: workspacePath, - name: workspaceName, - hasWorkspace: response.has_workspace !== false && workspacePath.length > 0, - gitBranch: response.git_branch || '', - workspaceKind: response.workspace_kind || 'normal', - assistantId: response.assistant_id, - remoteConnectionId: (response.workspace_kind === 'normal' || response.workspace_kind === 'assistant') ? undefined : response.remote_connection_id, - remoteSshHost: (response.workspace_kind === 'normal' || response.workspace_kind === 'assistant') ? undefined : response.remote_ssh_host - }; - } - - static workspaceFromResponse(response: WorkspaceInfoResponse): WorkspaceInfo { - const workspacePath = response.path || response.workspace_path || ''; - const workspaceName = RemoteResponseMapper.workspaceDisplayName( - response.project_name || response.workspace_name, - workspacePath, - response.remote_ssh_host, - response.remote_connection_id - ); - return { - workspaceId: response.workspace_id, - path: workspacePath, - name: workspaceName, - hasWorkspace: response.has_workspace !== false && workspacePath.length > 0, - gitBranch: response.git_branch || '', - workspaceKind: response.workspace_kind || 'normal', - assistantId: response.assistant_id, - remoteConnectionId: (response.workspace_kind === 'normal' || response.workspace_kind === 'assistant') ? undefined : response.remote_connection_id, - remoteSshHost: (response.workspace_kind === 'normal' || response.workspace_kind === 'assistant') ? undefined : response.remote_ssh_host - }; - } - - static recentWorkspaces(items: RecentWorkspaceEntryResponse[]): RecentWorkspaceEntry[] { - return items.map((item: RecentWorkspaceEntryResponse) => { - const workspace: RecentWorkspaceEntry = { - workspaceId: item.workspace_id, - path: item.path || '', - name: RemoteResponseMapper.workspaceDisplayName( - item.name, - item.path || '', - item.remote_ssh_host, - item.remote_connection_id - ), - lastOpened: RemoteResponseMapper.firstTimeValue([ - item.last_opened, - item.lastOpened, - item.updated_at, - item.updatedAt - ]), - remoteSshHost: (item.workspace_kind === 'normal' || item.workspace_kind === 'assistant') ? undefined : item.remote_ssh_host, - remoteConnectionId: (item.workspace_kind === 'normal' || item.workspace_kind === 'assistant') ? undefined : item.remote_connection_id, - workspaceKind: item.workspace_kind || 'normal' - }; - return workspace; - }).filter((item: RecentWorkspaceEntry) => item.path.length > 0); - } - - /** Keep remote root workspaces readable when older hosts persisted "Unknown". */ - private static workspaceDisplayName( - rawName: string | undefined, - path: string, - remoteSshHost?: string, - remoteConnectionId?: string - ): string { - const name = (rawName || '').trim(); - const normalized = name.toLowerCase(); - const host = (remoteSshHost || '').trim(); - const connection = (remoteConnectionId || '').trim(); - const isTransportName = (host.length > 0 && name === host) || - (connection.length > 0 && name === connection); - if (name.length > 0 && !isTransportName && normalized !== 'unknown' && normalized !== 'unknown project' && name !== '未知' && name !== '未知项目') { - return name; - } - const basename = RemoteResponseMapper.basename(path); - if (basename.length > 0 && basename !== '/') { - return basename; - } - // Keep the remote root addressable without presenting the transport - // address as if it were a workspace name. - return '/'; - } - - static sessions(items: SessionItemResponse[]): RemoteSession[] { - return RemoteResponseMapper.visibleSessions(RemoteResponseMapper.allSessions(items)); - } - - /** Maps a server page before mobile-only visibility rules are applied. */ - static allSessions(items: SessionItemResponse[]): RemoteSession[] { - return items.map((item: SessionItemResponse) => { - const id = item.id || item.session_id || ''; - const session: RemoteSession = { - id, - title: item.title || item.name || `Session ${id.slice(0, 6)}`, - agentType: item.agent_type || 'code', - status: item.status || 'idle', - updatedAt: RemoteResponseMapper.firstTimeValue([ - item.updated_at, - item.updatedAt, - item.updated, - item.updated_time, - item.update_time, - item.modified_at, - item.last_active_at, - item.last_activity_at, - item.last_message_at, - item.last_interaction_at, - item.lastUpdated, - item.lastActivityAt, - item.lastMessageAt, - item.timestamp - ]), - createdAt: RemoteResponseMapper.firstTimeValue([ - item.created_at, - item.createdAt, - item.created, - item.created_time, - item.create_time, - item.inserted_at, - item.started_at, - item.start_time - ]), - messageCount: item.message_count || 0, - workspacePath: item.workspace_path, - workspaceName: item.workspace_name, - parentSessionId: item.parent_session_id, - relationshipKind: item.relationship_kind - }; - // An ID-aware host pins every session to its workspace record. Keep that - // ID as the identity; the listing scope may later fill in display facts. - const workspaceId = (item.workspace_id || '').trim(); - if (workspaceId.length > 0) { - session.workspaceIdentity = { workspaceId: workspaceId, path: item.workspace_path || '' }; - } - return session; - }); - } - - /** - * ACP sessions are created on Desktop and are not controllable on HarmonyOS. - * Child sessions (Desktop's 侧问 / review / miniapp / subagent) belong under - * their parent, so they must not appear as standalone conversations. - */ - static visibleSessions(sessions: RemoteSession[]): RemoteSession[] { - return sessions.filter((session: RemoteSession) => RemoteResponseMapper.isVisibleSession(session)); - } - - static isVisibleSession(session: RemoteSession): boolean { - if ((session.agentType || '').trim().toLowerCase().startsWith('acp:')) { - return false; - } - return !RemoteResponseMapper.isChildSession(session); - } - - static isChildSession(session: RemoteSession): boolean { - return (session.parentSessionId || '').trim().length > 0; - } - - static chatMessage(item: ChatMessageResponse): ChatMessage { - const text = RemoteResponseMapper.messageText(item); - const tools = RemoteResponseMapper.toolsFromExplicitOrItems(item.tools || [], item.items || []); - const message: ChatMessage = { - id: RemoteResponseMapper.messageId(item, text), - turnId: item.turn_id, - role: item.role, - text: text || item.content || '', - status: item.status || (item.role === 'assistant' ? 'done' : 'sent'), - detail: RemoteResponseMapper.messageDetail(tools), - error: item.error, - timestamp: item.timestamp, - thinking: item.thinking, - tools, - items: item.items || [], - images: item.images || [] - }; - return message; - } - - /** - * Decode the answer to `rollback_session_to_turn` (`resp: - * "session_rolled_back"`). - * - * The variant is checked rather than assumed: the relay forwards whatever the - * addressed host replies, and a payload that is not this answer must not be - * read as a rollback that retired nothing. Absent host fields stay absent here - * so a caller can tell "no prompt offered" from "an empty prompt". - */ - static sessionRolledBack(response: SessionRolledBackResponse): SessionRolledBackResult { - if (response.resp !== 'session_rolled_back') { - throw new Error(`Unexpected rollback response: ${response.resp || 'none'}`); - } - return { - sessionId: response.session_id || '', - retiredTurnIds: response.retired_turn_ids || [], - restoredFiles: response.restored_files || [], - composerText: response.composer_text, - changed: response.changed === true - }; - } - - static activeTurnToMessage(turn: ActiveTurnSnapshotResponse, renderVersion: number = 0): ChatMessage { - const body = RemoteResponseMapper.activeTurnText(turn); - const tools = RemoteResponseMapper.toolsFromExplicitOrItems(turn.tools || [], turn.items || []); - const message: ChatMessage = { - id: `active-${turn.turn_id}`, - turnId: turn.turn_id, - role: 'assistant', - text: body, - status: turn.status || 'active', - renderVersion, - detail: RemoteResponseMapper.messageDetail(tools), - error: turn.error, - thinking: turn.thinking, - tools, - items: turn.items || [] - }; - return message; - } - - static basename(path: string): string { - if (!path) { - return ''; - } - const normalized = path.replace(/\\/g, '/'); - const parts = normalized.split('/'); - return parts[parts.length - 1] || normalized; - } - - private static messageText(item: ChatMessageResponse): string { - if (item.content && item.content.trim().length > 0) { - return item.content; - } - const topLevelText = RemoteResponseMapper.lastTopLevelText(item.items || []); - if (topLevelText.length > 0) { - return topLevelText; - } - return ''; - } - - private static messageId(item: ChatMessageResponse, text: string): string { - if (item.id && item.id.length > 0) { - return item.id; - } - if (item.message_id && item.message_id.length > 0) { - return item.message_id; - } - const timestamp = item.timestamp || ''; - return `${item.role || 'message'}-${timestamp}-${RemoteResponseMapper.stableTextHash(text || item.content || '')}`; - } - - private static stableTextHash(text: string): string { - let hash = 0; - for (let index = 0; index < text.length; index++) { - hash = ((hash << 5) - hash + text.charCodeAt(index)) | 0; - } - return Math.abs(hash).toString(36); - } - - private static activeTurnText(turn: ActiveTurnSnapshotResponse): string { - if (turn.text && turn.text.trim().length > 0) { - return turn.text; - } - const topLevelText = RemoteResponseMapper.lastTopLevelText(turn.items || []); - if (topLevelText.length > 0) { - return topLevelText; - } - return ''; - } - - private static lastTopLevelText(items: ChatMessageItemResponse[]): string { - for (let index = items.length - 1; index >= 0; index--) { - if (RemoteResponseMapper.isFinalTextItem(items[index])) { - return (items[index].content || '').trim(); - } - } - return ''; - } - - private static isFinalTextItem(item: ChatMessageItemResponse): boolean { - const type = (item.type || '').toLowerCase(); - if ((item.content || '').trim().length === 0 || item.tool || item.is_subagent === true) { - return false; - } - if (type === 'thinking' || type === 'user-steering' || type === 'tool' || - type === 'subagent' || type === 'agent') { - return false; - } - return type === 'text' || type === 'message' || type.length === 0; - } - - private static firstTimeValue(values: (string | number | undefined)[]): string { - for (const value of values) { - if (value === undefined) { - continue; - } - if (typeof value === 'number') { - return `${value}`; - } - if (value.trim().length > 0) { - return value.trim(); - } - } - return ''; - } - - private static toolsFromExplicitOrItems( - explicitTools: RemoteToolStatusResponse[], - items: ChatMessageItemResponse[] - ): RemoteToolStatusResponse[] { - if (explicitTools.length > 0) { - return explicitTools; - } - return RemoteResponseMapper.itemTools(items); - } - - private static messageDetail(tools: RemoteToolStatusResponse[]): string { - if (tools.length === 0) { - return ''; - } - const labels: string[] = []; - tools.forEach((tool: RemoteToolStatusResponse) => { - labels.push(`${tool.name || 'Tool'} · ${tool.status || 'pending'}`); - }); - return labels.join('\n'); - } - - private static itemTools(items: ChatMessageItemResponse[]): RemoteToolStatusResponse[] { - const tools: RemoteToolStatusResponse[] = []; - items.forEach((item: ChatMessageItemResponse) => { - if (item.tool) { - tools.push(item.tool); - } - if (item.subItems) { - RemoteResponseMapper.itemTools(item.subItems).forEach((tool: RemoteToolStatusResponse) => { - tools.push(tool); - }); - } - }); - return tools; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionController.ets deleted file mode 100644 index f4efa440be..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionController.ets +++ /dev/null @@ -1,291 +0,0 @@ -import { - CreateSessionOptions, - RemoteSession, - SessionListResult, - SessionSummary -} from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { RemoteLogger } from './RemoteLogger'; -import { RemoteUiState } from './RemoteUiState'; - -export interface RemoteSessionClient { - listSessions(limit: number, offset: number, query: string, agentType: string): Promise; - createSession( - options: CreateSessionOptions, - onAllocated?: (session: SessionSummary) => Promise - ): Promise; - deleteSession(sessionId: string): Promise; -} - -export interface RemoteSessionControllerCallbacks { - onSessions: (sessions: RemoteSession[], hasMore: boolean) => void; - onActiveSession: (session: SessionSummary) => void; - onStatusText: (statusText: string) => void; - onBusy: (isBusy: boolean) => void; - onLoading: (isLoading: boolean) => void; - onSessionError: (errorText: string) => void; - onReconnecting: () => void; - onConnected: () => void; - onConnectionFailed: (err: Object) => void; - onStartHeartbeat: () => void; -} - -export class RemoteSessionController { - private readonly client: RemoteSessionClient; - private readonly pageSize: number; - private readonly callbacks: RemoteSessionControllerCallbacks; - private sessions: RemoteSession[] = []; - private hasMore: boolean = false; - private offset: number = 0; - private openGeneration: number = 0; - private listGeneration: number = 0; - private listing: boolean = false; - private loadingMore: boolean = false; - - constructor( - client: RemoteSessionClient, - pageSize: number, - callbacks: RemoteSessionControllerCallbacks - ) { - this.client = client; - this.pageSize = pageSize; - this.callbacks = callbacks; - } - - private static shortId(value: string): string { - if (value.length <= 10) { - return value; - } - return `${value.slice(0, 6)}...${value.slice(-4)}`; - } - - setSessions(sessions: RemoteSession[], hasMore: boolean): void { - this.supersedeListRequest(); - this.sessions = sessions.slice(); - this.hasMore = hasMore; - this.offset = this.sessions.length; - this.callbacks.onSessions(this.sessions, this.hasMore); - } - - clearSessions(): void { - this.supersedeListRequest(); - this.sessions = []; - this.hasMore = false; - this.offset = 0; - this.callbacks.onSessions(this.sessions, this.hasMore); - } - - updateSessionTitle(sessionId: string, title: string): void { - this.sessions = RemoteUiState.updateSessionTitle(this.sessions, sessionId, title); - this.offset = this.sessions.length; - this.callbacks.onSessions(this.sessions, this.hasMore); - } - - async refresh( - query: string, - filter: string, - remoteAvailable: boolean, - isConnected: boolean, - propagateFailure: boolean = false - ): Promise { - if (!remoteAvailable) { - return; - } - const generation = this.supersedeListRequest(); - this.listing = true; - try { - if (!isConnected) { - this.callbacks.onReconnecting(); - } - this.callbacks.onStatusText(RemoteI18n.t('status.refreshSessions')); - this.callbacks.onLoading(true); - this.offset = 0; - const result = await this.client.listSessions(this.pageSize, this.offset, query, filter); - if (generation !== this.listGeneration) return; - this.sessions = result.sessions; - this.hasMore = result.hasMore; - this.offset = this.sessions.length; - this.callbacks.onSessions(this.sessions, this.hasMore); - this.callbacks.onConnected(); - this.callbacks.onStatusText(RemoteI18n.t('connection.connected')); - this.callbacks.onStartHeartbeat(); - } catch (err) { - if (generation !== this.listGeneration) return; - this.callbacks.onSessionError(ConnectionErrorPolicy.errorText(err)); - this.callbacks.onConnectionFailed(err); - if (propagateFailure) throw new Error(String(err)); - } finally { - if (generation === this.listGeneration) this.finishListRequest(); - } - } - - async loadMore( - query: string, - filter: string, - isBusy: boolean, - remoteAvailable: boolean - ): Promise { - if (isBusy || !this.hasMore || !remoteAvailable) { - return; - } - const generation = this.supersedeListRequest(); - this.listing = true; - this.loadingMore = true; - try { - this.callbacks.onBusy(true); - this.callbacks.onLoading(true); - this.callbacks.onStatusText(RemoteI18n.t('status.loadMoreSessions')); - const result = await this.client.listSessions(this.pageSize, this.offset, query, filter); - if (generation !== this.listGeneration) return; - this.sessions = RemoteUiState.mergeSessions(this.sessions, result.sessions); - this.hasMore = result.hasMore; - this.offset = this.sessions.length; - this.callbacks.onSessions(this.sessions, this.hasMore); - this.callbacks.onStatusText(RemoteI18n.t('status.sessionsUpdated')); - } catch (err) { - if (generation !== this.listGeneration) return; - this.callbacks.onSessionError(ConnectionErrorPolicy.errorText(err)); - this.callbacks.onConnectionFailed(err); - } finally { - if (generation === this.listGeneration) this.finishListRequest(); - } - } - - /** A sidebar snapshot or target reset supersedes older list responses. */ - private supersedeListRequest(): number { - this.listGeneration++; - this.finishListRequest(); - return this.listGeneration; - } - - private finishListRequest(): void { - if (this.loadingMore) this.callbacks.onBusy(false); - if (this.listing) this.callbacks.onLoading(false); - this.loadingMore = false; - this.listing = false; - } - - async create( - agentType: string, - isBusy: boolean, - remoteAvailable: boolean, - onCreated: (session: SessionSummary) => Promise, - instruction: string = '', - modelId: string = '', - workspacePath: string = '', - remoteConnectionId?: string, - remoteSshHost?: string, - workspaceId?: string - ): Promise { - if (isBusy || !remoteAvailable) { - return undefined; - } - try { - this.callbacks.onBusy(true); - this.callbacks.onStatusText(RemoteI18n.t('status.createSession')); - let allocationHandled = false; - const handleAllocated = async (session: SessionSummary): Promise => { - allocationHandled = true; - this.callbacks.onActiveSession(session); - this.callbacks.onStatusText(RemoteI18n.t('status.sessionCreated')); - await onCreated(session); - }; - const session = await this.client.createSession({ - workspaceId: workspaceId?.trim() || undefined, - agentType, - title: '', - instruction, - modelId, - workspacePath, - remoteConnectionId, - remoteSshHost - }, handleAllocated); - if (!allocationHandled) { - await handleAllocated(session); - } else { - // Allocation routes immediately. Refresh the summary after the model - // and initial turn settle without rebuilding the conversation again. - this.callbacks.onActiveSession(session); - } - return session; - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - return undefined; - } finally { - this.callbacks.onBusy(false); - } - } - - async open( - item: RemoteSession, - workspacePath: string, - isBusy: boolean, - remoteAvailable: boolean, - onOpened: (session: SessionSummary) => Promise - ): Promise { - if (isBusy || item.id.length === 0 || !remoteAvailable) { - RemoteLogger.info(`open session dropped session=${RemoteSessionController.shortId(item.id)} busy=${isBusy ? '1' : '0'} available=${remoteAvailable ? '1' : '0'}`); - return; - } - // Opens supersede each other, so the one that finishes first is not - // necessarily the one still on screen. Lowering the busy flag from that one - // would tell the composer the session it is attached to had finished - // loading while the newer open was still fetching. - this.openGeneration += 1; - const generation = this.openGeneration; - try { - this.callbacks.onBusy(true); - this.callbacks.onStatusText(RemoteI18n.t('status.loadMessages')); - const session: SessionSummary = { - sessionId: item.id, - title: item.title, - workspaceId: item.workspaceIdentity?.workspaceId, - workspacePath: item.workspaceIdentity?.path || workspacePath, - remoteConnectionId: item.workspaceIdentity?.remoteConnectionId, - remoteSshHost: item.workspaceIdentity?.remoteSshHost, - agentType: item.agentType - }; - this.callbacks.onActiveSession(session); - await onOpened(session); - } finally { - if (generation === this.openGeneration) { - this.callbacks.onBusy(false); - } - } - } - - async delete( - item: RemoteSession, - activeSessionId: string, - isBusy: boolean, - remoteAvailable: boolean, - query: string, - filter: string, - onDeletedActive: () => Promise - ): Promise { - if (isBusy || item.id.length === 0 || !remoteAvailable) { - return; - } - try { - this.callbacks.onBusy(true); - this.callbacks.onStatusText(RemoteI18n.t('status.deletingSession')); - await this.client.deleteSession(item.id); - this.sessions = this.sessions.filter((session: RemoteSession) => session.id !== item.id); - this.offset = this.sessions.length; - this.callbacks.onSessions(this.sessions, this.hasMore); - if (activeSessionId === item.id) { - await onDeletedActive(); - } - this.callbacks.onStatusText(RemoteI18n.t('status.sessionDeleted')); - if (this.hasMore && this.sessions.length < this.pageSize) { - this.callbacks.onBusy(false); - await this.loadMore(query, filter, false, remoteAvailable); - } - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionIdentity.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionIdentity.ets deleted file mode 100644 index 6e31c7ac62..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionIdentity.ets +++ /dev/null @@ -1,157 +0,0 @@ -import { RemoteSession, RemoteWorkspaceIdentity } from '../model/RemoteModels'; -import { LegacyWorkspaceCompatibility } from './LegacyWorkspaceCompatibility'; - -/** - * Stable grouping key for a workspace reference. - * - * A reference that carries `workspaceId` is keyed by that ID alone; path and - * SSH facts are display strings that must not split or merge groups. Only - * references without an ID (pre-ID hosts, old caches) use the legacy triple. - */ -export function remoteWorkspaceKey(scope: RemoteWorkspaceIdentity): string { - const workspaceId = scope.workspaceId; - if (workspaceId !== undefined && workspaceId.length > 0) { - return `workspace:${workspaceId.length}:${workspaceId}`; - } - return legacyRemoteWorkspaceKey(scope); -} - -/** Upgrade-only key for caches and peers predating workspace IDs. */ -export function legacyRemoteWorkspaceKey(scope: RemoteWorkspaceIdentity): string { - const trimmedPath = scope.path.trim(); - const path = trimmedPath.length > 0 ? trimmedPath.replace(/\/+$/, '') || '/' : ''; - return [scope.remoteConnectionId?.trim() || '', scope.remoteSshHost?.trim() || '', path] - .map((part: string): string => `${part.length}:${part}`).join(''); -} - -/** - * Whether two references name the same workspace. - * - * With IDs on both sides only the IDs are compared. A side without an ID is - * first attributed through the legacy compatibility resolver against the - * catalog; an unresolvable or ambiguous legacy side never matches an - * identified one. - */ -export function remoteWorkspaceIdentityMatches( - left: RemoteWorkspaceIdentity, - right: RemoteWorkspaceIdentity, - catalog: RemoteWorkspaceIdentity[] -): boolean { - if (left.workspaceId && right.workspaceId) { - return left.workspaceId === right.workspaceId; - } - const resolvedLeft = LegacyWorkspaceCompatibility.resolve(left, catalog) || left; - const resolvedRight = LegacyWorkspaceCompatibility.resolve(right, catalog) || right; - return remoteWorkspaceKey(resolvedLeft) === remoteWorkspaceKey(resolvedRight); -} - -/** Unknown legacy sessions are eligible only for an unambiguous local catalog row. */ -export function remoteSessionBelongsToWorkspace( - session: RemoteSession, scope: RemoteWorkspaceIdentity, catalog: RemoteWorkspaceIdentity[] -): boolean { - if (session.workspaceIdentity) { - return remoteWorkspaceIdentityMatches(session.workspaceIdentity, scope, catalog); - } - if (scope.remoteConnectionId?.trim() || scope.remoteSshHost?.trim() || !session.workspacePath?.trim()) return false; - const local: RemoteWorkspaceIdentity = { path: session.workspacePath }; - const resolved = LegacyWorkspaceCompatibility.resolve(local, catalog); - return resolved !== undefined && remoteWorkspaceKey(resolved) === remoteWorkspaceKey(scope); -} - -/** Stable key for a session that may exist on more than one desktop. */ -export function remoteSessionIdentity(session: RemoteSession): string { - return `${session.deviceId || ''}\u0001${session.id}`; -} - -export function stampRemoteSessionDevice(session: RemoteSession, deviceId: string): RemoteSession { - if (deviceId.length === 0 || session.deviceId === deviceId) { - return session; - } - return { - id: session.id, - title: session.title, - agentType: session.agentType, - status: session.status, - updatedAt: session.updatedAt, - createdAt: session.createdAt, - messageCount: session.messageCount, - workspacePath: session.workspacePath, - workspaceName: session.workspaceName, - workspaceIdentity: session.workspaceIdentity, - pinned: session.pinned, - titleGenerated: session.titleGenerated, - deviceId - }; -} - -export function stampRemoteSessionsDevice(sessions: RemoteSession[], deviceId: string): RemoteSession[] { - if (deviceId.length === 0) { - return sessions; - } - return sessions.map((item: RemoteSession): RemoteSession => stampRemoteSessionDevice(item, deviceId)); -} - -/** - * Fills the scope omitted by older list_sessions payloads without mutating it. - * - * A session the host already pinned to a workspace ID keeps that ID; the - * listing scope may only complete its display path and SSH projection, and - * only when the scope names the same workspace or has no ID of its own. A - * session already scoped by a legacy triple is left untouched. - */ -export function stampRemoteSessionWorkspace(session: RemoteSession, scope: RemoteWorkspaceIdentity): RemoteSession { - const scopeId = scope.workspaceId || ''; - if (scope.path.length === 0 && scopeId.length === 0) { - return session; - } - const existing = session.workspaceIdentity; - let identity: RemoteWorkspaceIdentity; - if (existing === undefined) { - identity = { - workspaceId: scopeId.length > 0 ? scopeId : undefined, - path: session.workspacePath || scope.path, - remoteConnectionId: scope.remoteConnectionId, - remoteSshHost: scope.remoteSshHost - }; - } else { - const existingId = existing.workspaceId || ''; - if (existingId.length === 0 || (scopeId.length > 0 && scopeId !== existingId)) { - return session; - } - const path = existing.path.length > 0 ? existing.path : (session.workspacePath || scope.path); - const remoteConnectionId = existing.remoteConnectionId !== undefined ? existing.remoteConnectionId : scope.remoteConnectionId; - const remoteSshHost = existing.remoteSshHost !== undefined ? existing.remoteSshHost : scope.remoteSshHost; - if (path === existing.path && remoteConnectionId === existing.remoteConnectionId && - remoteSshHost === existing.remoteSshHost && (session.workspacePath || '').length > 0) { - return session; - } - identity = { - workspaceId: existingId, - path: path, - remoteConnectionId: remoteConnectionId, - remoteSshHost: remoteSshHost - }; - } - return { - id: session.id, - title: session.title, - agentType: session.agentType, - status: session.status, - updatedAt: session.updatedAt, - createdAt: session.createdAt, - messageCount: session.messageCount, - workspacePath: session.workspacePath || identity.path, - workspaceIdentity: identity, - workspaceName: session.workspaceName, - pinned: session.pinned, - titleGenerated: session.titleGenerated, - deviceId: session.deviceId - }; -} - -export function stampRemoteSessionsWorkspace( - sessions: RemoteSession[], - scope: RemoteWorkspaceIdentity -): RemoteSession[] { - return sessions.map((item: RemoteSession): RemoteSession => stampRemoteSessionWorkspace(item, scope)); -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListCache.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListCache.ets deleted file mode 100644 index 5de0ff8f0d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListCache.ets +++ /dev/null @@ -1,182 +0,0 @@ -import { RecentWorkspaceEntry, RemoteSession } from '../model/RemoteModels'; -import { RemoteLogger } from './RemoteLogger'; -import { RemoteResponseMapper } from './RemoteResponseMapper'; - -/** A device's session list as it was last shown. */ -export interface RemoteSessionListSlice { - sessions: RemoteSession[]; - hasMore: boolean; -} - -/** Storage behind [RemoteSessionListCache]; see `RemoteSessionListRdbStore`. */ -export interface RemoteSessionListStore { - init(context: Context): Promise; - loadList(deviceKey: string): Promise; - /** The list for whichever device was written last, for a cold start. */ - loadLastList(): Promise; - saveList(deviceKey: string, sessions: RemoteSession[], hasMore: boolean): Promise; - /** Same row as [saveList], but does not move the cold-start last-device pointer. */ - saveObservedList(deviceKey: string, sessions: RemoteSession[], hasMore: boolean): Promise; - loadWorkspaces(deviceKey: string): Promise; - saveWorkspaces(deviceKey: string, workspaces: RecentWorkspaceEntry[]): Promise; - clearAll(): Promise; -} - -/** - * How many sessions per desktop are worth keeping. - * - * The list exists to fill the first screen while the connection settles, and - * the desktop replaces it wholesale a moment later, so storing past what the - * user can scroll to in that moment buys nothing. - */ -const CACHED_SESSIONS_PER_DEVICE: number = 60; - -/** - * The session list on disk, so Remote Home has something to show before the - * desktop answers. - * - * Same bargain as `RemoteChatCache`: every failure is swallowed, because a - * cache that cannot be read leaves the app exactly as slow as it was without - * one. What is served here is a snapshot that may already be stale — titles - * change, sessions get deleted — which is safe only because opening a session - * goes through the desktop anyway and the live list overwrites this one as soon - * as the connection is up. - */ -export class RemoteSessionListCache { - private readonly store: RemoteSessionListStore; - private readonly deviceKeyProvider: () => string; - private ready: boolean = false; - // Signature of the last list written, so the repeated `onSessions` callbacks - // behind one refresh cost one write rather than one write each. - private writtenScope: string = ''; - private writtenSignature: string = ''; - - constructor(store: RemoteSessionListStore, deviceKeyProvider: () => string) { - this.store = store; - this.deviceKeyProvider = deviceKeyProvider; - } - - async init(context: Context): Promise { - try { - await this.store.init(context); - this.ready = true; - } catch (err) { - RemoteLogger.error(`remote session list cache unavailable: ${RemoteSessionListCache.reason(err)}`); - } - } - - /** - * The list for the device the phone last talked to. - * - * Used at startup, where the device to key on is not known yet: identity is - * still being restored and the auto-reconnect that follows targets exactly - * the device this list came from. - */ - async restoreLast(): Promise { - if (!this.ready) { - return RemoteSessionListCache.empty(); - } - try { - return RemoteSessionListCache.visible(await this.store.loadLastList()); - } catch (err) { - RemoteLogger.error(`remote session list cache read failed: ${RemoteSessionListCache.reason(err)}`); - return RemoteSessionListCache.empty(); - } - } - - /** The list stored for the device currently being controlled. */ - async load(): Promise { - const deviceKey = this.scope(); - if (deviceKey.length === 0) { - return RemoteSessionListCache.empty(); - } - try { - return RemoteSessionListCache.visible(await this.store.loadList(deviceKey)); - } catch (err) { - RemoteLogger.error(`remote session list cache read failed: ${RemoteSessionListCache.reason(err)}`); - return RemoteSessionListCache.empty(); - } - } - - /** - * Stores the list now on screen. - * - * An empty list is never written: disconnecting clears the list through the - * same path a real refresh takes, and a user who steps away from a desktop - * should still find their sessions there on the next launch. - */ - async save(sessions: RemoteSession[], hasMore: boolean): Promise { - const deviceKey = this.scope(); - const visibleSessions = RemoteResponseMapper.visibleSessions(sessions); - if (deviceKey.length === 0 || visibleSessions.length === 0) { - return; - } - const kept = visibleSessions.slice(0, CACHED_SESSIONS_PER_DEVICE); - const keptHasMore = hasMore || kept.length < visibleSessions.length; - const signature = RemoteSessionListCache.signature(kept, keptHasMore); - if (this.writtenScope === deviceKey && this.writtenSignature === signature) { - return; - } - try { - await this.store.saveList(deviceKey, kept, keptHasMore); - this.writtenScope = deviceKey; - this.writtenSignature = signature; - } catch (err) { - this.forgetSignature(); - RemoteLogger.error(`remote session list cache write failed: ${RemoteSessionListCache.reason(err)}`); - } - } - - /** Drops every stored list, for signing out. */ - async clear(): Promise { - this.forgetSignature(); - if (!this.ready) { - return; - } - try { - await this.store.clearAll(); - } catch (err) { - RemoteLogger.error(`remote session list cache clear failed: ${RemoteSessionListCache.reason(err)}`); - } - } - - private forgetSignature(): void { - this.writtenScope = ''; - this.writtenSignature = ''; - } - - /** The device to key on, or '' when there is nothing safe to key on. */ - private scope(): string { - const deviceKey = this.deviceKeyProvider().trim(); - if (!this.ready || deviceKey.length === 0) { - return ''; - } - return deviceKey; - } - - /** - * Everything the list renders from, so a stored list is rewritten when a - * title changes but not when the same list is published twice. - */ - private static signature(sessions: RemoteSession[], hasMore: boolean): string { - const parts = sessions.map((item: RemoteSession): string => { - return `${item.id}${item.title}${item.status}${item.updatedAt}${item.messageCount}`; - }); - return `${hasMore ? '1' : '0'}${parts.join('')}`; - } - - private static empty(): RemoteSessionListSlice { - return { sessions: [], hasMore: false }; - } - - private static visible(slice: RemoteSessionListSlice): RemoteSessionListSlice { - return { - sessions: RemoteResponseMapper.visibleSessions(slice.sessions), - hasMore: slice.hasMore - }; - } - - private static reason(err: Object): string { - return err instanceof Error ? err.message : `${err}`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListRdbStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListRdbStore.ets deleted file mode 100644 index ae9f80929c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionListRdbStore.ets +++ /dev/null @@ -1,221 +0,0 @@ -import { relationalStore } from '@kit.ArkData'; -import { RecentWorkspaceEntry, RemoteSession } from '../model/RemoteModels'; -import { Encoding } from './Encoding'; -import { OhosError } from './OhosError'; -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; -import { RemoteSessionListSlice, RemoteSessionListStore } from './RemoteSessionListCache'; - -const STORE_CONFIG: relationalStore.StoreConfig = { - name: HarmonyUpgradeIdentityContract.REMOTE_SESSIONS_DATABASE, - // Session titles are as revealing as the transcripts themselves, so this - // matches the level the transcript store uses. - securityLevel: relationalStore.SecurityLevel.S2 -}; - -/** Bumped whenever a stored row stops meaning what it used to; see the chat store. */ -const SCHEMA_VERSION: number = 2; -const SCHEMA_VERSION_KEY: string = 'schema_version'; -const LAST_DEVICE_KEY: string = 'last_device_key'; - -const CREATE_META_SQL = - 'CREATE TABLE IF NOT EXISTS remote_session_meta (' + - 'key TEXT PRIMARY KEY, value TEXT NOT NULL)'; -// One row per device: the list is small, is always replaced as a whole, and is -// only ever read in full, so there is nothing for a per-session row to buy. -const CREATE_LIST_SQL = - 'CREATE TABLE IF NOT EXISTS remote_session_list (' + - 'device_key TEXT PRIMARY KEY, payload TEXT NOT NULL, has_more INTEGER NOT NULL, ' + - 'updated_at INTEGER NOT NULL)'; -const CREATE_WORKSPACES_SQL = - 'CREATE TABLE IF NOT EXISTS remote_device_workspaces (' + - 'device_key TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER NOT NULL)'; - -/** Session lists on disk, keyed by the desktop that owns them. */ -export class RemoteSessionListRdbStore implements RemoteSessionListStore { - private store?: relationalStore.RdbStore; - - async init(context: Context): Promise { - try { - const store = await relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_META_SQL); - if (await RemoteSessionListRdbStore.storedValue(store, SCHEMA_VERSION_KEY) !== `${SCHEMA_VERSION}`) { - await store.executeSql('DROP TABLE IF EXISTS remote_session_list'); - await store.executeSql('DROP TABLE IF EXISTS remote_device_workspaces'); - await store.executeSql( - 'DELETE FROM remote_session_meta WHERE key = ?', - [LAST_DEVICE_KEY] - ); - await store.executeSql( - 'INSERT OR REPLACE INTO remote_session_meta (key, value) VALUES (?, ?)', - [SCHEMA_VERSION_KEY, `${SCHEMA_VERSION}`] - ); - } - await store.executeSql(CREATE_LIST_SQL); - await store.executeSql(CREATE_WORKSPACES_SQL); - this.store = store; - } catch (err) { - throw OhosError.wrap('remote session list store init', err); - } - } - - async loadList(deviceKey: string): Promise { - if (deviceKey.length === 0) { - return RemoteSessionListRdbStore.empty(); - } - try { - const rows = await this.requireStore().querySql( - 'SELECT payload, has_more FROM remote_session_list WHERE device_key = ?', - [deviceKey] - ); - try { - if (!rows.goToNextRow()) { - return RemoteSessionListRdbStore.empty(); - } - return { - sessions: Encoding.parseJsonObject(rows.getString(rows.getColumnIndex('payload'))), - hasMore: rows.getLong(rows.getColumnIndex('has_more')) === 1 - }; - } finally { - RemoteSessionListRdbStore.closeResult(rows); - } - } catch (err) { - throw OhosError.wrap('remote session list load', err); - } - } - - async loadLastList(): Promise { - const deviceKey = await RemoteSessionListRdbStore.storedValue(this.requireStore(), LAST_DEVICE_KEY); - return await this.loadList(deviceKey); - } - - async saveList(deviceKey: string, sessions: RemoteSession[], hasMore: boolean): Promise { - await this.writeList(deviceKey, sessions, hasMore, true); - } - - async saveObservedList(deviceKey: string, sessions: RemoteSession[], hasMore: boolean): Promise { - await this.writeList(deviceKey, sessions, hasMore, false); - } - - private async writeList( - deviceKey: string, - sessions: RemoteSession[], - hasMore: boolean, - rememberAsLast: boolean - ): Promise { - if (deviceKey.length === 0) { - return; - } - try { - const store = this.requireStore(); - const values: relationalStore.ValuesBucket = { - device_key: deviceKey, - payload: JSON.stringify(sessions), - has_more: hasMore ? 1 : 0, - updated_at: Date.now() - }; - await store.insert('remote_session_list', values, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); - if (rememberAsLast) { - // Written after the list, so a pointer never names a row that is not there. - await store.executeSql( - 'INSERT OR REPLACE INTO remote_session_meta (key, value) VALUES (?, ?)', - [LAST_DEVICE_KEY, deviceKey] - ); - } - } catch (err) { - throw OhosError.wrap('remote session list save', err); - } - } - - async loadWorkspaces(deviceKey: string): Promise { - if (deviceKey.length === 0) { - return []; - } - try { - const rows = await this.requireStore().querySql( - 'SELECT payload FROM remote_device_workspaces WHERE device_key = ?', - [deviceKey] - ); - try { - if (!rows.goToNextRow()) { - return []; - } - return Encoding.parseJsonObject( - rows.getString(rows.getColumnIndex('payload')) - ); - } finally { - RemoteSessionListRdbStore.closeResult(rows); - } - } catch (err) { - throw OhosError.wrap('remote device workspace load', err); - } - } - - async saveWorkspaces(deviceKey: string, workspaces: RecentWorkspaceEntry[]): Promise { - if (deviceKey.length === 0) { - return; - } - try { - const values: relationalStore.ValuesBucket = { - device_key: deviceKey, - payload: JSON.stringify(workspaces), - updated_at: Date.now() - }; - await this.requireStore().insert( - 'remote_device_workspaces', - values, - relationalStore.ConflictResolution.ON_CONFLICT_REPLACE - ); - } catch (err) { - throw OhosError.wrap('remote device workspace save', err); - } - } - - async clearAll(): Promise { - try { - const store = this.requireStore(); - await store.executeSql('DELETE FROM remote_session_list'); - await store.executeSql('DELETE FROM remote_device_workspaces'); - await store.executeSql('DELETE FROM remote_session_meta WHERE key = ?', [LAST_DEVICE_KEY]); - } catch (err) { - throw OhosError.wrap('remote session list clear', err); - } - } - - private static async storedValue(store: relationalStore.RdbStore, key: string): Promise { - try { - const rows = await store.querySql( - 'SELECT value FROM remote_session_meta WHERE key = ?', - [key] - ); - try { - if (!rows.goToNextRow()) { - return ''; - } - return rows.getString(rows.getColumnIndex('value')); - } finally { - RemoteSessionListRdbStore.closeResult(rows); - } - } catch (err) { - throw OhosError.wrap('remote session list stored value', err); - } - } - - private static closeResult(result: relationalStore.ResultSet): void { - try { - result.close(); - } catch (err) { - throw OhosError.wrap('remote session list close cursor', err); - } - } - - private static empty(): RemoteSessionListSlice { - return { sessions: [], hasMore: false }; - } - - private requireStore(): relationalStore.RdbStore { - if (!this.store) { - throw new Error('Remote session list local store is not initialized.'); - } - return this.store; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets deleted file mode 100644 index fd1b445c5a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets +++ /dev/null @@ -1,976 +0,0 @@ -import { MessageQueueRequest, MessageQueueResponse, MessageQueueSnapshot } from '../model/MessageQueue'; -import { WorkspaceCatalog, projectWorkspaceCatalog } from './WorkspaceCatalog'; -import { RuntimeFileLocation } from '../model/RemoteModels'; -import { HostSessionCallbacks, HostSessionStream, REMOTE_CAPABILITY_HOST_STREAM_V1 } from './HostSessionStream'; -import { SavedRuntimeConnection, SavedRuntimeConnectionsResponse } from '../model/RemoteModels'; -import { AssistantEntry, AssistantListResponse, ChatMessageItemResponse, ChatMessageResponse, CommandStatusResponse, CreateSessionOptions, CreateSessionResponse, FileInfo, FileInfoResponse, InitialSyncResult, ModelCatalogResponse, ModelDefaultsUpdatedResponse, PermissionModeResponse, PollSessionResponse, PollSessionResult, REMOTE_CAPABILITY_WORKSPACE_ID_REFERENCES_V1, ReadFileChunkResponse, ReadFileChunkResult, ReadFileResult, RecentWorkspaceEntry, RecentWorkspaceListResponse, RemoteCommand, RemoteCommandCatalog, RemoteDefaultModels, RemoteImageContext, RemoteModelCatalog, RemotePermissionMode, RemoteQuestionAnswerPayload, RemoteSession, RemoteSessionUsageReport, RemoteTurnAcceptedValue, RemoteWorkspaceIdentity, SendMessageResponse, SessionListResponse, SessionListResult, SessionMessagesResponse, SessionMessagesResult, SessionRolledBackResponse, SessionRolledBackResult, SessionSummary, SetAssistantResponse, SetSessionModelResponse, SetWorkspaceResponse, SteerTurnResponse, SteerTurnResult, WorkspaceInfo, WorkspaceInfoResponse } from '../model/RemoteModels'; -import { Encoding } from './Encoding'; -import { CloudAccountClient, CloudAccountRequestError, CloudAccountSession } from './CloudAccountClient'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { - AccountDeviceCommandTransport, - INTERACTIVE_DIRECTORY_TIMEOUT_MS, - RemoteCommandTransport -} from './RemoteCommandTransport'; -import { RemoteCommandFactory } from './RemoteCommandFactory'; -import { RemoteChatCommandClient } from './RemoteChatCommandController'; -import { RemoteFileDownloadClient } from './RemoteFileDownloadController'; -import { RemoteLogger } from './RemoteLogger'; -import { RemoteModelClient } from './RemoteModelController'; -import { RemoteModelDefaultsClient } from './RemoteModelDefaultsController'; -import { RemoteCommandPaletteClient, RemoteCommandPaletteScope, RemoteSkillCatalogQuery } from './RemoteCommandPaletteController'; -import { HostInvokeRefusal } from './HostInvokeRefusal'; -import { CommandCatalogProjection, RemoteModeSkillRow } from './CommandCatalogProjection'; -import { RemoteResponseMapper } from './RemoteResponseMapper'; -import { stampRemoteSessionsWorkspace } from './RemoteSessionIdentity'; -import { TranscriptIntegrityPolicy } from './TranscriptIntegrityPolicy'; -import { RemoteSessionClient } from './RemoteSessionController'; -import { SubagentStreamSource } from './SubagentStreamCoordinator'; -import { RemoteToolActionClient } from './RemoteToolActionController'; - -/** - * How long the first command of an account-device connect may take. - * - * A desktop that is actually running answers `get_workspace_info` from memory, - * so anything past a few seconds means it is not there. The relay waits 130 s - * before giving up on it, and the phone tears the previous connection down - * before dialling — so without a deadline of our own, tapping a session on a - * desktop that has gone away costs two minutes of a blank screen. Only the - * handshake is bounded this tightly; once the desktop has answered once, the - * longer transport default applies to everything after it. - */ -const ACCOUNT_HANDSHAKE_TIMEOUT_MS: number = 15000; - -interface PermissionReplyArgs { request: PermissionReplyRequest; } -interface PermissionReplyRequest { requestId: string; reply: string; feedback?: string; updatedInput?: Object; } - -/** - * HostInvoke arguments for the composer palette's verbs. - * - * Shapes are per-command, not a shared envelope: `get_mode_skill_configs` takes - * flat arguments, and the three session verbs take a `request` object whose - * field spelling differs between their two Rust structs. - */ -interface ModeSkillConfigArgs { - modeId: string; - forceRefresh?: boolean; - workspaceId?: string; - workspacePath?: string; -} - -interface SessionRequest { - sessionId: string; - workspaceId?: string; - workspacePath?: string; - remoteConnectionId?: string; - remoteSshHost?: string; -} - -interface SessionRequestArgs { request: SessionRequest; } - -/** `GetSessionUsageReportRequest` is declared without `rename_all`. */ -interface SessionUsageRequest { - session_id: string; - workspace_id?: string; - workspace_path?: string; - remote_connection_id?: string; - remote_ssh_host?: string; -} - -interface SessionUsageArgs { request: SessionUsageRequest; } - -export class RemoteSessionManager implements RemoteChatCommandClient, RemoteFileDownloadClient, RemoteModelClient, RemoteSessionClient, RemoteToolActionClient, RemoteCommandPaletteClient, SubagentStreamSource, RemoteModelDefaultsClient { - private transport?: RemoteCommandTransport; - private transportGeneration: number = 0; - private workspace?: WorkspaceInfo; - /** Capabilities the connected host advertised in its handshake response. */ - private hostCapabilities: string[] = []; - - /** - * Opens a host-owned stream on the connected desktop. Pages are read from - * that desktop on demand and the relay stores none of them, so a host that - * predates `host_stream_v1` has nothing to answer with: refuse up front with - * the message the user can act on instead of probing it with a command it - * does not know. - */ - subscribeSession(logicalId: string, callbacks: HostSessionCallbacks): HostSessionStream { - const transport = this.transport; - if (!transport?.subscribeSession) throw new Error('Remote session streaming is unavailable'); - if (!this.supportsHostStreams()) throw new Error(RemoteI18n.t('errors.hostStreamUnsupported')); - return transport.subscribeSession(logicalId, callbacks); - } - - /** Whether the connected host serves `read_stream`, per its handshake `capabilities`. */ - supportsHostStreams(): boolean { - return (this.hostCapabilities || []).indexOf(REMOTE_CAPABILITY_HOST_STREAM_V1) >= 0; - } - - /** - * Sends one product command through the host bridge. - * - * A refusal is thrown as `HostInvokeRefusal` rather than a bare `Error` so the - * caller can tell a host that answered from a connection that did not: only the - * first may be described to the user as the host's own decision. - */ - supportsMessageQueue(): boolean { return this.hostCapabilities.includes('dialog_queue_v1'); } - async manageMessageQueue(request: MessageQueueRequest): Promise { - if (!this.supportsMessageQueue()) throw new Error('Host message queue is unsupported'); - const response = await this.send({ cmd: 'dialog_queue', request: request }); - if (response.resp === 'error' || !response.snapshot) throw new Error(response.message || 'Queue request failed'); - return response.snapshot; - } - - async hostInvoke(command: string, args: Object): Promise { - const response = await this.send>({ cmd: 'host_invoke', command: command, args: args }); - if (!response.ok) throw new HostInvokeRefusal(command, response.error || ''); - return response.value as T; - } - - reset(): void { - this.beginTransportReplacement(); - } - - private beginTransportReplacement(): number { - this.transportGeneration += 1; - this.transport?.reset(); - this.transport = undefined; - this.workspace = undefined; - this.hostCapabilities = []; - return this.transportGeneration; - } - - private requireCurrentGeneration(generation: number): void { - if (generation !== this.transportGeneration) { - throw new Error('Remote target changed while the connection was in flight.'); - } - } - - async connectAccountDevice( - accountClient: CloudAccountClient, - relayUrl: string, - session: CloudAccountSession, - targetDeviceId: string - ): Promise { - const generation = this.beginTransportReplacement(); - const transport = new AccountDeviceCommandTransport(accountClient, relayUrl, session, targetDeviceId); - let workspaceResponse: WorkspaceInfoResponse; - try { - workspaceResponse = await this.sendOnTransport( - transport, - generation, - RemoteCommandFactory.getWorkspaceInfo(), - ACCOUNT_HANDSHAKE_TIMEOUT_MS - ); - } catch (err) { - transport.reset(); - throw RemoteSessionManager.handshakeFailure(err); - } - try { - const workspace = RemoteResponseMapper.workspaceFromResponse(workspaceResponse); - const capabilities = workspaceResponse.capabilities || []; - const scope = RemoteSessionManager.workspaceScope(workspace); - RemoteSessionManager.requireWorkspaceIdReferences(scope, capabilities); - const sessionResponse = await this.sendOnTransport( - transport, - generation, - RemoteCommandFactory.listSessions(scope, 50, 0, '') - ); - const sessions = stampRemoteSessionsWorkspace(RemoteResponseMapper.sessions(sessionResponse.sessions || []), scope); - this.requireCurrentGeneration(generation); - this.transport = transport; - this.workspace = workspace; - this.hostCapabilities = capabilities.slice(); - return { - workspace, - sessions, - hasMoreSessions: sessionResponse.has_more || false, - authenticatedUserId: session.userId, - capabilities - }; - } catch (err) { - transport.reset(); - throw err instanceof Error ? err : new Error(String(err)); - } - } - - async getWorkspaceInfo(): Promise { - const response = await this.send(RemoteCommandFactory.getWorkspaceInfo()); - return RemoteResponseMapper.workspaceFromResponse(response); - } - - async listWorkspaceCatalog(): Promise { - const response = await this.send(RemoteCommandFactory.listRecentWorkspaces()); - return projectWorkspaceCatalog(response, await this.listAssistants()); - } - - async listRecentWorkspaces(): Promise { - const response = await this.send(RemoteCommandFactory.listRecentWorkspaces()); - return RemoteResponseMapper.recentWorkspaces(response.workspaces || []); - } - - async savedConnections(): Promise { - const command: RemoteCommand = { cmd: 'host_invoke', command: 'ssh_list_saved_connections' }; - const response = await this.send(command); - if (!response.ok) throw new Error(response.error || 'Saved connections unavailable'); - return response.value || []; - } - - /** - * Whether the connected host resolves `workspace_id` in commands. - * - * Read from the `capabilities` array of the handshake response. Absent on - * pre-ID hosts, where only references that never had an ID may be sent. - */ - supportsWorkspaceIdReferences(): boolean { - return (this.hostCapabilities || []).indexOf(REMOTE_CAPABILITY_WORKSPACE_ID_REFERENCES_V1) >= 0; - } - - /** - * Guards every command that would carry a `workspace_id`. - * - * A reference with an ID must never be downgraded to its display path: an - * ID-aware host could then open a different workspace under the same path, - * and a pre-ID host would silently do so. Surfacing the unsupported state is - * the only correct degradation. - */ - private static requireWorkspaceIdReferences(scope: RemoteWorkspaceIdentity, capabilities: string[]): void { - if (!scope.workspaceId) return; - if (capabilities.indexOf(REMOTE_CAPABILITY_WORKSPACE_ID_REFERENCES_V1) >= 0) return; - throw new Error(RemoteI18n.t('errors.workspaceIdUnsupported')); - } - - private requireWorkspaceIdReference(scope: RemoteWorkspaceIdentity): void { - RemoteSessionManager.requireWorkspaceIdReferences(scope, this.hostCapabilities || []); - } - - private static workspaceScope(workspace: WorkspaceInfo | undefined): RemoteWorkspaceIdentity { - return { - workspaceId: workspace?.workspaceId || undefined, - path: workspace?.path || '', - remoteConnectionId: workspace?.remoteConnectionId, - remoteSshHost: workspace?.remoteSshHost - }; - } - - async setWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - const scope: RemoteWorkspaceIdentity = { - workspaceId: workspaceId || undefined, - path, - remoteConnectionId: connectionId, - remoteSshHost: sshHost - }; - this.requireWorkspaceIdReference(scope); - const command = RemoteCommandFactory.setWorkspace(path, scope.workspaceId, connectionId, sshHost); - const response = await this.send(command); - if (response.success !== true) { - throw new Error(response.error || 'Failed to set workspace.'); - } - this.workspace = await this.getWorkspaceInfo(); - } - - async listAssistants(): Promise { - const response = await this.send(RemoteCommandFactory.listAssistants()); - return response.assistants || []; - } - - async setAssistant(path: string, workspaceId?: string): Promise { - const scope: RemoteWorkspaceIdentity = { workspaceId: workspaceId || undefined, path }; - this.requireWorkspaceIdReference(scope); - const response = await this.send(RemoteCommandFactory.setAssistant(path, scope.workspaceId)); - if (response.success !== true) { - throw new Error(response.error || 'Failed to set assistant workspace.'); - } - this.workspace = await this.getWorkspaceInfo(); - } - - async listRecentSessions(): Promise { - const result = await this.listSessions(8, 0, '', ''); - return result.sessions; - } - - async listSessionsForWorkspace(workspace: RemoteWorkspaceIdentity, limit: number = 50): Promise { - return (await this.listSessionPageForWorkspace(workspace, limit)).sessions; - } - - async listSessionPageForWorkspace(workspace: RemoteWorkspaceIdentity, limit: number = 50): Promise { - const scope: RemoteWorkspaceIdentity = { - workspaceId: workspace.workspaceId || undefined, - path: workspace.path.trim(), - remoteConnectionId: workspace.remoteConnectionId, - remoteSshHost: workspace.remoteSshHost - }; - if (!scope.workspaceId && scope.path.length === 0) { - return { sessions: [], hasMore: false }; - } - this.requireWorkspaceIdReference(scope); - const response = await this.send( - RemoteCommandFactory.listSessions(scope, limit, 0, ''), - INTERACTIVE_DIRECTORY_TIMEOUT_MS - ); - return { - sessions: stampRemoteSessionsWorkspace(RemoteResponseMapper.sessions(response.sessions || []), scope), - hasMore: response.has_more || false - }; - } - - async listSessions(limit: number, offset: number, query: string, agentType: string): Promise { - const scope = RemoteSessionManager.workspaceScope(this.workspace); - this.requireWorkspaceIdReference(scope); - const normalizedAgentType = RemoteSessionManager.normalizedSessionFilter(agentType); - const trimmedQuery = query.trim(); - const pageSize = normalizedAgentType ? Math.max(100, limit) : Math.max(1, limit); - const targetCount = offset + limit; - const filteredSessions: RemoteSession[] = []; - let pageOffset = 0; - let hasMore = true; - while (hasMore && filteredSessions.length < targetCount) { - const command = RemoteCommandFactory.listSessions(scope, pageSize, pageOffset, trimmedQuery); - const response = await this.send(command); - const sessions = stampRemoteSessionsWorkspace(RemoteResponseMapper.allSessions(response.sessions || []), scope); - for (const session of sessions) { - if (RemoteResponseMapper.isVisibleSession(session) && - (!normalizedAgentType || RemoteSessionManager.agentMatchesFilter(session.agentType, normalizedAgentType))) { - filteredSessions.push(session); - } - } - hasMore = response.has_more || false; - pageOffset += sessions.length; - if (sessions.length === 0) { - break; - } - } - return { - sessions: filteredSessions.slice(offset, targetCount), - hasMore: filteredSessions.length > targetCount || hasMore - }; - } - - async createSession( - options: CreateSessionOptions, - onAllocated?: (session: SessionSummary) => Promise - ): Promise { - const requestedPath = options.workspacePath?.trim() || ''; - const requestedWorkspaceId = options.workspaceId?.trim() || ''; - const workspacePath = requestedPath; - this.requireWorkspaceIdReference({ workspaceId: requestedWorkspaceId || undefined, path: workspacePath }); - const command = RemoteCommandFactory.createSession(options, workspacePath); - const response = await this.send(command); - const sessionId = response.session_id || response.id || ''; - if (!sessionId) throw new Error('Session creation returned no session identity'); - // The host answers with the record it actually created the session in; its - // ID wins over whatever the caller asked for. - const workspaceId = (response.workspace_id || '').trim() || (requestedWorkspaceId || undefined); - const resolvedPath = response.workspace_path ?? workspacePath; - const remoteConnectionId = response.workspace_path !== undefined ? response.remote_connection_id : - (requestedPath ? options.remoteConnectionId : undefined); - const remoteSshHost = response.workspace_path !== undefined ? response.remote_ssh_host : - (requestedPath ? options.remoteSshHost : undefined); - const title = response.title || options.title.trim() || RemoteI18n.t('session.newTitle'); - if (onAllocated) { - await onAllocated({ - sessionId, - title, - workspaceId, - workspacePath: resolvedPath, - remoteConnectionId, - remoteSshHost, - agentType: options.agentType - }); - } - const modelId = options.modelId?.trim() || ''; - if (modelId.length > 0) { - await this.setSessionModel(sessionId, modelId); - } - let initialTurnId = ''; - if (options.instruction.trim().length > 0) { - initialTurnId = await this.sendMessage(sessionId, options.instruction.trim(), options.agentType); - } - return { - sessionId, - title, - workspaceId, - workspacePath: resolvedPath, - remoteConnectionId, - remoteSshHost, - agentType: options.agentType, - initialTurnId - }; - } - - async sendMessage(sessionId: string, text: string, agentType?: string, turnId?: string): Promise { - const startedAt = Date.now(); - RemoteLogger.info(`send_message start session=${RemoteSessionManager.shortId(sessionId)} len=${text.length}`); - const response = await this.send( - RemoteCommandFactory.sendMessage(sessionId, text, agentType, undefined, turnId) - ); - RemoteLogger.info(`send_message done session=${RemoteSessionManager.shortId(sessionId)} turn=${response.turn_id || ''} ms=${Date.now() - startedAt}`); - return response.turn_id || ''; - } - - async sendMessageWithImages( - sessionId: string, - text: string, - agentType: string, - imageContexts: RemoteImageContext[], - turnId?: string - ): Promise { - const startedAt = Date.now(); - RemoteLogger.info(`send_message_images start session=${RemoteSessionManager.shortId(sessionId)} len=${text.length} images=${imageContexts.length}`); - const response = - await this.send( - RemoteCommandFactory.sendMessage(sessionId, text, agentType, imageContexts, turnId) - ); - RemoteLogger.info(`send_message_images done session=${RemoteSessionManager.shortId(sessionId)} turn=${response.turn_id || ''} ms=${Date.now() - startedAt}`); - return response.turn_id || ''; - } - - async steerTurn( - sessionId: string, - turnId: string, - text: string, - displayContent: string, - imageContexts: RemoteImageContext[] - ): Promise { - const startedAt = Date.now(); - RemoteLogger.info( - `steer_turn start session=${RemoteSessionManager.shortId(sessionId)} ` + - `turn=${RemoteSessionManager.shortId(turnId)} len=${text.length} images=${imageContexts.length}` - ); - const response = await this.send( - RemoteCommandFactory.steerTurn(sessionId, turnId, text, displayContent, imageContexts) - ); - const result: SteerTurnResult = { - sessionId: response.session_id || sessionId, - turnId: response.turn_id || turnId, - steeringId: response.steering_id || '' - }; - if (result.steeringId.length === 0) { - throw new Error('Remote host accepted steering without a steering id.'); - } - RemoteLogger.info( - `steer_turn done session=${RemoteSessionManager.shortId(result.sessionId)} ` + - `turn=${RemoteSessionManager.shortId(result.turnId)} ms=${Date.now() - startedAt}` - ); - return result; - } - - async buildPlan(sessionId: string, planFilePath: string, planName: string, agentType: string): Promise { - const startedAt = Date.now(); - RemoteLogger.info( - `build_plan start session=${RemoteSessionManager.shortId(sessionId)} path_len=${planFilePath.length}` - ); - const response = await this.send( - RemoteCommandFactory.buildPlan(sessionId, planFilePath, planName, agentType) - ); - RemoteLogger.info( - `build_plan done session=${RemoteSessionManager.shortId(sessionId)} ` + - `turn=${response.turn_id || ''} ms=${Date.now() - startedAt}` - ); - return response.turn_id || ''; - } - - async getSessionMessages(sessionId: string): Promise { - const startedAt = Date.now(); - const response = await this.send(RemoteCommandFactory.getSessionMessages(sessionId)); - const rawMessages = response.messages || []; - const messages = rawMessages.map((item: ChatMessageResponse) => RemoteResponseMapper.chatMessage(item)); - RemoteLogger.info( - `get_session_messages done session=${RemoteSessionManager.shortId(sessionId)} ` + - `raw=${rawMessages.length} ${TranscriptIntegrityPolicy.describeMessages(messages)} ` + - `ms=${Date.now() - startedAt}` - ); - const result: SessionMessagesResult = { - messages, - hasMore: false - }; - return result; - } - - async getModelCatalog(sessionId?: string): Promise { - const response = await this.send(RemoteCommandFactory.getModelCatalog(sessionId)); - return response.catalog || { - version: 0, - models: [], - default_models: {} - }; - } - - async setSessionModel(sessionId: string, modelId: string): Promise { - const response = await this.send(RemoteCommandFactory.setSessionModel(sessionId, modelId)); - return response.model_id || modelId; - } - - /** - * Writes the desktop's model role defaults and answers with what is stored. - * - * All six slots come back because the desktop reconciles on every write: a - * model that was removed can leave a role pointing at another model, and the - * caller must show the result rather than the request. A host that only - * acknowledges the command without echoing the slots leaves the answer to an - * authoritative read, exactly like a legacy permission-mode acknowledgement. - */ - async setModelDefaults( - primary: string | null, - fast: string | null, - imageUnderstanding: string | null - ): Promise { - const response = await this.send( - RemoteCommandFactory.setModelDefaults(primary, fast, imageUnderstanding) - ); - const defaults = response.default_models; - if (!defaults) { - const catalog = await this.getModelCatalog(); - return RemoteSessionManager.modelDefaults(catalog.default_models); - } - return RemoteSessionManager.modelDefaults(defaults); - } - - /** - * Normalizes an echoed defaults projection into all six slots. - * - * A slot that is neither a string nor null cannot be a stored selection, so - * it is refused instead of being shown as a configured model. - */ - private static modelDefaults(defaults: RemoteDefaultModels): RemoteDefaultModels { - return { - primary: RemoteSessionManager.modelDefaultsSlot(defaults.primary), - fast: RemoteSessionManager.modelDefaultsSlot(defaults.fast), - search: RemoteSessionManager.modelDefaultsSlot(defaults.search), - image_understanding: RemoteSessionManager.modelDefaultsSlot(defaults.image_understanding), - image_generation: RemoteSessionManager.modelDefaultsSlot(defaults.image_generation), - speech_recognition: RemoteSessionManager.modelDefaultsSlot(defaults.speech_recognition) - }; - } - - private static modelDefaultsSlot(value: string | null | undefined): string | null { - if (value === undefined || value === null) { - return null; - } - if (typeof value !== 'string') { - throw new Error('Model defaults unavailable'); - } - return value; - } - - /** - * The skill catalog the palette's picker shows. - * - * `get_mode_skill_configs` takes flat arguments and answers with the mode's - * skill rows; without `includeDiagnostics` the value is that rows array, which - * the projection turns into palette entries. A host that does not serve the - * command rejects the invoke, and that rejection is the palette's probe. - */ - async skillCatalog(query: RemoteSkillCatalogQuery): Promise { - const args: ModeSkillConfigArgs = { - modeId: query.modeId, - forceRefresh: query.forceRefresh - }; - if (query.workspaceId) { - args.workspaceId = query.workspaceId; - } - if (query.workspacePath) { - args.workspacePath = query.workspacePath; - } - const rows = await this.hostInvoke('get_mode_skill_configs', args); - return CommandCatalogProjection.parseHostCatalog(rows); - } - - /** - * `compact_session`, whose handler answers with the turn it started. - * - * The workspace locator is an upgrade projection: a host that still has the - * session in memory ignores it, and one that does not needs it to restore the - * session before compacting. - */ - async compactSession(query: RemoteCommandPaletteScope): Promise { - const args: SessionRequestArgs = { request: RemoteSessionManager.sessionRequest(query) }; - const value = await this.hostInvoke('compact_session', args); - RemoteLogger.info( - `compact_session accepted session=${RemoteSessionManager.shortId(query.sessionId)}`); - return value?.message || ''; - } - - async runInitAgentsMd(query: RemoteCommandPaletteScope): Promise { - const args: SessionRequestArgs = { request: RemoteSessionManager.sessionRequest(query) }; - const value = await this.hostInvoke('run_init_agents_md', args); - RemoteLogger.info( - `run_init_agents_md accepted session=${RemoteSessionManager.shortId(query.sessionId)}`); - return value?.message || ''; - } - - /** - * `get_session_usage_report`, whose request keeps its snake_case spelling. - * - * Unlike the two turn verbs this struct carries no `rename_all`, so its fields - * travel exactly as the desktop declares them. - */ - async sessionUsageReport(query: RemoteCommandPaletteScope): Promise { - const request: SessionUsageRequest = { session_id: query.sessionId }; - if (query.workspaceId) { - request.workspace_id = query.workspaceId; - } - if (query.workspacePath) { - request.workspace_path = query.workspacePath; - } - if (query.remoteConnectionId) { - request.remote_connection_id = query.remoteConnectionId; - } - if (query.remoteSshHost) { - request.remote_ssh_host = query.remoteSshHost; - } - const args: SessionUsageArgs = { request }; - return await this.hostInvoke('get_session_usage_report', args); - } - - private static sessionRequest(query: RemoteCommandPaletteScope): SessionRequest { - const request: SessionRequest = { sessionId: query.sessionId }; - if (query.workspaceId) { - request.workspaceId = query.workspaceId; - } - if (query.workspacePath) { - request.workspacePath = query.workspacePath; - } - if (query.remoteConnectionId) { - request.remoteConnectionId = query.remoteConnectionId; - } - if (query.remoteSshHost) { - request.remoteSshHost = query.remoteSshHost; - } - return request; - } - - async pollSession( - sessionId: string, - sinceVersion: number, - knownMessageCount: number, - knownModelCatalogVersion: number - ): Promise { - const startedAt = Date.now(); - const command = - RemoteCommandFactory.pollSession(sessionId, sinceVersion, knownMessageCount, knownModelCatalogVersion); - const response = await this.send(command); - const rawMessages = response.new_messages || []; - const newMessages = rawMessages.map((item: ChatMessageResponse) => RemoteResponseMapper.chatMessage(item)); - const rawSnapshot = response.message_snapshot; - const messageSnapshot = rawSnapshot ? - rawSnapshot.map((item: ChatMessageResponse) => RemoteResponseMapper.chatMessage(item)) : undefined; - const result: PollSessionResult = { - version: response.version || sinceVersion, - changed: response.changed, - sessionState: response.session_state || '', - title: response.title || '', - newMessages, - totalMessageCount: response.total_msg_count || knownMessageCount, - messageSnapshot, - activeTurn: response.active_turn - ? RemoteResponseMapper.activeTurnToMessage(response.active_turn, response.version || sinceVersion) - : undefined, - modelCatalog: response.model_catalog - }; - const rawActive = response.active_turn; - RemoteLogger.info(`poll_session done session=${RemoteSessionManager.shortId(sessionId)} changed=${result.changed ? '1' : '0'} state=${result.sessionState} active=${rawActive ? rawActive.turn_id : ''} activeStatus=${rawActive ? rawActive.status : ''} rawText=${rawActive && rawActive.text ? rawActive.text.length : 0} rawThinking=${rawActive && rawActive.thinking ? rawActive.thinking.length : 0} rawItems=${rawActive && rawActive.items ? rawActive.items.length : 0} rawItemText=${RemoteSessionManager.itemsContentLength(rawActive ? rawActive.items : undefined)} projectedText=${result.activeTurn ? result.activeTurn.text.length : 0} new=${newMessages.length} snapshot=${messageSnapshot ? messageSnapshot.length : 0} ${newMessages.length > 0 ? TranscriptIntegrityPolicy.describeMessages(newMessages) + ' ' : ''}ms=${Date.now() - startedAt}`); - return result; - } - - async cancelTask(sessionId: string, turnId?: string): Promise { - await this.send(RemoteCommandFactory.cancelTask(sessionId, turnId)); - } - - /** - * Retires one turn and everything the host recorded after it. - * - * The reply is decoded through the mapper rather than read off the response, so - * a host that answers with something other than `session_rolled_back` — an older - * build replying with a generic error, say — throws instead of arriving here as - * an empty success. The stale-view guard is deliberately not sent: this client - * has no storage index for the turn, and inventing one would only widen the race - * window without changing which turn is addressed. - */ - async rollbackSessionToTurn(sessionId: string, targetTurnId: string): Promise { - const startedAt = Date.now(); - RemoteLogger.info( - `rollback_session_to_turn start session=${RemoteSessionManager.shortId(sessionId)} ` + - `target=${RemoteSessionManager.shortId(targetTurnId)}` - ); - const response = await this.send( - RemoteCommandFactory.rollbackSessionToTurn(sessionId, targetTurnId) - ); - const result = RemoteResponseMapper.sessionRolledBack(response); - RemoteLogger.info( - `rollback_session_to_turn done session=${RemoteSessionManager.shortId(result.sessionId)} ` + - `retired=${result.retiredTurnIds.length} restored=${result.restoredFiles.length} ` + - `changed=${result.changed ? '1' : '0'} ms=${Date.now() - startedAt}` - ); - return result; - } - - async renameSession(sessionId: string, title: string): Promise { - await this.send(RemoteCommandFactory.renameSession(sessionId, title)); - } - - async deleteSession(sessionId: string): Promise { - await this.send(RemoteCommandFactory.deleteSession(sessionId)); - } - - async startQuestionInteraction(sessionId: string, toolId: string): Promise { - const command: RemoteCommand = { cmd: 'start_question_interaction', session_id: sessionId, tool_id: toolId }; - await this.send(command); - } - - async confirmTool(toolId: string, updatedInput?: Object): Promise { - if (toolId.startsWith('permission:')) { - const args: PermissionReplyArgs = { request: { requestId: toolId.slice('permission:'.length), reply: 'once', updatedInput: updatedInput } }; - await this.hostInvoke('respond_permission', args); return; - } - await this.send(RemoteCommandFactory.confirmTool(toolId, updatedInput)); - } - - async rejectTool(toolId: string, reason: string): Promise { - if (toolId.startsWith('permission:')) { - const args: PermissionReplyArgs = { request: { requestId: toolId.slice('permission:'.length), reply: 'reject', feedback: reason } }; - await this.hostInvoke('respond_permission', args); return; - } - await this.send(RemoteCommandFactory.rejectTool(toolId, reason)); - } - - async cancelTool(toolId: string, reason: string): Promise { - await this.send(RemoteCommandFactory.cancelTool(toolId, reason)); - } - - async getPermissionMode(): Promise { - const response = await this.send(RemoteCommandFactory.getPermissionMode()); - if (response.mode !== 'ask' && response.mode !== 'auto' && response.mode !== 'full_access') { - throw new Error('Permission mode unavailable'); - } - return response.mode; - } - - async setPermissionMode(mode: RemotePermissionMode): Promise { - const response = await this.send(RemoteCommandFactory.setPermissionMode(mode)); - if (!response.mode) return this.getPermissionMode(); - if (response.mode !== 'ask' && response.mode !== 'auto' && response.mode !== 'full_access') { - throw new Error('Permission mode unavailable'); - } - return response.mode; - } - - async answerQuestion(toolId: string, answers: RemoteQuestionAnswerPayload): Promise { - await this.send(RemoteCommandFactory.answerQuestion(toolId, answers)); - } - - private currentFileLocation(): RuntimeFileLocation | undefined { - return this.workspace ? { - path: this.workspace.path, remoteConnectionId: this.workspace.remoteConnectionId - } : undefined; - } - - private applyFileWorkspace(command: RemoteCommand, sessionId: string | undefined, workspace: RuntimeFileLocation | undefined): void { - if (sessionId) return; - if (!workspace?.path) throw new Error('File workspace identity is unavailable.'); - command.workspace_path = workspace.path; - command.remote_connection_id = workspace.remoteConnectionId; - } - - async getFileInfo(path: string, sessionId?: string): Promise { - const command = RemoteCommandFactory.getFileInfo(path, sessionId); - this.applyFileWorkspace(command, sessionId, this.currentFileLocation()); - - const response = await this.send(command); - return { - name: response.name || RemoteResponseMapper.basename(path), - size: response.size || 0, - mimeType: response.mime_type || 'application/octet-stream' - }; - } - - async readFileChunk( - path: string, - offset: number, - limit: number, - sessionId?: string, - fileWorkspace?: RuntimeFileLocation - ): Promise { - const command = RemoteCommandFactory.readFileChunk(path, offset, limit, sessionId); - this.applyFileWorkspace(command, sessionId, fileWorkspace || this.currentFileLocation()); - const response = await this.send(command); - return { - name: response.name || RemoteResponseMapper.basename(path), - contentBase64: response.chunk_base64 || '', - revision: response.revision, - offset: response.offset ?? offset, - chunkSize: response.chunk_size || 0, - totalSize: response.total_size || 0, - mimeType: response.mime_type || 'application/octet-stream' - }; - } - - async readFile(path: string, sessionId?: string, onProgress?: (downloaded: number, total: number) => void, maxBytes?: number): Promise { - const chunks: Uint8Array[] = []; - const info = await this.streamFile(path, sessionId, async (bytes: Uint8Array, metadata: FileInfo): Promise => { - if (maxBytes !== undefined && metadata.size > maxBytes) throw new Error('File too large for preview.'); - chunks.push(bytes); - }, onProgress); - const bytes = new Uint8Array(info.size); let offset = 0; - for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } - return { name: info.name, mimeType: info.mimeType, size: info.size, contentBase64: Encoding.bytesToBase64(bytes) }; - } - - async streamFile(path: string, sessionId: string | undefined, onChunk: (bytes: Uint8Array, info: FileInfo) => Promise, onProgress?: (downloaded: number, total: number) => void, location?: RuntimeFileLocation): Promise { - const chunkSize = 3 * 1024 * 1024; - let offset = 0; - let fileName = RemoteResponseMapper.basename(path); - let mimeType = 'application/octet-stream'; - let totalSize = 0; - let revision: string | undefined; - const generation = this.transportGeneration; - const transport = this.transport; - const source = location || this.workspace; - const fileWorkspace: RuntimeFileLocation | undefined = source ? { - path: source.path, remoteConnectionId: source.remoteConnectionId - } : undefined; - if (!sessionId && !fileWorkspace?.path) throw new Error('File workspace identity is unavailable.'); - let received = false; - while (true) { - if (generation !== this.transportGeneration || transport !== this.transport) { - throw new Error('Remote target changed during file transfer.'); - } - const response = await this.readFileChunk(path, offset, chunkSize, sessionId, fileWorkspace); - if (generation !== this.transportGeneration || transport !== this.transport) { - throw new Error('Remote target changed during file transfer.'); - } - const readSize = response.chunkSize; - const bytes = Encoding.base64ToBytes(response.contentBase64); - if (!Number.isSafeInteger(response.totalSize) || response.totalSize < 0 || - response.offset !== offset || readSize !== bytes.length || readSize > chunkSize || - readSize > response.totalSize - offset || (readSize === 0 && offset < response.totalSize)) { - throw new Error('Remote file transfer is incomplete or inconsistent.'); - } - if (received && (response.totalSize !== totalSize || response.name !== fileName || response.mimeType !== mimeType || response.revision !== revision)) { - throw new Error('Remote file changed during transfer.'); - } - await onChunk(bytes, { name: response.name, size: response.totalSize, mimeType: response.mimeType }); - received = true; - if (generation !== this.transportGeneration || transport !== this.transport) throw new Error('Remote target changed during file transfer.'); - fileName = response.name; - mimeType = response.mimeType; - totalSize = response.totalSize; - revision = response.revision; - offset += readSize; - if (onProgress) { - onProgress(offset, totalSize); - } - if (readSize === 0 || offset >= totalSize) { - break; - } - } - if (generation !== this.transportGeneration || transport !== this.transport) { - throw new Error('Remote target changed during file transfer.'); - } - return { name: fileName, mimeType: mimeType, size: totalSize }; - } - - async ping(): Promise { - // Bound key lookup and RPC together, like mobile-web's health probe. - let timer: number = -1; - try { - await Promise.race([ - this.send(RemoteCommandFactory.ping(), 10000), - new Promise((_resolve, reject) => { - timer = setTimeout(() => reject(new Error('Remote health probe timed out')), 10000); - }) - ]); - return true; - } finally { - if (timer !== -1) clearTimeout(timer); - } - } - - /** - * [readTimeoutMs] is left undefined so each transport applies its own - * default: a room command and an account command do not travel the same - * number of hops and never shared a sensible number. - */ - private async send(command: RemoteCommand, readTimeoutMs?: number): Promise { - if (!this.transport) { - throw new Error('Remote transport is not connected.'); - } - const generation = this.transportGeneration; - const transport = this.transport; - return this.sendOnTransport(transport, generation, command, readTimeoutMs, true); - } - - private async sendOnTransport( - transport: RemoteCommandTransport, - generation: number, - command: RemoteCommand, - readTimeoutMs?: number, - requireCommittedTransport: boolean = false - ): Promise { - command._request_id = `req_${Date.now()}_${Encoding.randomId('harmony').slice(0, 20)}`; - const response = await transport.send(command, readTimeoutMs); - if (generation !== this.transportGeneration || (requireCommittedTransport && transport !== this.transport)) { - throw new Error('Remote target changed while the request was in flight.'); - } - return response; - } - - /** - * Keeps a handshake failure readable. - * - * Everything but a relay status here is the SDK's own errno text for "nobody - * answered", which is both English and meaningless to the person holding the - * phone. A status still carries something the caller acts on — 401 expires - * the account session — so those pass through untouched. - */ - private static handshakeFailure(err: Object): Error { - if (err instanceof CloudAccountRequestError) { - return err; - } - RemoteLogger.warn(`account device handshake failed: ${String(err)}`); - return new Error(RemoteI18n.t('remote.settings.deviceUnavailable')); - } - - private static normalizedSessionFilter(agentType: string): string { - const normalized = (agentType || '').toLowerCase(); - if (normalized === 'code' || normalized === 'agentic') { - return 'code'; - } - if (normalized === 'cowork') { - return 'cowork'; - } - return ''; - } - - private static agentMatchesFilter(agentType: string, filter: string): boolean { - const normalized = (agentType || '').toLowerCase(); - if (filter === 'code') { - return normalized === 'code' || normalized === 'agentic'; - } - if (filter === 'cowork') { - return normalized === 'cowork'; - } - return true; - } - - private static shortId(value: string): string { - if (value.length <= 8) { - return value; - } - return value.slice(0, 4) + '...' + value.slice(value.length - 4); - } - - private static itemsContentLength(items?: ChatMessageItemResponse[]): number { - if (!items || items.length === 0) { - return 0; - } - let total = 0; - items.forEach((item: ChatMessageItemResponse) => { - total += item.content ? item.content.length : 0; - total += RemoteSessionManager.itemsContentLength(item.subItems); - }); - return total; - } - -} - -interface HostInvokeResponse extends CommandStatusResponse { ok: boolean; value?: T; error?: string; } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteToolActionController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteToolActionController.ets deleted file mode 100644 index de4ddd166e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteToolActionController.ets +++ /dev/null @@ -1,124 +0,0 @@ -import { RemoteQuestionAnswerPayload } from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { RemoteLogger } from './RemoteLogger'; - -export interface RemoteToolActionClient { - confirmTool(toolId: string, updatedInput?: Object): Promise; - rejectTool(toolId: string, reason: string): Promise; - cancelTool(toolId: string, reason: string): Promise; - answerQuestion(toolId: string, answers: RemoteQuestionAnswerPayload): Promise; -} - -export class RemoteToolActionController { - private readonly client: RemoteToolActionClient; - private readonly onStatusText: (statusText: string) => void; - private readonly onBusy: (isBusy: boolean) => void; - private readonly onPoll: () => void; - - constructor( - client: RemoteToolActionClient, - onStatusText: (statusText: string) => void, - onBusy: (isBusy: boolean) => void, - onPoll: () => void - ) { - this.client = client; - this.onStatusText = onStatusText; - this.onBusy = onBusy; - this.onPoll = onPoll; - } - - async approve( - toolId: string, - sessionId: string, - remoteAvailable: boolean, - updatedInput?: Object - ): Promise { - await this.runToolAction( - toolId, - sessionId, - remoteAvailable, - RemoteI18n.t('status.approvingTool'), - RemoteI18n.t('status.toolApproved'), - () => { - return this.client.confirmTool(toolId, updatedInput); - } - ); - } - - async reject(toolId: string, sessionId: string, remoteAvailable: boolean): Promise { - await this.runToolAction( - toolId, - sessionId, - remoteAvailable, - RemoteI18n.t('status.rejectingTool'), - RemoteI18n.t('status.toolRejected'), - () => { - return this.client.rejectTool(toolId, 'Rejected from HarmonyOS remote client'); - } - ); - } - - async cancel(toolId: string, sessionId: string, remoteAvailable: boolean): Promise { - RemoteLogger.info(`tool cancel requested tool=${RemoteToolActionController.shortId(toolId)} session=${RemoteToolActionController.shortId(sessionId)}`); - await this.runToolAction( - toolId, - sessionId, - remoteAvailable, - RemoteI18n.t('status.cancellingTool'), - RemoteI18n.t('status.toolCancelRequested'), - () => { - return this.client.cancelTool(toolId, 'Cancelled from HarmonyOS remote client'); - } - ); - } - - async answer( - toolId: string, - sessionId: string, - remoteAvailable: boolean, - answers: RemoteQuestionAnswerPayload - ): Promise { - RemoteLogger.info(`question answer requested tool=${RemoteToolActionController.shortId(toolId)} session=${RemoteToolActionController.shortId(sessionId)} fields=${Object.keys(answers).length}`); - await this.runToolAction( - toolId, - sessionId, - remoteAvailable, - RemoteI18n.t('status.submittingAnswer'), - RemoteI18n.t('status.answerSubmitted'), - () => { - return this.client.answerQuestion(toolId, answers); - } - ); - } - - private async runToolAction( - toolId: string, - sessionId: string, - remoteAvailable: boolean, - pendingText: string, - successText: string, - action: () => Promise - ): Promise { - if (sessionId.length === 0 || toolId.length === 0 || !remoteAvailable) { - return; - } - try { - this.onBusy(true); - this.onStatusText(pendingText); - await action(); - RemoteLogger.info(`tool action accepted tool=${RemoteToolActionController.shortId(toolId)}`); - this.onStatusText(successText); - this.onPoll(); - } catch (err) { - this.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.onBusy(false); - } - } - - private static shortId(value: string): string { - if (value.length <= 10) return value; - return `${value.slice(0, 6)}...${value.slice(-4)}`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteUiState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteUiState.ets deleted file mode 100644 index 08965cabd0..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteUiState.ets +++ /dev/null @@ -1,301 +0,0 @@ -import { - ChatMessage, - ImageAttachment, - RemoteModelCatalog, - RemoteModelConfig, - RemoteSession -} from '../model/RemoteModels'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { remoteSessionIdentity } from './RemoteSessionIdentity'; -import { TranscriptIntegrityPolicy } from './TranscriptIntegrityPolicy'; - -export class RemoteUiState { - static canUseRemote(connectionState: string): boolean { - return connectionState === 'connected' || - connectionState === 'reconnecting' || - connectionState === 'pairing'; - } - - static desktopNameFromRemoteUrl(value: string): string { - return RemoteUiState.queryValueFromRemoteUrl(value, 'dn'); - } - - static desktopIdFromRemoteUrl(value: string): string { - return RemoteUiState.queryValueFromRemoteUrl(value, 'did'); - } - - private static queryValueFromRemoteUrl(value: string, key: string): string { - const marker = `${key}=`; - const index = value.indexOf(marker); - if (index < 0) { - return ''; - } - const tail = value.slice(index + marker.length); - const end = tail.indexOf('&'); - const encoded = end >= 0 ? tail.slice(0, end) : tail; - try { - return decodeURIComponent(encoded.replace(/\+/g, ' ')); - } catch (_err) { - return encoded; - } - } - - static normalizeRemoteFilePath(path: string): string { - return path - .replace(/^computer:\/\//, '') - .replace(/^file:\/\//, '') - .trim(); - } - - static formatBytes(value: number): string { - if (value < 1024) { - return `${value} B`; - } - if (value < 1024 * 1024) { - return `${Math.round(value / 1024)} KB`; - } - return `${Math.round(value / 1024 / 1024)} MB`; - } - - static mergeMessages(current: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] { - const merged = current.slice(); - incoming.forEach((item: ChatMessage) => { - const existingIndex = merged.findIndex((existing: ChatMessage) => { - return existing.id === item.id; - }); - if (existingIndex >= 0) { - merged[existingIndex] = RemoteUiState.mergeMessageSnapshot(merged[existingIndex], item); - } else { - merged.push(item); - } - }); - return merged; - } - - static mergeRemoteWithLocalOptimistic(remoteMessages: ChatMessage[], currentMessages: ChatMessage[]): ChatMessage[] { - const merged = remoteMessages.slice(); - const acknowledgedRemoteIndexes = new Set(); - currentMessages.forEach((item: ChatMessage) => { - if (!RemoteUiState.isLocalOptimisticMessage(item)) { - return; - } - const acknowledgedIndex = merged.findIndex((remote: ChatMessage, index: number) => { - return !acknowledgedRemoteIndexes.has(index) && RemoteUiState.isOptimisticDuplicate(item, remote); - }); - if (acknowledgedIndex >= 0) { - acknowledgedRemoteIndexes.add(acknowledgedIndex); - } else { - merged.push(item); - } - }); - return merged; - } - - static mergeSessions(current: RemoteSession[], incoming: RemoteSession[]): RemoteSession[] { - const seen = new Set(); - current.forEach((item: RemoteSession) => { - seen.add(remoteSessionIdentity(item)); - }); - const merged = current.slice(); - incoming.forEach((item: RemoteSession) => { - const key = remoteSessionIdentity(item); - if (!seen.has(key)) { - merged.push(item); - seen.add(key); - } - }); - return merged; - } - - static updateSessionTitle(items: RemoteSession[], sessionId: string, title: string): RemoteSession[] { - return items.map((item: RemoteSession) => { - if (item.id !== sessionId) { - return item; - } - const updated: RemoteSession = { - id: item.id, - title, - agentType: item.agentType, - status: item.status, - updatedAt: item.updatedAt, - createdAt: item.createdAt, - messageCount: item.messageCount, - workspacePath: item.workspacePath, - workspaceName: item.workspaceName, - pinned: item.pinned, - titleGenerated: item.titleGenerated, - deviceId: item.deviceId - }; - return updated; - }); - } - - static markMessageFailed(messages: ChatMessage[], messageId: string): ChatMessage[] { - return messages.map((item: ChatMessage) => { - if (item.id !== messageId) { - return item; - } - const failed: ChatMessage = { - id: item.id, - turnId: item.turnId, - role: item.role, - text: item.text, - status: 'failed', - detail: item.detail, - error: item.error, - timestamp: item.timestamp, - thinking: item.thinking, - tools: item.tools, - items: item.items, - images: item.images - }; - return failed; - }); - } - - static localUserMessage(text: string, images?: ImageAttachment[], turnId?: string): ChatMessage { - return { - id: `optimistic-user-${Date.now()}`, - turnId, - role: 'user', - text, - status: 'sent', - timestamp: new Date().toISOString(), - images: images || [] - }; - } - - static emptyActiveTurn(): ChatMessage { - return { - id: '', - role: 'assistant', - text: '', - status: '', - detail: '' - }; - } - - static emptyModelCatalog(): RemoteModelCatalog { - return { - version: 0, - models: [], - default_models: {} - }; - } - - static selectedModelIdForCatalog(catalog: RemoteModelCatalog, currentSelectedModelId: string): string { - const sessionModelId = catalog.session_model_id || ''; - if (sessionModelId.length > 0) { - return sessionModelId; - } - if (currentSelectedModelId.length > 0) { - // A semantic selector stays semantic while the host can still resolve it, - // so the composer keeps showing the role that will actually run. The - // canonical value is returned, not the padded one that came in. - const semanticModelId = RemoteUiState.resolveSemanticModelId(catalog, currentSelectedModelId); - if (semanticModelId.length > 0) { - return semanticModelId; - } - const exists = catalog.models.some((model: RemoteModelConfig) => { - return model.id === currentSelectedModelId && model.enabled; - }); - if (exists) { - return currentSelectedModelId; - } - } - return catalog.default_models.primary || catalog.default_models.fast || currentSelectedModelId; - } - - /** - * Keeps a semantic selector (`primary` / `fast`) only while it resolves to an - * enabled model, mirroring the host's own selection semantics including the - * fast-to-primary fallback. Returns an empty string for anything else. - * - * This repeats `ConversationModelPresentationPolicy.resolveModel` because the - * service layer may not import the page policy layer. Both sides trim, so a - * padded selector or default resolves the same way in either one. - */ - private static resolveSemanticModelId(catalog: RemoteModelCatalog, modelId: string): string { - const value = (modelId || '').trim(); - const primary = (catalog.default_models.primary || '').trim(); - if (value === 'primary') { - return RemoteUiState.hasEnabledModel(catalog, primary) ? value : ''; - } - if (value === 'fast') { - const fast = (catalog.default_models.fast || '').trim(); - if (RemoteUiState.hasEnabledModel(catalog, fast)) { - return value; - } - return RemoteUiState.hasEnabledModel(catalog, primary) ? value : ''; - } - return ''; - } - - private static hasEnabledModel(catalog: RemoteModelCatalog, modelId: string): boolean { - const value = (modelId || '').trim(); - if (value.length === 0) { - return false; - } - return catalog.models.some((model: RemoteModelConfig) => model.id === value && model.enabled); - } - - static seedMessage(title: string): ChatMessage { - return { - id: `system-${Date.now()}`, - role: 'assistant', - text: RemoteI18n.f('ui.seedConnected', title), - status: 'ready' - }; - } - - private static isLocalOptimisticMessage(item: ChatMessage): boolean { - return item.role === 'user' && item.id.indexOf('optimistic-user-') === 0; - } - - private static isOptimisticDuplicate(local: ChatMessage, remote: ChatMessage): boolean { - if (!RemoteUiState.isLocalOptimisticMessage(local) || local.role !== remote.role) { - return false; - } - const localTurnId = (local.turnId || '').trim(); - const remoteTurnId = (remote.turnId || '').trim(); - if (localTurnId.length > 0 && remoteTurnId.length > 0) { - return localTurnId === remoteTurnId; - } - return local.text.trim() === remote.text.trim() && - local.text.trim().length > 0 && - RemoteUiState.imageSignature(local.images || []) === RemoteUiState.imageSignature(remote.images || []); - } - - private static imageSignature(images: ImageAttachment[]): string { - return images.map((image: ImageAttachment) => { - return `${image.name || ''}:${image.data_url || ''}`; - }).sort().join('|'); - } - - private static mergeMessageSnapshot(previous: ChatMessage, incoming: ChatMessage): ChatMessage { - const hasIncomingText = (incoming.text || '').trim().length > 0; - const incomingThinking = (incoming.thinking || '').trim(); - const incomingTools = incoming.tools && incoming.tools.length > 0 ? incoming.tools : undefined; - const incomingItems = TranscriptIntegrityPolicy.hasRenderableItems(incoming.items) ? incoming.items : undefined; - const incomingImages = incoming.images && incoming.images.length > 0 ? incoming.images : undefined; - return { - id: incoming.id, - turnId: incoming.turnId || previous.turnId, - role: incoming.role || previous.role, - text: hasIncomingText ? incoming.text : previous.text, - status: incoming.status || previous.status, - detail: incoming.detail || previous.detail, - error: incoming.error || previous.error, - timestamp: incoming.timestamp || previous.timestamp, - // Final text without a thinking field still clears streamed thinking. - // An empty stub must not wipe a body the previous snapshot already had. - thinking: incomingThinking.length > 0 - ? incoming.thinking - : (hasIncomingText ? incoming.thinking : previous.thinking), - tools: incomingTools !== undefined ? incomingTools : previous.tools, - items: incomingItems !== undefined ? incomingItems : previous.items, - images: incomingImages !== undefined ? incomingImages : previous.images, - renderVersion: incoming.renderVersion !== undefined ? incoming.renderVersion : previous.renderVersion - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceCoordinator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceCoordinator.ets deleted file mode 100644 index 940aac4648..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceCoordinator.ets +++ /dev/null @@ -1,74 +0,0 @@ -import { WorkspaceCatalog } from './WorkspaceCatalog'; -import { - SavedRuntimeConnection, - AssistantEntry, - RecentWorkspaceEntry, - RemoteSession, - RemoteWorkspaceIdentity, - WorkspaceInfo -} from '../model/RemoteModels'; -import { - CONCURRENT_WORKSPACE_LISTINGS, - mapInConcurrentBatches, - mergeUniqueSessions -} from './ConcurrentWorkspaceListing'; -import { RemoteWorkspaceDataSource } from './RemoteWorkspaceRepository'; -import { RemoteLogger } from './RemoteLogger'; - -/** Coordinates workspace/assistant selection and cross-workspace session discovery. */ -export class RemoteWorkspaceCoordinator { - private readonly repository: RemoteWorkspaceDataSource; - - constructor(repository: RemoteWorkspaceDataSource) { - this.repository = repository; - } - - async workspaceCatalog(): Promise { - return await this.repository.listWorkspaceCatalog(); - } - - async recentWorkspaces(): Promise { - return await this.repository.listRecentWorkspaces(); - } - - async assistants(): Promise { - return await this.repository.listAssistants(); - } - - async savedConnections(): Promise { return await this.repository.savedConnections(); } - - async switchWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - return await this.repository.setWorkspace(path, connectionId, sshHost, workspaceId); - } - - async switchAssistant(path: string, workspaceId?: string): Promise { - return await this.repository.setAssistant(path, workspaceId); - } - - /** - * Every session the given workspaces know about, first occurrence winning. - * - * Listings run a batch at a time rather than all at once or one at a time, - * and results are merged in the order the workspaces were given, so widening - * the batch changes how long this takes and nothing about what it returns. - */ - async sessionsForWorkspaces(workspaces: RemoteWorkspaceIdentity[]): Promise { - const listings = await mapInConcurrentBatches( - workspaces, - (workspace: RemoteWorkspaceIdentity): Promise => this.sessionsForWorkspace(workspace), - CONCURRENT_WORKSPACE_LISTINGS - ); - return mergeUniqueSessions(listings); - } - - /** One workspace's sessions, or none when that workspace cannot be read. */ - private async sessionsForWorkspace(workspace: RemoteWorkspaceIdentity): Promise { - try { - return await this.repository.listSessionsForWorkspace(workspace, 50); - } catch (err) { - // One unreadable workspace is not a reason to lose the other twenty. - RemoteLogger.warn(`load workspace sessions failed workspace=${workspace.workspaceId || ''} path=${workspace.path}: ${String(err)}`); - return []; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceFileClient.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceFileClient.ets deleted file mode 100644 index ebf3d056e1..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceFileClient.ets +++ /dev/null @@ -1,14 +0,0 @@ -import { RuntimeFileLocation, FileInfo, ReadFileChunkResult, ReadFileResult } from '../model/RemoteModels'; - -/** Stable mobile-side port for files owned by the active remote workspace. */ -export interface RemoteWorkspaceFileClient { - getFileInfo(path: string, sessionId?: string): Promise; - readFileChunk(path: string, offset: number, limit: number, sessionId?: string): Promise; - streamFile(path: string, sessionId: string | undefined, onChunk: (bytes: Uint8Array, info: FileInfo) => Promise, onProgress?: (downloaded: number, total: number) => void, location?: RuntimeFileLocation): Promise; - readFile( - path: string, - sessionId?: string, - onProgress?: (downloaded: number, total: number) => void, - maxBytes?: number - ): Promise; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceRepository.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceRepository.ets deleted file mode 100644 index f3a59c3393..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteWorkspaceRepository.ets +++ /dev/null @@ -1,67 +0,0 @@ -import { WorkspaceCatalog } from './WorkspaceCatalog'; -import { - SavedRuntimeConnection, - AssistantEntry, - RecentWorkspaceEntry, - RemoteSession, - RemoteWorkspaceIdentity, - WorkspaceInfo -} from '../model/RemoteModels'; -import { RemoteSessionManager } from './RemoteSessionManager'; - -export interface RemoteWorkspaceDataSource { - listWorkspaceCatalog(): Promise; - savedConnections(): Promise; - listRecentWorkspaces(): Promise; - setWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise; - listAssistants(): Promise; - setAssistant(path: string, workspaceId?: string): Promise; - listSessionsForWorkspace(workspace: RemoteWorkspaceIdentity, limit: number): Promise; - ping(): Promise; - reset(): void; -} - -/** Repository boundary for workspace, assistant and connection health data. */ -export class RemoteWorkspaceRepository implements RemoteWorkspaceDataSource { - private readonly sessionManager: RemoteSessionManager; - - constructor(sessionManager: RemoteSessionManager) { - this.sessionManager = sessionManager; - } - - async savedConnections(): Promise { return await this.sessionManager.savedConnections(); } - - async listWorkspaceCatalog(): Promise { - return await this.sessionManager.listWorkspaceCatalog(); - } - - async listRecentWorkspaces(): Promise { - return await this.sessionManager.listRecentWorkspaces(); - } - - async setWorkspace(path: string, connectionId?: string, sshHost?: string, workspaceId?: string): Promise { - await this.sessionManager.setWorkspace(path, connectionId, sshHost, workspaceId); - return await this.sessionManager.getWorkspaceInfo(); - } - - async listAssistants(): Promise { - return await this.sessionManager.listAssistants(); - } - - async setAssistant(path: string, workspaceId?: string): Promise { - await this.sessionManager.setAssistant(path, workspaceId); - return await this.sessionManager.getWorkspaceInfo(); - } - - async listSessionsForWorkspace(workspace: RemoteWorkspaceIdentity, limit: number): Promise { - return await this.sessionManager.listSessionsForWorkspace(workspace, limit); - } - - async ping(): Promise { - await this.sessionManager.ping(); - } - - reset(): void { - this.sessionManager.reset(); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RollbackOutcomePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RollbackOutcomePolicy.ets deleted file mode 100644 index 7f7304f234..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RollbackOutcomePolicy.ets +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Which staged-rollback outcome a refused `rollback_session_to_turn` is. - * - * The transport hands back the host's own error text and nothing else, and the - * staged rollback reacts to the two cases differently: a target the host no - * longer holds means this client's view moved on, which is repaired by resyncing - * quietly, while every other refusal is a failure the user has to be told about. - * - * The markers below are the host's own words for the first case, taken from the - * rollback handler that answers the command - * (`src/crates/assembly/core/src/agentic/coordination/coordinator.rs`): - * 8760 "Session rollback target is stale" - * 8768 "Session rollback target was not found" - * 8773 "Session rollback target storage identity is stale" - * Everything unmatched — an unsupported remote workspace, an unfinished revert, - * a busy session, a broken link — stays a failure, because a classification that - * guesses "stale" would swallow a real error behind a silent retry. - */ -export enum RollbackFailureKind { - /** The host does not hold the turn the client addressed; resync and drop. */ - StaleView = 'stale_view', - /** Everything else: resync and say so. */ - Failed = 'failed' -} - -const STALE_TARGET_MARKERS: string[] = [ - 'session rollback target is stale', - 'session rollback target storage identity is stale', - 'session rollback target was not found' -]; - -export class RollbackOutcomePolicy { - /** Classify one thrown refusal from the rollback command. */ - static failureKind(err: Object): RollbackFailureKind { - const text = RollbackOutcomePolicy.messageOf(err).toLowerCase(); - for (const marker of STALE_TARGET_MARKERS) { - if (text.indexOf(marker) >= 0) { - return RollbackFailureKind.StaleView; - } - } - return RollbackFailureKind.Failed; - } - - /** The host's message, kept as it arrived. */ - static messageOf(err: Object): string { - if (err instanceof Error) { - return err.message; - } - return JSON.stringify(err); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RpcPayload.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RpcPayload.ets deleted file mode 100644 index f6ee87034d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RpcPayload.ets +++ /dev/null @@ -1,67 +0,0 @@ -import { http } from '@kit.NetworkKit'; -import { util } from '@kit.ArkTS'; - -interface PayloadDescriptor { id: string; bytes: number; } -interface PayloadReference { $relayPayload?: PayloadDescriptor; } - -/** Opaque temporary RPC blocks; never contains a caller-controlled fetch URL. */ -export class RpcPayload { - private readonly endpoint: string; - private requests: Set = new Set(); - private closed: boolean = false; - private token: string; - constructor(relayUrl: string, token: string) { - this.token = token; - this.endpoint = `${relayUrl}/v1/rpc/payloads`; - } - close(): void { - this.closed = true; - this.requests.forEach((request: http.HttpRequest) => { request.destroy(); }); - this.requests.clear(); - } - async uploadIfLarge(value: Object): Promise { - const text = JSON.stringify(value); - const size = new util.TextEncoder().encodeInto(text).byteLength; - if (size <= 128 * 1024) return value; - if (size > 64 * 1024 * 1024) throw new Error('RPC payload exceeds a transfer block; use chunked operations'); - const reply = await this.request(this.endpoint, text); - const reference = JSON.parse(reply) as PayloadReference; - this.validate(reference); - return reference; - } - async resolve(value: Object): Promise { - const reference = value as PayloadReference; - if (!reference.$relayPayload) return value; - const descriptor = this.validate(reference); - const text = await this.request(`${this.endpoint}/${descriptor.id}`); - if (new util.TextEncoder().encodeInto(text).byteLength !== descriptor.bytes) throw new Error('Relay payload length mismatch'); - return JSON.parse(text) as Object; - } - private validate(reference: PayloadReference): PayloadDescriptor { - const value = reference.$relayPayload; - if (!value || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value.id) - || !Number.isInteger(value.bytes) || value.bytes < 1 || value.bytes > 64 * 1024 * 1024) { - throw new Error('Invalid Relay payload reference'); - } - return value; - } - private async request(url: string, body?: string): Promise { - if (this.closed) throw new Error('Relay is closed'); - const request = http.createHttp(); - this.requests.add(request); - try { - const options: http.HttpRequestOptions = { - method: body === undefined ? http.RequestMethod.GET : http.RequestMethod.POST, - header: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/octet-stream' }, - expectDataType: http.HttpDataType.STRING, - maxLimit: 64 * 1024 * 1024, - connectTimeout: 15000, readTimeout: 120000 - }; - if (body !== undefined) options.extraData = body; - const response = await request.request(url, options); - if (this.closed) throw new Error('Relay is closed'); - if (response.responseCode !== 200 || typeof response.result !== 'string') throw new Error(`Relay payload transfer failed (${response.responseCode})`); - return response.result; - } finally { this.requests.delete(request); request.destroy(); } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/StartupRevealPreference.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/StartupRevealPreference.ets deleted file mode 100644 index 39d56822e2..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/StartupRevealPreference.ets +++ /dev/null @@ -1,23 +0,0 @@ -import { preferences } from '@kit.ArkData'; -import { RemoteLogger } from './RemoteLogger'; - -/** Installation-local presentation state, independent of accounts and app versions. */ -export class StartupRevealPreference { - private static claimed: boolean = false; - - static claim(context: Context): boolean { - if (StartupRevealPreference.claimed) return false; - StartupRevealPreference.claimed = true; - try { - const store = preferences.getPreferencesSync(context, { name: 'startup_presentation' }); - if (store.getSync('brand_reveal_shown', false) === true) return false; - // Persist before playback so interrupted launches do not replay the reveal. - store.putSync('brand_reveal_shown', true); - store.flush().catch(() => RemoteLogger.warn('Startup reveal preference could not be persisted.')); - return true; - } catch (_err) { - RemoteLogger.warn('Startup reveal preference unavailable; skipping reveal.'); - return false; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets deleted file mode 100644 index e4fa56520b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets +++ /dev/null @@ -1,906 +0,0 @@ -import { ChatMessage, ChatMessageItemResponse, RemoteToolStatusResponse } from '../model/RemoteModels'; -import { DurableSessionReducer } from './DurableSessionReducer'; -import { HostSessionCallbacks, HostSessionEvent, HostSessionStream } from './HostSessionStream'; -import { RemoteLogger } from './RemoteLogger'; - -/** - * The one call the coordinator needs from the runtime connection. - * - * `RemoteSessionManager` implements it, so the production path opens child - * streams exactly the way it opens the session on screen; a preview fixture can - * implement it over its own pages. - */ -export interface SubagentStreamSource { - subscribeSession(sessionId: string, callbacks: HostSessionCallbacks): HostSessionStream; -} - -/** - * Where a child branch's records are kept between app launches. - * - * This is the phone's own transcript cache, keyed by the child Session id — - * `RemoteChatBranchCache` adapts `RemoteChatCache`, which is the storage the - * parent session's transcript already uses. A child is an ordinary session on - * its own stream id, so its transcript caches the same way; and because the - * child Session id is what the parent's launching item names, the key is also - * what maps a stored child back to the parent and the branch that owns it. - */ -export interface SubagentBranchCache { - loadBranch(sessionId: string): Promise; - saveBranch(sessionId: string, messages: ChatMessage[]): Promise; -} - -/** How many of a session's children are followed, and how many are waiting for a slot. */ -export interface SubagentFollowState { - branches: number; - subscribed: number; - waiting: number; - /** Steps currently drawn from the transcript cache, i.e. what a cold start had. */ - restored: number; -} - -/** - * How many child sessions one parent session follows at once. - * - * Every child is another paged stream read over the same device RPC lane as the - * parent session, and a delegation wider than this is past what a phone screen - * presents at once. The cap never costs a card its content: a child that holds - * no slot keeps the branch it already published (or what the transcript cache - * holds for it), and takes a slot as soon as one frees or the reader opens its - * card. - */ -const MAX_CONCURRENT_CHILD_STREAMS: number = 8; - -/** - * Longest a branch's transcript write is held back, in milliseconds. - * - * The same interval the parent transcript's own cache write uses, for the same - * reason: a worker publishing a step at a time would otherwise rewrite (and - * re-encrypt) the child's whole transcript on the thread that draws the screen. - */ -const BRANCH_CACHE_FLUSH_MS: number = 400; - -/** Tool-item fields a launching record carries; the child Session id names its stream. */ -interface SubagentOwnerItemData { - toolName?: string; - subagentSessionId?: string; - toolCall?: SubagentOwnerToolCall; -} -interface SubagentOwnerToolCall { id?: string; } -interface SubagentOwnerItem { type?: string; data?: SubagentOwnerItemData; } -interface SubagentOwnerRecord { item?: SubagentOwnerItem; } - -/** One child session whose records are drawn inside the branch that launched it. */ -interface SubagentBranch { - sessionId: string; - ownerToolCallId: string; - reducer: DurableSessionReducer; - stream?: HostSessionStream; - /** Whether this child's own stream is open right now. */ - subscribed: boolean; - /** False until the child's first page settled, so its backfill is one publish. */ - caughtUp: boolean; - /** True when the child's stream failed before it published anything. */ - streamFailed: boolean; - /** - * Steps read back from the transcript cache, i.e. what this branch published - * in an earlier launch of the app. They are merged with whatever the child's - * stream publishes now, never replaced by it: a child stream can start at its - * newest page, so the cached prefix is the only copy of its earlier steps. - */ - cached: ChatMessageItemResponse[]; - /** - * The outcome the cached transcript ended on: running, completed or failed. - * - * A worker this phone watched before a restart is the one case where no stream - * will ever say how it ended — the records it published are on the host, and a - * host that is gone answers nothing — so its stored outcome is the only - * reading of it left. - */ - cachedStatus: string; - items: ChatMessageItemResponse[]; - /** How many times this branch's content or status changed. Monotonic per branch. */ - changes: number; - signature: string; - /** - * The worker's own lifecycle, derived from its stream: running, completed or - * failed. Empty means this coordinator has nothing to say about the worker, - * e.g. its stream failed before it published anything. - */ - status: string; - /** - * Whether that reading came from the worker's own stream. - * - * A branch restored from the transcript cache answers with the outcome it was - * stored with, and that is not a worker this session has seen finish: a phone - * that just started holds a stored "completed" for a worker that may be - * running its next turn right now. Until this child's stream has read a turn of - * its own, nothing here is treated as settled — in particular its stream is - * kept, because releasing it is what would make the stored reading permanent. - */ - liveStatus: boolean; - /** Monotonic stamp of when this child was last seen working; decides release order. */ - lastActivity: number; - /** Pending transcript write, or -1 when none is scheduled. */ - flushTimer: number; -} - -/** - * Streams a delegation tool's child sessions into the branch that launched them. - * - * A host keeps a spawned child agent in its own hidden session: the parent - * record names that session on the launching tool item, and nothing the child - * does appears in the parent's own stream. The only place the child's steps - * exist is its stream, so the branch content is grouped by the subscription the - * records arrived on — the child session id the host named — and never by a - * marker on a record. - * - * The parent session's reducer stays the single author of the parent - * transcript: this coordinator only attaches each child's own projection as the - * branch items of the item that owns it, and the transcript grouping policy - * then draws that item as the card it already knew how to draw. A host that does - * not name a child session produces no branch here at all, so an older desktop - * keeps the plain tool rows it has always sent. - * - * Two facts about a branch are read from two different places, and are kept - * apart on purpose: - * - * - The launching item's own status is the spawn call's outcome. A host answers - * an asynchronous `AgentSpawn` as soon as the worker starts, so that status - * says nothing about whether the worker is still working. - * - The card's lifecycle is the worker's, so it is derived from the child's own - * stream here, and only that reading is what the card is fed. - */ -export class SubagentStreamCoordinator { - private source: SubagentStreamSource; - private branchCache?: SubagentBranchCache; - private notify: () => void; - private onError: (error: Error) => void; - private parentSessionId: string = ''; - private branches: Map = new Map(); - /** Owner tool call id -> child session id, i.e. which item a child belongs to. */ - private owners: Map = new Map(); - /** Owner tool call id -> the digest of the last launch state this coordinator published. */ - private ownerDigests: Map = new Map(); - /** Owner tool call id -> the render version this coordinator has published for it. */ - private ownerVersions: Map = new Map(); - /** Child session ids holding no slot, oldest first; newest is served first. */ - private waiters: string[] = []; - /** Monotonic stamp backing `lastActivity`, so release order needs no clock. */ - private activitySeq: number = 0; - - constructor(source: SubagentStreamSource, notify: () => void, onError: (error: Error) => void, - branchCache?: SubagentBranchCache) { - this.source = source; - this.branchCache = branchCache; - this.notify = notify; - this.onError = onError; - } - - /** - * Binds the coordinator to the parent session that is being opened. - * - * Nothing survives a session switch: another session's children are not this - * session's branches, and their streams would keep pushing records into a - * transcript that is no longer on screen. - */ - beginSession(parentSessionId: string): void { - this.detach(); - this.parentSessionId = parentSessionId; - } - - /** Closes every child stream; the parent session's own transcript is untouched. */ - endSession(): void { - this.detach(); - } - - /** - * Follows the parent's own records, which are the only place a child session - * id is named. - * - * Nothing else is inferred: a launch item without that field is an ordinary - * tool call, and no amount of tool ordering is treated as a subagent. - */ - observeParentEvent(event: HostSessionEvent): void { - if (this.parentSessionId.length === 0) return; - const owner = SubagentStreamCoordinator.ownerData(event); - if (!owner) return; - this.openBranch(owner.subagentSessionId || '', - owner.toolCall ? (owner.toolCall.id || '') : ''); - } - - /** - * Follows the children the transcript itself names. - * - * A session that is read from its cached transcript — a phone that just - * restarted, or a host that is not answering — delivers no parent records at - * all, and the durable link is still there: the launching item keeps the child - * Session id it was recorded with. Discovering children here is what lets a - * cold or offline view open the same branches, whose steps then come from the - * branch cache until the child's stream catches up. - */ - observeParentMessages(messages: ChatMessage[]): void { - if (this.parentSessionId.length === 0) return; - messages.forEach((message: ChatMessage) => { - (message.items || []).forEach((item: ChatMessageItemResponse) => { - const tool = item.tool; - if (!tool) return; - this.openBranch(tool.subagent_session_id || '', tool.id || ''); - }); - }); - } - - /** - * Makes sure the child behind one launching item is being followed. - * - * This is what a reader opening a card asks for. The branch may have lost its - * slot to the cap, or never had one; either way an open card has to show the - * worker's own steps rather than a prefix that stopped where its slot did. - */ - ensureSubscribed(ownerToolCallId: string): void { - if (this.parentSessionId.length === 0) return; - const childSessionId = this.owners.get(ownerToolCallId); - if (childSessionId === undefined) return; - const branch = this.branches.get(childSessionId); - if (!branch || branch.subscribed) return; - RemoteLogger.info(`subagent branch re-attached session=${SubagentStreamCoordinator.shortId(childSessionId)}`); - this.acquireSubscriber(branch); - } - - /** What this coordinator currently follows, for previews and focused tests. */ - followState(): SubagentFollowState { - let restored = 0; - this.branches.forEach((branch: SubagentBranch) => { restored += branch.cached.length; }); - return { - branches: this.branches.size, - subscribed: this.subscribedCount(), - waiting: this.waiters.length, - restored: restored - }; - } - - /** - * The child branch items for every launching item the parent has published. - * - * Messages are returned unchanged when no branch applies, so a session without - * spawned children pays nothing beyond one map lookup per tool item. An - * affected message is copied with its owner's render version advanced by the - * branch's own change count, because ArkUI keys the row by what changed in - * the message and a branch grows without any parent record changing. - */ - decorate(messages: ChatMessage[]): ChatMessage[] { - if (this.branches.size === 0) return messages; - return messages.map((message: ChatMessage) => this.decorateMessage(message)); - } - - private decorateMessage(message: ChatMessage): ChatMessage { - const items = message.items; - if (!items || items.length === 0) return message; - let attached = 0; - const decorated: ChatMessageItemResponse[] = items.map((item: ChatMessageItemResponse, index: number) => { - const toolId = item.tool ? (item.tool.id || '') : ''; - if (toolId.length === 0) return item; - const childSessionId = this.owners.get(toolId); - if (!childSessionId) return item; - const branch = this.branches.get(childSessionId); - if (!branch) return item; - attached += this.ownerVersion(toolId, branch, item.tool); - return SubagentStreamCoordinator.ownerItem(item, branch, index, items); - }); - if (attached === 0) return message; - return { - id: message.id, - role: message.role, - text: message.text, - status: message.status, - renderVersion: (message.renderVersion || 0) + attached, - turnId: message.turnId, - detail: message.detail, - error: message.error, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: decorated, - images: message.images - }; - } - - /** - * One launching item, as the card reads it. - * - * Two things are replaced and nothing else: the status the card draws is the - * worker's own lifecycle, and the branch's items are the worker's own process. - * The launching record's status stays where it belongs — in the digest below, - * which is what decides whether the card repaints. - * - * A host that publishes the process inside its own stream keeps this item on - * the path it has always used, and needs no branch attached here. - */ - private static ownerItem(item: ChatMessageItemResponse, branch: SubagentBranch, ownerIndex: number, - items: ChatMessageItemResponse[]): ChatMessageItemResponse { - const tool = branch.status.length > 0 ? SubagentStreamCoordinator.toolWithStatus(item.tool, branch.status) : item.tool; - const subItems = branch.items.length === 0 || - SubagentStreamCoordinator.parentCarriesBranchItems(items, ownerIndex) ? item.subItems : branch.items; - if (tool === item.tool && subItems === item.subItems) return item; - return { - type: item.type, - steering_id: item.steering_id, - round_index: item.round_index, - content: item.content, - tool: tool, - is_subagent: item.is_subagent, - subItems: subItems, - images: item.images - }; - } - - /** The same tool record, with the worker's lifecycle as its status. */ - private static toolWithStatus(tool: RemoteToolStatusResponse | undefined, - status: string): RemoteToolStatusResponse | undefined { - if (!tool) return tool; - return { - permission_request_id: tool.permission_request_id, - id: tool.id, - name: tool.name, - status: status, - duration_ms: tool.duration_ms, - start_ms: tool.start_ms, - input_preview: tool.input_preview, - tool_input: tool.tool_input, - stdout: tool.stdout, - stderr: tool.stderr, - tool_output: tool.tool_output, - result_preview: tool.result_preview, - error_preview: tool.error_preview, - exit_code: tool.exit_code, - plan: tool.plan, - subagent_session_id: tool.subagent_session_id - }; - } - - /** - * The render version this coordinator publishes for one launch item. - * - * Three independent things alter a card: the worker's own process grew, the - * worker's own lifecycle changed (a turn settling adds no step), and the - * launch item's own record was updated. A launch settles as soon as the worker - * starts, and a background worker's launch settles while its stream has - * nothing new to say, so a version that only counted branch growth would leave - * the header of exactly that card behind: the row is keyed by what changed in - * the message, and a tool item's own status is not part of that key. Folding - * every one of those readings in here means a settled launch repaints the card - * it belongs to even when its worker publishes no further step. - * - * The value is cumulative rather than a per-publication delta: the transcript - * the controller publishes must be identical when nothing changed, or a row - * would be rebuilt from a message that no longer carries its branch. - */ - private ownerVersion(ownerToolCallId: string, branch: SubagentBranch, - tool?: RemoteToolStatusResponse): number { - const digest = [ - `${branch.changes}`, - branch.status, - tool ? (tool.name || '') : '', - tool ? (tool.status || '') : '' - ].join('\u0000'); - if (this.ownerDigests.get(ownerToolCallId) !== digest) { - this.ownerDigests.set(ownerToolCallId, digest); - this.ownerVersions.set(ownerToolCallId, (this.ownerVersions.get(ownerToolCallId) || 0) + 1); - } - return this.ownerVersions.get(ownerToolCallId) || 0; - } - - /** - * Whether the parent stream itself already carries this owner's process. - * - * Older hosts published a subagent's records inside the parent stream and - * marked them, and the transcript grouping already attaches those records to - * the item that launched them. Attaching the child session's records here as - * well would draw every step twice, so a marked sibling record — up to the - * next launch item, which owns its own records — keeps that host on the path - * it has always used. - */ - private static parentCarriesBranchItems(items: ChatMessageItemResponse[], ownerIndex: number): boolean { - for (let index = ownerIndex + 1; index < items.length; index++) { - const entry = items[index]; - if (entry.is_subagent !== true) continue; - if (entry.tool && SubagentStreamCoordinator.isOwnerToolName(entry.tool.name || '')) return false; - return true; - } - return false; - } - - private static isOwnerToolName(rawName: string): boolean { - const name = rawName.trim().replace(/[\s-]/g, '_').toLowerCase(); - return name === 'task' || name === 'agentspawn'; - } - - private static ownerData(event: HostSessionEvent): SubagentOwnerItemData | undefined { - if (event.event !== 'session-record') return undefined; - const record = event.payload as SubagentOwnerRecord; - const item = record.item; - if (!item || item.type !== 'tool' || !item.data) return undefined; - return item.data.subagentSessionId ? item.data : undefined; - } - - private openBranch(childSessionId: string, ownerToolCallId: string): void { - // A host that names no child session, or names this very session, has no - // branch to open: the launch item stays the plain tool row it always was. - if (childSessionId.length === 0 || ownerToolCallId.length === 0) return; - if (this.parentSessionId === childSessionId) return; - if (this.owners.has(ownerToolCallId)) return; - const resumed = this.branches.get(childSessionId); - if (resumed !== undefined) { - // The same worker, named by a launch this session has not seen before: a - // reusable child that was continued. It is one branch — its steps are the - // worker's, not the launch's — but the launch happening now is what its - // records have to land under, and a branch the cap released has to be - // followed again, or the turn it is taking would never arrive. Only a new - // launch does this: the same launch republished by every poll is not a - // reason to take a slot back from a worker that is using one. - this.owners.set(ownerToolCallId, childSessionId); - resumed.ownerToolCallId = ownerToolCallId; - resumed.lastActivity = ++this.activitySeq; - if (!resumed.subscribed) this.acquireSubscriber(resumed); - return; - } - const branch: SubagentBranch = { - sessionId: childSessionId, - ownerToolCallId: ownerToolCallId, - reducer: new DurableSessionReducer(), - subscribed: false, - caughtUp: false, - streamFailed: false, - cached: [], - cachedStatus: '', - items: [], - changes: 0, - signature: '', - status: '', - liveStatus: false, - lastActivity: ++this.activitySeq, - flushTimer: -1 - }; - this.branches.set(childSessionId, branch); - this.owners.set(ownerToolCallId, childSessionId); - this.hydrate(branch); - this.acquireSubscriber(branch); - } - - /** - * Reads back what this child published in an earlier launch of the app. - * - * The steps land as the branch's cached prefix, and the child's stream is - * merged into them as it arrives, so a cold start shows a worker's process - * before (and without) its stream — and a worker whose stream only starts at - * its newest page keeps the earlier steps it had. - */ - private hydrate(branch: SubagentBranch): void { - const cache = this.branchCache; - if (!cache) return; - cache.loadBranch(branch.sessionId).then((messages: ChatMessage[]): void => { - const current = this.branches.get(branch.sessionId); - // A branch replaced by a session switch belongs to nobody now. - if (!current || current !== branch) return; - const cached = SubagentStreamCoordinator.branchItems(messages); - if (cached.length === 0) return; - branch.cached = cached; - branch.cachedStatus = SubagentStreamCoordinator.turnStatus(messages); - RemoteLogger.info( - `subagent branch restored session=${SubagentStreamCoordinator.shortId(branch.sessionId)} ` + - `steps=${cached.length} status=${branch.cachedStatus}` - ); - this.refresh(branch); - }).catch((error: Object): void => { - RemoteLogger.error(`subagent branch restore failed: ${SubagentStreamCoordinator.reason(error)}`); - }); - } - - /** - * Opens a child's stream if this session can follow one more child. - * - * Past the cap a slot is taken from another child, oldest activity first and - * a settled child before a working one: a worker that already reported is the - * one whose stream can be released for nothing, and a working one that loses - * its slot keeps the branch it published and waits to be re-attached. - */ - private acquireSubscriber(branch: SubagentBranch): void { - if (branch.subscribed) return; - if (this.subscribedCount() >= MAX_CONCURRENT_CHILD_STREAMS) { - const victim = this.releaseCandidate(branch); - if (!victim) { - this.waitForSlot(branch); - return; - } - this.releaseSubscription(victim, true); - } - this.forgetWaiter(branch); - this.subscribe(branch); - // Subscribing decides what can be said about the worker: a branch opened - // over the cap has no reading until this point. - this.refresh(branch); - } - - private subscribe(branch: SubagentBranch): void { - try { - branch.stream = this.source.subscribeSession(branch.sessionId, { - onEvent: async (event: HostSessionEvent): Promise => { - this.applyChildEvent(branch.sessionId, event); - }, - onCaughtUp: async (): Promise => { - const current = this.branches.get(branch.sessionId); - if (!current) return; - current.caughtUp = true; - current.streamFailed = false; - this.refresh(current); - }, - onGap: async (): Promise => { - // The host restarted this child's stream: everything reduced so far - // came from its previous epoch, so it is dropped before the replay. - const current = this.branches.get(branch.sessionId); - if (!current) return; - current.reducer = new DurableSessionReducer(); - current.caughtUp = false; - }, - onError: (error: Error): void => { - const current = this.branches.get(branch.sessionId); - // A child stream that failed before it published anything says nothing - // about the worker, so no lifecycle is invented for it: the card keeps - // the launching item's own status. The stream keeps retrying by itself. - if (current && current.items.length === 0 && current.cached.length === 0) { - current.streamFailed = true; - this.refresh(current); - } - this.onError(error); - } - }); - branch.subscribed = true; - RemoteLogger.info( - `subagent branch followed session=${SubagentStreamCoordinator.shortId(branch.sessionId)} ` + - `streams=${this.subscribedCount()}/${this.branches.size}` - ); - } catch (_error) { - // A child stream that cannot be opened is not a reason to fail the - // session on screen: the launch item keeps its own row and result, and its - // branch stays empty instead of showing fabricated steps. - this.releaseSubscription(branch, false); - if (branch.items.length === 0 && branch.cached.length === 0 && !branch.caughtUp) { - this.branches.delete(branch.sessionId); - this.owners.delete(branch.ownerToolCallId); - } - } - } - - /** Closes one child's stream, keeping the branch and everything it published. */ - private releaseSubscription(branch: SubagentBranch, wait: boolean): void { - const wasSubscribed = branch.subscribed; - const before = this.subscribedCount(); - branch.stream?.close(); - branch.stream = undefined; - branch.subscribed = false; - if (wasSubscribed) { - RemoteLogger.info( - `subagent branch released session=${SubagentStreamCoordinator.shortId(branch.sessionId)} ` + - `streams=${before - 1}/${this.branches.size}` - ); - } - // Whatever the child has published so far is written now: this branch may - // not be the one that is subscribed when its stream would have said more. - if (branch.changes > 0) this.flushBranch(branch); - if (wait) this.waitForSlot(branch); - } - - /** - * Which child gives up its slot, or undefined when every other child is - * already waiting. - * - * The most recently active children stay followed — a card the reader is - * watching is the one that just changed — and a settled child goes before a - * working one, because releasing it cannot lose a step. - */ - private releaseCandidate(except: SubagentBranch): SubagentBranch | undefined { - let settled: SubagentBranch | undefined = undefined; - let oldest: SubagentBranch | undefined = undefined; - this.branches.forEach((branch: SubagentBranch) => { - if (branch === except || !branch.subscribed) return; - if (oldest === undefined || branch.lastActivity < oldest.lastActivity) oldest = branch; - if (SubagentStreamCoordinator.isSettled(branch) && - (settled === undefined || branch.lastActivity < settled.lastActivity)) settled = branch; - }); - return settled || oldest; - } - - private waitForSlot(branch: SubagentBranch): void { - if (this.waiters.indexOf(branch.sessionId) < 0) this.waiters.push(branch.sessionId); - } - - private forgetWaiter(branch: SubagentBranch): void { - this.waiters = this.waiters.filter((sessionId: string): boolean => sessionId !== branch.sessionId); - } - - /** - * Follows waiting children as slots free, newest first. - * - * Newest first because a launch the reader just watched appear is the card - * most likely to be on screen; the older ones keep their branch and are served - * when their turn comes or when their card is opened. - */ - private drainWaiters(): void { - let budget = this.waiters.length; - while (budget > 0 && this.subscribedCount() < MAX_CONCURRENT_CHILD_STREAMS) { - budget--; - const sessionId = this.waiters.pop(); - if (sessionId === undefined) return; - const branch = this.branches.get(sessionId); - if (!branch || branch.subscribed) continue; - this.acquireSubscriber(branch); - } - } - - private subscribedCount(): number { - let count = 0; - this.branches.forEach((branch: SubagentBranch) => { - if (branch.subscribed) count++; - }); - return count; - } - - /** - * A child that has settled: its own stream read a turn of it and no turn of it - * is in progress. - * - * The stream is what makes a branch settled. A reading that came out of the - * transcript cache is a reading of an earlier launch of the app, and releasing - * on it would keep a worker that is working right now reported as finished. - */ - private static isSettled(branch: SubagentBranch): boolean { - return branch.caughtUp && branch.liveStatus && branch.status.length > 0 && branch.status !== 'running'; - } - - /** - * One record of one child session. - * - * Records are deduplicated by identity and revision inside the child's own - * reducer, which is the same reducer the session on screen uses, so a - * replayed page cannot publish a step twice. Until the child's first page has - * settled the parent is not republished at all: a child that finished before - * its branch was opened backfills hundreds of records, and each of them - * republishing the parent transcript would repaint the whole conversation per - * record for a branch nobody has seen yet. - */ - private applyChildEvent(childSessionId: string, event: HostSessionEvent): void { - const branch = this.branches.get(childSessionId); - if (!branch || this.parentSessionId.length === 0) return; - if (!branch.reducer.apply(event)) return; - branch.streamFailed = false; - branch.lastActivity = ++this.activitySeq; - if (!branch.caughtUp) return; - this.refresh(branch); - } - - /** - * Republishes a branch that changed in any way the card can show. - * - * The items are what the card draws; the status is what its header says, and a - * child's turn can settle without publishing another item, so both are - * compared before the transcript is republished. - */ - private refresh(branch: SubagentBranch): void { - const wasSettled = SubagentStreamCoordinator.isSettled(branch); - const items = SubagentStreamCoordinator.mergeBranchItems( - branch.cached, SubagentStreamCoordinator.branchItems(branch.reducer.messages())); - const signature = SubagentStreamCoordinator.branchSignature(items); - const live = SubagentStreamCoordinator.turnStatus(branch.reducer.messages()); - const status = SubagentStreamCoordinator.childStatus(branch, live); - branch.liveStatus = live.length > 0; - if (signature === branch.signature && status === branch.status) return; - branch.signature = signature; - branch.items = items; - branch.status = status; - branch.changes++; - this.notify(); - this.scheduleFlush(branch); - // A settled worker will not publish again, so it costs nothing to stop - // following it — unless it is the child that just held a slot, in which case - // its stream has already been closed above. It is the transition that - // releases: a worker that settled, was continued and then settled again keeps - // its stream until the cap wants the slot back, which is where a settled - // branch is the first one to be taken. - if (!wasSettled && SubagentStreamCoordinator.isSettled(branch) && branch.subscribed) { - this.releaseSubscription(branch, false); - this.drainWaiters(); - } - } - - /** - * The worker's own lifecycle, as its stream describes it. - * - * A child session is an ordinary session with its own turns, so the reading is - * the child's own: a turn of it still in progress means the worker is working, - * and the last turn's outcome is what a finished worker reported. Multi-turn - * children — a worker continued after it answered once — are running again the - * moment any of their turns is. - * - * Nothing is invented from what is missing. Before the child has said anything - * at all the worker was started and is not finished, so it reads as running; - * a stream that failed before publishing anything says nothing, and the - * launching item's own status stands. The one reading that survives a restart - * is the branch itself: a worker whose stored transcript is all this phone has - * left is reported at the outcome it was stored with, because its stream will - * never say more. - */ - private static childStatus(branch: SubagentBranch, live: string): string { - if (live.length > 0) return live; - if (branch.streamFailed && branch.cached.length === 0) return ''; - return branch.caughtUp && branch.cachedStatus.length > 0 ? branch.cachedStatus : 'running'; - } - - /** A child transcript's lifecycle reading, or '' when it holds no turn yet. */ - private static turnStatus(messages: ChatMessage[]): string { - let sawTurn = false; - let running = false; - let lastOutcome = ''; - messages.forEach((message: ChatMessage) => { - if (message.role !== 'assistant') return; - sawTurn = true; - const status = (message.status || '').toLowerCase(); - if (SubagentStreamCoordinator.isRunningStatus(status)) { - running = true; - return; - } - lastOutcome = SubagentStreamCoordinator.isFailedStatus(status) ? 'failed' : 'completed'; - }); - if (!sawTurn) return ''; - return running ? 'running' : lastOutcome; - } - - private static isRunningStatus(status: string): boolean { - return status === 'running' || status === 'active' || status === 'inprogress' || - status === 'preparing' || status === 'pending' || status === 'queued'; - } - - private static isFailedStatus(status: string): boolean { - return status === 'failed' || status === 'error' || status === 'timeout' || - status === 'cancelled' || status === 'canceled' || status === 'rejected'; - } - - /** - * Writes the child's transcript to the phone cache, at most once per interval. - * - * A child that is still publishing is not a reason to hold the write back - * either: the flush is what a later cold start renders from, so the newest - * state of a worker in progress is worth having. - * - * A stored child is one more session in the same per-device store the sessions - * the reader opens live in, and the store keeps its own bounded number of them. - * That is the right shelf for it: a child transcript is reconstructible by - * asking the host for the child's stream again, so being evicted costs a read, - * not a step. - */ - private scheduleFlush(branch: SubagentBranch): void { - if (!this.branchCache || branch.flushTimer !== -1) return; - branch.flushTimer = setTimeout((): void => { - branch.flushTimer = -1; - this.flushBranch(branch); - }, BRANCH_CACHE_FLUSH_MS); - } - - private flushBranch(branch: SubagentBranch): void { - const cache = this.branchCache; - if (!cache) return; - const messages = branch.reducer.messages(); - // Nothing of this child's own stream has arrived, so there is nothing to - // store: writing an empty transcript would erase what the cache holds. - if (messages.length === 0) return; - cache.saveBranch(branch.sessionId, messages).catch((error: Object): void => { - RemoteLogger.error(`subagent branch cache write failed: ${SubagentStreamCoordinator.reason(error)}`); - }); - } - - /** - * The process a child session publishes, in its own order. - * - * A child session is an ordinary session: it has its own turns and its own - * user message (the brief it was spawned with), which the card already shows - * as the branch title, so only the assistant's items are branch content. - */ - private static branchItems(messages: ChatMessage[]): ChatMessageItemResponse[] { - const items: ChatMessageItemResponse[] = []; - messages.forEach((message: ChatMessage) => { - if (message.role !== 'assistant') return; - (message.items || []).forEach((item: ChatMessageItemResponse) => { items.push(item); }); - }); - return items; - } - - /** - * What the cache restored, with everything the child's stream published since. - * - * Neither list can replace the other. The stream replays a child session from - * its own start, so it restates steps the cache already holds — those are - * updated in place, which is how a step that finished while the app was closed - * shows its newer state without a second copy. And a stream can also start - * only at its newest page, so a cached step the stream never mentions is the - * only copy of it: it stays where it was. - */ - private static mergeBranchItems(cached: ChatMessageItemResponse[], - live: ChatMessageItemResponse[]): ChatMessageItemResponse[] { - if (cached.length === 0) return live; - if (live.length === 0) return cached; - const merged = cached.slice(); - const claimed: boolean[] = merged.map((_item: ChatMessageItemResponse): boolean => false); - live.forEach((item: ChatMessageItemResponse) => { - const index = merged.findIndex((candidate: ChatMessageItemResponse, position: number): boolean => - !claimed[position] && SubagentStreamCoordinator.sameStep(candidate, item)); - if (index < 0) { - merged.push(item); - return; - } - claimed[index] = true; - merged[index] = item; - }); - return merged; - } - - /** - * What makes two branch steps the same piece of work. - * - * A tool call is identified by its id, exactly as the transcript grouping - * identifies it; reasoning and text carry no id, so their kind and content are - * all there is to tell one from the other. Status and output are deliberately - * left out: a restated step carries the newer ones for the same step. - */ - private static sameStep(a: ChatMessageItemResponse, b: ChatMessageItemResponse): boolean { - const aId = a.tool ? (a.tool.id || '') : ''; - const bId = b.tool ? (b.tool.id || '') : ''; - if (aId.length > 0 || bId.length > 0) return aId.length > 0 && aId === bId; - return SubagentStreamCoordinator.stepFingerprint(a) === SubagentStreamCoordinator.stepFingerprint(b); - } - - private static stepFingerprint(item: ChatMessageItemResponse): string { - return [(item.type || '').toLowerCase(), item.content || ''].join('\u0000'); - } - - /** Everything about a branch that can change what the card draws. */ - private static branchSignature(items: ChatMessageItemResponse[]): string { - const parts: string[] = []; - items.forEach((item: ChatMessageItemResponse) => { - const tool = item.tool; - parts.push([ - item.type || '', - `${(item.content || '').length}`, - tool ? `${tool.id || ''}:${tool.name || ''}:${tool.status || ''}` : '' - ].join('\u0000')); - }); - return `${items.length}\u0001${parts.join('\u0002')}`; - } - - private static shortId(value: string): string { - if (value.length <= 10) return value; - return `${value.slice(0, 6)}...${value.slice(-4)}`; - } - - private static reason(error: Object): string { - return error instanceof Error ? error.message : `${error}`; - } - - private detach(): void { - this.branches.forEach((branch: SubagentBranch) => { - if (branch.flushTimer !== -1) { - clearTimeout(branch.flushTimer); - branch.flushTimer = -1; - } - // The session is closing, so what the child published is written now: - // the timer that would have written it belongs to a session that is gone. - if (branch.changes > 0) this.flushBranch(branch); - branch.stream?.close(); - branch.stream = undefined; - branch.subscribed = false; - }); - this.branches.clear(); - this.owners.clear(); - this.ownerDigests.clear(); - this.ownerVersions.clear(); - this.waiters = []; - this.parentSessionId = ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TaskCompletionNotificationController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/TaskCompletionNotificationController.ets deleted file mode 100644 index 3dc5de5fdd..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TaskCompletionNotificationController.ets +++ /dev/null @@ -1,126 +0,0 @@ -export type TaskCompletionSource = 'remote' | 'general'; - -export interface TaskCompletionObservation { - source: TaskCompletionSource; - sessionId: string; - turnId: string; -} - -export interface TaskCompletionNotificationPort { - keepAlive(onExpired: () => void): boolean; - releaseKeepAlive(): void; - publish(observation: TaskCompletionObservation): Promise; -} - -export type TaskCompletionObservationExpired = (observation: TaskCompletionObservation) => void; - -/** - * Owns the foreground/background completion-notification state machine. - * - * Platform notification and background-task APIs stay behind the injected - * port so lifecycle policy remains deterministic and unit-testable. - */ -export class TaskCompletionNotificationController { - private readonly port: TaskCompletionNotificationPort; - private readonly onExpired: TaskCompletionObservationExpired; - private observation?: TaskCompletionObservation; - private backgrounded: boolean = false; - - constructor( - port: TaskCompletionNotificationPort, - onExpired: TaskCompletionObservationExpired = (_observation: TaskCompletionObservation): void => {} - ) { - this.port = port; - this.onExpired = onExpired; - } - - track(observation: TaskCompletionObservation): void { - const sessionId = observation.sessionId.trim(); - const turnId = observation.turnId.trim(); - if (sessionId.length === 0 || turnId.length === 0) { - return; - } - if (this.backgrounded && this.observation && this.observation.sessionId !== sessionId) { - return; - } - this.observation = { - source: observation.source, - sessionId, - turnId - }; - } - - onBackground(): boolean { - if (!this.observation) { - return false; - } - this.backgrounded = true; - const observation = this.observation; - const keptAlive = this.port.keepAlive((): void => { - const expired = this.observation; - if (!this.backgrounded || !expired) { - return; - } - this.backgrounded = false; - this.observation = undefined; - this.onExpired(expired); - }); - if (!keptAlive) { - this.backgrounded = false; - this.observation = undefined; - this.onExpired(observation); - return false; - } - return true; - } - - onForeground(): void { - this.backgrounded = false; - this.observation = undefined; - this.port.releaseKeepAlive(); - } - - complete(source: TaskCompletionSource, sessionId: string, turnId: string): boolean { - const observation = this.observation; - if (!observation || observation.source !== source || - observation.sessionId !== sessionId.trim() || observation.turnId !== turnId.trim()) { - return false; - } - const shouldPublish = this.backgrounded; - this.backgrounded = false; - this.observation = undefined; - this.port.releaseKeepAlive(); - if (shouldPublish) { - void this.port.publish(observation); - } - return shouldPublish; - } - - /** Clears a failed or cancelled observation and reports whether it was backgrounded. */ - cancel(source: TaskCompletionSource, sessionId: string, turnId: string = ''): boolean { - const observation = this.observation; - const expectedTurnId = turnId.trim(); - if (!observation || observation.source !== source || observation.sessionId !== sessionId.trim() || - (expectedTurnId.length > 0 && observation.turnId !== expectedTurnId)) { - return false; - } - const wasBackgrounded = this.backgrounded; - this.backgrounded = false; - this.observation = undefined; - this.port.releaseKeepAlive(); - return wasBackgrounded; - } - - stop(): void { - this.onForeground(); - } - - isWatchingInBackground(): boolean { - return this.backgrounded && this.observation !== undefined; - } - - isTracking(source: TaskCompletionSource): boolean { - return this.observation !== undefined && this.observation.source === source; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets deleted file mode 100644 index ba13739891..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TimeFormat.ets +++ /dev/null @@ -1,69 +0,0 @@ -import { RemoteI18n } from '../i18n/RemoteI18n'; - -export class TimeFormat { - static message(value: string): string { - const timestamp = TimeFormat.timestampMs(value); - return Number.isFinite(new Date(timestamp).getTime()) ? RemoteI18n.formatMessageTime(timestamp) : ''; - } - - static relative(value: string, nowMs: number = Date.now()): string { - const timestamp = TimeFormat.timestampMs(value); - if (Number.isNaN(timestamp)) { - return RemoteI18n.t('time.unknown'); - } - const minute = 60 * 1000; - const hour = 60 * minute; - const day = 24 * hour; - const rawDiffMs = nowMs - timestamp; - if (rawDiffMs < -minute) { - return RemoteI18n.formatAbsoluteDate(timestamp); - } - const diffMs = Math.max(0, rawDiffMs); - if (diffMs < minute) { - return RemoteI18n.t('time.justNow'); - } - if (diffMs < hour) { - return RemoteI18n.f('time.minutesAgo', `${Math.max(1, Math.floor(diffMs / minute))}`); - } - if (diffMs < day) { - return RemoteI18n.f('time.hoursAgo', `${Math.floor(diffMs / hour)}`); - } - if (diffMs < 7 * day) { - return RemoteI18n.f('time.daysAgo', `${Math.floor(diffMs / day)}`); - } - return RemoteI18n.formatAbsoluteDate(timestamp); - } - - static timestampMs(value: string): number { - const text = (value || '').trim(); - if (text.length === 0) { - return Number.NaN; - } - - if (/^\d+(\.\d+)?$/.test(text)) { - const numeric = Number(text); - if (!Number.isNaN(numeric)) { - if (numeric < 100000000000) { - return numeric * 1000; - } - if (numeric < 100000000000000) { - return numeric; - } - if (numeric < 100000000000000000) { - return numeric / 1000; - } - return numeric / 1000000; - } - } - - const direct = Date.parse(text); - if (!Number.isNaN(direct)) { - return direct; - } - - const normalized = text.replace(' ', 'T'); - const parsed = Date.parse(normalized); - return Number.isNaN(parsed) ? Number.NaN : parsed; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TranscriptIntegrityPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/TranscriptIntegrityPolicy.ets deleted file mode 100644 index aac1b97eaf..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/TranscriptIntegrityPolicy.ets +++ /dev/null @@ -1,80 +0,0 @@ -import { ChatMessage, ChatMessageItemResponse } from '../model/RemoteModels'; - -/** - * Whether a persisted or polled transcript row still has a body the timeline - * can show. A hollow assistant is a real id with no text, thinking, tools, - * items, or images — the shape left behind when a slim poll stub overwrites a - * live turn, or when a cache row was written before the desktop settled. - */ -export class TranscriptIntegrityPolicy { - static hasDisplayableBody(message: ChatMessage): boolean { - if ((message.text || '').trim().length > 0) { - return true; - } - if ((message.thinking || '').trim().length > 0) { - return true; - } - if (message.tools && message.tools.length > 0) { - return true; - } - if (TranscriptIntegrityPolicy.hasRenderableItems(message.items)) { - return true; - } - if (message.images && message.images.length > 0) { - return true; - } - return false; - } - - static isHollowAssistant(message: ChatMessage): boolean { - return (message.role || '').toLowerCase() === 'assistant' && - !TranscriptIntegrityPolicy.hasDisplayableBody(message); - } - - static hasHollowAssistants(messages: ChatMessage[]): boolean { - return messages.some((message: ChatMessage) => { - return TranscriptIntegrityPolicy.isHollowAssistant(message); - }); - } - - static hasRenderableItems(items?: ChatMessageItemResponse[]): boolean { - if (!items || items.length === 0) { - return false; - } - return items.some((entry: ChatMessageItemResponse) => { - if ((entry.content || '').trim().length > 0 || !!entry.tool) { - return true; - } - return TranscriptIntegrityPolicy.hasRenderableItems(entry.subItems); - }); - } - - static describeMessages(messages: ChatMessage[]): string { - const assistants = messages.filter((message: ChatMessage) => { - return (message.role || '').toLowerCase() === 'assistant'; - }); - let hollow = 0; - const parts: string[] = []; - assistants.forEach((message: ChatMessage) => { - if (TranscriptIntegrityPolicy.isHollowAssistant(message)) { - hollow += 1; - } - parts.push( - `id=${TranscriptIntegrityPolicy.shortId(message.id)} ` + - `text=${(message.text || '').length} ` + - `thinking=${(message.thinking || '').length} ` + - `tools=${message.tools ? message.tools.length : 0} ` + - `items=${message.items ? message.items.length : 0}` - ); - }); - const detail = parts.length > 0 ? ` ${parts.join(' ')}` : ''; - return `total=${messages.length} assistants=${assistants.length} hollow=${hollow}${detail}`; - } - - private static shortId(value: string): string { - if (value.length <= 10) { - return value; - } - return `${value.slice(0, 6)}...${value.slice(-4)}`; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputLifecycleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputLifecycleController.ets deleted file mode 100644 index 5611e9aaf5..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputLifecycleController.ets +++ /dev/null @@ -1,119 +0,0 @@ -import { Context } from '@kit.AbilityKit'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from './ConnectionErrorPolicy'; -import { VoiceInputCallbacks, VoiceInputService, VoiceInputState } from './VoiceInputService'; - -export interface VoiceInputRouteSnapshot { - routeId: string; - isListening: boolean; - isBusy: boolean; - inputText: string; - selectedImageCount: number; -} - -export interface VoiceInputLifecycleCallbacks { - currentInputText: () => string; - currentStatusText: () => string; - onInputText: (routeId: string, text: string) => void; - onListening: (routeId: string, isListening: boolean) => void; - onStatusText: (statusText: string) => void; - onError: (message: string) => void; -} - -export class VoiceInputLifecycleController { - private readonly service: VoiceInputService; - private readonly callbacks: VoiceInputLifecycleCallbacks; - - constructor(service: VoiceInputService, callbacks: VoiceInputLifecycleCallbacks) { - this.service = service; - this.callbacks = callbacks; - } - - async toggle(context: Context, snapshot: VoiceInputRouteSnapshot): Promise { - if (snapshot.isListening || this.service.isListening()) { - return this.stop(snapshot, true); - } - if (snapshot.isBusy) { - return false; - } - // Intermediate recognizer results replace one another. Merge every result - // against the immutable draft captured at start so partial callbacks do - // not duplicate speech and existing text or attachments never block a - // user from continuing the prompt by voice. - const baseDraft = snapshot.inputText; - try { - this.callbacks.onStatusText(RemoteI18n.t('status.voiceStarting')); - await this.service.start(context, { - onText: (text: string, isFinal: boolean): void => { - this.callbacks.onInputText(snapshot.routeId, this.mergeDraft(baseDraft, text)); - if (isFinal) { - this.callbacks.onStatusText(RemoteI18n.t('status.voiceRecognized')); - } - }, - onState: (state: VoiceInputState): void => { - this.handleState(snapshot.routeId, state); - }, - onError: (message: string): void => { - this.callbacks.onListening(snapshot.routeId, false); - this.callbacks.onError(message || RemoteI18n.t('errors.voiceInputUnavailable')); - } - }); - return true; - } catch (err) { - this.callbacks.onListening(snapshot.routeId, false); - this.callbacks.onError(ConnectionErrorPolicy.errorText(err)); - return false; - } - } - - private mergeDraft(baseDraft: string, transcript: string): string { - const spoken = transcript.trim(); - if (baseDraft.length === 0 || spoken.length === 0) { - return baseDraft.length === 0 ? spoken : baseDraft; - } - const last = baseDraft.charAt(baseDraft.length - 1); - const first = spoken.charAt(0); - const needsSpace = !/\s/.test(last) && /[\x21-\x7E]/.test(last) && /[A-Za-z0-9]/.test(first); - return `${baseDraft}${needsSpace ? ' ' : ''}${spoken}`; - } - - async stop(snapshot: VoiceInputRouteSnapshot, showStatus: boolean): Promise { - if (!snapshot.isListening && !this.service.isListening()) { - return false; - } - this.callbacks.onListening(snapshot.routeId, false); - try { - await this.service.stop(); - if (showStatus) { - this.callbacks.onStatusText(this.callbacks.currentInputText().trim().length > 0 ? - RemoteI18n.t('status.voiceRecognized') : - RemoteI18n.t('status.voiceStopped')); - } - return true; - } catch (err) { - this.callbacks.onError(ConnectionErrorPolicy.errorText(err)); - return false; - } - } - - async cancel(routeId: string, clearAllListening: () => void): Promise { - await this.service.cancel(); - clearAllListening(); - this.callbacks.onListening(routeId, false); - } - - private handleState(routeId: string, state: VoiceInputState): void { - this.callbacks.onListening(routeId, state === 'listening'); - if (state === 'listening') { - this.callbacks.onStatusText(RemoteI18n.t('status.voiceListening')); - return; - } - const statusText = this.callbacks.currentStatusText(); - if (statusText === RemoteI18n.t('status.voiceListening') || - statusText === RemoteI18n.t('status.voiceStarting')) { - this.callbacks.onStatusText(this.callbacks.currentInputText().trim().length > 0 ? - RemoteI18n.t('status.voiceRecognized') : - RemoteI18n.t('status.voiceStopped')); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputService.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputService.ets deleted file mode 100644 index a8ae93c55c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/VoiceInputService.ets +++ /dev/null @@ -1,297 +0,0 @@ -import { abilityAccessCtrl, Context, Permissions } from '@kit.AbilityKit'; -import { audio } from '@kit.AudioKit'; -import { speechRecognizer } from '@kit.CoreSpeechKit'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { Encoding } from './Encoding'; -import { OhosError } from './OhosError'; - -export type VoiceInputState = 'idle' | 'listening'; - -export interface VoiceInputCallbacks { - onText: (text: string, isFinal: boolean) => void; - onState?: (state: VoiceInputState) => void; - onError?: (message: string) => void; -} - -const MICROPHONE_PERMISSION: Permissions = 'ohos.permission.MICROPHONE'; -const AUDIO_CHUNK_BYTES = 1280; -const HALF_AUDIO_CHUNK_BYTES = 640; - -export class VoiceInputService { - private engine?: speechRecognizer.SpeechRecognitionEngine; - private capturer?: audio.AudioCapturer; - private sessionId: string = ''; - private listening: boolean = false; - private reading: boolean = false; - private callbacks?: VoiceInputCallbacks; - private readDataListener?: (buffer: ArrayBuffer) => void; - - isListening(): boolean { - return this.listening; - } - - async start(context: Context, callbacks: VoiceInputCallbacks): Promise { - await this.cancelInternal(false); - this.callbacks = callbacks; - try { - await this.ensureMicrophonePermission(context); - this.sessionId = Encoding.randomId('voice'); - this.engine = await speechRecognizer.createEngine({ - language: RemoteI18n.speechLanguage(), - online: 1, - extraParams: { - locate: RemoteI18n.speechLocate(), - recognizerMode: 'short' - } - }); - this.engine.setListener(this.recognitionListener()); - this.capturer = await this.createCapturer(); - this.engine.startListening({ - sessionId: this.sessionId, - audioInfo: { - audioType: 'pcm', - sampleRate: 16000, - soundChannel: 1, - sampleBit: 16 - }, - extraParams: { - recognitionMode: 1, - vadBegin: 2000, - vadEnd: 3000, - maxAudioDuration: 55000 - } - }); - this.attachReadData(this.sessionId); - await this.capturer.start(); - this.listening = true; - this.reading = true; - this.callbacks?.onState?.('listening'); - } catch (err) { - await this.cancelInternal(true); - throw new Error(this.errorMessage(err)); - } - } - - async stop(): Promise { - if (!this.listening && !this.reading) { - return; - } - const engine = this.engine; - const sessionId = this.sessionId; - this.listening = false; - this.reading = false; - this.callbacks?.onState?.('idle'); - await this.releaseCapturer(); - if (engine && sessionId.length > 0) { - try { - engine.finish(sessionId); - } catch (err) { - this.releaseEngine(); - throw new Error(this.errorMessage(err)); - } - } - } - - async cancel(): Promise { - await this.cancelInternal(true); - } - - private async ensureMicrophonePermission(context: Context): Promise { - try { - const atManager = abilityAccessCtrl.createAtManager(); - const result = await atManager.requestPermissionsFromUser(context, [MICROPHONE_PERMISSION]); - if (result.authResults.length === 0 || - result.authResults[0] !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - throw new Error(RemoteI18n.t('errors.voicePermissionDenied')); - } - } catch (err) { - throw OhosError.wrap('voice microphone permission', err); - } - } - - private async createCapturer(): Promise { - try { - return await audio.createAudioCapturer(this.capturerOptions(audio.SourceType.SOURCE_TYPE_VOICE_RECOGNITION)); - } catch (_err) { - return await audio.createAudioCapturer(this.capturerOptions(audio.SourceType.SOURCE_TYPE_MIC)); - } - } - - private capturerOptions(source: audio.SourceType): audio.AudioCapturerOptions { - return { - streamInfo: { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - }, - capturerInfo: { - source, - capturerFlags: 0 - } - }; - } - - private recognitionListener(): speechRecognizer.RecognitionListener { - return { - onStart: (_sessionId: string, _eventMessage: string): void => { - }, - onEvent: (_sessionId: string, _eventCode: number, _eventMessage: string): void => { - }, - onResult: (_sessionId: string, result: speechRecognizer.SpeechRecognitionResult): void => { - const text = result.result.trim(); - if (text.length > 0) { - this.callbacks?.onText(text, result.isFinal || result.isLast); - } - if (result.isLast) { - this.releaseAfterRecognizer(true); - } - }, - onComplete: (_sessionId: string, _eventMessage: string): void => { - this.releaseAfterRecognizer(true); - }, - onError: (_sessionId: string, errorCode: number, errorMessage: string): void => { - this.callbacks?.onError?.(errorMessage || RemoteI18n.f('errors.voiceInputFailed', `${errorCode}`)); - this.releaseAfterRecognizer(true); - } - }; - } - - private attachReadData(sessionId: string): void { - const capturer = this.capturer; - if (!capturer) { - return; - } - this.detachReadData(); - this.readDataListener = (buffer: ArrayBuffer): void => { - if (!this.reading || this.sessionId !== sessionId) { - return; - } - try { - this.writeAudioBuffer(sessionId, buffer); - } catch (err) { - this.callbacks?.onError?.(this.errorMessage(err)); - void this.cancelInternal(true); - } - }; - try { - capturer.on('readData', this.readDataListener); - } catch (err) { - throw OhosError.wrap('voice attach read data', err); - } - } - - private detachReadData(): void { - const capturer = this.capturer; - const listener = this.readDataListener; - this.readDataListener = undefined; - if (!capturer || !listener) { - return; - } - try { - capturer.off('readData', listener); - } catch (_err) { - } - } - - private writeAudioBuffer(sessionId: string, buffer: ArrayBuffer): void { - const engine = this.engine; - if (!engine || buffer.byteLength === 0) { - return; - } - const data = new Uint8Array(buffer); - let offset = 0; - try { - while (offset + AUDIO_CHUNK_BYTES <= data.length) { - engine.writeAudio(sessionId, data.subarray(offset, offset + AUDIO_CHUNK_BYTES)); - offset += AUDIO_CHUNK_BYTES; - } - const remaining = data.length - offset; - if (remaining === HALF_AUDIO_CHUNK_BYTES) { - engine.writeAudio(sessionId, data.subarray(offset, offset + HALF_AUDIO_CHUNK_BYTES)); - } - } catch (err) { - throw OhosError.wrap('voice write audio', err); - } - } - - private releaseAfterRecognizer(notifyState: boolean): void { - this.listening = false; - this.reading = false; - if (notifyState) { - this.callbacks?.onState?.('idle'); - } - this.releaseCapturer(); - this.releaseEngine(); - } - - private async cancelInternal(notifyState: boolean): Promise { - const engine = this.engine; - const sessionId = this.sessionId; - this.listening = false; - this.reading = false; - if (notifyState) { - this.callbacks?.onState?.('idle'); - } - await this.releaseCapturer(); - if (engine && sessionId.length > 0) { - try { - engine.cancel(sessionId); - } catch (_err) { - } - } - this.releaseEngine(); - } - - private async releaseCapturer(): Promise { - this.detachReadData(); - const capturer = this.capturer; - this.capturer = undefined; - if (!capturer) { - return; - } - try { - await capturer.stop(); - } catch (_err) { - } - try { - await capturer.release(); - } catch (_err) { - } - } - - private releaseEngine(): void { - const engine = this.engine; - this.engine = undefined; - this.sessionId = ''; - if (!engine) { - return; - } - try { - engine.shutdown(); - } catch (_err) { - } - } - - private errorMessage(err: Object): string { - if (err instanceof Error && err.message.length > 0) { - return err.message; - } - const details = this.errorDetails(err); - if (details.length > 0 && details !== '{}') { - return RemoteI18n.f('errors.voiceInputFailed', details); - } - return RemoteI18n.t('errors.voiceInputUnavailable'); - } - - private errorDetails(err: Object): string { - if (err instanceof Error) { - return `${err.name}: ${err.message}`; - } - try { - return JSON.stringify(err); - } catch (_jsonErr) { - return `${err}`; - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchHandoffStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchHandoffStore.ets deleted file mode 100644 index 7fec0be089..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchHandoffStore.ets +++ /dev/null @@ -1,219 +0,0 @@ -import distributedKVStore from '@ohos.data.distributedKVStore'; -import { common } from '@kit.AbilityKit'; -import { distributedDeviceManager } from '@kit.DistributedServiceKit'; -import { OhosError } from './OhosError'; -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; -import { RemoteLogger } from './RemoteLogger'; -import { - WATCH_PROVISION_REQUEST_KEY, - WATCH_PROVISION_RESPONSE_KEY -} from './WatchProvisionProtocol'; - -/** - * Versioned because a store's `securityLevel` is fixed at creation: it can only - * ever be raised, and for a store that syncs across devices it cannot be changed - * at all. The pre-release S2 handoff store had to be - * abandoned rather than relabelled — see the S1 note on `securityLevel` below. - * Must stay identical to the watch's `DistributedHandoffStore`. - */ -const STORE_ID: string = HarmonyUpgradeIdentityContract.WATCH_HANDOFF_STORE; - -export type WatchProvisionRequestHandler = (payload: string) => void; - -/** - * Phone half of the distributed KV channel the watch already listens on. - * - * `distributedKVStore` isolates stores by bundle name *and* store id and only - * replicates between installs of the same app on the same account, which is - * why the phone and watch retain one stable compatibility bundle id rather - * than using platform-specific ids. - * - * The isolation key is really bundle name + **AppID**, and AppID is derived from - * the signing certificate — so this project and the watch's must also be built - * with the same signing material. Two DevEco-generated debug identities under - * one bundle name produce two stores that never see each other, with no error on - * either side. The store, the id and the option set below all have - * to match the watch's `DistributedHandoffStore` exactly or the two apps end - * up with private stores that never see each other's writes. - */ -export class WatchHandoffStore { - private readonly context: common.UIAbilityContext; - private kvManager?: distributedKVStore.KVManager; - private kvStore?: distributedKVStore.SingleKVStore; - private listener?: (change: distributedKVStore.ChangeNotification) => void; - private syncListener?: (results: Array<[string, number]>) => void; - private deviceManager?: distributedDeviceManager.DeviceManager; - - constructor(context: common.UIAbilityContext) { - this.context = context; - } - - async start(handler: WatchProvisionRequestHandler): Promise { - const store = await this.getStore(); - this.listener = (change: distributedKVStore.ChangeNotification): void => { - const entries = change.insertEntries.concat(change.updateEntries); - entries.forEach((entry: distributedKVStore.Entry) => { - if (entry.key === WATCH_PROVISION_REQUEST_KEY && - entry.value.type === distributedKVStore.ValueType.STRING) { - RemoteLogger.info('watch provision request arrived over KV'); - handler(String(entry.value.value)); - } - }); - }; - try { - store.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, this.listener); - } catch (err) { - throw OhosError.wrap('watch handoff subscribe', err); - } - // A watch that asked while the phone app was closed gets picked up here; - // the request's own age decides whether it is still worth acting on. The - // pull first: the watch pushes on write, but a write that happened while - // this app was not running was pushed at a replica that was not listening, - // and only an explicit pull goes back for it. - this.sync(store, distributedKVStore.SyncMode.PULL_ONLY); - try { - const value = await store.get(WATCH_PROVISION_REQUEST_KEY); - if (typeof value === 'string' && value.trim().length > 0) { - handler(value); - } - } catch (_err) { - // No request pending. dataChange delivers the next one. - } - } - - async writeResponse(payload: string): Promise { - const store = await this.getStore(); - try { - await store.put(WATCH_PROVISION_RESPONSE_KEY, payload); - } catch (err) { - throw OhosError.wrap('watch handoff write response', err); - } - // The watch is waiting on a foreground screen that blanks after nine - // seconds; `autoSync`'s own schedule is far too slack to catch that window. - this.sync(store, distributedKVStore.SyncMode.PUSH_ONLY); - } - - /** - * `autoSync` is a hint, not a guarantee — it batches on the platform's - * schedule, which on this pair can be never. Both halves of the handoff push - * their own writes explicitly, so a missing answer means a missing answer - * rather than a sync that was still pending. - */ - private sync(store: distributedKVStore.SingleKVStore, mode: distributedKVStore.SyncMode): void { - const peers = this.peerNetworkIds(); - if (peers.length === 0) { - RemoteLogger.warn('watch handoff: no trusted device online to sync with'); - return; - } - try { - store.sync(peers, mode, 0); - RemoteLogger.info(`watch handoff sync requested mode=${mode} peers=${peers.length}`); - } catch (err) { - RemoteLogger.warn(`watch handoff sync failed: ${WatchHandoffStore.errorText(err)}`); - } - } - - /** - * Network ids of the trusted devices currently online. `sync` addresses - * devices by network id, which is per-session, so this is resolved per call - * rather than cached. - */ - private peerNetworkIds(): string[] { - try { - if (!this.deviceManager) { - this.deviceManager = distributedDeviceManager.createDeviceManager( - this.context.abilityInfo.bundleName); - } - const ids: string[] = []; - this.deviceManager.getAvailableDeviceListSync() - .forEach((device: distributedDeviceManager.DeviceBasicInfo) => { - const networkId = device.networkId; - if (networkId && networkId.length > 0) { - ids.push(networkId); - } - }); - return ids; - } catch (err) { - RemoteLogger.warn(`watch handoff device list failed: ${WatchHandoffStore.errorText(err)}`); - return []; - } - } - - stop(): void { - if (this.kvStore) { - try { - if (this.listener) { - this.kvStore.off('dataChange', this.listener); - } - // By reference, never bare: an argument-less `off` drops every ArkTS - // instance's listener on this store, not just this one's. - if (this.syncListener) { - this.kvStore.off('syncComplete', this.syncListener); - } - } catch (err) { - RemoteLogger.warn(`watch handoff unsubscribe failed: ${WatchHandoffStore.errorText(err)}`); - } - } - this.listener = undefined; - this.syncListener = undefined; - if (this.deviceManager) { - try { - distributedDeviceManager.releaseDeviceManager(this.deviceManager); - } catch (err) { - RemoteLogger.warn(`watch handoff release device manager failed: ${WatchHandoffStore.errorText(err)}`); - } - this.deviceManager = undefined; - } - } - - private async getStore(): Promise { - if (this.kvStore) { - return this.kvStore; - } - if (!this.kvManager) { - this.kvManager = distributedKVStore.createKVManager({ - bundleName: this.context.abilityInfo.bundleName, - context: this.context - }); - } - const options: distributedKVStore.Options = { - createIfMissing: true, - encrypt: true, - backup: false, - autoSync: true, - kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, - // S1, and it has to be: a store only replicates to a device whose security - // level is at least its data label, and a watch is an SL1 device — SL1 - // accepts S1 and nothing else. At S2 the sync was refused by policy before - // it was ever attempted, which is indistinguishable from a dead link: no - // `dataChange` here, and an empty RecentError on both devices. - // - // S1 is honest for what actually rides this store rather than a shortcut - // around the rule. The master key is never here in the clear — the request - // carries the watch's ephemeral public key, and the response carries a - // blob sealed to it that only the watch can open. If plaintext credentials - // needed to cross, the answer would be a second store, not a lower label. - securityLevel: distributedKVStore.SecurityLevel.S1 - }; - try { - this.kvStore = await this.kvManager.getKVStore(STORE_ID, options); - await this.kvStore.enableSync(true); - } catch (err) { - throw OhosError.wrap('watch handoff open store', err); - } - // The only place a refused or failed replication reports itself. Without it - // a sync the platform dropped is indistinguishable from a watch that never - // asked. - this.syncListener = (results: Array<[string, number]>): void => { - results.forEach((result: [string, number]) => { - RemoteLogger.info(`watch handoff sync complete device=${result[0].substring(0, 8)} code=${result[1]}`); - }); - }; - this.kvStore.on('syncComplete', this.syncListener); - return this.kvStore; - } - - private static errorText(err: Object): string { - return err instanceof Error ? err.message : JSON.stringify(err); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionController.ets deleted file mode 100644 index 2f847f0e78..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionController.ets +++ /dev/null @@ -1,307 +0,0 @@ -import { abilityAccessCtrl, common, Context, Permissions } from '@kit.AbilityKit'; -import { RemoteI18n } from '../i18n/RemoteI18n'; -import { RemoteLogger } from './RemoteLogger'; -import { WatchHandoffStore } from './WatchHandoffStore'; -import { WatchProvisionCrypto } from './WatchProvisionCrypto'; -import { - WatchProvisionCredential, - WatchProvisionProtocol, - WatchProvisionRequest -} from './WatchProvisionProtocol'; -import { WatchProvisionDisplay } from './WatchProvisionDisplay'; -import { CloudAccountRequestError } from './CloudAccountClient'; - -const DATASYNC_PERMISSION: Permissions = 'ohos.permission.DISTRIBUTED_DATASYNC'; - -/** - * A minting attempt's result, whoever performed it. - * - * `relayUrl` travels with the credential rather than being asked for - * separately, because the two are only valid together: a token minted by this - * phone's own account authenticates against the account's relay, one minted by - * a paired desktop against the room's. Reporting them from two places is how - * they would come to disagree. - */ -export interface WatchProvisionOutcome { - ok: boolean; - /** The relay requires the account's normal login path for this device. */ - passwordRequired: boolean; - relayUrl: string; - token: string; - userId: string; - masterKeyBase64: string; - deviceId: string; - failure: string; - /** True when a desktop answered and refused, so `failure` is worth showing. */ - desktopReported: boolean; -} - -/** What the controller needs from the remote stack, kept narrow for testing. */ -export interface WatchProvisionPort { - /** True when some path to a credential exists — account or paired desktop. */ - readonly canProvision: () => boolean; - readonly provision: ( - deviceId: string, - deviceName: string, - requestId: string, - password: string - ) => Promise; -} - -/** - * Phone side of watch onboarding: watch asks, owner confirms here, desktop - * mints, phone seals the credential to the watch's public key. - * - * The confirmation is not a formality. The watch's request travels over a - * store shared by every install of this app on the account, so the only thing - * standing between "a device claims to be your watch" and a 30-day account - * credential is a person looking at this phone. Approval is therefore never - * implicit and never remembered. - */ -export class WatchProvisionController { - private readonly state: WatchProvisionDisplay; - private readonly port: WatchProvisionPort; - private store?: WatchHandoffStore; - private starting: boolean = false; - private started: boolean = false; - private pending?: WatchProvisionRequest; - private inFlight: boolean = false; - /** - * Requests already answered in this process. The watch clears its own - * request key once it consumes the response, so this only has to cover the - * window before that lands — and the TTL covers everything after a restart. - */ - private readonly answered: Set = new Set(); - - constructor(state: WatchProvisionDisplay, port: WatchProvisionPort) { - this.state = state; - this.port = port; - } - - /** - * Idempotent: called on every page appear, because the permission may have - * been granted since the last attempt. A denied permission is not an error - * worth surfacing — the phone simply cannot hear the watch until it is - * granted, and the watch's own screen says so. - */ - async start(context: Context): Promise { - if (this.started || this.starting) { - return; - } - this.starting = true; - try { - const atManager = abilityAccessCtrl.createAtManager(); - const result = await atManager.requestPermissionsFromUser(context, [DATASYNC_PERMISSION]); - if (result.authResults.length === 0 || - result.authResults[0] !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - RemoteLogger.info('watch provisioning idle: distributed data sync permission not granted'); - return; - } - const store = new WatchHandoffStore(context as common.UIAbilityContext); - await store.start((payload: string) => { - this.onRequestPayload(payload); - }); - this.store = store; - this.started = true; - RemoteLogger.info('watch provisioning listener started'); - } catch (err) { - RemoteLogger.warn(`watch provisioning listener failed to start: ${WatchProvisionController.errorText(err)}`); - this.store = undefined; - } finally { - this.starting = false; - } - } - - stop(): void { - if (this.store) { - this.store.stop(); - } - this.store = undefined; - this.started = false; - } - - /** Visible for tests and for the KV listener; validates before it prompts. */ - onRequestPayload(payload: string): void { - const request = WatchProvisionProtocol.parseRequest(payload); - if (!request) { - // Nothing usable to answer — a malformed request has no request_id to - // address a response to, so silence is the only available reply. - RemoteLogger.warn('watch provisioning request ignored: malformed payload'); - return; - } - if (this.answered.has(request.requestId)) { - return; - } - if (WatchProvisionProtocol.isExpired(request, Date.now())) { - RemoteLogger.info('watch provisioning request ignored: expired'); - return; - } - if (this.pending && this.pending.requestId === request.requestId) { - return; - } - if (this.inFlight || (this.pending && this.pending.deviceId !== request.deviceId)) { - // One at a time: a second watch waiting behind a silent card would look - // identical to a phone that never heard it. - this.answered.add(request.requestId); - void this.writeError(request.requestId, RemoteI18n.t('watchProvision.busy')); - return; - } - if (this.pending) { - // The same watch asking again: it gave up on the last attempt and started - // over, and the card still up here is for a request nobody is waiting on. - // Replace it — telling a watch it is busy with itself is the one answer - // that cannot be true. - RemoteLogger.info('watch provisioning request replaced by a newer one from the same watch'); - this.answered.add(this.pending.requestId); - } - this.pending = request; - this.state.ask(request.deviceName, request.deviceId); - } - - async approve(password: string = ''): Promise { - const request = this.pending; - if (!request || this.inFlight) { - return; - } - this.inFlight = true; - this.state.working(); - let settled = false; - try { - settled = await this.runProvisioning(request, password); - } finally { - if (settled) { - this.answered.add(request.requestId); - this.pending = undefined; - } - this.inFlight = false; - } - } - - async reject(): Promise { - const request = this.pending; - if (!request || this.inFlight) { - return; - } - this.answered.add(request.requestId); - this.pending = undefined; - this.state.hide(); - await this.writeError(request.requestId, RemoteI18n.t('watchProvision.rejected')); - } - - /** Closes the card after a finished attempt. Never cancels one in flight. */ - dismiss(): void { - if (this.inFlight) { - return; - } - if (this.pending) { - void this.reject(); - return; - } - this.state.hide(); - } - - private async runProvisioning(request: WatchProvisionRequest, password: string): Promise { - if (WatchProvisionProtocol.isExpired(request, Date.now())) { - await this.failAttempt(request.requestId, RemoteI18n.t('watchProvision.errors.requestExpired')); - return true; - } - if (!this.port.canProvision()) { - await this.failAttempt(request.requestId, RemoteI18n.t('watchProvision.errors.noDesktop')); - return true; - } - let outcome: WatchProvisionOutcome; - try { - outcome = await this.port.provision(request.deviceId, request.deviceName, request.requestId, password); - } catch (err) { - RemoteLogger.error(`watch provisioning failed: ${WatchProvisionController.errorText(err)}`); - if (err instanceof CloudAccountRequestError && err.statusCode === 409) { - await this.failAttempt(request.requestId, RemoteI18n.t('watchProvision.errors.alreadyRegistered')); - return true; - } - if (password.length > 0) { - this.state.requirePassword(RemoteI18n.t('watchProvision.errors.passwordFailed')); - return false; - } - await this.failAttempt(request.requestId, RemoteI18n.t('watchProvision.errors.accountUnavailable')); - return true; - } - if (outcome.passwordRequired) { - this.state.requirePassword(''); - return false; - } - if (!outcome.ok) { - // A desktop that answered and refused knows why; a desktop that never - // answered is either offline or on a build that does not know this - // command, and the copy has to cover both because they look the same. - const message = outcome.desktopReported ? - RemoteI18n.t('watchProvision.errors.desktopAuthorizationFailed') : - RemoteI18n.t('watchProvision.errors.desktopUnreachable'); - await this.failAttempt(request.requestId, message); - return true; - } - - if (outcome.relayUrl.trim().length === 0) { - // A credential with no relay to present it at is unusable, and the watch - // would only discover that after signing in. Stop here instead. - RemoteLogger.error('watch provisioning produced a credential without a relay url'); - await this.failAttempt(request.requestId, RemoteI18n.t('watchProvision.errors.handoffFailed')); - return true; - } - const credential: WatchProvisionCredential = { - relay_url: outcome.relayUrl, - token: outcome.token, - user_id: outcome.userId, - master_key: outcome.masterKeyBase64, - device_id: outcome.deviceId - }; - try { - // Fresh key pair per attempt: a credential written to the shared store - // stays unreadable to anything but the watch that asked for it. - const crypto = new WatchProvisionCrypto(); - const sealed = await crypto.seal(request.publicKeyBase64, JSON.stringify(credential)); - await this.requireStore().writeResponse(WatchProvisionProtocol.successResponse( - request.requestId, - crypto.publicKeyBase64(), - sealed.encryptedData, - sealed.nonce - )); - } catch (err) { - // The device is registered on the account either way — the relay call - // already succeeded — so say so rather than implying nothing happened. - RemoteLogger.error(`watch provisioning handoff failed: ${WatchProvisionController.errorText(err)}`); - await this.failAttempt(request.requestId, RemoteI18n.t('watchProvision.errors.handoffFailed')); - return true; - } - RemoteLogger.info('watch provisioning credential handed off'); - this.state.done(RemoteI18n.f('watchProvision.doneBody', request.deviceName)); - return true; - } - - private async failAttempt(requestId: string, message: string): Promise { - this.state.fail(message); - await this.writeError(requestId, message); - } - - private async writeError(requestId: string, message: string): Promise { - if (!this.store) { - return; - } - try { - await this.store.writeResponse(WatchProvisionProtocol.errorResponse(requestId, message)); - } catch (err) { - // The watch falls back to its own timeout copy when no response lands. - RemoteLogger.warn(`watch provisioning error reply failed: ${WatchProvisionController.errorText(err)}`); - } - } - - private requireStore(): WatchHandoffStore { - if (!this.store) { - throw new Error('Watch handoff store is not available.'); - } - return this.store; - } - - private static errorText(err: Object): string { - return err instanceof Error ? err.message : JSON.stringify(err); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionCrypto.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionCrypto.ets deleted file mode 100644 index c9f69a73b4..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionCrypto.ets +++ /dev/null @@ -1,45 +0,0 @@ -import { Encoding } from './Encoding'; -import { HarmonyRemoteCryptoCipher, RemoteCryptoCipher } from './RemoteCrypto'; -import { X25519, X25519KeyPair } from './X25519'; - -export interface WatchSealedPayload { - encryptedData: string; - nonce: string; -} - -/** - * Seals a provisioned credential to the watch's ephemeral public key. - * - * Same construction as the room channel — raw X25519 shared secret used - * directly as the AES-256-GCM key, ciphertext‖tag, base64 — so the watch can - * open it with the `CryptoService` it already has. A fresh key pair per - * provisioning attempt means a credential captured off the KV store stays - * unreadable even if the watch's stored keys later leak. - */ -export class WatchProvisionCrypto { - private readonly keyPair: X25519KeyPair; - private readonly cipher: RemoteCryptoCipher; - - constructor(keyPair?: X25519KeyPair, cipher?: RemoteCryptoCipher) { - this.keyPair = keyPair || X25519.generateKeyPair(); - this.cipher = cipher || new HarmonyRemoteCryptoCipher(); - } - - publicKeyBase64(): string { - return Encoding.bytesToBase64(this.keyPair.publicKey); - } - - async seal(watchPublicKeyBase64: string, plaintext: string): Promise { - const peerPublicKey = Encoding.base64ToBytes(watchPublicKeyBase64); - if (peerPublicKey.length !== 32) { - throw new Error('Watch public key must be 32 bytes.'); - } - const key = X25519.scalarMult(this.keyPair.privateKey, peerPublicKey); - const nonce = Encoding.randomBytes(12); - const sealed = await this.cipher.encrypt(Encoding.utf8ToBytes(plaintext), key, nonce); - return { - encryptedData: Encoding.bytesToBase64(sealed), - nonce: Encoding.bytesToBase64(nonce) - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionDisplay.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionDisplay.ets deleted file mode 100644 index fb9197b3dc..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionDisplay.ets +++ /dev/null @@ -1,9 +0,0 @@ -/** Observable card the page owns. Model must not import pages/state. */ -export interface WatchProvisionDisplay { - ask(deviceName: string, deviceId: string): void; - working(): void; - requirePassword(message: string): void; - done(message: string): void; - fail(message: string): void; - hide(): void; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionProtocol.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionProtocol.ets deleted file mode 100644 index ef3b8a9b7b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WatchProvisionProtocol.ets +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Wire format for the watch → phone → desktop device-provisioning handoff. - * - * The watch has no keyboard, so it cannot type an account password. Instead it - * writes a provisioning request into the distributed KV store both apps share - * (same bundle name, same store id), the phone asks its owner to confirm, and - * the phone relays the request to the paired desktop over the already - * encrypted room channel. The credential comes back through the same two keys. - * - * Only the credential itself is secret, and it is sealed to the watch's - * ephemeral X25519 public key before it is ever written, so neither the relay - * nor the KV replication layer sees the account master key in plaintext. - * Errors are written unsealed on purpose: the watch must be able to render - * them even when the failure was in key agreement. - */ - -import { HarmonyUpgradeIdentityContract } from './HarmonyUpgradeIdentityContract'; - -export const WATCH_PROVISION_REQUEST_KEY: string = HarmonyUpgradeIdentityContract.WATCH_PROVISION_REQUEST_KEY; -export const WATCH_PROVISION_RESPONSE_KEY: string = HarmonyUpgradeIdentityContract.WATCH_PROVISION_RESPONSE_KEY; -export const WATCH_PROVISION_PROTOCOL_VERSION: number = 1; - -/** - * A request older than this is treated as abandoned. Without it, a request the - * watch never got to clear would re-open the confirmation card on every phone - * launch, long after whoever asked for it walked away. - */ -export const WATCH_PROVISION_REQUEST_TTL_MS: number = 5 * 60 * 1000; - -export const WATCH_PROVISION_STATUS_OK: string = 'ok'; -export const WATCH_PROVISION_STATUS_ERROR: string = 'error'; - -/** As read off the KV store, before any field has been trusted. */ -export interface WatchProvisionRequestPayload { - v?: number; - request_id?: string; - device_id?: string; - device_name?: string; - public_key?: string; - created_ms?: number; -} - -/** A request that passed every shape check the relay would apply later. */ -export interface WatchProvisionRequest { - requestId: string; - deviceId: string; - deviceName: string; - publicKeyBase64: string; - createdMs: number; -} - -export interface WatchProvisionResponsePayload { - v: number; - request_id: string; - status: string; - message?: string; - public_key?: string; - nonce?: string; - encrypted_data?: string; -} - -/** The plaintext sealed into `encrypted_data` of a successful response. */ -export interface WatchProvisionCredential { - relay_url: string; - token: string; - user_id: string; - master_key: string; - device_id: string; -} - -/** Longest device name we will forward; the watch picks it, so bound it. */ -const MAX_DEVICE_NAME_LENGTH: number = 64; - -export class WatchProvisionProtocol { - /** - * Parse and fully validate a request. Returns `undefined` for anything we - * would not be able to act on, because a malformed request has no usable - * `request_id` to answer and silently ignoring it is the only option. - * - * The `device_id` rule mirrors the relay's exactly (32 lowercase hex): a - * request that would be refused at the far end is refused here, before the - * owner is asked to approve something that cannot succeed. - */ - static parseRequest(payload: string): WatchProvisionRequest | undefined { - const text = payload.trim(); - if (text.length === 0 || !text.startsWith('{')) { - return undefined; - } - let value: WatchProvisionRequestPayload; - try { - value = JSON.parse(text) as WatchProvisionRequestPayload; - } catch (_err) { - return undefined; - } - if ((value.v || 0) !== WATCH_PROVISION_PROTOCOL_VERSION) { - return undefined; - } - const requestId = (value.request_id || '').trim(); - const deviceId = (value.device_id || '').trim(); - const deviceName = (value.device_name || '').trim(); - const publicKey = (value.public_key || '').trim(); - if (!WatchProvisionProtocol.isUuid(requestId) || !WatchProvisionProtocol.isRelayDeviceId(deviceId)) { - return undefined; - } - if (deviceName.length === 0 || deviceName.length > MAX_DEVICE_NAME_LENGTH || publicKey.length === 0) { - return undefined; - } - return { - requestId, - deviceId, - deviceName, - publicKeyBase64: publicKey, - createdMs: value.created_ms || 0 - }; - } - - /** - * A request is stale once it is older than the TTL. A watch clock running - * ahead of the phone yields a negative age and is accepted: clock skew - * between two devices on one account is not the user's problem to solve. - */ - static isExpired(request: WatchProvisionRequest, nowMs: number): boolean { - if (request.createdMs <= 0) { - return true; - } - return nowMs - request.createdMs > WATCH_PROVISION_REQUEST_TTL_MS; - } - - static successResponse( - requestId: string, - phonePublicKeyBase64: string, - encryptedData: string, - nonce: string - ): string { - const payload: WatchProvisionResponsePayload = { - v: WATCH_PROVISION_PROTOCOL_VERSION, - request_id: requestId, - status: WATCH_PROVISION_STATUS_OK, - public_key: phonePublicKeyBase64, - encrypted_data: encryptedData, - nonce - }; - return JSON.stringify(payload); - } - - static errorResponse(requestId: string, message: string): string { - const payload: WatchProvisionResponsePayload = { - v: WATCH_PROVISION_PROTOCOL_VERSION, - request_id: requestId, - status: WATCH_PROVISION_STATUS_ERROR, - message - }; - return JSON.stringify(payload); - } - - /** The relay rejects any `device_id` that is not 32 lowercase hex digits. */ - static isRelayDeviceId(value: string): boolean { - return /^[0-9a-f]{32}$/.test(value); - } - - /** The desktop parses `request_id` as a UUID before it calls the relay. */ - static isUuid(value: string): boolean { - return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value); - } - - /** Short form for the confirmation card; the full id means nothing to a reader. */ - static shortDeviceId(deviceId: string): string { - return deviceId.length <= 8 ? deviceId : deviceId.slice(0, 4) + '…' + deviceId.slice(deviceId.length - 4); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WindowSystemBarService.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WindowSystemBarService.ets deleted file mode 100644 index d4f8b65918..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WindowSystemBarService.ets +++ /dev/null @@ -1,371 +0,0 @@ -import { Context } from '@kit.AbilityKit'; -import { UIContext, window } from '@kit.ArkUI'; -import { RemoteLogger } from './RemoteLogger'; - -/** - * The strip one avoid area claims along each edge of the window, in px. - */ -export interface AvoidEdges { - top: number; - bottom: number; - left: number; - right: number; -} - -/** - * How much of the window the app has to keep clear of its own content, in px. - * - * Every number is read rather than assumed. The shell runs in immersive layout, - * so the page draws from the edges of the window: the status bar is the app's - * own top inset to reserve, the bottom strip is the navigation indicator until - * the soft keyboard takes its place, and the sides are the camera cutout once - * the device has rotated it onto one of them. - */ -export interface WindowInsets { - top: number; - bottom: number; - left: number; - right: number; -} - -/** The four edge widths one avoid area reports, in px. */ -export function avoidEdgesOf(area: window.AvoidArea): AvoidEdges { - return { - top: area.topRect.height, - bottom: area.bottomRect.height, - left: area.leftRect.width, - right: area.rightRect.width - }; -} - -/** - * Merges the avoid areas that share an edge into the strip that edge needs. - * - * More than one area can claim the same edge — the status bar and a landscape - * camera cutout both touch the top, the navigation indicator and a reverse - * cutout both touch the bottom — and they are overlapping regions of one window - * rather than strips stacked on top of each other, so an edge is the widest - * claim among them and never their sum. The official `handleCutoutAvoidArea` - * sample merges the same way, one `Math.max` per edge. - * - * Pure, four numbers in and four numbers out, so the merge is assertable - * without a window; `insetsOf` keeps only the reading and the keyboard rule. - */ -export function mergeAvoidEdges(areas: AvoidEdges[]): AvoidEdges { - let top = 0; - let bottom = 0; - let left = 0; - let right = 0; - for (const area of areas) { - top = Math.max(top, area.top); - bottom = Math.max(bottom, area.bottom); - left = Math.max(left, area.left); - right = Math.max(right, area.right); - } - return { top: top, bottom: bottom, left: left, right: right }; -} - -/** One read of the insets, plus the listener that keeps them current. */ -export type WindowInsetListener = (insets: WindowInsets) => void; -export type WindowInsetSubscription = () => void; - -/** - * Platform window adapter for surfaces that need to draw behind system bars. - * - * The shell's immersive layout itself is the ability's decision — `EntryAbility` - * lays the window out full-screen — and it is what makes the insets below the - * app's own to reserve rather than the framework's. - */ -export class WindowSystemBarService { - /** - * Reads the insets once and re-reads them on every avoid-area change — folding, - * rotation and the soft keyboard all move the avoid areas without recreating - * the page, and a stale number either clips the composer or leaves the - * transcript reserving space nothing is drawn in. - * - * The returned function unregisters the listener. This is the app's one window - * read: every surface reaches it through `WindowInsetsBinding`, which shares a - * single subscription (`InsetsBroadcast`) instead of opening one per component. - */ - static async observeInsets(context: Context, onChange: WindowInsetListener): Promise { - // Swapped for the real release as soon as the window is in hand. Until then - // there is nothing on the window to take back, so the placeholder is what a - // failure before `on` registered ends up calling. - let detach: WindowInsetSubscription = (): void => {}; - try { - const appWindow = await window.getLastWindow(context); - const read: () => void = (): void => { onChange(WindowSystemBarService.insetsOf(appWindow)); }; - const onAvoidAreaChange: (data: window.AvoidAreaOptions) => void = (_data: window.AvoidAreaOptions): void => { - read(); - }; - // `listening` records whether `on` actually took. The release takes back - // exactly the listener this call put on and never one it did not: the - // failure path below runs after `on` may or may not have registered, and - // releasing blind would detach a callback that is not ours. - let listening = false; - detach = (): void => { - if (!listening) { - return; - } - listening = false; - appWindow.off('avoidAreaChange', onAvoidAreaChange); - }; - appWindow.on('avoidAreaChange', onAvoidAreaChange); - listening = true; - read(); - return detach; - } catch (err) { - // A window that cannot hand over its avoid areas must not stop the page - // rendering, so this still falls back to zero insets — but it is not the - // silent no-op it used to be. The listener registered above is released - // first: leaving it on would keep the window alive past every unmount, and - // leaving the shared broadcast at zero would let every later avoid-area - // change throw inside the system's own callback with nobody watching, so - // the whole app would lay itself out against zero insets for the rest of - // the process with nothing in the log to say why. - detach(); - RemoteLogger.error( - `window insets read failed, falling back to zero insets: ${err instanceof Error ? err.message : String(err)}` - ); - onChange({ top: 0, bottom: 0, left: 0, right: 0 }); - return (): void => {}; - } - } - - private static avoidEdges(appWindow: window.Window, type: window.AvoidAreaType): AvoidEdges { - return avoidEdgesOf(appWindow.getWindowAvoidArea(type)); - } - - private static insetsOf(appWindow: window.Window): WindowInsets { - // The camera cutout is an avoid area of its own, and only because the module - // declares `avoid_cutout` (see module.json5). Rotating the device moves it - // from the top edge to a side one, which is why it is merged here with the - // system and navigation areas instead of being left to the top strip. - // - // `TYPE_SYSTEM_GESTURE` is deliberately not read here, and that is a decision - // rather than an oversight. It is the region a system return gesture can be - // started from; the official immersive-layout sample reads it beside the - // areas above. This app registers the omission as an open follow-up instead - // of merging it now: the bottom of that region is already covered by the - // navigation indicator here, and reserving its side part unconditionally - // would move every full-width band inward on a gesture-navigation device - // with no measured overlap to justify it. Merge it in the day a swiped edge - // is observed to swallow a control. - const merged = mergeAvoidEdges([ - WindowSystemBarService.avoidEdges(appWindow, window.AvoidAreaType.TYPE_SYSTEM), - WindowSystemBarService.avoidEdges(appWindow, window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR), - WindowSystemBarService.avoidEdges(appWindow, window.AvoidAreaType.TYPE_CUTOUT) - ]); - // The keyboard covers the navigation indicator while it is up, and - // `KeyboardAvoidMode.RESIZE` has already lifted the page above it, so the - // bottom strip belongs to the keyboard for as long as it is visible. - const keyboardVisible = - appWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD).bottomRect.height > 0; - return { - top: merged.top, - bottom: keyboardVisible ? 0 : merged.bottom, - left: merged.left, - right: merged.right - }; - } -} - -/** - * The window's one avoid-area subscription, shared by every binding. - * - * The four numbers are a fact about one window, not about one component. While - * each of the 14+ bindings opened its own `getLastWindow` and its own - * `avoidAreaChange` listener, the app held one subscription per mounted surface, - * and those surfaces disagreed with each other for as long as each one's - * asynchronous window call took to resolve: a page that mounted just after a - * rotation could lay itself out from the previous numbers while its neighbour - * already had the new ones. - * - * This is reference-counted instead. The first subscriber opens the one window - * listener, the last release closes it, and every binding in between is a - * callback on this object. A new subscriber is handed the current value as it - * registers, so a surface that mounts after the last change still starts from - * real numbers rather than from zeroes. - * - * The values it broadcasts are px, the unit the window reports. Each binding - * converts them with its own `UIContext`, because two windows on one device need - * not share a scale. - */ -class InsetsBroadcast { - private listeners: WindowInsetListener[] = []; - private current: WindowInsets = { top: 0, bottom: 0, left: 0, right: 0 }; - private subscription?: WindowInsetSubscription; - private opened: boolean = false; - /** - * Bumped by every open and every close, so a window read that resolves late - * can tell whether it still belongs to the current subscription. - */ - private generation: number = 0; - - /** - * Registers one listener and returns its release. - * - * Registration is synchronous — the shared window call happens inside `open` - * and is not awaited here — so a component that unmounts immediately after - * binding has nothing in flight to leak: it releases a listener that is - * already in the list, and the shared subscription is torn down by that same - * release if it was the last one. - */ - subscribe(context: Context, listener: WindowInsetListener): WindowInsetSubscription { - this.listeners.push(listener); - if (this.listeners.length === 1) { - this.open(context); - } - listener(this.current); - return (): void => { - this.release(listener); - }; - } - - private release(listener: WindowInsetListener): void { - const index = this.listeners.indexOf(listener); - if (index >= 0) { - this.listeners.splice(index, 1); - } - if (this.listeners.length === 0) { - this.close(); - } - } - - private open(context: Context): void { - if (this.opened) { - return; - } - this.opened = true; - this.generation += 1; - const generation = this.generation; - RemoteLogger.info('window insets subscription opened'); - void WindowSystemBarService.observeInsets(context, (insets: WindowInsets): void => { - // observeInsets publishes before its promise resolves, including its - // zero-inset failure fallback. Reject stale data before touching the - // shared cache or listeners; the cleanup guard below runs too late. - if (generation !== this.generation || this.listeners.length === 0) { - return; - } - this.current = insets; - for (const listener of this.listeners) { - listener(insets); - } - }).then((subscription: WindowInsetSubscription): void => { - // The last subscriber can be gone, or a later open can already own the - // window, before this read resolves. Either way this subscription has no - // one left to serve, so it is handed straight back instead of being kept. - if (generation !== this.generation || this.listeners.length === 0) { - subscription(); - return; - } - this.subscription = subscription; - }); - } - - private close(): void { - this.opened = false; - this.generation += 1; - if (this.subscription) { - this.subscription(); - this.subscription = undefined; - RemoteLogger.info('window insets subscription closed'); - } - } -} - -/** The process-wide instance every `WindowInsetsBinding` registers with. */ -const sharedInsetsBroadcast: InsetsBroadcast = new InsetsBroadcast(); - -/** - * One component's live view of the window insets, in vp. - * - * The shell is immersive, so every surface that puts chrome against a screen - * edge reads these numbers instead of assuming the framework reserved the strip - * for it: the chat page's fade fills the bottom edge, and the interactive rows - * of every other page — drawers, sheets, covers, galleries — keep clear of it. - * The sides are part of the same model: they are the camera cutout, which a - * rotated device moves onto one of them, so a full-width band reserves them - * before its own design spacing rather than assuming the page starts clear. - * They mount and unmount independently, so the binding holds a registration on - * the app's one shared subscription rather than leaving each page to juggle a - * window listener of its own, and it holds vp because padding, margins and radii - * in this app are vp. - */ -@ObservedV2 -export class WindowInsetsBinding { - @Trace top: number = 0; - @Trace bottom: number = 0; - @Trace left: number = 0; - @Trace right: number = 0; - private subscription?: WindowInsetSubscription; - private disposed: boolean = false; - - bind(uiContext: UIContext, context: Context): void { - this.disposed = false; - // Registering is synchronous and immediately delivers the current value, so - // this surface is laid out from real numbers as soon as it mounts and is - // releasable the moment it goes. The callback still checks `disposed` - // because the broadcast can deliver a change across an unmount. - const callback: WindowInsetListener = (insets: WindowInsets): void => { - if (this.disposed) { - return; - } - this.top = uiContext.px2vp(insets.top); - this.bottom = uiContext.px2vp(insets.bottom); - this.left = uiContext.px2vp(insets.left); - this.right = uiContext.px2vp(insets.right); - RemoteLogger.info(`window insets top=${this.top} bottom=${this.bottom} left=${this.left} right=${this.right}`); - }; - // A binding that is bound twice replaces its own registration instead of - // leaving the previous one behind on the shared subscription. - const previous = this.subscription; - this.subscription = sharedInsetsBroadcast.subscribe(context, callback); - if (previous) { - previous(); - } - } - - unbind(): void { - this.disposed = true; - if (this.subscription) { - this.subscription(); - this.subscription = undefined; - } - } - - /** - * The padding a bottom-anchored content layer needs: the design's own spacing - * where it already clears the strip, and the strip itself where it does not. - * The strip is a device fact, so a page never hard-codes it. - */ - bottomPadding(designSpacing: number): number { - return Math.max(designSpacing, this.bottom); - } - - /** - * The padding a side-anchored content layer needs. Split by side rather than - * exposed as one pair because a cutout only ever lands on one of them: the - * left strip stays 0 while the right one carries the camera, and padding both - * by the wider value would push the content of a full-width band off-centre. - */ - leftPadding(designSpacing: number): number { - return Math.max(designSpacing, this.left); - } - - rightPadding(designSpacing: number): number { - return Math.max(designSpacing, this.right); - } - - /** - * The tail spacer a scrolling surface appends after its last row: the strip - * itself plus the design's own breathing. The viewport then runs to the - * screen edge — rows roll under the navigation indicator while they are - * still moving — while the last row still comes to rest above the bar. - * Padding on the scrolling container cannot do that: it shrinks the viewport - * and leaves a band of bare page colour under the bar instead. - */ - tailSpacing(designSpacing: number): number { - return this.bottom + designSpacing; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets deleted file mode 100644 index d3c9b4d67d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceCatalog.ets +++ /dev/null @@ -1,64 +0,0 @@ -import { AssistantEntry, RecentWorkspaceEntry, RecentWorkspaceListResponse } from '../model/RemoteModels'; -import { RemoteResponseMapper } from './RemoteResponseMapper'; -import { remoteWorkspaceKey } from './RemoteSessionIdentity'; - -export type WorkspaceCatalogSource = 'opened' | 'recent'; - -export interface WorkspaceCatalog { - workspaces: RecentWorkspaceEntry[]; - recentWorkspaces: RecentWorkspaceEntry[]; - source: WorkspaceCatalogSource; -} - -/** Membership comes from the host; assistant metadata only enriches local rows. */ -export function projectWorkspaceCatalog( - response: RecentWorkspaceListResponse, - assistants: AssistantEntry[] -): WorkspaceCatalog { - const recent = RemoteResponseMapper.recentWorkspaces(response.workspaces || []); - const opened = Array.isArray(response.opened_workspaces); - const rows = opened ? RemoteResponseMapper.recentWorkspaces(response.opened_workspaces || []) : - mergeLegacyWorkspaces(recent, assistants); - const seen: Set = new Set(); - const workspaces: RecentWorkspaceEntry[] = []; - rows.forEach((row: RecentWorkspaceEntry) => { - // Rows with an ID dedup by ID alone; only pre-ID rows fall back to the legacy triple. - const key = remoteWorkspaceKey(row); - if (!row.path || seen.has(key)) return; - seen.add(key); - const assistant = !row.remoteConnectionId && !row.remoteSshHost ? - assistants.find((item: AssistantEntry): boolean => (row.workspaceId ? item.workspace_id === row.workspaceId : !item.workspace_id && item.path === row.path) && item.name.trim().length > 0) : undefined; - workspaces.push({ - workspaceId: row.workspaceId, - path: row.path, name: assistant ? assistant.name : row.name, - lastOpened: row.lastOpened, workspaceKind: assistant ? 'assistant' : row.workspaceKind, - remoteConnectionId: row.remoteConnectionId, remoteSshHost: row.remoteSshHost - }); - }); - workspaces.sort((left: RecentWorkspaceEntry, right: RecentWorkspaceEntry): number => - Number(right.workspaceKind === 'assistant') - Number(left.workspaceKind === 'assistant')); - return { workspaces, recentWorkspaces: recent, source: opened ? 'opened' : 'recent' }; -} - -/** - * Upgrade-only merge for hosts without `opened_workspaces`. - * - * Assistant rows come first; a recent row is skipped when a row with the same - * key exists, where the key is the workspace ID when present and the legacy - * (connection, ssh host, path) triple otherwise. - */ -export function mergeLegacyWorkspaces(recent: RecentWorkspaceEntry[], assistants: AssistantEntry[]): RecentWorkspaceEntry[] { - const rows: RecentWorkspaceEntry[] = assistants.map((item: AssistantEntry): RecentWorkspaceEntry => ({ - workspaceId: item.workspace_id, - path: item.path, name: item.name, lastOpened: '', workspaceKind: 'assistant' - })); - const seen: Set = new Set(); - rows.forEach((row: RecentWorkspaceEntry) => seen.add(remoteWorkspaceKey(row))); - recent.forEach((item: RecentWorkspaceEntry) => { - const key = remoteWorkspaceKey(item); - if (seen.has(key)) return; - seen.add(key); - rows.push(item); - }); - return rows; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceFileUploadClient.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceFileUploadClient.ets deleted file mode 100644 index a207ca1a2e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/WorkspaceFileUploadClient.ets +++ /dev/null @@ -1,114 +0,0 @@ -import fs from '@ohos.file.fs'; -import picker from '@ohos.file.picker'; -import { cryptoFramework } from '@kit.CryptoArchitectureKit'; -import { Encoding } from './Encoding'; -import { RemoteSessionManager } from './RemoteSessionManager'; - -interface UploadRequest { action: string; transferId: string; path: string; workspacePath: string; remoteConnectionId?: string; totalBytes?: number; sha256?: string; expectedHash?: string; offset?: number; contentBase64?: string; } -interface UploadArgs { request: UploadRequest; } -interface UploadStatus { transferId: string; nextOffset: number; totalBytes: number; completed: boolean; } -interface PendingUpload { file: fs.File; request: UploadRequest; targetId: string; started: boolean; } - -/** Native file IO remains on the phone; only bounded encrypted chunks cross to the runtime. */ -export class WorkspaceFileUploadClient { - private pending?: PendingUpload; - private manager: RemoteSessionManager; - private target: () => string; - constructor(manager: RemoteSessionManager, target: () => string) { this.manager = manager; this.target = target; } - hasPending(): boolean { return this.pending !== undefined; } - private async call(request: UploadRequest): Promise { - if (this.pending && this.pending.targetId !== this.target()) throw new Error('Reconnect to the upload owning runtime first'); - const args: UploadArgs = { request: request }; - const status = await this.manager.hostInvoke('workspace_file_upload', args); - if (request.action !== 'cancel' && (status.transferId !== request.transferId || - status.totalBytes !== request.totalBytes || !Number.isSafeInteger(status.nextOffset) || - status.nextOffset < 0 || status.nextOffset > (request.totalBytes || 0))) { - throw new Error('Invalid upload acknowledgement'); - } - return status; - } - async select(path: string, remoteConnectionId: string | undefined, expectedHash: string, current: () => boolean, workspacePath: string): Promise { - if (this.pending) throw new Error('Finish or cancel the current file upload first'); - if (!workspacePath) throw new Error('Upload workspace identity is required'); - const targetId = this.target(); - const options = new picker.DocumentSelectOptions(); options.maxSelectNumber = 1; - const files = await new picker.DocumentViewPicker().select(options); - if (!files.length || !current() || targetId !== this.target()) return; - const file = await fs.open(files[0], fs.OpenMode.READ_ONLY); - try { - const metadata = await fs.stat(file.fd); - if (!Number.isSafeInteger(metadata.size) || metadata.size < 0) throw new Error('Selected file size is not supported'); - if (!metadata.isFile()) throw new Error('Select a regular file'); - const digest = cryptoFramework.createMd('SHA256'); - let offset = 0; - while (offset < metadata.size) { - if (!current() || targetId !== this.target()) throw new Error('File upload target changed'); - const buffer = new ArrayBuffer(Math.min(1024 * 1024, metadata.size - offset)); - const count = await fs.read(file.fd, buffer, { offset: offset, length: buffer.byteLength }); - if (count <= 0) throw new Error('Selected file changed during hashing'); - await digest.update({ data: new Uint8Array(buffer.slice(0, count)) }); offset += count; - } - const hash = await digest.digest(); - if (!current() || targetId !== this.target()) throw new Error('File upload target changed'); - const transferId = Array.from(Encoding.randomBytes(32)).map((value: number) => value.toString(16).padStart(2, '0')).join(''); - const request: UploadRequest = { action: 'begin', transferId: transferId, path: path, workspacePath: workspacePath, remoteConnectionId: remoteConnectionId, totalBytes: metadata.size, - sha256: Array.from(hash.data).map((value: number) => value.toString(16).padStart(2, '0')).join(''), expectedHash: expectedHash }; - this.pending = { file: file, request: request, targetId: targetId, started: false }; - } catch (error) { await fs.close(file); throw error as Error; } - } - async resume(current: () => boolean, progress: (offset: number, total: number) => void): Promise { - const pending = this.pending; - if (!pending) return; - if (pending.targetId !== this.target()) throw new Error('Reconnect to the upload owning runtime first'); - const request = pending.request; - // Begin is idempotent even when its earlier acknowledgement was lost. - pending.started = true; - request.action = 'begin'; request.contentBase64 = undefined; request.offset = undefined; - let status: UploadStatus; - try { status = await this.call(request); } - catch (error) { - if (!current() || pending.targetId !== this.target()) throw error as Error; - request.action = 'status'; - status = await this.call(request); - } - while (!status.completed && status.nextOffset < (request.totalBytes || 0)) { - if (!current() || pending.targetId !== this.target()) return; - const offset = status.nextOffset; - const buffer = new ArrayBuffer(Math.min(1024 * 1024, (request.totalBytes || 0) - offset)); - const count = await fs.read(pending.file.fd, buffer, { offset: offset, length: buffer.byteLength }); - if (count <= 0) throw new Error('Selected file changed during upload'); - request.action = 'append'; request.offset = offset; - request.contentBase64 = Encoding.bytesToBase64(new Uint8Array(buffer.slice(0, count))); - try { status = await this.call(request); } - catch (error) { - // Query the owning runtime before deciding whether an uncertain chunk needs resending. - request.action = 'status'; request.contentBase64 = undefined; - status = await this.call(request); - if (status.nextOffset === offset) throw error as Error; - } - if (status.nextOffset <= offset || status.nextOffset > (request.totalBytes || 0)) throw new Error('Invalid upload acknowledgement offset'); - progress(status.nextOffset, request.totalBytes || 0); - } - if (!current() || pending.targetId !== this.target()) return; - if (!status.completed) { - request.action = 'finish'; request.contentBase64 = undefined; - try { status = await this.call(request); } - catch (error) { - if (!current() || pending.targetId !== this.target()) throw error as Error; - request.action = 'status'; - status = await this.call(request); - if (!status.completed) throw error as Error; - } - } - if (!status.completed || status.nextOffset !== request.totalBytes) throw new Error('Runtime did not complete the file upload'); - await fs.close(pending.file); if (this.pending === pending) this.pending = undefined; - } - async cancel(): Promise { - const pending = this.pending; - if (!pending) return; - if (pending.targetId !== this.target()) throw new Error('Reconnect to the upload owning runtime before cancelling'); - pending.request.action = 'cancel'; pending.request.contentBase64 = undefined; - if (pending.started) await this.call(pending.request); - await fs.close(pending.file); if (this.pending === pending) this.pending = undefined; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/X25519.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/X25519.ets deleted file mode 100644 index 1d4f99899b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/X25519.ets +++ /dev/null @@ -1,122 +0,0 @@ -import { Encoding } from './Encoding'; - -const P: bigint = (1n << 255n) - 19n; -const A24: bigint = 121665n; - -export interface X25519KeyPair { - privateKey: Uint8Array; - publicKey: Uint8Array; -} - -function mod(value: bigint): bigint { - const result = value % P; - return result >= 0n ? result : result + P; -} - -function decodeLittleEndian(bytes: Uint8Array): bigint { - let value = 0n; - for (let index = bytes.length - 1; index >= 0; index--) { - value = (value << 8n) + BigInt(bytes[index]); - } - return value; -} - -function encodeLittleEndian(value: bigint): Uint8Array { - let current = mod(value); - const bytes = new Uint8Array(32); - for (let index = 0; index < 32; index++) { - bytes[index] = Number(current & 255n); - current >>= 8n; - } - return bytes; -} - -function powMod(base: bigint, exponent: bigint): bigint { - let result = 1n; - let current = mod(base); - let exp = exponent; - while (exp > 0n) { - if ((exp & 1n) === 1n) { - result = mod(result * current); - } - current = mod(current * current); - exp >>= 1n; - } - return result; -} - -export class X25519 { - static generateKeyPair(): X25519KeyPair { - const privateKey = Encoding.randomBytes(32); - const publicKey = X25519.scalarMultBase(privateKey); - return { privateKey, publicKey }; - } - - static scalarMultBase(privateKey: Uint8Array): Uint8Array { - const base = new Uint8Array(32); - base[0] = 9; - return X25519.scalarMult(privateKey, base); - } - - static scalarMult(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array { - if (privateKey.length !== 32 || publicKey.length !== 32) { - throw new Error('X25519 keys must be 32 bytes.'); - } - - const scalar = Encoding.copyBytes(privateKey); - scalar[0] &= 248; - scalar[31] &= 127; - scalar[31] |= 64; - - const uBytes = Encoding.copyBytes(publicKey); - uBytes[31] &= 127; - - const x1 = decodeLittleEndian(uBytes); - let x2 = 1n; - let z2 = 0n; - let x3 = x1; - let z3 = 1n; - let swap = 0; - const k = decodeLittleEndian(scalar); - - for (let bit = 254; bit >= 0; bit--) { - const currentBit = Number((k >> BigInt(bit)) & 1n); - swap = swap ^ currentBit; - if (swap === 1) { - const tx = x2; - x2 = x3; - x3 = tx; - const tz = z2; - z2 = z3; - z3 = tz; - } - swap = currentBit; - - const a = mod(x2 + z2); - const aa = mod(a * a); - const b = mod(x2 - z2); - const bb = mod(b * b); - const e = mod(aa - bb); - const c = mod(x3 + z3); - const d = mod(x3 - z3); - const da = mod(d * a); - const cb = mod(c * b); - x3 = mod((da + cb) * (da + cb)); - z3 = mod(x1 * mod((da - cb) * (da - cb))); - x2 = mod(aa * bb); - z2 = mod(e * mod(aa + A24 * e)); - } - - if (swap === 1) { - const tx = x2; - x2 = x3; - x3 = tx; - const tz = z2; - z2 = z3; - z3 = tz; - } - - const inverse = powMod(z2, P - 2n); - return encodeLittleEndian(x2 * inverse); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiClient.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiClient.ets deleted file mode 100644 index a16a30364b..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiClient.ets +++ /dev/null @@ -1,148 +0,0 @@ -import { Encoding } from '../Encoding'; -import { - GeneralChatCancelTurnRequest, - GeneralChatCapabilityResponse, - GeneralChatCreateSessionRequest, - GeneralChatMessagePageResponse, - GeneralChatRenameSessionRequest, - GeneralChatSendTurnRequest, - GeneralChatSessionPageResponse, - GeneralChatSessionResponse, - GeneralChatTurnReceiptResponse -} from './GeneralChatApiModels'; -import { - GeneralChatHttpHeaders, - GeneralChatHttpMethod, - GeneralChatHttpResponse, - GeneralChatHttpTransport, - GeneralChatTokenProvider -} from './GeneralChatHttpTransport'; - -export class GeneralChatApiClient { - private readonly baseUrl: string; - private readonly tokenProvider: GeneralChatTokenProvider; - private readonly transport: GeneralChatHttpTransport; - - constructor( - baseUrl: string, - tokenProvider: GeneralChatTokenProvider, - transport: GeneralChatHttpTransport - ) { - this.baseUrl = GeneralChatApiClient.normalizeBaseUrl(baseUrl); - this.tokenProvider = tokenProvider; - this.transport = transport; - } - - async capabilities(): Promise { - return this.request(GeneralChatHttpMethod.Get, '/api/mobile/v1/chat/capabilities'); - } - - async listSessions(cursor: string = ''): Promise { - const query = cursor.trim().length > 0 ? `?cursor=${encodeURIComponent(cursor.trim())}` : ''; - return this.request(GeneralChatHttpMethod.Get, `/api/mobile/v1/chat/sessions${query}`); - } - - async createSession(title: string): Promise { - const body: GeneralChatCreateSessionRequest = { title: title.trim() }; - return this.request(GeneralChatHttpMethod.Post, '/api/mobile/v1/chat/sessions', body); - } - - async renameSession(sessionId: string, title: string): Promise { - const body: GeneralChatRenameSessionRequest = { title: title.trim() }; - return this.request( - GeneralChatHttpMethod.Put, - `/api/mobile/v1/chat/sessions/${encodeURIComponent(sessionId)}`, - body - ); - } - - async deleteSession(sessionId: string): Promise { - await this.request( - GeneralChatHttpMethod.Delete, - `/api/mobile/v1/chat/sessions/${encodeURIComponent(sessionId)}` - ); - } - - async loadMessages(sessionId: string, cursor: string = ''): Promise { - const query = cursor.trim().length > 0 ? `?cursor=${encodeURIComponent(cursor.trim())}` : ''; - return this.request( - GeneralChatHttpMethod.Get, - `/api/mobile/v1/chat/sessions/${encodeURIComponent(sessionId)}/messages${query}` - ); - } - - async sendTurn(sessionId: string, content: string, modelName: string): Promise { - const body: GeneralChatSendTurnRequest = { - content: content.trim(), - model: modelName.trim() - }; - if (body.model.length === 0) { - throw new Error('General chat model name is not configured.'); - } - return this.request( - GeneralChatHttpMethod.Post, - `/api/mobile/v1/chat/sessions/${encodeURIComponent(sessionId)}/turns`, - body - ); - } - - async cancelTurn(sessionId: string, turnId: string): Promise { - const body: GeneralChatCancelTurnRequest = { reason: 'user_requested' }; - await this.request( - GeneralChatHttpMethod.Post, - `/api/mobile/v1/chat/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}/cancel`, - body - ); - } - - private async request(method: GeneralChatHttpMethod, path: string, body?: Object): Promise { - if (this.baseUrl.length === 0) { - throw new Error('General chat API base URL is not configured.'); - } - const accessToken = (await this.tokenProvider.accessToken()).trim(); - if (accessToken.length === 0) { - throw new Error('General chat access token is not available.'); - } - const headers: GeneralChatHttpHeaders = { - authorization: `Bearer ${accessToken}`, - contentType: 'application/json', - accept: 'application/json' - }; - const response = await this.transport.request( - `${this.baseUrl}${path}`, - method, - headers, - body ? JSON.stringify(body) : undefined - ); - this.ensureSuccess(response); - if (response.body.trim().length === 0) { - return undefined as T; - } - try { - return Encoding.parseJsonObject(response.body); - } catch (_err) { - throw new Error('General chat API returned invalid JSON.'); - } - } - - private ensureSuccess(response: GeneralChatHttpResponse): void { - if (response.statusCode >= 200 && response.statusCode < 300) { - return; - } - if (response.statusCode === 401 || response.statusCode === 403) { - throw new Error('General chat authentication expired.'); - } - if (response.statusCode === 429) { - throw new Error('General chat request was rate limited.'); - } - if (response.statusCode >= 500) { - throw new Error('General chat service is temporarily unavailable.'); - } - throw new Error(`General chat request failed with HTTP ${response.statusCode}.`); - } - - private static normalizeBaseUrl(value: string): string { - const trimmed = value.trim(); - return trimmed.endsWith('/') ? trimmed.slice(0, trimmed.length - 1) : trimmed; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiModels.ets deleted file mode 100644 index fec517d837..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatApiModels.ets +++ /dev/null @@ -1,79 +0,0 @@ -export interface GeneralChatCapabilityResponse { - capabilities: string[]; -} - -export interface GeneralChatApiSession { - id: string; - title: string; - status: string; - created_at: string; - updated_at: string; - message_count: number; -} - -export interface GeneralChatSessionPageResponse { - sessions: GeneralChatApiSession[]; - next_cursor?: string; -} - -export interface GeneralChatSessionResponse { - session: GeneralChatApiSession; -} - -export interface GeneralChatApiMessage { - id: string; - role: string; - content: string; - status: string; - timestamp: string; -} - -export interface GeneralChatMessagePageResponse { - messages: GeneralChatApiMessage[]; - next_cursor?: string; - version: number; -} - -export interface GeneralChatTurnReceiptResponse { - turn_id: string; - accepted_at: string; - version: number; -} - -export interface GeneralChatCreateSessionRequest { - title: string; -} - -export interface GeneralChatRenameSessionRequest { - title: string; -} - -export interface GeneralChatSendTurnRequest { - content: string; - model: string; -} - -export interface GeneralChatCancelTurnRequest { - reason: string; -} - -export interface GeneralChatApiTool { - id: string; - name: string; - status: string; - input_preview?: string; - result_preview?: string; - error_preview?: string; -} - -export interface GeneralChatStreamEvent { - event_id: string; - version: number; - session_id: string; - turn_id: string; - type: string; - delta?: string; - tool?: GeneralChatApiTool; - error_code?: string; - capability?: string; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatBootstrapController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatBootstrapController.ets deleted file mode 100644 index 891e0f7301..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatBootstrapController.ets +++ /dev/null @@ -1,56 +0,0 @@ -import { GeneralChatConfigSnapshot, GeneralChatConfigStore } from './GeneralChatConfigStore'; -import { GeneralChatCommandController } from './GeneralChatCommandController'; -import { GeneralChatDraftLifecycleController } from './GeneralChatDraftLifecycleController'; -import { ConnectionErrorPolicy } from '../ConnectionErrorPolicy'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { RemoteLogger } from '../RemoteLogger'; - -export interface GeneralChatBootstrapCallbacks { - onConfigRestored: (snapshot: GeneralChatConfigSnapshot) => void; - onHomeDraftRestored: (text: string) => void; - onStatusText: (statusText: string) => void; -} - -export class GeneralChatBootstrapController { - private readonly configStore: GeneralChatConfigStore; - private readonly commandController: GeneralChatCommandController; - private readonly draftLifecycleController: GeneralChatDraftLifecycleController; - private readonly callbacks: GeneralChatBootstrapCallbacks; - - constructor( - configStore: GeneralChatConfigStore, - commandController: GeneralChatCommandController, - draftLifecycleController: GeneralChatDraftLifecycleController, - callbacks: GeneralChatBootstrapCallbacks - ) { - this.configStore = configStore; - this.commandController = commandController; - this.draftLifecycleController = draftLifecycleController; - this.callbacks = callbacks; - } - - async restore(context: Context): Promise { - await this.restoreConfig(context); - await this.restoreLocalChat(context); - } - - private async restoreConfig(context: Context): Promise { - try { - const snapshot = await this.configStore.init(context); - this.callbacks.onConfigRestored(snapshot); - } catch (err) { - RemoteLogger.warn(`general chat configuration restore failed: ${ConnectionErrorPolicy.errorText(err)}`); - } - } - - private async restoreLocalChat(context: Context): Promise { - try { - await this.commandController.init(context); - this.commandController.refreshSessions(); - this.callbacks.onHomeDraftRestored(await this.draftLifecycleController.restoreHome()); - } catch (err) { - RemoteLogger.warn(`general chat restore failed: ${ConnectionErrorPolicy.errorText(err)}`); - this.callbacks.onStatusText(RemoteI18n.t('generalChat.localRestoreFailed')); - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCloudConfigPolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCloudConfigPolicy.ets deleted file mode 100644 index dda3d5aa2c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCloudConfigPolicy.ets +++ /dev/null @@ -1,119 +0,0 @@ -import { GeneralChatRuntimeModelConfig } from './GeneralChatConfigStore'; - -interface CloudModelAuthWire { - type?: string; -} - -interface CloudModelWire { - id?: string; - name?: string; - provider?: string; - model_name?: string; - base_url?: string; - api_key?: string; - enabled?: boolean; - category?: string; - auth?: CloudModelAuthWire; -} - -interface CloudDefaultModelsWire { - primary?: string; -} - -interface CloudAiConfigWire { - models?: CloudModelWire[]; - default_models?: CloudDefaultModelsWire; -} - -interface CloudGlobalConfigWire { - ai?: CloudAiConfigWire; -} - -interface CloudSettingsPayloadWire { - config?: CloudGlobalConfigWire; - ai?: CloudAiConfigWire; -} - -/** Maps the shared encrypted account settings payload to the smaller HarmonyOS chat contract. */ -export class GeneralChatCloudConfigPolicy { - static models(payload: string): GeneralChatRuntimeModelConfig[] { - let parsed: CloudSettingsPayloadWire; - try { - parsed = JSON.parse(payload) as CloudSettingsPayloadWire; - } catch (_err) { - return []; - } - const ai = parsed.config?.ai || parsed.ai; - const models = ai?.models || []; - const primaryId = ai?.default_models?.primary || ''; - const ordered: CloudModelWire[] = []; - if (primaryId.length > 0) { - models.forEach((model: CloudModelWire) => { - if (model.id === primaryId) { - GeneralChatCloudConfigPolicy.pushCompatible(ordered, model); - } - }); - } - models.forEach((model: CloudModelWire) => { - if (model.category === 'general_chat') { - GeneralChatCloudConfigPolicy.pushCompatible(ordered, model); - } - }); - models.forEach((model: CloudModelWire) => { - GeneralChatCloudConfigPolicy.pushCompatible(ordered, model); - }); - return ordered.map((model: CloudModelWire): GeneralChatRuntimeModelConfig => { - const sourceId = GeneralChatCloudConfigPolicy.stringValue(model.id).trim() || - `${GeneralChatCloudConfigPolicy.stringValue(model.provider)}:${GeneralChatCloudConfigPolicy.stringValue(model.model_name)}`; - const modelName = GeneralChatCloudConfigPolicy.stringValue(model.model_name).trim(); - return { - modelId: `cloud:${sourceId}`, - name: GeneralChatCloudConfigPolicy.stringValue(model.name).trim() || modelName, - provider: GeneralChatCloudConfigPolicy.stringValue(model.provider).trim() || 'account', - apiUrl: GeneralChatCloudConfigPolicy.normalizedApiUrl(model), - apiKey: GeneralChatCloudConfigPolicy.stringValue(model.api_key).trim(), - modelName - }; - }); - } - - static selectModel(payload: string): GeneralChatRuntimeModelConfig | undefined { - const models = GeneralChatCloudConfigPolicy.models(payload); - return models.length > 0 ? models[0] : undefined; - } - - private static pushCompatible(target: CloudModelWire[], model: CloudModelWire): void { - if (!GeneralChatCloudConfigPolicy.isCompatible(model)) { - return; - } - const id = GeneralChatCloudConfigPolicy.stringValue(model.id); - const duplicate = target.some((candidate: CloudModelWire): boolean => { - return GeneralChatCloudConfigPolicy.stringValue(candidate.id) === id; - }); - if (!duplicate) { - target.push(model); - } - } - - private static isCompatible(model: CloudModelWire): boolean { - if (model.enabled !== true || model.auth?.type === 'subscription') { - return false; - } - return GeneralChatCloudConfigPolicy.stringValue(model.base_url).trim().length > 0 && - GeneralChatCloudConfigPolicy.stringValue(model.model_name).trim().length > 0 && - GeneralChatCloudConfigPolicy.stringValue(model.api_key).trim().length > 0; - } - - private static normalizedApiUrl(model: CloudModelWire): string { - const baseUrl = GeneralChatCloudConfigPolicy.stringValue(model.base_url).trim().replace(/\/+$/, ''); - const provider = GeneralChatCloudConfigPolicy.stringValue(model.provider).trim().toLowerCase(); - if (provider === 'anthropic' && baseUrl.indexOf('openbitfun.com') < 0 && !baseUrl.endsWith('/v1/messages')) { - return `${baseUrl}/v1/messages`; - } - return baseUrl; - } - - private static stringValue(value?: string): string { - return typeof value === 'string' ? value : ''; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCommandController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCommandController.ets deleted file mode 100644 index c0bca0f314..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatCommandController.ets +++ /dev/null @@ -1,267 +0,0 @@ -import { ChatMessage, ImageAttachment, RemoteSession, SessionSummary } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { ConnectionErrorPolicy } from '../ConnectionErrorPolicy'; -import { RemoteLogger } from '../RemoteLogger'; -import { GeneralChatExportFormatter } from './GeneralChatExportFormatter'; -import { GeneralChatSendResult, GeneralChatStreamObserver } from './GeneralChatPort'; - -export interface GeneralChatCommandClient { - init(context: Context): Promise; - sessions(): RemoteSession[]; - createSession(firstMessage: string): Promise; - messages(sessionId: string): Promise; - sendMessage( - sessionId: string, - text: string, - images: ImageAttachment[], - observer?: GeneralChatStreamObserver - ): Promise; - cancelCurrentRequest(): void; - recordAssistantMessage(sessionId: string, message: ChatMessage): Promise; - renameSession(sessionId: string, title: string): Promise; - archiveSession(sessionId: string, archived: boolean): Promise; - pinSession(sessionId: string, pinned: boolean): Promise; - deleteSession(sessionId: string): Promise; - removeFailedUserMessage(sessionId: string, text: string): Promise; -} - -export interface GeneralChatCommandCallbacks { - onSessions: (sessions: RemoteSession[]) => void; - onSessionPrepared: (sessionId: string) => void; - onActiveSession: (session: SessionSummary) => void; - onMessagesLoaded: (messages: ChatMessage[]) => void; - onClearComposer: () => void; - onChatInput: (text: string) => void; - onStatusText: (statusText: string) => void; - onBusy: (isBusy: boolean) => void; - onToast: (statusText: string) => void; -} - -export class GeneralChatCommandController { - private readonly client: GeneralChatCommandClient; - private readonly callbacks: GeneralChatCommandCallbacks; - - constructor(client: GeneralChatCommandClient, callbacks: GeneralChatCommandCallbacks) { - this.client = client; - this.callbacks = callbacks; - } - - async init(context: Context): Promise { - await this.client.init(context); - } - - async openSession( - session: RemoteSession, - isBusy: boolean, - restoreDraft: (sessionId: string) => Promise, - onOpened: (sessionId: string) => void - ): Promise { - if (!this.isValidChatSession(session) || isBusy) { - return false; - } - try { - this.callbacks.onBusy(true); - this.callbacks.onSessionPrepared(session.id); - this.callbacks.onActiveSession({ - sessionId: session.id, - title: session.title, - workspacePath: '', - agentType: 'chat' - }); - this.callbacks.onClearComposer(); - this.callbacks.onChatInput(await restoreDraft(session.id)); - this.callbacks.onMessagesLoaded(await this.client.messages(session.id)); - this.callbacks.onStatusText(RemoteI18n.t('generalChat.ready')); - onOpened(session.id); - return true; - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - return false; - } finally { - this.callbacks.onBusy(false); - } - } - - async createSession( - firstMessage: string, - isBusy: boolean, - clearHomeDraft: () => Promise, - onCreated: (sessionId: string) => void - ): Promise { - const trimmed = firstMessage.trim(); - if (trimmed.length === 0 || isBusy) { - return false; - } - try { - this.callbacks.onBusy(true); - const session = await this.client.createSession(trimmed); - this.callbacks.onSessions(this.client.sessions()); - this.callbacks.onSessionPrepared(session.id); - this.callbacks.onActiveSession({ - sessionId: session.id, - title: session.title, - workspacePath: '', - agentType: 'chat' - }); - onCreated(session.id); - await clearHomeDraft(); - return true; - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - return false; - } finally { - this.callbacks.onBusy(false); - } - } - - refreshSessions(): void { - this.callbacks.onSessions(this.client.sessions()); - } - - async loadMessages(sessionId: string): Promise { - return this.client.messages(sessionId); - } - - async sendMessage( - sessionId: string, - text: string, - images: ImageAttachment[], - observer?: GeneralChatStreamObserver - ): Promise { - return this.client.sendMessage(sessionId, text, images, observer); - } - - cancelCurrentRequest(): void { - this.client.cancelCurrentRequest(); - } - - async recordAssistantMessage(sessionId: string, message: ChatMessage): Promise { - if (sessionId.length === 0) { - return false; - } - try { - await this.client.recordAssistantMessage(sessionId, message); - this.refreshSessions(); - return true; - } catch (err) { - RemoteLogger.warn(`general chat message persistence failed: ${ConnectionErrorPolicy.errorText(err)}`); - return false; - } - } - - async deleteSession(session: RemoteSession, isBusy: boolean): Promise { - if (!this.isValidChatSession(session) || isBusy) { - return; - } - try { - this.callbacks.onBusy(true); - this.callbacks.onStatusText(RemoteI18n.t('status.deletingSession')); - await this.client.deleteSession(session.id); - this.callbacks.onSessions(this.client.sessions()); - this.callbacks.onStatusText(RemoteI18n.t('status.sessionDeleted')); - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } - - async archiveSession(session: RemoteSession, archived: boolean, isBusy: boolean): Promise { - if (!this.isValidChatSession(session) || isBusy) { - return; - } - try { - this.callbacks.onBusy(true); - await this.client.archiveSession(session.id, archived); - this.callbacks.onSessions(this.client.sessions()); - const statusText = RemoteI18n.t(archived ? 'status.sessionArchived' : 'status.sessionUnarchived'); - this.callbacks.onStatusText(statusText); - this.callbacks.onToast(statusText); - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } - - async pinSession(session: RemoteSession, pinned: boolean, isBusy: boolean): Promise { - if (!this.isValidChatSession(session) || isBusy) { - return; - } - try { - this.callbacks.onBusy(true); - await this.client.pinSession(session.id, pinned); - this.callbacks.onSessions(this.client.sessions()); - this.callbacks.onToast(pinned ? '已置顶会话' : '已取消置顶'); - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } - - async exportSession( - session: RemoteSession, - isBusy: boolean, - onExportText: (text: string) => Promise - ): Promise { - if (!this.isValidChatSession(session) || isBusy) { - return; - } - try { - this.callbacks.onBusy(true); - const messages = await this.client.messages(session.id); - await onExportText(GeneralChatExportFormatter.markdown(session, messages)); - const statusText = RemoteI18n.t('status.sessionExported'); - this.callbacks.onStatusText(statusText); - this.callbacks.onToast(statusText); - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - } finally { - this.callbacks.onBusy(false); - } - } - - async renameActiveSession(session: SessionSummary, title: string): Promise { - const sessionId = session.sessionId || ''; - const nextTitle = title.trim(); - if (sessionId.length === 0 || nextTitle.length === 0 || nextTitle === session.title) { - return false; - } - try { - await this.client.renameSession(sessionId, nextTitle); - this.callbacks.onSessions(this.client.sessions()); - this.callbacks.onActiveSession({ - sessionId, - title: nextTitle, - workspacePath: '', - agentType: 'chat', - initialTurnId: session.initialTurnId - }); - this.callbacks.onStatusText(RemoteI18n.t('status.titleUpdated')); - return true; - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - return false; - } - } - - async retryMessage(sessionId: string, text: string, isBusy: boolean): Promise { - if (isBusy || sessionId.length === 0) { - return false; - } - try { - await this.client.removeFailedUserMessage(sessionId, text); - this.callbacks.onMessagesLoaded(await this.client.messages(sessionId)); - this.callbacks.onChatInput(text); - return true; - } catch (err) { - this.callbacks.onStatusText(ConnectionErrorPolicy.errorText(err)); - return false; - } - } - - private isValidChatSession(session: RemoteSession): boolean { - return session.agentType === 'chat' && session.id.length > 0; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatConfigStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatConfigStore.ets deleted file mode 100644 index 13c28dc718..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatConfigStore.ets +++ /dev/null @@ -1,370 +0,0 @@ -import { preferences } from '@kit.ArkData'; -import { huks } from '@kit.UniversalKeystoreKit'; -import { RemoteModelCatalog, RemoteModelConfig } from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { Encoding } from '../Encoding'; -import { HarmonyUpgradeIdentityContract } from '../HarmonyUpgradeIdentityContract'; -import { OhosError } from '../OhosError'; -import { GeneralChatTokenProvider } from './GeneralChatHttpTransport'; - -const STORE_NAME = HarmonyUpgradeIdentityContract.GENERAL_CHAT_CONFIG_STORE; -const API_URL_KEY = 'api_url'; -const MODEL_NAME_KEY = 'model_name'; -const API_KEY_CIPHER_KEY = 'api_key_cipher'; -const API_KEY_IV_KEY = 'api_key_iv'; -const HUKS_ALIAS = HarmonyUpgradeIdentityContract.GENERAL_CHAT_HUKS_ALIAS; -const SELECTED_MODEL_ID_KEY = 'selected_model_id'; -export const GENERAL_CHAT_LOCAL_MODEL_ID = 'local-general-chat'; - -export interface GeneralChatConfigSnapshot { - apiUrl: string; - modelName: string; - hasApiKey: boolean; -} - -export interface GeneralChatConfigUpdate { - apiUrl: string; - modelName: string; - apiKey: string; - clearApiKey: boolean; -} - -export interface GeneralChatRuntimeModelConfig { - modelId: string; - name: string; - provider: string; - apiUrl: string; - modelName: string; - apiKey: string; -} - -export class GeneralChatModelSelectionPolicy { - static shouldActivateSavedLocalModel(catalog: RemoteModelCatalog): boolean { - const selectedModelId = catalog.session_model_id || catalog.default_models.primary || ''; - return !catalog.models.some((model: RemoteModelConfig): boolean => model.id === selectedModelId); - } -} - -export class GeneralChatConfigValidator { - static validate(update: GeneralChatConfigUpdate, hasExistingApiKey: boolean): string { - const apiUrl = update.apiUrl.trim(); - const modelName = update.modelName.trim(); - if (!GeneralChatConfigValidator.isHttpUrl(apiUrl)) { - return RemoteI18n.t('settings.modelService.invalidUrl'); - } - if (modelName.length === 0) { - return RemoteI18n.t('settings.modelService.modelRequired'); - } - if (!update.clearApiKey && update.apiKey.trim().length === 0 && !hasExistingApiKey) { - return RemoteI18n.t('settings.modelService.apiKeyRequired'); - } - return ''; - } - - private static isHttpUrl(value: string): boolean { - const lower = value.toLowerCase(); - if (!(lower.startsWith('https://') || lower.startsWith('http://'))) { - return false; - } - const schemeLength = lower.startsWith('https://') ? 8 : 7; - const hostAndPath = value.slice(schemeLength); - return hostAndPath.length > 0 && hostAndPath.indexOf(' ') < 0 && hostAndPath.indexOf('#') < 0; - } -} - -export class GeneralChatConfigStore implements GeneralChatTokenProvider { - private store?: preferences.Preferences; - private accountModels: GeneralChatRuntimeModelConfig[] = []; - private preferredModelId: string = GENERAL_CHAT_LOCAL_MODEL_ID; - private catalogRevision: number = 1; - - async init(context: Context): Promise { - try { - this.store = await preferences.getPreferences(context, STORE_NAME); - this.preferredModelId = await this.getString(SELECTED_MODEL_ID_KEY) || GENERAL_CHAT_LOCAL_MODEL_ID; - return this.snapshot(); - } catch (err) { - throw OhosError.wrap('general chat config init', err); - } - } - - async snapshot(): Promise { - try { - const store = this.requireStore(); - const cipher = await store.get(API_KEY_CIPHER_KEY, ''); - const iv = await store.get(API_KEY_IV_KEY, ''); - const hasStoredSecret = typeof cipher === 'string' && cipher.length > 0 && - typeof iv === 'string' && iv.length > 0; - const hasKeyItem = hasStoredSecret ? await this.keyItemExists() : false; - return { - apiUrl: await this.getString(API_URL_KEY), - modelName: await this.getString(MODEL_NAME_KEY), - hasApiKey: hasStoredSecret && hasKeyItem - }; - } catch (err) { - throw OhosError.wrap('general chat config snapshot', err); - } - } - - async save(update: GeneralChatConfigUpdate): Promise { - const current = await this.snapshot(); - const validationError = GeneralChatConfigValidator.validate(update, current.hasApiKey); - if (validationError.length > 0) { - throw new Error(validationError); - } - try { - const store = this.requireStore(); - await store.put(API_URL_KEY, GeneralChatConfigStore.normalizeBaseUrl(update.apiUrl)); - await store.put(MODEL_NAME_KEY, update.modelName.trim()); - if (update.clearApiKey) { - await store.delete(API_KEY_CIPHER_KEY); - await store.delete(API_KEY_IV_KEY); - } else if (update.apiKey.trim().length > 0) { - try { - const encrypted = await this.encryptApiKey(update.apiKey.trim()); - await store.put(API_KEY_CIPHER_KEY, encrypted.cipherText); - await store.put(API_KEY_IV_KEY, encrypted.iv); - } catch (_err) { - throw new Error(RemoteI18n.t('settings.modelService.secureStoreFailed')); - } - } - await store.flush(); - return this.snapshot(); - } catch (err) { - throw OhosError.wrap('general chat config save', err); - } - } - - async accessToken(): Promise { - const store = this.requireStore(); - const cipherText = await this.getString(API_KEY_CIPHER_KEY); - const iv = await this.getString(API_KEY_IV_KEY); - if (cipherText.length === 0 || iv.length === 0) { - return ''; - } - const exists = await this.keyItemExists(); - if (!exists) { - return ''; - } - return this.decryptApiKey(cipherText, iv); - } - - replaceAccountModels(models: GeneralChatRuntimeModelConfig[]): void { - this.accountModels = models.map((model: GeneralChatRuntimeModelConfig): GeneralChatRuntimeModelConfig => ({ - modelId: model.modelId, - name: model.name, - provider: model.provider, - apiUrl: model.apiUrl, - modelName: model.modelName, - apiKey: model.apiKey - })); - this.catalogRevision += 1; - } - - async modelCatalog(): Promise { - const local = await this.snapshot(); - const models: RemoteModelConfig[] = []; - if (GeneralChatConfigStore.isComplete(local)) { - models.push({ - id: GENERAL_CHAT_LOCAL_MODEL_ID, - name: local.modelName, - provider: 'local', - base_url: local.apiUrl, - model_name: local.modelName, - enabled: true, - capabilities: ['text_chat'] - }); - } - this.accountModels.forEach((model: GeneralChatRuntimeModelConfig) => { - models.push({ - id: model.modelId, - name: model.name || model.modelName, - provider: model.provider || 'account', - base_url: model.apiUrl, - model_name: model.modelName, - enabled: true, - capabilities: ['text_chat'] - }); - }); - const selectedModelId = this.effectiveSelectedModelId(models); - return { - version: this.catalogRevision, - models, - default_models: { primary: selectedModelId || undefined }, - session_model_id: selectedModelId || undefined - }; - } - - async selectModel(modelId: string): Promise { - const catalog = await this.modelCatalog(); - if (!catalog.models.some((model: RemoteModelConfig): boolean => model.id === modelId)) { - return false; - } - this.preferredModelId = modelId; - try { - const store = this.requireStore(); - await store.put(SELECTED_MODEL_ID_KEY, modelId); - await store.flush(); - } catch (err) { - throw OhosError.wrap('general chat config select model', err); - } - this.catalogRevision += 1; - return true; - } - - async selectLocalModel(): Promise { - this.preferredModelId = GENERAL_CHAT_LOCAL_MODEL_ID; - try { - const store = this.requireStore(); - await store.put(SELECTED_MODEL_ID_KEY, GENERAL_CHAT_LOCAL_MODEL_ID); - await store.flush(); - } catch (err) { - throw OhosError.wrap('general chat config select local model', err); - } - this.catalogRevision += 1; - } - - async activeSnapshot(): Promise { - const selectedModelId = this.effectiveSelectedModelId((await this.modelCatalog()).models); - const accountModel = this.accountModels.find((model: GeneralChatRuntimeModelConfig): boolean => { - return model.modelId === selectedModelId; - }); - if (accountModel) { - return { apiUrl: accountModel.apiUrl, modelName: accountModel.modelName, hasApiKey: true }; - } - return this.snapshot(); - } - - async activeAccessToken(): Promise { - const selectedModelId = this.effectiveSelectedModelId((await this.modelCatalog()).models); - const accountModel = this.accountModels.find((model: GeneralChatRuntimeModelConfig): boolean => { - return model.modelId === selectedModelId; - }); - return accountModel ? accountModel.apiKey : this.accessToken(); - } - - private async encryptApiKey(apiKey: string): Promise { - try { - await this.ensureHuksKey(); - const iv = Encoding.randomBytes(16); - const options = this.operationOptions(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, iv); - const session = await huks.initSession(HUKS_ALIAS, options); - const result = await huks.finishSession(session.handle, { - properties: options.properties, - inData: Encoding.utf8ToBytes(apiKey) - }); - if (!result.outData || result.outData.length === 0) { - throw new Error(RemoteI18n.t('settings.modelService.encryptFailed')); - } - return { - cipherText: Encoding.bytesToBase64(result.outData), - iv: Encoding.bytesToBase64(iv) - }; - } catch (err) { - throw OhosError.wrap('general chat encrypt api key', err); - } - } - - private async decryptApiKey(cipherText: string, ivText: string): Promise { - try { - const iv = Encoding.base64ToBytes(ivText); - const options = this.operationOptions(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, iv); - const session = await huks.initSession(HUKS_ALIAS, options); - const result = await huks.finishSession(session.handle, { - properties: options.properties, - inData: Encoding.base64ToBytes(cipherText) - }); - if (!result.outData) { - return ''; - } - return Encoding.bytesToUtf8(result.outData); - } catch (err) { - throw OhosError.wrap('general chat decrypt api key', err); - } - } - - private async ensureHuksKey(): Promise { - if (await this.keyItemExists()) { - return; - } - try { - await huks.generateKeyItem(HUKS_ALIAS, { - properties: [ - { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES }, - { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }, - { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - }, - { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC }, - { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 } - ] - }); - } catch (err) { - throw OhosError.wrap('general chat generate huks key', err); - } - } - - private async keyItemExists(): Promise { - try { - return await huks.isKeyItemExist(HUKS_ALIAS, {}); - } catch (err) { - const message = err instanceof Error ? err.message : JSON.stringify(err); - if (message.indexOf('12000011') >= 0 || message.toLowerCase().indexOf('does not exist') >= 0) { - return false; - } - throw new Error(message || 'HUKS key lookup failed.'); - } - } - - private operationOptions(purpose: huks.HuksKeyPurpose, iv: Uint8Array): huks.HuksOptions { - return { - properties: [ - { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES }, - { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: purpose }, - { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC }, - { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }, - { tag: huks.HuksTag.HUKS_TAG_IV, value: iv } - ] - }; - } - - private async getString(key: string): Promise { - try { - const value = await this.requireStore().get(key, ''); - return typeof value === 'string' ? value : ''; - } catch (err) { - throw OhosError.wrap('general chat config get string', err); - } - } - - private requireStore(): preferences.Preferences { - if (!this.store) { - throw new Error('General chat configuration store is not initialized.'); - } - return this.store; - } - - private effectiveSelectedModelId(models: RemoteModelConfig[]): string { - if (models.some((model: RemoteModelConfig): boolean => model.id === this.preferredModelId)) { - return this.preferredModelId; - } - const local = models.find((model: RemoteModelConfig): boolean => model.id === GENERAL_CHAT_LOCAL_MODEL_ID); - return local ? local.id : (models.length > 0 ? models[0].id : ''); - } - - private static isComplete(snapshot: GeneralChatConfigSnapshot): boolean { - return snapshot.apiUrl.trim().length > 0 && snapshot.modelName.trim().length > 0 && snapshot.hasApiKey; - } - - private static normalizeBaseUrl(value: string): string { - const trimmed = value.trim(); - return trimmed.endsWith('/') ? trimmed.slice(0, trimmed.length - 1) : trimmed; - } -} - -interface EncryptedApiKey { - cipherText: string; - iv: string; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatController.ets deleted file mode 100644 index a81ed03d48..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatController.ets +++ /dev/null @@ -1,87 +0,0 @@ -import { ChatMessage, ImageAttachment, RemoteSession } from '../../model/RemoteModels'; -import { GeneralChatCommandClient } from './GeneralChatCommandController'; -import { GeneralChatLocalRdbStore } from './GeneralChatLocalRdbStore'; -import { GeneralChatConfigStore } from './GeneralChatConfigStore'; -import { GeneralChatDraftStore, GeneralChatSendResult, GeneralChatStreamObserver } from './GeneralChatPort'; -import { GeneralChatRepository } from './GeneralChatRepository'; -import { ModelProviderGeneralChatAdapter } from './ModelProviderGeneralChatAdapter'; - -export class GeneralChatController implements GeneralChatCommandClient, GeneralChatDraftStore { - private readonly repository: GeneralChatRepository; - - constructor(repository: GeneralChatRepository) { - this.repository = repository; - } - - static createDefault(configStore: GeneralChatConfigStore): GeneralChatController { - return new GeneralChatController(new GeneralChatRepository( - new ModelProviderGeneralChatAdapter(configStore), - new GeneralChatLocalRdbStore() - )); - } - - async init(context: Context): Promise { - await this.repository.init(context); - } - - sessions(): RemoteSession[] { - return this.repository.listSessions(); - } - - async createSession(firstMessage: string): Promise { - return this.repository.createSession(firstMessage); - } - - async messages(sessionId: string): Promise { - return this.repository.messages(sessionId); - } - - async sendMessage( - sessionId: string, - text: string, - images: ImageAttachment[] = [], - observer?: GeneralChatStreamObserver - ): Promise { - return this.repository.sendMessage(sessionId, text, images, observer); - } - - cancelCurrentRequest(): void { - this.repository.cancelCurrentRequest(); - } - - async recordAssistantMessage(sessionId: string, message: ChatMessage): Promise { - await this.repository.recordAssistantMessage(sessionId, message); - } - - async renameSession(sessionId: string, title: string): Promise { - await this.repository.renameSession(sessionId, title); - } - - async archiveSession(sessionId: string, archived: boolean): Promise { - await this.repository.archiveSession(sessionId, archived); - } - - async pinSession(sessionId: string, pinned: boolean): Promise { - await this.repository.pinSession(sessionId, pinned); - } - - async deleteSession(sessionId: string): Promise { - await this.repository.deleteSession(sessionId); - } - - async draft(draftId: string): Promise { - return this.repository.draft(draftId); - } - - async saveDraft(draftId: string, text: string): Promise { - await this.repository.saveDraft(draftId, text); - } - - async clearDraft(draftId: string): Promise { - await this.repository.clearDraft(draftId); - } - - async removeFailedUserMessage(sessionId: string, text: string): Promise { - await this.repository.removeFailedUserMessage(sessionId, text); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftController.ets deleted file mode 100644 index 7ece71c257..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftController.ets +++ /dev/null @@ -1,114 +0,0 @@ -import { GeneralChatDraftStore } from './GeneralChatPort'; - -export interface GeneralChatDraftScheduler { - setTimeout(callback: () => void, delayMs: number): number; - clearTimeout(timerId: number): void; -} - -class SystemGeneralChatDraftScheduler implements GeneralChatDraftScheduler { - setTimeout(callback: () => void, delayMs: number): number { - return setTimeout(callback, delayMs); - } - - clearTimeout(timerId: number): void { - clearTimeout(timerId); - } -} - -export class GeneralChatDraftController { - private readonly store: GeneralChatDraftStore; - private readonly delayMs: number; - private readonly scheduler: GeneralChatDraftScheduler; - private readonly onError: (err: Error) => void; - private timerId: number = 0; - - constructor( - store: GeneralChatDraftStore, - delayMs: number = 250, - onError: (err: Error) => void = (_err: Error) => {}, - scheduler: GeneralChatDraftScheduler = new SystemGeneralChatDraftScheduler() - ) { - this.store = store; - this.delayMs = delayMs; - this.scheduler = scheduler; - this.onError = onError; - } - - scheduleSave(draftId: string, text: string): void { - if (draftId.length === 0) { - return; - } - this.cancel(); - this.timerId = this.scheduler.setTimeout(() => { - this.timerId = 0; - this.save(draftId, text); - }, this.delayMs); - } - - persistNow(draftId: string, text: string): void { - if (draftId.length === 0) { - return; - } - this.cancel(); - this.saveNow(draftId, text).catch((_err: Error) => {}); - } - - async saveNow(draftId: string, text: string): Promise { - if (draftId.length === 0) { - return; - } - this.cancel(); - try { - await this.store.saveDraft(draftId, text); - } catch (err) { - this.onError(err as Error); - } - } - - async restore(draftId: string): Promise { - if (draftId.length === 0) { - return ''; - } - try { - return await this.store.draft(draftId); - } catch (err) { - this.onError(err as Error); - return ''; - } - } - - clear(draftId: string): void { - if (draftId.length === 0) { - return; - } - this.cancel(); - this.clearNow(draftId).catch((_err: Error) => {}); - } - - async clearNow(draftId: string): Promise { - if (draftId.length === 0) { - return; - } - this.cancel(); - try { - await this.store.clearDraft(draftId); - } catch (err) { - this.onError(err as Error); - } - } - - cancel(): void { - if (this.timerId !== 0) { - this.scheduler.clearTimeout(this.timerId); - this.timerId = 0; - } - } - - isPending(): boolean { - return this.timerId !== 0; - } - - private save(draftId: string, text: string): void { - this.saveNow(draftId, text).catch((_err: Error) => {}); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftLifecycleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftLifecycleController.ets deleted file mode 100644 index bfa5fca6a9..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatDraftLifecycleController.ets +++ /dev/null @@ -1,61 +0,0 @@ -import { GeneralChatDraftController } from './GeneralChatDraftController'; - -export class GeneralChatDraftLifecycleController { - private readonly draftController: GeneralChatDraftController; - private readonly homeDraftId: string; - private readonly visibleDraftId: () => string; - - constructor( - draftController: GeneralChatDraftController, - homeDraftId: string, - visibleDraftId: () => string - ) { - this.draftController = draftController; - this.homeDraftId = homeDraftId; - this.visibleDraftId = visibleDraftId; - } - - cancel(): void { - this.draftController.cancel(); - } - - clear(draftId: string): void { - this.draftController.clear(draftId); - } - - clearHome(): void { - this.clear(this.homeDraftId); - } - - async clearHomeNow(): Promise { - await this.draftController.clearNow(this.homeDraftId); - } - - async restore(draftId: string): Promise { - return this.draftController.restore(draftId); - } - - async restoreHome(): Promise { - return this.restore(this.homeDraftId); - } - - scheduleVisible(text: string): void { - const draftId = this.visibleDraftId(); - if (draftId.length === 0) { - return; - } - this.draftController.scheduleSave(draftId, text); - } - - persistVisible(text: string): void { - const draftId = this.visibleDraftId(); - if (draftId.length === 0) { - return; - } - this.draftController.persistNow(draftId, text); - } - - async saveNow(draftId: string, text: string): Promise { - await this.draftController.saveNow(draftId, text); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatEventMapper.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatEventMapper.ets deleted file mode 100644 index 1ea540651c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatEventMapper.ets +++ /dev/null @@ -1,218 +0,0 @@ -import { RemoteToolStatusResponse } from '../../model/RemoteModels'; -import { GeneralChatApiTool, GeneralChatStreamEvent } from './GeneralChatApiModels'; - -export interface GeneralChatProjectionItem { - id: string; - type: string; - content: string; - tool?: RemoteToolStatusResponse; -} - -export interface GeneralChatTurnProjection { - sessionId: string; - turnId: string; - version: number; - text: string; - thinking: string; - status: string; - errorCode: string; - capabilityRequired: string; - tools: RemoteToolStatusResponse[]; - items: GeneralChatProjectionItem[]; -} - -export class GeneralChatEventMapper { - static emptyProjection(sessionId: string, turnId: string, version: number = 0): GeneralChatTurnProjection { - return { - sessionId, - turnId, - version, - text: '', - thinking: '', - status: 'starting', - errorCode: '', - capabilityRequired: '', - tools: [], - items: [] - }; - } - - static apply(current: GeneralChatTurnProjection, event: GeneralChatStreamEvent): GeneralChatTurnProjection { - if (event.session_id !== current.sessionId || event.turn_id !== current.turnId) { - throw new Error('General chat event does not belong to the active turn.'); - } - if (event.version <= current.version || GeneralChatEventMapper.isTerminal(current.status)) { - return current; - } - if (event.version !== current.version + 1) { - throw new Error(`General chat event version gap: expected ${current.version + 1}, received ${event.version}.`); - } - - const next: GeneralChatTurnProjection = { - sessionId: current.sessionId, - turnId: current.turnId, - version: event.version, - text: current.text, - thinking: current.thinking, - status: current.status, - errorCode: current.errorCode, - capabilityRequired: current.capabilityRequired, - tools: current.tools.slice(), - items: current.items.slice() - }; - if (event.type === 'turn.started') { - next.status = 'starting'; - } else if (event.type === 'message.delta') { - const delta = event.delta || ''; - next.text += delta; - next.items = GeneralChatEventMapper.appendTextItem(next.items, event.event_id, 'text', delta); - next.status = 'streaming'; - } else if (event.type === 'thinking.delta') { - const delta = event.delta || ''; - next.thinking += delta; - next.items = GeneralChatEventMapper.appendTextItem(next.items, event.event_id, 'thinking', delta); - next.status = 'thinking'; - } else if (GeneralChatEventMapper.isToolEvent(event.type)) { - if (event.tool) { - const mapped = GeneralChatEventMapper.mapTool(event.tool, event.type); - next.tools = GeneralChatEventMapper.upsertTool(next.tools, mapped); - next.items = GeneralChatEventMapper.upsertToolItem(next.items, mapped, event.event_id); - } - next.status = 'tool_calling'; - } else if (event.type === 'permission.required') { - if (event.tool) { - const mapped = GeneralChatEventMapper.mapTool(event.tool, event.type); - next.tools = GeneralChatEventMapper.upsertTool(next.tools, mapped); - next.items = GeneralChatEventMapper.upsertToolItem(next.items, mapped, event.event_id); - } - next.status = 'pending_confirmation'; - } else if (event.type === 'capability.required') { - next.capabilityRequired = event.capability || 'unknown'; - next.status = 'capability_required'; - } else if (event.type === 'turn.finishing') { - next.status = 'finishing'; - } else if (event.type === 'turn.completed') { - next.status = 'completed'; - } else if (event.type === 'turn.cancelled') { - next.status = 'cancelled'; - } else if (event.type === 'turn.failed') { - next.status = 'failed'; - next.errorCode = event.error_code || 'unknown'; - } - return next; - } - - private static appendTextItem( - items: GeneralChatProjectionItem[], - eventId: string, - type: string, - delta: string - ): GeneralChatProjectionItem[] { - if (delta.length === 0) { - return items; - } - const next = items.slice(); - const lastIndex = next.length - 1; - const last = lastIndex >= 0 ? next[lastIndex] : undefined; - if (last && last.type === type && !last.tool) { - next[lastIndex] = { - id: last.id, - type: last.type, - content: last.content + delta - }; - return next; - } - next.push({ - id: eventId, - type, - content: delta - }); - return next; - } - - private static upsertToolItem( - items: GeneralChatProjectionItem[], - incoming: RemoteToolStatusResponse, - eventId: string - ): GeneralChatProjectionItem[] { - const toolId = incoming.id || ''; - const index = items.findIndex((item: GeneralChatProjectionItem) => { - return !!item.tool && (item.tool?.id || '') === toolId; - }); - const mapped: GeneralChatProjectionItem = { - id: toolId.length > 0 ? toolId : eventId, - type: 'tool', - content: '', - tool: index < 0 || !items[index].tool ? incoming : - GeneralChatEventMapper.mergeTool(items[index].tool as RemoteToolStatusResponse, incoming) - }; - if (index < 0) { - return items.concat([mapped]); - } - const next = items.slice(); - next[index] = mapped; - return next; - } - - private static upsertTool( - tools: RemoteToolStatusResponse[], - incoming: RemoteToolStatusResponse - ): RemoteToolStatusResponse[] { - const incomingId = incoming.id || ''; - const index = tools.findIndex((tool: RemoteToolStatusResponse) => (tool.id || '') === incomingId); - if (index < 0) { - return tools.concat([incoming]); - } - const next = tools.slice(); - next[index] = GeneralChatEventMapper.mergeTool(tools[index], incoming); - return next; - } - - private static mergeTool( - previous: RemoteToolStatusResponse, - incoming: RemoteToolStatusResponse - ): RemoteToolStatusResponse { - return { - id: incoming.id || previous.id, - name: incoming.name || previous.name, - status: incoming.status || previous.status, - duration_ms: incoming.duration_ms !== undefined ? incoming.duration_ms : previous.duration_ms, - start_ms: incoming.start_ms !== undefined ? incoming.start_ms : previous.start_ms, - input_preview: (incoming.input_preview || '').length > 0 ? incoming.input_preview : previous.input_preview, - tool_input: incoming.tool_input !== undefined ? incoming.tool_input : previous.tool_input, - stdout: incoming.stdout !== undefined ? incoming.stdout : previous.stdout, - stderr: incoming.stderr !== undefined ? incoming.stderr : previous.stderr, - tool_output: incoming.tool_output !== undefined ? incoming.tool_output : previous.tool_output, - result_preview: incoming.result_preview !== undefined ? incoming.result_preview : previous.result_preview, - error_preview: incoming.error_preview !== undefined ? incoming.error_preview : previous.error_preview, - exit_code: incoming.exit_code !== undefined ? incoming.exit_code : previous.exit_code - }; - } - - private static mapTool(incoming: GeneralChatApiTool, eventType: string): RemoteToolStatusResponse { - let status = incoming.status; - if (eventType === 'permission.required') { - status = 'pending_confirmation'; - } else if (status.length === 0 && eventType === 'tool.started') { - status = 'preparing'; - } else if (status.length === 0 && eventType === 'tool.completed') { - status = 'completed'; - } - return { - id: incoming.id, - name: incoming.name, - status, - input_preview: incoming.input_preview, - result_preview: incoming.result_preview, - error_preview: incoming.error_preview - }; - } - - private static isToolEvent(type: string): boolean { - return type === 'tool.started' || type === 'tool.updated' || type === 'tool.completed'; - } - - private static isTerminal(status: string): boolean { - return status === 'completed' || status === 'cancelled' || status === 'failed'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatExportFormatter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatExportFormatter.ets deleted file mode 100644 index 9f08111064..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatExportFormatter.ets +++ /dev/null @@ -1,50 +0,0 @@ -import { ChatMessage, RemoteSession } from '../../model/RemoteModels'; - -export class GeneralChatExportFormatter { - static markdown(session: RemoteSession, messages: ChatMessage[]): string { - const title = session.title.trim().length > 0 ? session.title.trim() : '未命名会话'; - const firstUserContent = GeneralChatExportFormatter.firstVisibleUserContent(messages); - const sections: string[] = []; - if (!GeneralChatExportFormatter.repeatsFirstUserMessage(title, firstUserContent)) { - sections.push(`# ${title}`); - } - messages.forEach((message: ChatMessage) => { - const content = message.text.trim(); - if (content.length === 0) { - return; - } - sections.push(`## ${GeneralChatExportFormatter.roleLabel(message.role)}\n\n${content}`); - }); - return `${sections.join('\n\n')}\n`; - } - - private static firstVisibleUserContent(messages: ChatMessage[]): string { - for (let index = 0; index < messages.length; index += 1) { - const message = messages[index]; - if (message.role === 'user' && message.text.trim().length > 0) { - return message.text.trim(); - } - } - return ''; - } - - private static repeatsFirstUserMessage(title: string, firstUserContent: string): boolean { - if (firstUserContent.length === 0) { - return false; - } - return GeneralChatExportFormatter.comparableHeading(title) === - GeneralChatExportFormatter.comparableHeading(firstUserContent); - } - - private static comparableHeading(value: string): string { - return value - .trim() - .replace(/\s+/g, ' ') - .replace(/[。!?!?…,,;;::]+$/g, '') - .trim(); - } - - private static roleLabel(role: string): string { - return role === 'user' ? '用户' : 'OpenBitFun'; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatHttpTransport.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatHttpTransport.ets deleted file mode 100644 index 6a056955fc..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatHttpTransport.ets +++ /dev/null @@ -1,79 +0,0 @@ -import { http } from '@kit.NetworkKit'; -import { OhosError } from '../OhosError'; - -export enum GeneralChatHttpMethod { - Get = 'GET', - Post = 'POST', - Put = 'PUT', - Delete = 'DELETE' -} - -export interface GeneralChatHttpHeaders { - authorization: string; - contentType: string; - accept: string; -} - -export interface GeneralChatHttpResponse { - statusCode: number; - body: string; -} - -export interface GeneralChatHttpTransport { - request( - url: string, - method: GeneralChatHttpMethod, - headers: GeneralChatHttpHeaders, - body?: string - ): Promise; -} - -export interface GeneralChatTokenProvider { - accessToken(): Promise; -} - -export class HarmonyGeneralChatHttpTransport implements GeneralChatHttpTransport { - async request( - url: string, - method: GeneralChatHttpMethod, - headers: GeneralChatHttpHeaders, - body?: string - ): Promise { - const request = http.createHttp(); - try { - const response = await request.request(url, { - method: this.requestMethod(method), - header: { - 'Authorization': headers.authorization, - 'Content-Type': headers.contentType, - 'Accept': headers.accept - }, - extraData: body || '', - expectDataType: http.HttpDataType.STRING, - connectTimeout: 15000, - readTimeout: 30000 - }); - return { - statusCode: response.responseCode, - body: typeof response.result === 'string' ? response.result : JSON.stringify(response.result) - }; - } catch (err) { - throw OhosError.wrap('general chat http request', err); - } finally { - request.destroy(); - } - } - - private requestMethod(method: GeneralChatHttpMethod): http.RequestMethod { - if (method === GeneralChatHttpMethod.Get) { - return http.RequestMethod.GET; - } - if (method === GeneralChatHttpMethod.Put) { - return http.RequestMethod.PUT; - } - if (method === GeneralChatHttpMethod.Delete) { - return http.RequestMethod.DELETE; - } - return http.RequestMethod.POST; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatLocalRdbStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatLocalRdbStore.ets deleted file mode 100644 index 9d702a9925..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatLocalRdbStore.ets +++ /dev/null @@ -1,196 +0,0 @@ -import { relationalStore } from '@kit.ArkData'; -import { ChatMessage, RemoteSession } from '../../model/RemoteModels'; -import { Encoding } from '../Encoding'; -import { OhosError } from '../OhosError'; -import { HarmonyUpgradeIdentityContract } from '../HarmonyUpgradeIdentityContract'; -import { GeneralChatLocalStore } from './GeneralChatPort'; - -const STORE_CONFIG: relationalStore.StoreConfig = { - name: HarmonyUpgradeIdentityContract.GENERAL_CHAT_DATABASE, - securityLevel: relationalStore.SecurityLevel.S1 -}; - -const CREATE_SESSIONS_SQL = - 'CREATE TABLE IF NOT EXISTS general_chat_sessions (' + - 'id TEXT PRIMARY KEY, updated_at TEXT NOT NULL, payload TEXT NOT NULL)'; -const CREATE_MESSAGES_SQL = - 'CREATE TABLE IF NOT EXISTS general_chat_messages (' + - 'id TEXT PRIMARY KEY, session_id TEXT NOT NULL, sort_order INTEGER NOT NULL, payload TEXT NOT NULL)'; -const CREATE_DRAFTS_SQL = - 'CREATE TABLE IF NOT EXISTS general_chat_drafts (' + - 'draft_id TEXT PRIMARY KEY, text TEXT NOT NULL, updated_at TEXT NOT NULL)'; - -export class GeneralChatLocalRdbStore implements GeneralChatLocalStore { - private store?: relationalStore.RdbStore; - - async init(context: Context): Promise { - try { - this.store = await relationalStore.getRdbStore(context, STORE_CONFIG); - await this.store.executeSql(CREATE_SESSIONS_SQL); - await this.store.executeSql(CREATE_MESSAGES_SQL); - await this.store.executeSql(CREATE_DRAFTS_SQL); - await this.store.executeSql( - 'CREATE INDEX IF NOT EXISTS idx_general_chat_messages_session ' + - 'ON general_chat_messages(session_id, sort_order)' - ); - } catch (err) { - throw OhosError.wrap('general chat store init', err); - } - } - - async listSessions(): Promise { - try { - const store = this.requireStore(); - const result = await store.querySql( - 'SELECT payload FROM general_chat_sessions ORDER BY updated_at DESC' - ); - const sessions: RemoteSession[] = []; - try { - const payloadColumn = result.getColumnIndex('payload'); - while (result.goToNextRow()) { - sessions.push(Encoding.parseJsonObject(result.getString(payloadColumn))); - } - } finally { - GeneralChatLocalRdbStore.closeResult(result); - } - return sessions; - } catch (err) { - throw OhosError.wrap('general chat list sessions', err); - } - } - - async loadMessages(sessionId: string): Promise { - try { - const store = this.requireStore(); - const result = await store.querySql( - 'SELECT payload FROM general_chat_messages WHERE session_id = ? ORDER BY sort_order ASC', - [sessionId] - ); - const messages: ChatMessage[] = []; - try { - const payloadColumn = result.getColumnIndex('payload'); - while (result.goToNextRow()) { - messages.push(Encoding.parseJsonObject(result.getString(payloadColumn))); - } - } finally { - GeneralChatLocalRdbStore.closeResult(result); - } - return messages; - } catch (err) { - throw OhosError.wrap('general chat load messages', err); - } - } - - async upsertSession(session: RemoteSession): Promise { - try { - const values: relationalStore.ValuesBucket = { - id: session.id, - updated_at: session.updatedAt, - payload: JSON.stringify(session) - }; - await this.requireStore().insert( - 'general_chat_sessions', - values, - relationalStore.ConflictResolution.ON_CONFLICT_REPLACE - ); - } catch (err) { - throw OhosError.wrap('general chat upsert session', err); - } - } - - async replaceMessages(sessionId: string, messages: ChatMessage[]): Promise { - try { - const store = this.requireStore(); - await store.executeSql('DELETE FROM general_chat_messages WHERE session_id = ?', [sessionId]); - for (let index = 0; index < messages.length; index++) { - const message = messages[index]; - const values: relationalStore.ValuesBucket = { - id: message.id, - session_id: sessionId, - sort_order: index, - payload: JSON.stringify(message) - }; - await store.insert( - 'general_chat_messages', - values, - relationalStore.ConflictResolution.ON_CONFLICT_REPLACE - ); - } - } catch (err) { - throw OhosError.wrap('general chat replace messages', err); - } - } - - async deleteSession(sessionId: string): Promise { - try { - const store = this.requireStore(); - await store.executeSql('DELETE FROM general_chat_messages WHERE session_id = ?', [sessionId]); - await store.executeSql('DELETE FROM general_chat_drafts WHERE draft_id = ?', [sessionId]); - await store.executeSql('DELETE FROM general_chat_sessions WHERE id = ?', [sessionId]); - } catch (err) { - throw OhosError.wrap('general chat delete session', err); - } - } - - async loadDraft(draftId: string): Promise { - try { - const result = await this.requireStore().querySql( - 'SELECT text FROM general_chat_drafts WHERE draft_id = ?', - [draftId] - ); - try { - if (!result.goToNextRow()) { - return ''; - } - return result.getString(result.getColumnIndex('text')); - } finally { - GeneralChatLocalRdbStore.closeResult(result); - } - } catch (err) { - throw OhosError.wrap('general chat load draft', err); - } - } - - async saveDraft(draftId: string, text: string): Promise { - try { - const values: relationalStore.ValuesBucket = { - draft_id: draftId, - text, - updated_at: new Date().toISOString() - }; - await this.requireStore().insert( - 'general_chat_drafts', - values, - relationalStore.ConflictResolution.ON_CONFLICT_REPLACE - ); - } catch (err) { - throw OhosError.wrap('general chat save draft', err); - } - } - - async deleteDraft(draftId: string): Promise { - try { - await this.requireStore().executeSql( - 'DELETE FROM general_chat_drafts WHERE draft_id = ?', - [draftId] - ); - } catch (err) { - throw OhosError.wrap('general chat delete draft', err); - } - } - - private static closeResult(result: relationalStore.ResultSet): void { - try { - result.close(); - } catch (err) { - throw OhosError.wrap('general chat close cursor', err); - } - } - - private requireStore(): relationalStore.RdbStore { - if (!this.store) { - throw new Error('General chat local store is not initialized.'); - } - return this.store; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatPort.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatPort.ets deleted file mode 100644 index a6db11a36a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatPort.ets +++ /dev/null @@ -1,65 +0,0 @@ -import { ChatMessage, ImageAttachment, RemoteSession, RemoteToolStatusResponse } from '../../model/RemoteModels'; - -export interface GeneralChatSendResult { - userMessage: ChatMessage; - assistantMessage: ChatMessage; - streamChunks: string[]; - tools: RemoteToolStatusResponse[]; -} - -export interface GeneralChatStreamObserver { - onUserMessage(message: ChatMessage): Promise; - onDelta(delta: string): void; -} - -export class GeneralChatStreamCallbacks implements GeneralChatStreamObserver { - private readonly userMessageCallback: (message: ChatMessage) => Promise; - private readonly deltaCallback: (delta: string) => void; - - constructor( - userMessageCallback: (message: ChatMessage) => Promise, - deltaCallback: (delta: string) => void - ) { - this.userMessageCallback = userMessageCallback; - this.deltaCallback = deltaCallback; - } - - async onUserMessage(message: ChatMessage): Promise { - await this.userMessageCallback(message); - } - - onDelta(delta: string): void { - this.deltaCallback(delta); - } -} - -export interface GeneralChatPort { - createSession(firstMessage: string): Promise; - sendMessage( - sessionId: string, - text: string, - images?: ImageAttachment[], - history?: ChatMessage[], - observer?: GeneralChatStreamObserver - ): Promise; - cancelCurrentRequest(): void; - generateTitle(firstMessage: string, assistantMessage: string): Promise; -} - -export interface GeneralChatLocalStore { - init(context: Context): Promise; - listSessions(): Promise; - loadMessages(sessionId: string): Promise; - upsertSession(session: RemoteSession): Promise; - replaceMessages(sessionId: string, messages: ChatMessage[]): Promise; - deleteSession(sessionId: string): Promise; - loadDraft(draftId: string): Promise; - saveDraft(draftId: string, text: string): Promise; - deleteDraft(draftId: string): Promise; -} - -export interface GeneralChatDraftStore { - draft(draftId: string): Promise; - saveDraft(draftId: string, text: string): Promise; - clearDraft(draftId: string): Promise; -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatRepository.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatRepository.ets deleted file mode 100644 index 911f69952c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatRepository.ets +++ /dev/null @@ -1,370 +0,0 @@ -import { ChatMessage, ImageAttachment, RemoteSession } from '../../model/RemoteModels'; -import { - GeneralChatLocalStore, - GeneralChatPort, - GeneralChatSendResult, - GeneralChatStreamCallbacks, - GeneralChatStreamObserver -} from './GeneralChatPort'; - -export class GeneralChatRepository { - private sessions: RemoteSession[] = []; - private messagesBySession: Map = new Map(); - private readonly port: GeneralChatPort; - private readonly localStore: GeneralChatLocalStore; - private requestCancelled: boolean = false; - - constructor(port: GeneralChatPort, localStore: GeneralChatLocalStore) { - this.port = port; - this.localStore = localStore; - } - - async init(context: Context): Promise { - await this.localStore.init(context); - await this.restoreFromLocal(); - } - - async restoreFromLocal(): Promise { - this.sessions = await this.localStore.listSessions(); - this.sortSessions(); - } - - listSessions(): RemoteSession[] { - return this.sessions.slice(); - } - - async createSession(firstMessage: string): Promise { - const session = await this.port.createSession(firstMessage); - this.sessions = [session].concat(this.sessions.filter((item: RemoteSession) => item.id !== session.id)); - this.messagesBySession.set(session.id, []); - await this.localStore.upsertSession(session); - return session; - } - - async messages(sessionId: string): Promise { - const cached = this.messagesBySession.get(sessionId); - if (cached) { - return cached.slice(); - } - const stored = await this.localStore.loadMessages(sessionId); - const normalized = stored.map((message: ChatMessage) => GeneralChatRepository.persistableMessage(message)); - this.messagesBySession.set(sessionId, normalized); - if (normalized.some((message: ChatMessage, index: number) => { - return message.detail !== stored[index].detail; - })) { - await this.localStore.replaceMessages(sessionId, normalized); - } - return normalized.slice(); - } - - async sendMessage( - sessionId: string, - text: string, - images: ImageAttachment[] = [], - observer?: GeneralChatStreamObserver - ): Promise { - const existingMessages = await this.messages(sessionId); - let didPersistUserMessage = false; - let didReceiveDelta = false; - let persistedUserMessage: ChatMessage | undefined = undefined; - this.requestCancelled = false; - const repositoryObserver = new GeneralChatStreamCallbacks( - async (message: ChatMessage): Promise => { - persistedUserMessage = message; - const messages = existingMessages.concat([message]); - this.messagesBySession.set(sessionId, messages); - await this.localStore.replaceMessages(sessionId, messages); - await this.bumpSession(sessionId, messages.length); - didPersistUserMessage = true; - if (observer) { - await observer.onUserMessage(message); - } - }, - (delta: string): void => { - if (delta.length > 0) { - didReceiveDelta = true; - } - if (observer) { - observer.onDelta(delta); - } - } - ); - try { - const result = await this.port.sendMessage(sessionId, text, images, existingMessages, repositoryObserver); - const sentUserMessage = GeneralChatRepository.messageWithStatus(result.userMessage, 'sent'); - if (!didPersistUserMessage) { - const messages = existingMessages.concat([sentUserMessage]); - this.messagesBySession.set(sessionId, messages); - await this.localStore.replaceMessages(sessionId, messages); - await this.bumpSession(sessionId, messages.length); - } else { - await this.replaceMessage(sessionId, sentUserMessage); - } - return { - userMessage: sentUserMessage, - assistantMessage: result.assistantMessage, - streamChunks: result.streamChunks, - tools: result.tools - }; - } catch (err) { - if (persistedUserMessage) { - const status = this.requestCancelled || didReceiveDelta ? 'sent' : 'failed'; - await this.replaceMessage(sessionId, GeneralChatRepository.messageWithStatus(persistedUserMessage, status)); - } - const message = err instanceof Error ? err.message : `${err}`; - throw new Error(message); - } finally { - this.requestCancelled = false; - } - } - - cancelCurrentRequest(): void { - this.requestCancelled = true; - this.port.cancelCurrentRequest(); - } - - async recordAssistantMessage(sessionId: string, message: ChatMessage): Promise { - const persistedMessage = GeneralChatRepository.persistableMessage(message); - const messages = (await this.messages(sessionId)) - .filter((item: ChatMessage) => item.id !== persistedMessage.id) - .concat([persistedMessage]); - this.messagesBySession.set(sessionId, messages); - await this.localStore.replaceMessages(sessionId, messages); - await this.bumpSession(sessionId, messages.length); - await this.generateFirstTurnTitle(sessionId, messages); - } - - private async generateFirstTurnTitle(sessionId: string, messages: ChatMessage[]): Promise { - const session = this.sessions.find((item: RemoteSession) => item.id === sessionId); - if (!session || session.titleGenerated === true) { - return; - } - const userMessages = messages.filter((item: ChatMessage) => item.role === 'user'); - const assistantMessages = messages.filter((item: ChatMessage) => item.role === 'assistant'); - if (userMessages.length !== 1 || assistantMessages.length !== 1) { - return; - } - try { - const title = await this.port.generateTitle(userMessages[0].text, assistantMessages[0].text); - if (title.trim().length === 0) { - return; - } - const updated: RemoteSession = { - id: session.id, - title: title.trim(), - agentType: session.agentType, - status: session.status, - updatedAt: session.updatedAt, - createdAt: session.createdAt, - messageCount: session.messageCount, - workspacePath: session.workspacePath, - workspaceName: session.workspaceName, - pinned: session.pinned, - titleGenerated: true - }; - this.replaceSession(updated); - await this.localStore.upsertSession(updated); - } catch (_err) { - } - } - - async renameSession(sessionId: string, title: string): Promise { - const nextTitle = title.trim(); - if (nextTitle.length === 0) { - return; - } - const session = this.sessions.find((item: RemoteSession) => item.id === sessionId); - if (!session) { - return; - } - const updated: RemoteSession = { - id: session.id, - title: nextTitle, - agentType: session.agentType, - status: session.status, - updatedAt: new Date().toISOString(), - createdAt: session.createdAt, - messageCount: session.messageCount, - workspacePath: session.workspacePath, - workspaceName: session.workspaceName, - pinned: session.pinned, - titleGenerated: session.titleGenerated - }; - this.replaceSession(updated); - await this.localStore.upsertSession(updated); - } - - async archiveSession(sessionId: string, archived: boolean): Promise { - const session = this.sessions.find((item: RemoteSession) => item.id === sessionId); - if (!session) { - return; - } - const updated: RemoteSession = { - id: session.id, - title: session.title, - agentType: session.agentType, - status: archived ? 'archived' : 'ready', - updatedAt: new Date().toISOString(), - createdAt: session.createdAt, - messageCount: session.messageCount, - workspacePath: session.workspacePath, - workspaceName: session.workspaceName, - pinned: session.pinned, - titleGenerated: session.titleGenerated - }; - this.replaceSession(updated); - await this.localStore.upsertSession(updated); - } - - async pinSession(sessionId: string, pinned: boolean): Promise { - for (let index = 0; index < this.sessions.length; index++) { - const session = this.sessions[index]; - const nextPinned = session.id === sessionId ? pinned : false; - if ((session.pinned === true) === nextPinned) { - continue; - } - const updated: RemoteSession = { - id: session.id, - title: session.title, - agentType: session.agentType, - status: session.status, - updatedAt: session.updatedAt, - createdAt: session.createdAt, - messageCount: session.messageCount, - workspacePath: session.workspacePath, - workspaceName: session.workspaceName, - pinned: nextPinned, - titleGenerated: session.titleGenerated - }; - this.sessions[index] = updated; - await this.localStore.upsertSession(updated); - } - } - - async deleteSession(sessionId: string): Promise { - this.sessions = this.sessions.filter((item: RemoteSession) => item.id !== sessionId); - this.messagesBySession.delete(sessionId); - await this.localStore.deleteSession(sessionId); - } - - async draft(draftId: string): Promise { - return this.localStore.loadDraft(draftId); - } - - async saveDraft(draftId: string, text: string): Promise { - if (text.length === 0) { - await this.localStore.deleteDraft(draftId); - return; - } - await this.localStore.saveDraft(draftId, text); - } - - async clearDraft(draftId: string): Promise { - await this.localStore.deleteDraft(draftId); - } - - async removeFailedUserMessage(sessionId: string, text: string): Promise { - const normalizedText = text.trim(); - const messages = await this.messages(sessionId); - let removeIndex = -1; - for (let index = messages.length - 1; index >= 0; index--) { - const message = messages[index]; - if (message.role === 'user' && message.status === 'failed' && - message.text.trim() === normalizedText) { - removeIndex = index; - break; - } - } - if (removeIndex < 0) { - return; - } - const remaining = messages.slice(0, removeIndex).concat(messages.slice(removeIndex + 1)); - this.messagesBySession.set(sessionId, remaining); - await this.localStore.replaceMessages(sessionId, remaining); - await this.bumpSession(sessionId, remaining.length); - } - - private async replaceMessage(sessionId: string, message: ChatMessage): Promise { - const messages = (await this.messages(sessionId)).map((item: ChatMessage) => { - return item.id === message.id ? message : item; - }); - this.messagesBySession.set(sessionId, messages); - await this.localStore.replaceMessages(sessionId, messages); - } - - private async bumpSession(sessionId: string, messageCount: number): Promise { - const session = this.sessions.find((item: RemoteSession) => item.id === sessionId); - if (!session) { - return; - } - const updated: RemoteSession = { - id: session.id, - title: session.title, - agentType: session.agentType, - status: 'ready', - updatedAt: new Date().toISOString(), - createdAt: session.createdAt, - messageCount, - workspacePath: session.workspacePath, - workspaceName: session.workspaceName, - pinned: session.pinned, - titleGenerated: session.titleGenerated - }; - this.replaceSession(updated); - await this.localStore.upsertSession(updated); - } - - private replaceSession(session: RemoteSession): void { - this.sessions = this.sessions.map((item: RemoteSession) => item.id === session.id ? session : item); - this.sortSessions(); - } - - private sortSessions(): void { - this.sessions.sort((first: RemoteSession, second: RemoteSession) => { - return GeneralChatRepository.timeValue(second.updatedAt) - GeneralChatRepository.timeValue(first.updatedAt); - }); - } - - private static timeValue(value: string): number { - const parsed = new Date(value).getTime(); - return Number.isNaN(parsed) ? 0 : parsed; - } - - private static messageWithStatus(message: ChatMessage, status: string): ChatMessage { - return { - id: message.id, - role: message.role, - text: message.text, - status, - renderVersion: message.renderVersion, - turnId: message.turnId, - detail: message.detail, - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: message.items, - images: message.images - }; - } - - private static persistableMessage(message: ChatMessage): ChatMessage { - if (message.role !== 'assistant' || (message.status || '').toLowerCase() !== 'failed' || - (message.detail || '').length === 0) { - return message; - } - return { - id: message.id, - role: message.role, - text: message.text, - status: message.status, - renderVersion: message.renderVersion, - turnId: message.turnId, - detail: '', - timestamp: message.timestamp, - thinking: message.thinking, - tools: message.tools, - items: message.items, - images: message.images - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatServiceState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatServiceState.ets deleted file mode 100644 index 3f070df836..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatServiceState.ets +++ /dev/null @@ -1,63 +0,0 @@ -import { RemoteI18n } from '../../i18n/RemoteI18n'; - -export enum GeneralChatServiceState { - Unconfigured = 'unconfigured', - Ready = 'ready', - Sending = 'sending', - Streaming = 'streaming', - Offline = 'offline', - AuthExpired = 'authExpired', - Failed = 'failed' -} - -export class GeneralChatServiceStatus { - static fromConfiguration(apiUrl: string, modelName: string, hasApiKey: boolean): GeneralChatServiceState { - return apiUrl.trim().length > 0 && modelName.trim().length > 0 && hasApiKey ? - GeneralChatServiceState.Ready : GeneralChatServiceState.Unconfigured; - } - - static fromError(message: string): GeneralChatServiceState { - const normalized = message.trim().toLowerCase(); - if (RemoteI18n.textEquals('generalChat.authenticationFailed', message) || - normalized.indexOf('authentication') >= 0 || normalized.indexOf('api key') >= 0) { - return GeneralChatServiceState.AuthExpired; - } - if (normalized.indexOf('network') >= 0 || normalized.indexOf('dns') >= 0 || - normalized.indexOf('timeout') >= 0 || normalized.indexOf('socket') >= 0 || - normalized.indexOf('connect') >= 0) { - return GeneralChatServiceState.Offline; - } - return GeneralChatServiceState.Failed; - } - - static connectionState(state: GeneralChatServiceState): string { - if (state === GeneralChatServiceState.Offline || - state === GeneralChatServiceState.AuthExpired || state === GeneralChatServiceState.Failed || - state === GeneralChatServiceState.Unconfigured) { - return 'failed'; - } - return 'connected'; - } - - static userMessage(state: GeneralChatServiceState, fallback: string = ''): string { - if (state === GeneralChatServiceState.Unconfigured) { - return RemoteI18n.t('generalChat.modelNotConfigured'); - } - if (state === GeneralChatServiceState.Offline) { - return RemoteI18n.t('generalChat.offline'); - } - if (state === GeneralChatServiceState.AuthExpired) { - return RemoteI18n.t('generalChat.authenticationFailed'); - } - if (state === GeneralChatServiceState.Failed) { - return fallback.length > 0 ? fallback : RemoteI18n.t('generalChat.serviceUnavailable'); - } - if (state === GeneralChatServiceState.Sending) { - return RemoteI18n.t('generalChat.sending'); - } - if (state === GeneralChatServiceState.Streaming) { - return RemoteI18n.t('generalChat.generating'); - } - return RemoteI18n.t('generalChat.ready'); - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamCoordinator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamCoordinator.ets deleted file mode 100644 index 5d1044e39a..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamCoordinator.ets +++ /dev/null @@ -1,95 +0,0 @@ -import { ChatMessage, ChatMessageItemResponse } from '../../model/RemoteModels'; -import { Encoding } from '../Encoding'; - -export class GeneralChatStreamCoordinator { - private sessionId: string = ''; - private turnId: string = ''; - private accumulatedText: string = ''; - private pendingDelta: string = ''; - private deltaTimerId: number = 0; - - begin(sessionId: string, turnId: string = ''): ChatMessage { - this.reset(); - this.sessionId = sessionId; - this.turnId = turnId.length > 0 ? turnId : Encoding.randomId('turn'); - return this.activeMessage(); - } - - append( - sessionId: string, - delta: string, - isVisible: () => boolean, - onFlush: (message: ChatMessage) => void - ): boolean { - if (delta.length === 0 || this.sessionId !== sessionId || !isVisible()) { - return false; - } - this.pendingDelta += delta; - if (this.deltaTimerId === 0) { - this.deltaTimerId = setTimeout(() => { - this.deltaTimerId = 0; - const message = this.flush(sessionId, isVisible()); - if (message) { - onFlush(message); - } - }, 32); - } - return true; - } - - flush(sessionId: string, visible: boolean): ChatMessage | undefined { - if (this.pendingDelta.length === 0 || this.sessionId !== sessionId || !visible) { - return undefined; - } - this.accumulatedText = (this.accumulatedText + this.pendingDelta).replace(/\n{3,}/g, '\n\n'); - this.pendingDelta = ''; - return this.activeMessage(); - } - - reset(): void { - if (this.deltaTimerId !== 0) { - clearTimeout(this.deltaTimerId); - this.deltaTimerId = 0; - } - this.sessionId = ''; - this.turnId = ''; - this.accumulatedText = ''; - this.pendingDelta = ''; - } - - currentSessionId(): string { - return this.sessionId; - } - - currentTurnId(): string { - return this.turnId; - } - - text(): string { - return this.accumulatedText; - } - - hasActiveStream(): boolean { - return this.sessionId.length > 0 || this.turnId.length > 0 || this.deltaTimerId !== 0; - } - - private activeMessage(): ChatMessage { - const items: ChatMessageItemResponse[] = []; - if (this.accumulatedText.trim().length > 0) { - items.push({ - type: 'text', - content: this.accumulatedText - }); - } - return { - id: `active-${this.turnId}`, - turnId: this.turnId, - role: 'assistant', - text: this.accumulatedText, - status: 'active', - detail: '', - items, - renderVersion: this.accumulatedText.length - }; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamLifecycleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamLifecycleController.ets deleted file mode 100644 index ea2a2f6e1e..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/GeneralChatStreamLifecycleController.ets +++ /dev/null @@ -1,76 +0,0 @@ -import { ChatMessage } from '../../model/RemoteModels'; -import { GeneralChatStreamCoordinator } from './GeneralChatStreamCoordinator'; - -export class GeneralChatStreamLifecycleController { - private readonly coordinator: GeneralChatStreamCoordinator = new GeneralChatStreamCoordinator(); - private requestCancelled: boolean = false; - private requestInFlight: boolean = false; - private pendingFinalMessage?: ChatMessage; - - begin(sessionId: string): ChatMessage { - this.requestCancelled = false; - this.pendingFinalMessage = undefined; - return this.coordinator.begin(sessionId); - } - - append( - sessionId: string, - delta: string, - isVisible: () => boolean, - onFlush: (message: ChatMessage) => void - ): boolean { - return this.coordinator.append(sessionId, delta, isVisible, onFlush); - } - - flush(sessionId: string, visible: boolean): ChatMessage | undefined { - return this.coordinator.flush(sessionId, visible); - } - - reset(): void { - this.coordinator.reset(); - } - - text(): string { - return this.coordinator.text(); - } - - currentSessionId(): string { - return this.coordinator.currentSessionId(); - } - - currentTurnId(): string { - return this.coordinator.currentTurnId(); - } - - hasActiveStream(): boolean { - return this.coordinator.hasActiveStream(); - } - - setRequestInFlight(requestInFlight: boolean): void { - this.requestInFlight = requestInFlight; - } - - isRequestInFlight(): boolean { - return this.requestInFlight; - } - - markRequestCancelled(): void { - this.requestCancelled = true; - } - - takeRequestCancelled(): boolean { - const cancelled = this.requestCancelled; - this.requestCancelled = false; - return cancelled; - } - - setPendingFinalMessage(message: ChatMessage): void { - this.pendingFinalMessage = message; - } - - takePendingFinalMessage(): ChatMessage | undefined { - const message = this.pendingFinalMessage; - this.pendingFinalMessage = undefined; - return message; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/MockGeneralChatAdapter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/MockGeneralChatAdapter.ets deleted file mode 100644 index ae9cca3f13..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/MockGeneralChatAdapter.ets +++ /dev/null @@ -1,300 +0,0 @@ -import { ChatMessage, ChatMessageItemResponse, ImageAttachment, RemoteSession, RemoteToolStatusResponse } from '../../model/RemoteModels'; -import { Encoding } from '../Encoding'; -import { GeneralChatPort, GeneralChatSendResult, GeneralChatStreamObserver } from './GeneralChatPort'; - -export class MockGeneralChatAdapter implements GeneralChatPort { - async generateTitle(firstMessage: string, _assistantMessage: string): Promise { - return firstMessage.trim().slice(0, 12); - } - async createSession(firstMessage: string): Promise { - const now = new Date().toISOString(); - const title = MockGeneralChatAdapter.titleFromMessage(firstMessage); - const session: RemoteSession = { - id: Encoding.randomId('chat'), - title, - agentType: 'chat', - status: 'ready', - updatedAt: now, - createdAt: now, - messageCount: 0, - workspacePath: '', - workspaceName: 'OpenBitFun' - }; - return session; - } - - async sendMessage( - _sessionId: string, - text: string, - images: ImageAttachment[] = [], - _history: ChatMessage[] = [], - observer?: GeneralChatStreamObserver - ): Promise { - const trimmed = text.trim(); - const now = new Date().toISOString(); - const userMessage: ChatMessage = { - id: Encoding.randomId('msg'), - role: 'user', - text: trimmed, - status: 'pending', - timestamp: now, - images - }; - const tools = MockGeneralChatAdapter.toolsFor(trimmed, images); - const assistantMessage: ChatMessage = { - id: Encoding.randomId('assistant'), - turnId: Encoding.randomId('turn'), - role: 'assistant', - text: MockGeneralChatAdapter.replyFor(trimmed, images), - status: 'completed', - timestamp: new Date().toISOString(), - tools, - items: MockGeneralChatAdapter.itemsFor(tools, MockGeneralChatAdapter.replyFor(trimmed, images)) - }; - if (observer) { - await observer.onUserMessage(userMessage); - MockGeneralChatAdapter.streamChunks(assistantMessage.text).forEach((delta: string) => { - observer.onDelta(delta); - }); - } - return { - userMessage, - assistantMessage, - streamChunks: MockGeneralChatAdapter.streamChunks(assistantMessage.text), - tools - }; - } - - cancelCurrentRequest(): void { - } - - private static titleFromMessage(text: string): string { - const normalized = text.trim().replace(/\s+/g, ' '); - if (normalized.length === 0) { - return '新建聊天'; - } - return normalized.length > 18 ? `${normalized.slice(0, 18)}...` : normalized; - } - - private static replyFor(text: string, images: ImageAttachment[]): string { - const normalized = text.trim(); - if (images.length > 0) { - return [ - '我可以作为手机端助手处理图片。', - '', - '当前是 mock 流程:我会模拟图片理解、重点提取和后续追问;接入 OpenBitFun harness 后,这里会真正把图片内容交给视觉模型分析。', - '', - '你可以继续问我:这张图里有什么、帮我提取文字、总结界面问题,或者让它和一个文件/网页一起分析。' - ].join('\n'); - } - if (MockGeneralChatAdapter.looksLikeSearchTask(normalized)) { - return [ - '我可以帮你做网络搜索和资料整理。', - '', - '当前是 mock 搜索流程:我会先判断搜索关键词,再模拟抓取多来源信息,最后给你摘要、要点和可继续追问的问题。接入 OpenBitFun harness 后,这里会真正调用搜索工具并返回带来源的结果。', - '', - '建议的处理方式:', - '1. 先搜索权威来源和最近资料。', - '2. 合并重复信息,标出不确定点。', - '3. 按你的目标输出摘要、对比表或行动建议。' - ].join('\n'); - } - if (MockGeneralChatAdapter.looksLikeCodeTask(normalized)) { - return [ - '这个问题可能需要远程能力来读取本地项目、运行命令或查看日志。', - '', - '如果只是要通用建议,我可以先给排查路径;如果要看本地仓库、改代码或运行命令,就应该从侧栏进入远程。', - '', - '当前是 mock 回复。接入 OpenBitFun harness 后,普通聊天会给出真实模型建议,远程模块会继续负责本地 workspace 和工具执行。' - ].join('\n'); - } - if (normalized.indexOf('图片') >= 0 || normalized.toLowerCase().indexOf('image') >= 0) { - return [ - '我可以帮你分析图片。', - '', - '手机端助手可以覆盖看图解释、OCR 提取、界面走查、截图问题定位和图片内容总结。当前是 mock 回复;接入 OpenBitFun harness 后会把图片交给真实视觉模型处理。' - ].join('\n'); - } - if (normalized.indexOf('文件') >= 0 || normalized.toLowerCase().indexOf('file') >= 0) { - return [ - '我可以帮你处理文件。', - '', - '手机端助手适合做文件总结、重点提取、改写、翻译、生成待办和跨文件对比。当前是 mock 回复;接入 OpenBitFun harness 后会对真实附件内容进行处理。' - ].join('\n'); - } - if (MockGeneralChatAdapter.looksLikeWritingTask(normalized)) { - return [ - '我可以帮你写作、改写和整理表达。', - '', - '你可以让我把内容改成更正式、更短、更像产品说明,或者生成邮件、方案、会议纪要、社媒文案。当前是 mock 回复,后续会接入真实模型输出。' - ].join('\n'); - } - if (normalized.length === 0) { - return '你可以直接问 OpenBitFun。'; - } - return [ - `我收到了:${normalized}`, - '', - '在手机端,OpenBitFun 不应该只是普通聊天框,而是一个通用助手入口:可以问答、搜索资料、分析图片、处理文件、写作改写,也可以在需要本地项目能力时引导进入远程。', - '', - '当前回复是 mock,用来验证移动端交互和流式 UI。下一步把这个 backend 替换为 OpenBitFun harness 的普通聊天接口后,就会返回真实模型结果。' - ].join('\n'); - } - - private static looksLikeSearchTask(text: string): boolean { - const normalized = text.toLowerCase(); - return normalized.indexOf('搜索') >= 0 || - normalized.indexOf('查找') >= 0 || - normalized.indexOf('查一下') >= 0 || - normalized.indexOf('资料') >= 0 || - normalized.indexOf('新闻') >= 0 || - normalized.indexOf('最新') >= 0 || - normalized.indexOf('联网') >= 0 || - normalized.indexOf('search') >= 0 || - normalized.indexOf('web') >= 0; - } - - private static looksLikeWritingTask(text: string): boolean { - const normalized = text.toLowerCase(); - return normalized.indexOf('写') >= 0 || - normalized.indexOf('改写') >= 0 || - normalized.indexOf('润色') >= 0 || - normalized.indexOf('总结') >= 0 || - normalized.indexOf('翻译') >= 0 || - normalized.indexOf('邮件') >= 0 || - normalized.indexOf('文案') >= 0 || - normalized.indexOf('rewrite') >= 0 || - normalized.indexOf('translate') >= 0 || - normalized.indexOf('summarize') >= 0; - } - - private static streamChunks(text: string): string[] { - const chunks: string[] = []; - let buffer = ''; - for (let index = 0; index < text.length; index++) { - const char = text.charAt(index); - buffer += char; - const shouldBreak = char === '\n' || - char === '。' || - char === ';' || - char === ':' || - char === ',' || - char === '.' || - char === ',' || - buffer.length >= 14; - if (shouldBreak) { - chunks.push(buffer); - buffer = ''; - } - } - if (buffer.length > 0) { - chunks.push(buffer); - } - return chunks.length > 0 ? chunks : [text]; - } - - private static toolsFor(text: string, images: ImageAttachment[]): RemoteToolStatusResponse[] { - const normalized = text.trim(); - if (images.length > 0) { - return [ - MockGeneralChatAdapter.tool( - 'analyze_image', - '分析图片内容', - '识别图片、提取文字和主要视觉元素', - `已接收 ${images.length} 张图片,准备进行视觉理解。` - ) - ]; - } - if (MockGeneralChatAdapter.looksLikeSearchTask(normalized)) { - return [ - MockGeneralChatAdapter.tool( - 'web_search', - '搜索网络资料', - normalized, - '找到 5 条相关结果,已合并重复信息并保留待核验点。' - ), - MockGeneralChatAdapter.tool( - 'summarize_sources', - '整理搜索结果', - '提取要点、冲突信息和下一步建议', - '已整理摘要、关键结论和后续可追问方向。' - ) - ]; - } - if (normalized.indexOf('文件') >= 0 || normalized.toLowerCase().indexOf('file') >= 0) { - return [ - MockGeneralChatAdapter.tool( - 'parse_file', - '读取文件内容', - '等待附件或文件上下文', - '当前没有真实附件,已模拟文件解析流程。' - ), - MockGeneralChatAdapter.tool( - 'summarize_document', - '总结文件', - '生成摘要、重点和待办', - '已准备文件总结输出结构。' - ) - ]; - } - if (MockGeneralChatAdapter.looksLikeCodeTask(normalized)) { - return [ - MockGeneralChatAdapter.tool( - 'classify_code_request', - '判断代码任务类型', - normalized, - '该请求可能需要本地工作区;普通聊天先给通用建议。' - ) - ]; - } - return []; - } - - private static itemsFor(tools: RemoteToolStatusResponse[], text: string): ChatMessageItemResponse[] { - const items: ChatMessageItemResponse[] = []; - tools.forEach((tool: RemoteToolStatusResponse) => { - items.push({ - type: 'tool', - tool - }); - }); - if (text.trim().length > 0) { - items.push({ - type: 'text', - content: text - }); - } - return items; - } - - private static tool( - name: string, - _label: string, - inputPreview: string, - resultPreview: string - ): RemoteToolStatusResponse { - return { - id: Encoding.randomId('tool'), - name, - status: 'completed', - duration_ms: 420, - input_preview: inputPreview, - result_preview: resultPreview - }; - } - - private static looksLikeCodeTask(text: string): boolean { - const normalized = text.toLowerCase(); - return normalized.indexOf('项目') >= 0 || - normalized.indexOf('仓库') >= 0 || - normalized.indexOf('启动失败') >= 0 || - normalized.indexOf('运行命令') >= 0 || - normalized.indexOf('改代码') >= 0 || - normalized.indexOf('workspace') >= 0 || - normalized.indexOf('repo') >= 0 || - normalized.indexOf('git') >= 0 || - normalized.indexOf('npm') >= 0 || - normalized.indexOf('build') >= 0; - } - -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderGeneralChatAdapter.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderGeneralChatAdapter.ets deleted file mode 100644 index 1bf1ab92d3..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderGeneralChatAdapter.ets +++ /dev/null @@ -1,631 +0,0 @@ -import { http } from '@kit.NetworkKit'; -import { - ChatMessage, - ChatMessageItemResponse, - ImageAttachment, - RemoteSession -} from '../../model/RemoteModels'; -import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { Encoding } from '../Encoding'; -import { OhosError } from '../OhosError'; -import { GeneralChatConfigStore } from './GeneralChatConfigStore'; -import { GeneralChatPort, GeneralChatSendResult, GeneralChatStreamObserver } from './GeneralChatPort'; -import { ModelProviderSseParser } from './ModelProviderSseParser'; -import { RemoteLogger } from '../RemoteLogger'; - -export const GENERAL_CHAT_SYSTEM_PROMPT: string = [ - 'You are the general-purpose AI work assistant in the OpenBitFun HarmonyOS mobile app.', - 'The OpenBitFun product is a local AI workbench built around a Code Agent for long-horizon engineering and productivity tasks.', - 'The mobile app provides general chat plus entry points to OpenBitFun Remote/Code; this chat itself does not have local workspace access.', - 'It is not a blockchain, gaming, NFT, cryptocurrency, or Web3 product. Never invent those product claims.', - 'Treat those product exclusions as internal factual constraints and do not mention them unless the user asks something directly related.', - 'Help with general questions, writing, summarization, planning, research preparation, and everyday work.', - 'The user may attach images. When images are present, look at them and answer from what you can see.', - 'This mobile chat currently has no local workspace, shell, desktop file, web browsing, or external tool access.', - 'Never claim to have used unavailable tools or accessed information you were not given.', - 'When a task requires reading or changing a local repository, running commands, or accessing desktop files, explain that the user should use OpenBitFun Remote/Code.', - 'Answer in the user\'s language. Be concise, concrete, and honest about uncertainty.' -].join('\n'); - -export interface ModelProviderImageSource { - type: string; - media_type?: string; - data?: string; -} - -export interface ModelProviderImageUrl { - url: string; -} - -export interface ModelProviderContentPart { - type: string; - text?: string; - source?: ModelProviderImageSource; - image_url?: ModelProviderImageUrl; -} - -export interface ModelProviderMessage { - role: string; - content: string | ModelProviderContentPart[]; -} - -interface AnthropicRequestBody { - model: string; - max_tokens: number; - stream: boolean; - system: string; - messages: ModelProviderMessage[]; -} - -interface OpenAiRequestBody { - model: string; - max_tokens: number; - stream: boolean; - messages: ModelProviderMessage[]; -} - -interface AnthropicContentBlock { - type?: string; - text?: string; -} - -interface AnthropicResponseBody { - id?: string; - content?: AnthropicContentBlock[]; -} - -interface OpenAiResponseMessage { - content?: string; -} - -interface OpenAiResponseChoice { - message?: OpenAiResponseMessage; -} - -interface OpenAiResponseBody { - id?: string; - choices?: OpenAiResponseChoice[]; -} - -interface ModelProviderHttpResponse { - statusCode: number; - body: string; -} - -export interface ModelProviderHttpTransport { - postStream( - url: string, - apiKey: string, - body: string, - protocol: ModelProviderProtocol, - onData: (chunk: string) => void - ): Promise; - cancel(): void; -} - -export enum ModelProviderProtocol { - Anthropic = 'anthropic', - OpenAi = 'openai' -} - -export class HarmonyModelProviderHttpTransport implements ModelProviderHttpTransport { - private activeRequest?: http.HttpRequest; - - async postStream( - url: string, - apiKey: string, - body: string, - protocol: ModelProviderProtocol, - onData: (chunk: string) => void - ): Promise { - const request = http.createHttp(); - this.activeRequest = request; - let responseBody = ''; - const dataCallback = (data: ArrayBuffer): void => { - const chunk = Encoding.bytesToUtf8(new Uint8Array(data)); - responseBody += chunk; - RemoteLogger.info(`general chat stream chunk bytes=${data.byteLength} total=${responseBody.length}`); - onData(chunk); - }; - request.on('dataReceive', dataCallback); - try { - const statusCode = await request.requestInStream( - url, - this.requestOptions(url, apiKey, body, protocol) - ); - return { - statusCode, - body: responseBody - }; - } catch (err) { - throw OhosError.wrap('general chat stream request', err); - } finally { - request.off('dataReceive', dataCallback); - request.destroy(); - if (this.activeRequest === request) { - this.activeRequest = undefined; - } - } - } - - cancel(): void { - const request = this.activeRequest; - this.activeRequest = undefined; - if (request) { - request.destroy(); - } - } - - private requestOptions( - url: string, - apiKey: string, - body: string, - protocol: ModelProviderProtocol - ): http.HttpRequestOptions { - if (protocol === ModelProviderProtocol.Anthropic && url.indexOf('openbitfun.com') >= 0) { - return { - method: http.RequestMethod.POST, - header: { - 'Content-Type': 'application/json', - 'Accept': 'text/event-stream', - 'x-api-key': apiKey, - 'anthropic-version': '2023-06-01', - 'X-Verification-Code': 'from_openbitfun' - }, - extraData: body, - connectTimeout: 15000, - readTimeout: 60000 - }; - } - if (protocol === ModelProviderProtocol.Anthropic) { - return { - method: http.RequestMethod.POST, - header: { - 'Content-Type': 'application/json', - 'Accept': 'text/event-stream', - 'x-api-key': apiKey, - 'anthropic-version': '2023-06-01' - }, - extraData: body, - connectTimeout: 15000, - readTimeout: 60000 - }; - } - return { - method: http.RequestMethod.POST, - header: { - 'Content-Type': 'application/json', - 'Accept': 'text/event-stream', - 'Authorization': `Bearer ${apiKey}` - }, - extraData: body, - connectTimeout: 15000, - readTimeout: 60000 - }; - } -} - -export class ModelProviderGeneralChatAdapter implements GeneralChatPort { - private readonly configStore: GeneralChatConfigStore; - private readonly transport: ModelProviderHttpTransport; - - constructor( - configStore: GeneralChatConfigStore, - transport: ModelProviderHttpTransport = new HarmonyModelProviderHttpTransport() - ) { - this.configStore = configStore; - this.transport = transport; - } - - async createSession(firstMessage: string): Promise { - const now = new Date().toISOString(); - return { - id: Encoding.randomId('chat'), - title: ModelProviderGeneralChatAdapter.titleFromMessage(firstMessage), - agentType: 'chat', - status: 'ready', - updatedAt: now, - createdAt: now, - messageCount: 0, - workspacePath: '', - workspaceName: 'OpenBitFun' - }; - } - - async generateTitle(firstMessage: string, assistantMessage: string): Promise { - const config = await this.configStore.activeSnapshot(); - const apiKey = (await this.configStore.activeAccessToken()).trim(); - if (config.apiUrl.length === 0 || config.modelName.length === 0 || apiKey.length === 0) { - return ''; - } - const protocol = ModelProviderGeneralChatAdapter.resolveProtocol(config.apiUrl); - const parser = new ModelProviderSseParser(protocol); - let title = ''; - const prompt = [ - 'Generate a concise title for this conversation.', - 'Use the user\'s language. Return only the title, with no quotes or punctuation.', - 'Limit it to at most 12 Chinese characters or 8 words.', - `User: ${firstMessage}`, - `Assistant: ${assistantMessage}` - ].join('\n'); - const response = await this.transport.postStream( - ModelProviderGeneralChatAdapter.resolveRequestUrl(config.apiUrl, protocol), - apiKey, - ModelProviderGeneralChatAdapter.buildRequestBody( - config.modelName, - [{ role: 'user', content: prompt }], - protocol, - 40, - 'You create short conversation titles and output only the title.' - ), - protocol, - (chunk: string): void => { - parser.feed(chunk).forEach((delta: string) => { - title += delta; - }); - } - ); - ModelProviderGeneralChatAdapter.ensureSuccess(response.statusCode); - parser.finish().forEach((delta: string) => { - title += delta; - }); - if (title.trim().length === 0) { - title = ModelProviderGeneralChatAdapter.responseText(response.body, protocol); - } - return ModelProviderGeneralChatAdapter.cleanGeneratedTitle(title); - } - - async sendMessage( - _sessionId: string, - text: string, - images: ImageAttachment[] = [], - history: ChatMessage[] = [], - observer?: GeneralChatStreamObserver - ): Promise { - const config = await this.configStore.activeSnapshot(); - const apiKey = (await this.configStore.activeAccessToken()).trim(); - if (config.apiUrl.length === 0 || config.modelName.length === 0 || apiKey.length === 0) { - throw new Error(RemoteI18n.t('generalChat.modelNotConfigured')); - } - - const userText = text.trim(); - const userMessage: ChatMessage = { - id: Encoding.randomId('msg'), - role: 'user', - text: userText, - status: 'pending', - timestamp: new Date().toISOString(), - images: images.slice() - }; - if (observer) { - await observer.onUserMessage(userMessage); - } - const protocol = ModelProviderGeneralChatAdapter.resolveProtocol(config.apiUrl); - const messages = ModelProviderGeneralChatAdapter.toProviderMessages(history, protocol); - messages.push(ModelProviderGeneralChatAdapter.userProviderMessage(userText, images, protocol)); - const parser = new ModelProviderSseParser(protocol); - const streamChunks: string[] = []; - let assistantText = ''; - const requestUrl = ModelProviderGeneralChatAdapter.resolveRequestUrl(config.apiUrl, protocol); - RemoteLogger.info(`general chat request start protocol=${protocol} url=${requestUrl}`); - const response = await this.transport.postStream( - requestUrl, - apiKey, - ModelProviderGeneralChatAdapter.buildRequestBody(config.modelName, messages, protocol), - protocol, - (chunk: string): void => { - const deltas = parser.feed(chunk); - deltas.forEach((delta: string) => { - assistantText += delta; - streamChunks.push(delta); - if (observer) { - observer.onDelta(delta); - } - }); - } - ); - RemoteLogger.info(`general chat response status=${response.statusCode} bodyLength=${response.body.length}`); - ModelProviderGeneralChatAdapter.ensureSuccess(response.statusCode); - parser.finish().forEach((delta: string) => { - assistantText += delta; - streamChunks.push(delta); - if (observer) { - observer.onDelta(delta); - } - }); - if (assistantText.trim().length === 0) { - assistantText = ModelProviderGeneralChatAdapter.responseText(response.body, protocol); - streamChunks.push(assistantText); - if (observer) { - observer.onDelta(assistantText); - } - } - RemoteLogger.info(`general chat response parsed textLength=${assistantText.length} chunks=${streamChunks.length}`); - const turnId = parser.responseId() || ModelProviderGeneralChatAdapter.responseId(response.body, protocol); - const assistantMessage: ChatMessage = { - id: Encoding.randomId('assistant'), - turnId: turnId || Encoding.randomId('turn'), - role: 'assistant', - text: assistantText, - status: 'completed', - timestamp: new Date().toISOString(), - tools: [], - items: ModelProviderGeneralChatAdapter.textItems(assistantText) - }; - return { - userMessage, - assistantMessage, - streamChunks, - tools: [] - }; - } - - static async probeConfiguration( - baseUrl: string, - apiKey: string, - modelName: string, - transport: ModelProviderHttpTransport = new HarmonyModelProviderHttpTransport() - ): Promise { - const protocol = ModelProviderGeneralChatAdapter.resolveProtocol(baseUrl); - const parser = new ModelProviderSseParser(protocol); - let receivedText = ''; - const response = await transport.postStream( - ModelProviderGeneralChatAdapter.resolveRequestUrl(baseUrl, protocol), - apiKey.trim(), - ModelProviderGeneralChatAdapter.buildRequestBody( - modelName.trim(), - [{ role: 'user', content: 'ping' }], - protocol, - 1, - 'You verify whether a model endpoint is reachable. Reply with one short word.' - ), - protocol, - (chunk: string): void => { - parser.feed(chunk).forEach((delta: string) => { - receivedText += delta; - }); - } - ); - ModelProviderGeneralChatAdapter.ensureSuccess(response.statusCode); - parser.finish().forEach((delta: string) => { - receivedText += delta; - }); - if (receivedText.trim().length === 0) { - throw new Error(RemoteI18n.t('generalChat.emptyResponse')); - } - } - - cancelCurrentRequest(): void { - this.transport.cancel(); - } - - static resolveProtocol(baseUrl: string): ModelProviderProtocol { - const normalized = baseUrl.trim().toLowerCase().replace(/\/+$/, ''); - if (normalized.indexOf('openbitfun.com') >= 0 || normalized.endsWith('/v1/messages')) { - return ModelProviderProtocol.Anthropic; - } - return ModelProviderProtocol.OpenAi; - } - - static resolveRequestUrl(baseUrl: string, protocol: ModelProviderProtocol): string { - const normalized = baseUrl.trim().replace(/\/+$/, ''); - if (protocol === ModelProviderProtocol.Anthropic) { - return normalized.endsWith('/v1/messages') ? normalized : `${normalized}/v1/messages`; - } - if (normalized.endsWith('/chat/completions')) { - return normalized; - } - return normalized.endsWith('/v1') ? `${normalized}/chat/completions` : `${normalized}/v1/chat/completions`; - } - - static buildRequestBody( - modelName: string, - messages: ModelProviderMessage[], - protocol: ModelProviderProtocol, - maxTokens: number = 4096, - systemPrompt: string = GENERAL_CHAT_SYSTEM_PROMPT - ): string { - if (protocol === ModelProviderProtocol.Anthropic) { - const request: AnthropicRequestBody = { - model: modelName, - max_tokens: maxTokens, - stream: true, - system: systemPrompt, - messages - }; - return JSON.stringify(request); - } - const openAiMessages: ModelProviderMessage[] = []; - openAiMessages.push({ role: 'system', content: systemPrompt }); - messages.forEach((message: ModelProviderMessage) => { - openAiMessages.push(message); - }); - const request: OpenAiRequestBody = { - model: modelName, - max_tokens: maxTokens, - stream: true, - messages: openAiMessages - }; - return JSON.stringify(request); - } - - private static cleanGeneratedTitle(value: string): string { - const normalized = value.trim().replace(/^[“”"'《》]+|[“”"'《》。!?!?]+$/g, '').replace(/\s+/g, ' '); - if (normalized.length === 0) { - return ''; - } - return normalized.length > 24 ? normalized.slice(0, 24) : normalized; - } - - static responseText(body: string, protocol: ModelProviderProtocol): string { - try { - if (protocol === ModelProviderProtocol.OpenAi) { - const response = Encoding.parseJsonObject(body); - const choices = response.choices || []; - const content = choices.length > 0 && choices[0].message ? choices[0].message?.content || '' : ''; - if (content.trim().length > 0) { - return content.trim(); - } - throw new Error(RemoteI18n.t('generalChat.emptyResponse')); - } - const response = Encoding.parseJsonObject(body); - const blocks = response.content || []; - const parts: string[] = []; - blocks.forEach((block: AnthropicContentBlock) => { - if (block.type === 'text' && block.text && block.text.trim().length > 0) { - parts.push(block.text); - } - }); - const text = parts.join('\n').trim(); - if (text.length === 0) { - throw new Error(RemoteI18n.t('generalChat.emptyResponse')); - } - return text; - } catch (_err) { - throw new Error(RemoteI18n.t('generalChat.invalidResponse')); - } - } - - private static responseId(body: string, protocol: ModelProviderProtocol): string { - try { - if (protocol === ModelProviderProtocol.OpenAi) { - return Encoding.parseJsonObject(body).id || ''; - } - return Encoding.parseJsonObject(body).id || ''; - } catch (_err) { - return ''; - } - } - - private static ensureSuccess(statusCode: number): void { - if (statusCode >= 200 && statusCode < 300) { - return; - } - if (statusCode === 401 || statusCode === 403) { - throw new Error(RemoteI18n.t('generalChat.authenticationFailed')); - } - if (statusCode === 429) { - throw new Error(RemoteI18n.t('generalChat.rateLimited')); - } - if (statusCode >= 500) { - throw new Error(RemoteI18n.t('generalChat.serviceUnavailable')); - } - throw new Error(RemoteI18n.f('generalChat.requestFailed', `${statusCode}`)); - } - - private static toProviderMessages( - history: ChatMessage[], - protocol: ModelProviderProtocol - ): ModelProviderMessage[] { - const messages: ModelProviderMessage[] = []; - history.forEach((message: ChatMessage) => { - const status = (message.status || '').toLowerCase(); - if (status === 'failed' || (message.role !== 'user' && message.role !== 'assistant')) { - return; - } - const text = (message.text || '').trim(); - if (message.role === 'user') { - const providerMessage = ModelProviderGeneralChatAdapter.userProviderMessage( - text, - message.images || [], - protocol - ); - if (ModelProviderGeneralChatAdapter.hasProviderContent(providerMessage)) { - messages.push(providerMessage); - } - return; - } - if (text.length > 0) { - messages.push({ role: 'assistant', content: text }); - } - }); - return messages; - } - - private static userProviderMessage( - text: string, - images: ImageAttachment[], - protocol: ModelProviderProtocol - ): ModelProviderMessage { - const parts: ModelProviderContentPart[] = []; - if (protocol === ModelProviderProtocol.OpenAi && text.length > 0) { - parts.push({ type: 'text', text }); - } - images.forEach((image: ImageAttachment) => { - const dataUrl = (image.data_url || '').trim(); - if (dataUrl.length === 0) { - return; - } - const mediaType = ModelProviderGeneralChatAdapter.imageMediaType(dataUrl, image.mime_type); - const rawBase64 = ModelProviderGeneralChatAdapter.imageBase64(dataUrl); - if (rawBase64.length === 0) { - return; - } - if (protocol === ModelProviderProtocol.Anthropic) { - const source: ModelProviderImageSource = { - type: 'base64', - media_type: mediaType, - data: rawBase64 - }; - parts.push({ type: 'image', source }); - return; - } - const imageUrl: ModelProviderImageUrl = { - url: dataUrl.indexOf('data:') === 0 ? dataUrl : `data:${mediaType};base64,${rawBase64}` - }; - parts.push({ type: 'image_url', image_url: imageUrl }); - }); - if (protocol === ModelProviderProtocol.Anthropic && text.length > 0) { - parts.push({ type: 'text', text }); - } - if (parts.length === 0) { - return { role: 'user', content: text }; - } - if (parts.length === 1 && parts[0].type === 'text') { - return { role: 'user', content: text }; - } - return { role: 'user', content: parts }; - } - - private static hasProviderContent(message: ModelProviderMessage): boolean { - if (typeof message.content === 'string') { - return message.content.trim().length > 0; - } - return message.content.length > 0; - } - - private static imageMediaType(dataUrl: string, explicitMime?: string): string { - const trimmed = (explicitMime || '').trim(); - if (trimmed.length > 0) { - return trimmed; - } - if (dataUrl.indexOf('data:') === 0) { - const semicolon = dataUrl.indexOf(';'); - if (semicolon > 5) { - return dataUrl.slice(5, semicolon); - } - } - return 'image/jpeg'; - } - - private static imageBase64(dataUrl: string): string { - const marker = ';base64,'; - const index = dataUrl.indexOf(marker); - if (index >= 0) { - return dataUrl.slice(index + marker.length); - } - return dataUrl; - } - - private static titleFromMessage(text: string): string { - const normalized = text.trim().replace(/\s+/g, ' '); - if (normalized.length === 0) { - return '新建聊天'; - } - return normalized.length > 18 ? `${normalized.slice(0, 18)}...` : normalized; - } - - private static textItems(text: string): ChatMessageItemResponse[] { - return [{ type: 'text', content: text }]; - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderSseParser.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderSseParser.ets deleted file mode 100644 index 532284844f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/general-chat/ModelProviderSseParser.ets +++ /dev/null @@ -1,110 +0,0 @@ -import { Encoding } from '../Encoding'; - -interface AnthropicStreamDelta { - type?: string; - text?: string; -} - -interface AnthropicStreamMessage { - id?: string; -} - -interface AnthropicStreamEvent { - type?: string; - delta?: AnthropicStreamDelta; - message?: AnthropicStreamMessage; -} - -interface OpenAiStreamDelta { - content?: string; -} - -interface OpenAiStreamChoice { - delta?: OpenAiStreamDelta; -} - -interface OpenAiStreamEvent { - id?: string; - choices?: OpenAiStreamChoice[]; -} - -export class ModelProviderSseParser { - private readonly protocol: string; - private buffer: string = ''; - private streamResponseId: string = ''; - - constructor(protocol: string) { - this.protocol = protocol; - } - - feed(chunk: string): string[] { - if (chunk.length === 0) { - return []; - } - this.buffer += chunk; - this.buffer = this.buffer.replace(/\r\n/g, '\n'); - const deltas: string[] = []; - let separatorIndex = this.buffer.indexOf('\n\n'); - while (separatorIndex >= 0) { - const eventText = this.buffer.slice(0, separatorIndex); - this.buffer = this.buffer.slice(separatorIndex + 2); - this.appendEventDeltas(eventText, deltas); - separatorIndex = this.buffer.indexOf('\n\n'); - } - return deltas; - } - - finish(): string[] { - const deltas: string[] = []; - const remaining = this.buffer.trim(); - this.buffer = ''; - if (remaining.length > 0) { - this.appendEventDeltas(remaining, deltas); - } - return deltas; - } - - responseId(): string { - return this.streamResponseId; - } - - private appendEventDeltas(eventText: string, deltas: string[]): void { - const lines = eventText.split('\n'); - let data = ''; - lines.forEach((line: string) => { - if (line.startsWith('data:')) { - const value = line.slice(5).trimStart(); - data += data.length > 0 ? `\n${value}` : value; - } - }); - if (data.length === 0 || data === '[DONE]') { - return; - } - try { - if (this.protocol === 'openai') { - const event = Encoding.parseJsonObject(data); - if (event.id && this.streamResponseId.length === 0) { - this.streamResponseId = event.id; - } - const choices = event.choices || []; - choices.forEach((choice: OpenAiStreamChoice) => { - const content = choice.delta && choice.delta.content ? choice.delta.content : ''; - if (content.length > 0) { - deltas.push(content); - } - }); - return; - } - const event = Encoding.parseJsonObject(data); - if (event.message && event.message.id && this.streamResponseId.length === 0) { - this.streamResponseId = event.message.id; - } - if (event.type === 'content_block_delta' && event.delta && - event.delta.type === 'text_delta' && event.delta.text) { - deltas.push(event.delta.text); - } - } catch (_err) { - // Ignore non-JSON keepalive events and incomplete provider metadata. - } - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/module.json5 b/src/apps/mobile/harmonyos/entry/src/main/module.json5 deleted file mode 100644 index 6e5460c280..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/module.json5 +++ /dev/null @@ -1,109 +0,0 @@ -{ - "module": { - "name": "entry", - "type": "entry", - "description": "$string:module_desc", - "mainElement": "EntryAbility", - "deviceTypes": [ - "phone", - "tablet" - ], - "deliveryWithInstall": true, - "installationFree": false, - // The camera cutout is not an avoid area by default, so a page does not stay - // clear of it — and in landscape it sits on a side edge of a full-width - // band. From API version 12 on, a module makes the cutout a default avoid - // area with this metadata, which is what lets the window report it through - // `getWindowAvoidArea(TYPE_CUTOUT)` and lets a component expand into it - // (`ts-universal-attributes-expand-safe-area`; module-level `metadata` is - // legal per `module-configuration-file`). - "metadata": [ - { - "name": "avoid_cutout", - "value": "true" - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.INTERNET" - }, - { - "name": "ohos.permission.GET_NETWORK_INFO" - }, - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC", - "reason": "$string:permission_distributed_datasync_reason", - "usedScene": { - "abilities": [ - "EntryAbility" - ], - "when": "inuse" - } - }, - { - "name": "ohos.permission.MICROPHONE", - "reason": "$string:permission_microphone_reason", - "usedScene": { - "abilities": [ - "EntryAbility" - ], - "when": "inuse" - } - } - ], - "pages": "$profile:main_pages", - "easyGo": "$profile:easy_go", - "abilities": [ - { - "name": "EntryAbility", - "orientation": "auto_rotation_unspecified", - "srcEntry": "./ets/entryability/EntryAbility.ets", - "description": "$string:EntryAbility_desc", - "icon": "$media:openbitfun_app_icon", - "label": "$string:EntryAbility_label", - "startWindowIcon": "$media:openbitfun_start_window", - "startWindowBackground": "$color:page_bg", - "exported": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "ohos.want.action.home" - ] - }, - { - "entities": [ - "entity.system.browsable" - ], - "actions": [ - "ohos.want.action.viewData" - ], - "uris": [ - { - "scheme": "openbitfun", - "host": "auth", - "path": "/callback" - } - ] - } - ] - } - ], - "extensionAbilities": [ - { - "name": "EntryBackupAbility", - "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", - "type": "backup", - "exported": false, - "metadata": [ - { - "name": "ohos.extension.backup", - "resource": "$profile:backup_config" - } - ], - } - ] - } -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/color.json b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/color.json deleted file mode 100644 index b48b8b2d8c..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/color.json +++ /dev/null @@ -1,248 +0,0 @@ -{ - "color": [ - { - "name": "start_window_background", - "value": "#FFFFFF" - }, - { - "name": "transparent", - "value": "#00000000" - }, - { - "name": "page_bg", - "value": "#FFFFFF" - }, - { - "name": "welcome_page_bg", - "value": "#FFFFFF" - }, - { - "name": "page_bg_fade", - "value": "#00FFFFFF" - }, - { - "name": "page_bg_overlay", - "value": "#B8FFFFFF" - }, - { - "name": "ink", - "value": "#171717" - }, - { - "name": "muted", - "value": "#706F6A" - }, - { - "name": "subtle", - "value": "#A5A39B" - }, - { - "name": "line", - "value": "#E9E7E2" - }, - { - "name": "card", - "value": "#FFFFFF" - }, - { - "name": "card_overlay", - "value": "#CCFFFFFF" - }, - { - "name": "accent", - "value": "#111111" - }, - { - "name": "file_link", - "value": "#2563EB" - }, - { - "name": "primary_action", - "value": "#111111" - }, - { - "name": "content_on_action", - "value": "#FFFFFF" - }, - { - "name": "connect_hero_bg", - "value": "#E6EDFF" - }, - { - "name": "connect_hero_accent", - "value": "#9DB4FF" - }, - { - "name": "connect_hero_secondary", - "value": "#C9C5FF" - }, - { - "name": "connect_hero_surface", - "value": "#F8FAFF" - }, - { - "name": "connect_scan_accent", - "value": "#FFD021" - }, - { - "name": "scrim", - "value": "#44000000" - }, - { - "name": "shell_scrim", - "value": "#24000000" - }, - { - "name": "media_background", - "value": "#FF000000" - }, - { - "name": "media_scrim", - "value": "#B8000000" - }, - { - "name": "media_control_background", - "value": "#8C000000" - }, - { - "name": "toast_background", - "value": "#D1171717" - }, - { - "name": "shadow_faint", - "value": "#08000000" - }, - { - "name": "shadow_subtle", - "value": "#12000000" - }, - { - "name": "shadow_medium", - "value": "#18000000" - }, - { - "name": "shadow_strong", - "value": "#24000000" - }, - { - "name": "floating_border", - "value": "#18000000" - }, - { - "name": "soft", - "value": "#F4F3F0" - }, - { - "name": "floating_panel_bg", - "value": "#F7F7F5" - }, - { - "name": "sidebar_bg", - "value": "#F8F8F9" - }, - { - "name": "sidebar_bg_fade", - "value": "#00F8F8F9" - }, - { - "name": "sidebar_raised", - "value": "#FFFFFF" - }, - { - "name": "sidebar_line", - "value": "#14101A27" - }, - { - "name": "sidebar_hover", - "value": "#F3F3F5" - }, - { - "name": "sidebar_selection", - "value": "#14000000" - }, - { - "name": "sidebar_ink", - "value": "#CC000000" - }, - { - "name": "sidebar_muted", - "value": "#99000000" - }, - { - "name": "sidebar_subtle", - "value": "#66000000" - }, - { - "name": "status_success", - "value": "#27C46A" - }, - { - "name": "status_danger", - "value": "#E04F4F" - }, - { - "name": "code_line_number", - "value": "#AAA69D" - }, - { - "name": "code_keyword", - "value": "#8F3F71" - }, - { - "name": "code_string", - "value": "#477A4A" - }, - { - "name": "code_number", - "value": "#9A5B13" - }, - { - "name": "code_comment", - "value": "#7A8078" - }, - { - "name": "code_function", - "value": "#2C6693" - }, - { - "name": "code_type", - "value": "#865A20" - }, - { - "name": "code_constant", - "value": "#A04444" - }, - { - "name": "code_property", - "value": "#466D78" - }, - { - "name": "code_target_bg", - "value": "#FFF1BE" - }, - { - "name": "brand_dot", - "value": "#16B9CE" - }, - { - "name": "welcome_dock", - "value": "#171917" - }, - { - "name": "welcome_button", - "value": "#FFFFFF" - }, - { - "name": "welcome_button_label", - "value": "#171917" - }, - { - "name": "welcome_secondary", - "value": "#B9BCB9" - }, - { - "name": "status_warning", - "value": "#FF8C00" - } - ] -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/float.json b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/float.json deleted file mode 100644 index 33ea22304f..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/float.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "float": [ - { - "name": "page_text_font_size", - "value": "50fp" - } - ] -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json deleted file mode 100644 index c16dd31a06..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "string": [ - { - "name": "module_desc", - "value": "OpenBitFun remote control client" - }, - { - "name": "EntryAbility_desc", - "value": "Connect to OpenBitFun desktop and control remote sessions" - }, - { - "name": "EntryAbility_label", - "value": "OpenBitFun" - }, - { - "name": "permission_microphone_reason", - "value": "Used to turn speech into text to send in a conversation." - }, - { - "name": "permission_distributed_datasync_reason", - "value": "Used to authorize a watch on the same GitHub account using a separate device credential." - }, - { - "name": "queue_title", - "value": "待发送 · %1$s" - }, - { - "name": "queue_reorder", - "value": "拖动排序" - }, - { - "name": "queue_moveUp", - "value": "上移" - }, - { - "name": "queue_moveDown", - "value": "下移" - }, - { - "name": "queue_refresh", - "value": "刷新" - }, - { - "name": "queue_refreshRequired", - "value": "队列状态已变化或未能确认,请刷新后再操作。" - }, - { - "name": "queue_attachments", - "value": "%1$s 个附件" - }, - { - "name": "queue_waiting", - "value": "等待执行端处理" - }, - { - "name": "queue_sendNow", - "value": "立即发送" - }, - { - "name": "queue_more", - "value": "消息操作" - }, - { - "name": "queue_remove", - "value": "从队列移除" - }, - { - "name": "queue_unsupported", - "value": "升级执行端后可调整消息顺序。" - } - ] -} diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/approval_shield.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/approval_shield.png deleted file mode 100644 index 8c0fb2022901ab1225e7d7ed273f97e49423c609..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1324 zcmV+{1=IS8P)g&UE5TM>2u2i3TS2M_VzG7Q0~boG7}AGSORLo*-^|3= zbpDyioquj-Zsx!bfh6BK|C#?e_xmo;ph1Iv24BT_6bw-&JBKkd+jefj#pq{Hv5ty^U6>O!!2t^H zLcf8dxQ2p{x;ExaqdwpWR-iA8QM^gPsT>`jq+)H{CUcl%G2fu#YSamA;Q|Wor(!n+ z|KuDI`zW~bzZe}Xr(%E3|22-C6x?gvs1g`pA&0S)0dA$>NebSl;P@=2%imOV*up?! zY{AytCP!u&_c#?#gqk943wvh>aTXO1$0E94Y@^P6Z=J~GRNPL%4+YmP(>hMU2J1sP z=5%m*c)~5dz#gOG8IIxn+}te;Q1KiUzkA@{Wqm1QP0@&gnH9K7|@D{)BQ;dqyg!rQ#7?gp=pbRtyWuP%A1C2o$Xbj3gV^9VfgZkbeX)dd&XkK^p{R=a}pNS+j z$RUi)PcrDFKN4|#<}{3pP>+l@mia;s;pa=qB+F27SXzxk`%nHz6nh;cYfy1eaGPU_ zec_Kp9Z8pMJc4>;(#VET zitijFXq}JvA*fj7Ooi*JDxJ3?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s&HvkY_Dj{Fechik4|N7Q?l!t9KjTAXh?}0&RSRLcFUy>I zQ|b>->0fNeztHwv+Nt9PD@(Ub{>vNu&Svut$@e0cc2u!k_EbHcBAmWMhZ9%6f@Qqj c4?l3nJ-9#Pd99xdFh4VRy85}Sb4q9e0G=lKJpcdz diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_mic.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_mic.png deleted file mode 100644 index ff4591718f52394092163c35fa2b8e381d9c39b4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2502 zcmV;%2|4zOP)4Tx0C=2zkg-d{P!PtyR;8eI5FH#GGKoW!k_x&wv=u~g2vx!Al)k2^kj6)n zA_X`9fr9^m3eIj8hdMeq2%?kd=H#T{qUCuniKHTWkK=xP@4MqTAUSSuZubMIJHA_7 z$}5|tEhY7g1ic^(=JA}auS))|KjZyA^xjU(S-=1PjlqiPF{+=G8OB{7NT|g6p3f!k z6OXyH6md(k74nJXa>(a_XT4Y;z9v>!&8QH+5Ub@L-Rj}G-C)rUa{ILDY^=#SloMFQ z4m@z!Fwleo9oawpvw^>WU2-?!QlEtyeCo-OA}5%{%W%Lj1C>}qhEkJvj_!9C-A|3R zgC}62BZRn!wUrKVHb*CG$J*39Ffs&OwYlLMfz(HttX6^7Q((9RjNVYswpYz+;r8h~ zFz_hE+a!=W1iCFDK8}Rw9#iuJaOr#j1E*pW!Pr_8000OnNklqsy5RZ(EaKQ`2 z`MD==7Kojcbql}g`0pre$O6gYbH=q-^*^eMbcP-HS05{t!PG#cHyAGe^~+uPQMNa2x!!5wT)`E`d4bT8tUuo z;pNMh#CuayQ{npc>l_Y;(`QX8W9%(I%&uGt|KfiZkKjQ1_3zsinzUb%Y_aAp` z=H=ycHf-2H$-j2(8t!-EfMGET<@M{=P+MC|$Z_^9ml1$H?q$ z!4GnS3%(rW|&OY z86o6Dr_5=;$>fbVdB%QuC6AO84F$w<%192|D!-4pyXFnRJ=D?+qJc~QAbAyY2TLY zTlJ>VCo?mXlGoha43(AF-TsEmW^??PUml_4^LRY$ljcqt6pO_YqEssX)z#JYg`?|s z@7^676cj|s|NQeJ(CKt8MjQ@ClDK6Yi=-AczzHYw?& zzxDLIApSmU)-3GxvqdL~L?YmFxzN_uh8^_q`0-=t@9(!;pYrl@{7Km@Td&twtX{pk zaN=aLxw-ipp-`9s&P0b?aq&^g+X@K@LEYWmpE|lvrBW&Jb)>iLZW4=skK73b!Jm@F zVqq@oAS)}gbfSM{aBvWg9Xocz(S31oaq;!_^?wf!4~NMLcc@2>9D$08Qw|+HDwRrG zRaHgF-?3wdt##58-Ogv{&Yi?JS6yA>^v(76_s10$7TUgRcUs5VwQG?=p?Ku19JARh zT(M#W<^F{W7b1hfki%$4YqeV8`|tlPS+HOMrNAXimLMFcL&pa0oVRV;MjHn1Xe%o# z(a6Y%Q`@+6wr9JzxY(uO9+v_EB@zjeNF>Dd$G6}9<9FfVVNyDFaM-zCub1ledcIz- z#~q_B;F!t@3CGIG<#Mg7HeIfS!C=VY^ZCR| zL`6j*jYjkJ&jn;?Xo$Oa?_Rr~AC8rC$F5tIX=!O`Uc7iQu_8EX@%HW89t-FEDH)B% zPf}7+91PuJx9i|`r5YO>M{%!Cst}HjJaFIu!qaq50I8{|LH1fJPTASnXk_HI+x90_ zxrT-Y6dW9Ew{m!`Q(j(n~lp;tn4^ z47+yi;?Q2xO!d(gg+kGB=FAzsOeSMAf-xc@0tyNW@V2MNPKkN^xLjvvXYs9D)hB9d zs_|}^TQ&j%10gLf4Yq9A0!c|9aeRDc!aH-?^v552({wuRO`T5n9tNaRso=?zC*!X1 z_xFdy#6;Vv)0h|`2!%0c_3hyVZp diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_plus.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_plus.png deleted file mode 100644 index d2562fa1e4bbdb09d065c5b24ed88012e1cc1711..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 929 zcmeAS@N?(olHy`uVBq!ia0vp^?jX#;1|&l_M9DKSFh*oLI|q0=J1Ybf<)>xlq%ts6 z%&DEQ(fe?Kz_I;dOBa+1$jZnVbvjR(#I?&}i>ON>N9e&*aqEyxYxUS~??#C7imU#tv-ynMJJv&rtghV*ryg2adw5keu33bGOMEL3jU(Xn+ZUxAssdiL>KS8NQ7SYo#Bd??j;#eL?Qu*U1b2|HMN?ggCR z7JfGC;kTDI1|Kwz+*X-j#j;CR(XOxMgfuX&%u9Ru59DKwrhQ9MTJ4n(Ij`jZM8CQqp!X$)t-I!RMN%?xdI$4PyYRTn3A9W z{p0cNp&KLa%re+kw_pGIb+^yE&s%mGOYo%Jw)pAW_bA0k@}^qc`tVCHzub+QXSw;N zk5q44=<2H}HgczTm0HQp^jq$oyfDC{#_s;D^`gCQs?$%$x+zWU?yZ=pFw-Y$ZCG~Z znwWi)HgDc?e5?M^QoduZ3dDE`q-KSj`{l6mrKV@K^MaN9lqN=4T`!G&^zp~eoKxK_ z`!(mEzbzfIEKx#;hiz$qhRyH4|D+3N3jGdS74&FZ5L)Q<)x70xt7#XAv9Ndu%z6x- Lu6{1-oD!M<*wU{N diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send.png deleted file mode 100644 index f7728678dde2adca6ffa1dd41313b29ccd6e8e8f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3785 zcmV;)4mR4Tx0C=2zkg-d{P!PtyR;8eI5FH#GGKoW!k_x&wv=u~g2vx!Al)k2^kj6)n zA_X`9fr9^m3eIj8hdMeq2%?kd=H#T{qUCuniKHTWkK=xP@4MqTAUSSuZubMIJHA_7 z$}5|tEhY7g1ic^(=JA}auS))|KjZyA^xjU(S-=1PjlqiPF{+=G8OB{7NT|g6p3f!k z6OXyH6md(k74nJXa>(a_X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;V5lM8LZCkq5mThV z68moU2ZIn|iUa|;mBgN&9`N}FuQ`Ge@r(Zh8C-@CQI);?00000NkvXXu0mjf$_+KB diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send_arrow.svg b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send_arrow.svg deleted file mode 100644 index acfac8ec3d..0000000000 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_composer_send_arrow.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_chat_glyph.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_chat_glyph.png deleted file mode 100644 index a4131e10c99438a2463a0964dd03fd92c92614e4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2809 zcmbVNc|6qX8Xv||Sw@)|Ix#7PAzDsH)=>=2B!()5BjLuLnr1`fvU?viVxT)Nk= z=|XOrE*ZD`3SZT=&sUiQF{GL#_{9HVaj&{=3r?Vuqtoh84GLv8mum;uUQ|`Ig2R!5 z9=6vXc+>UfSFf)|#2HLm3%-FtH#rMRrP9d0{1K{$nT~n<+4Jq}Zrbwx_DOltOUbtG z?wAMms_P#YPSTYW!qK(gy-ImexFrMSymr48ZFi$uPCe(Mf|_+SRt8 z8_m{g>RULQQy*DCEjST)dfxYRf8&`~H1dJWEMt!0%4qiq?k4_DR+_MULkxx938a$i zUDF_%UIJ9@TM1tC%{Q`mrgt>2*8Gw6ys9pkcH>}JYN43y{FxGsvaL~XY)S6)yr)PQ zZLgS`whvR*zqW>hy<+50uA<{_c`D?a;K%kRFINpmM@@`xWzbinB0J0 zPEk}NTh@g}PRge>nAfGKsTEoVZU`7}I=>ZUGQ^j4GnMn&e(ob4`yk&{*Y5=N?n{${ zOlh0?R4DTJ(5TwqU*hQ;tn8V4ILBO)+N0~+yaoH-q0lT>)ZD4U~ zA3K+$aUuB4!;z%>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3w~oC?nWqhf!UUzp1JNZ%R=A$Oi` zR@eUY$s-!$N^&%{1L&>nJ`X{-lwtNV>ex)dtPa55Jdn2w9n-UGG4ZicWt{3V!o2tV5=iM%J4o|6(hh$8Jo%zE zxVI{^KXT?^&HEZ(^#%kJ)g|y|Hv|q0D){i>tYoc47>IBCHwW`xwNzGohns28{LYt? zQfoEGox`#eBqt|3F>(YZBqrsOBYn%II@Xn?4}-8r|0|Of^XbO6|9@OyqFaFRAK2)> zvP_T!{|8opRJsT<7gk?IexPctwuCwRIzhE&XXd)G1Vj)8zn z;HB^TH#bGH81SqYVp^58ubheR;Irvzi?;%GkO+R{t+$-FU7VrdckP{D$}B894#uV4 z64OyT(ECm6;-&yY#)zNgWq+7hSrKgY8h(A!P7F`+jMxTXkM%MnlBnIQ)P_D5(eEaja ztPUH#{ahCCc%iV+j^t~aSBfsQu)Ld9>18To;Mi!LKHn)`d-j5cn~OY(LReVONTdcW zR?Kt+4O`wjhmi!^6w7#Iuz@GwQ4NfaTltKEG%pE&wZ;8B{Q_H2g zf90R2ADU+_a=G35b}j3>ndMxj@6@Cs4$OQE44$rjF6*2U FngE#F`SJh& diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_mic_glyph.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_mic_glyph.png deleted file mode 100644 index 0b045ad2ae996e37f748d179b9f73f3fece9e573..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5572 zcmeHLc{rQfx(|xB*+r!lt+4|-Bq%jcHIynvZEb0g3aTpRNGL^HYHHcGHYl2EOIxiW zv@xYIB&Y_ZlSG1&MvO64$qsR2-+S)q-e;fl+~+>${&)X)pS8a4TkBizu-1Ct-!IL@ z$!^=$-CF?wz&866Hm(4G2m=5Ry}VgM_{MkBWDEeXGsE7-(k;4hW^fA2_>50J-AA5X ze`|On9EG4?enzK=PU>)G_n)l`>X&qZ^1>B63;?Q}tS{^O0969u7f!bvpq27(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PjQMCq^SnyX*_CWs ztHzeOtW7)3oslD(a;za`bLRMDpj#IHft8T28vT+E@nmIX2#f$#*nf!_{){00|M`!& zdcz;B$A#c@rOHPGpIkywso3}5@G5K%e6ZCC0R*O*dpaO}JjS^K4%rp~G>|c+9Y^|X z&rXR=g+jLAdRwnjkUWem~F%e+iub*WXvLO9_~#UsD(4ozsQvEWrM_lTC%yh3o$T>&X diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_plus_glyph.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_plus_glyph.png deleted file mode 100644 index cf2cd0b13b25c4aef1d95faa15a5e66ca8d47a92..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1980 zcmeAS@N?(olHy`uVBq!ia0y~yU|a&i9Be?5I-fvO1_t(KPZ!6KiaBrZ9`uVgWN7z!+6(P!Z_Yj>RTV5Wj&gGQr5ql80C z>ye9IrIUX?Y zbw1v~*Q`ce4^uJhMvbCYDkL`~TMVD?3GFr9)y}+Qf#vfZu1}j(oEXxNX$q?-GFe#r zbY7ougd<`8sp1dcT0?%iF>EN;&E=jXz-V&TH}F(2uj@B67wC!!F?1Fx0#m;Z=cH_F2D@ZM#t9Olr<+n#84LPbSsaplba*FC zWpPMT>=Zg+dgf@o`zxT;M=EXzsc3U9$j+;3pPS3=IfbF>*|F`_(#7Xu<9|ODNPc6_ za^T^!XW!*~SzdN(FwT)&6f@zUfLg<5rzyObvLCU0*sEMJQ{muA`xjH@TRaf_BP+zf z*~H?|q`){q0h|*@xucu*IdPiT1Z{*>Zb+~jHi;*n`}xZG!FT55 zo_0Hf7LI?ZiU%JhbO`P_@6_a)?b-3b&asL8IFQZ;RdMTqxrF)&b$e5M%KU$S&(9GP Q2iD3Ap00i_>zopr09=pg&j0`b diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_voice_button.png b/src/apps/mobile/harmonyos/entry/src/main/resources/base/media/gpt_home_voice_button.png deleted file mode 100644 index 16ec9e9d67c320538c6376e92c24abdafb2f7803..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 337985 zcmeFZ^;27K)IA#9t$2~5E$;48+#P~Lad-FPrAULjySoP~5VUBEmlCwN`0000!-zsp)7WDU`jFiYcA{QJn=9@jK6Op z3kM`i-u%A~iNh)W`|N+dRQRp#e;uKo259`x8UB9j0+|au_kYj&a!eQ&gN^(D`Ag#Q zV*mTZ|Nm+JTZRA6*vuFD|F-Da;# zW7kd~{c(>m#LubZEM!*mC|BO+DUklW{7HX1!&6^kyZFiA*$8Ip&MBQoteG;sxMw}7 z>N%Z(2N*IN;mq@?DKs0OuGxP{v`_uw;HsgY$*6z-O(ceMHJSmVjJII2y7t;)d`Yqc zV~{zt4fG4O=jFOP4IwgXdXV82Mrg8^e7lzwL(q9F5;Do(7%BeuXpKb$&hxG_9s4`d zANxAf9s8+5?zhYRH~KWU?-}Wqw8Js-HR~EddwdSw)&e!)4-B(cG81-iA`_o9pLI^r zL&zUZgDWjnpB=8KMzEBmQKz?hKi2H8+hNLMaBC&BJhrm8hgN2s5ArVsZS4p-nb^U7 ziapgm1Tx1<(hpav*EljmsgF|561`GiUfR>mpx(z!M~uqFKdI6E$vU|FPqz4?%&^`o zltLY@OV6(Ei@Tmnc|WPTOl<`^rWDPGJ4#C9^Drq~mT3excFd#9*yI(wb&8S!%*&&c zsV8wEmMp-+tIGK>m-oGu(rT_^MoBMP;(U})G|sG62wGp`%4yE3?m0UI?iz&r)DDEY z)bI@*RG3%8XWdUhPkU?z1^gB9vpjvPJpC{}Kes9euL(kM{^l!5_Af~4 z`zi0RV6e(M$@KlYVvRVd#rb!Q7X#t4B7Ej@?Gt0>ax|_0C0S4fCSXLlwvVnMx+4AH z9IH<1d%PjbODf`KklowL@XFJcESmLVP-Qvkks@?$c6M9(hFwJoIKmV>J#(;T78@giSMoi-P@@~e#yrWMsxRLn4L!@-gecUBIAai`TfpW+Xg|& zjGN;iv4}v7wha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