@elizaos/app-core 2.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (399) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +90 -0
  3. package/src/App.tsx +472 -0
  4. package/src/actions/character.test.ts +139 -0
  5. package/src/actions/character.ts +152 -0
  6. package/src/actions/chat-helpers.ts +100 -0
  7. package/src/actions/cloud.ts +59 -0
  8. package/src/actions/index.ts +12 -0
  9. package/src/actions/lifecycle.ts +175 -0
  10. package/src/actions/onboarding.ts +46 -0
  11. package/src/actions/triggers.ts +190 -0
  12. package/src/ambient.d.ts +16 -0
  13. package/src/api/client.ts +5516 -0
  14. package/src/api/index.ts +1 -0
  15. package/src/autonomy/index.ts +477 -0
  16. package/src/bridge/capacitor-bridge.ts +295 -0
  17. package/src/bridge/electrobun-rpc.ts +58 -0
  18. package/src/bridge/electrobun-runtime.ts +28 -0
  19. package/src/bridge/index.ts +5 -0
  20. package/src/bridge/native-plugins.ts +134 -0
  21. package/src/bridge/plugin-bridge.ts +352 -0
  22. package/src/bridge/storage-bridge.ts +162 -0
  23. package/src/chat/index.ts +250 -0
  24. package/src/coding/index.ts +43 -0
  25. package/src/components/AdvancedPageView.tsx +362 -0
  26. package/src/components/AgentActivityBox.tsx +49 -0
  27. package/src/components/ApiKeyConfig.tsx +224 -0
  28. package/src/components/AppsPageView.tsx +52 -0
  29. package/src/components/AppsView.tsx +293 -0
  30. package/src/components/AvatarLoader.tsx +86 -0
  31. package/src/components/AvatarSelector.tsx +223 -0
  32. package/src/components/BscTradePanel.tsx +549 -0
  33. package/src/components/BugReportModal.tsx +499 -0
  34. package/src/components/CharacterView.tsx +1645 -0
  35. package/src/components/ChatAvatar.test.ts +96 -0
  36. package/src/components/ChatAvatar.tsx +147 -0
  37. package/src/components/ChatComposer.tsx +330 -0
  38. package/src/components/ChatMessage.tsx +448 -0
  39. package/src/components/ChatModalView.test.tsx +118 -0
  40. package/src/components/ChatModalView.tsx +125 -0
  41. package/src/components/ChatView.tsx +992 -0
  42. package/src/components/CloudSourceControls.tsx +80 -0
  43. package/src/components/CodingAgentSettingsSection.tsx +536 -0
  44. package/src/components/CommandPalette.tsx +284 -0
  45. package/src/components/CompanionSceneHost.tsx +497 -0
  46. package/src/components/CompanionShell.tsx +31 -0
  47. package/src/components/CompanionView.tsx +109 -0
  48. package/src/components/ConfigPageView.tsx +758 -0
  49. package/src/components/ConfigSaveFooter.tsx +41 -0
  50. package/src/components/ConfirmModal.tsx +379 -0
  51. package/src/components/ConnectionFailedBanner.tsx +91 -0
  52. package/src/components/ConnectorsPageView.tsx +13 -0
  53. package/src/components/ConversationsSidebar.tsx +279 -0
  54. package/src/components/CustomActionEditor.tsx +1125 -0
  55. package/src/components/CustomActionsPanel.tsx +288 -0
  56. package/src/components/CustomActionsView.tsx +322 -0
  57. package/src/components/DatabasePageView.tsx +55 -0
  58. package/src/components/DatabaseView.tsx +814 -0
  59. package/src/components/ElizaCloudDashboard.tsx +1696 -0
  60. package/src/components/EmotePicker.tsx +529 -0
  61. package/src/components/ErrorBoundary.tsx +76 -0
  62. package/src/components/FineTuningView.tsx +1077 -0
  63. package/src/components/GameView.tsx +552 -0
  64. package/src/components/GameViewOverlay.tsx +133 -0
  65. package/src/components/GlobalEmoteOverlay.tsx +155 -0
  66. package/src/components/Header.test.tsx +413 -0
  67. package/src/components/Header.tsx +403 -0
  68. package/src/components/HeartbeatsView.tsx +1003 -0
  69. package/src/components/InventoryView.tsx +385 -0
  70. package/src/components/KnowledgeView.tsx +1128 -0
  71. package/src/components/LanguageDropdown.tsx +188 -0
  72. package/src/components/LifoMonitorPanel.tsx +196 -0
  73. package/src/components/LifoSandboxView.tsx +499 -0
  74. package/src/components/LoadingScreen.tsx +77 -0
  75. package/src/components/LogsPageView.tsx +17 -0
  76. package/src/components/LogsView.tsx +239 -0
  77. package/src/components/MediaGalleryView.tsx +433 -0
  78. package/src/components/MediaSettingsSection.tsx +893 -0
  79. package/src/components/MessageContent.tsx +815 -0
  80. package/src/components/OnboardingWizard.test.tsx +107 -0
  81. package/src/components/OnboardingWizard.tsx +189 -0
  82. package/src/components/PairingView.tsx +110 -0
  83. package/src/components/PermissionsSection.tsx +1186 -0
  84. package/src/components/PluginsPageView.tsx +9 -0
  85. package/src/components/PluginsView.tsx +3157 -0
  86. package/src/components/ProviderSwitcher.tsx +908 -0
  87. package/src/components/RestartBanner.tsx +76 -0
  88. package/src/components/RuntimeView.tsx +460 -0
  89. package/src/components/SaveCommandModal.tsx +211 -0
  90. package/src/components/SecretsView.tsx +569 -0
  91. package/src/components/SettingsView.tsx +825 -0
  92. package/src/components/ShellOverlays.tsx +41 -0
  93. package/src/components/ShortcutsOverlay.tsx +155 -0
  94. package/src/components/SkillsView.tsx +1435 -0
  95. package/src/components/StartupFailureView.tsx +63 -0
  96. package/src/components/StreamView.tsx +483 -0
  97. package/src/components/StripeEmbeddedCheckout.tsx +155 -0
  98. package/src/components/SubscriptionStatus.tsx +640 -0
  99. package/src/components/SystemWarningBanner.tsx +71 -0
  100. package/src/components/ThemeToggle.tsx +100 -0
  101. package/src/components/TrajectoriesView.tsx +526 -0
  102. package/src/components/TrajectoryDetailView.tsx +426 -0
  103. package/src/components/TriggersView.tsx +1 -0
  104. package/src/components/VectorBrowserView.tsx +1633 -0
  105. package/src/components/VoiceConfigView.tsx +675 -0
  106. package/src/components/VrmStage.test.ts +219 -0
  107. package/src/components/VrmStage.tsx +432 -0
  108. package/src/components/WhatsAppQrOverlay.tsx +230 -0
  109. package/src/components/__tests__/chainConfig.test.ts +220 -0
  110. package/src/components/apps/AppDetailPane.tsx +242 -0
  111. package/src/components/apps/AppsCatalogGrid.tsx +137 -0
  112. package/src/components/apps/extensions/HyperscapeAppDetailPanel.tsx +577 -0
  113. package/src/components/apps/extensions/registry.ts +16 -0
  114. package/src/components/apps/extensions/types.ts +9 -0
  115. package/src/components/apps/helpers.ts +44 -0
  116. package/src/components/avatar/VrmAnimationLoader.test.ts +164 -0
  117. package/src/components/avatar/VrmAnimationLoader.ts +151 -0
  118. package/src/components/avatar/VrmBlinkController.ts +118 -0
  119. package/src/components/avatar/VrmCameraManager.ts +407 -0
  120. package/src/components/avatar/VrmEngine.ts +2678 -0
  121. package/src/components/avatar/VrmFootShadow.ts +96 -0
  122. package/src/components/avatar/VrmViewer.tsx +421 -0
  123. package/src/components/avatar/__tests__/VrmCameraManager.test.ts +168 -0
  124. package/src/components/avatar/__tests__/VrmEngine.test.ts +1574 -0
  125. package/src/components/avatar/mixamoVRMRigMap.ts +62 -0
  126. package/src/components/avatar/retargetMixamoFbxToVrm.ts +144 -0
  127. package/src/components/avatar/retargetMixamoGltfToVrm.ts +119 -0
  128. package/src/components/chainConfig.ts +380 -0
  129. package/src/components/companion/CompanionHeader.tsx +47 -0
  130. package/src/components/companion/CompanionSceneHost.tsx +1 -0
  131. package/src/components/companion/VrmStage.tsx +2 -0
  132. package/src/components/companion/__tests__/walletUtils.test.ts +742 -0
  133. package/src/components/companion/walletUtils.ts +290 -0
  134. package/src/components/companion-shell-styles.test.ts +142 -0
  135. package/src/components/companion-shell-styles.ts +270 -0
  136. package/src/components/confirm-delete-control.tsx +69 -0
  137. package/src/components/conversations/ConversationListItem.tsx +185 -0
  138. package/src/components/conversations/conversation-utils.ts +151 -0
  139. package/src/components/format.ts +131 -0
  140. package/src/components/index.ts +94 -0
  141. package/src/components/inventory/CopyableAddress.tsx +41 -0
  142. package/src/components/inventory/InventoryToolbar.tsx +142 -0
  143. package/src/components/inventory/NftGrid.tsx +99 -0
  144. package/src/components/inventory/TokenLogo.tsx +71 -0
  145. package/src/components/inventory/TokensTable.tsx +216 -0
  146. package/src/components/inventory/constants.ts +170 -0
  147. package/src/components/inventory/index.ts +29 -0
  148. package/src/components/inventory/media-url.test.ts +38 -0
  149. package/src/components/inventory/media-url.ts +36 -0
  150. package/src/components/inventory/useInventoryData.ts +460 -0
  151. package/src/components/knowledge-upload-image.ts +215 -0
  152. package/src/components/labels.ts +46 -0
  153. package/src/components/onboarding/ActivateStep.tsx +30 -0
  154. package/src/components/onboarding/ConnectionStep.tsx +1530 -0
  155. package/src/components/onboarding/IdentityStep.tsx +147 -0
  156. package/src/components/onboarding/OnboardingPanel.tsx +39 -0
  157. package/src/components/onboarding/OnboardingStepNav.tsx +31 -0
  158. package/src/components/onboarding/PermissionsStep.tsx +20 -0
  159. package/src/components/onboarding/RpcStep.tsx +402 -0
  160. package/src/components/onboarding/WakeUpStep.tsx +184 -0
  161. package/src/components/permissions/PermissionIcon.tsx +25 -0
  162. package/src/components/permissions/StreamingPermissions.tsx +413 -0
  163. package/src/components/plugins/showcase-data.ts +481 -0
  164. package/src/components/shared/ShellHeaderControls.tsx +193 -0
  165. package/src/components/shared-companion-scene-context.ts +15 -0
  166. package/src/components/skeletons.tsx +88 -0
  167. package/src/components/stream/ActivityFeed.tsx +113 -0
  168. package/src/components/stream/AvatarPip.tsx +10 -0
  169. package/src/components/stream/ChatContent.tsx +126 -0
  170. package/src/components/stream/ChatTicker.tsx +55 -0
  171. package/src/components/stream/IdleContent.tsx +73 -0
  172. package/src/components/stream/StatusBar.tsx +469 -0
  173. package/src/components/stream/StreamSettings.tsx +506 -0
  174. package/src/components/stream/StreamTerminal.tsx +94 -0
  175. package/src/components/stream/StreamVoiceConfig.tsx +160 -0
  176. package/src/components/stream/helpers.ts +134 -0
  177. package/src/components/stream/overlays/OverlayLayer.tsx +75 -0
  178. package/src/components/stream/overlays/built-in/ActionTickerWidget.tsx +64 -0
  179. package/src/components/stream/overlays/built-in/AlertPopupWidget.tsx +87 -0
  180. package/src/components/stream/overlays/built-in/BrandingWidget.tsx +51 -0
  181. package/src/components/stream/overlays/built-in/CustomHtmlWidget.tsx +105 -0
  182. package/src/components/stream/overlays/built-in/PeonGlassWidget.tsx +265 -0
  183. package/src/components/stream/overlays/built-in/PeonHudWidget.tsx +247 -0
  184. package/src/components/stream/overlays/built-in/PeonSakuraWidget.tsx +278 -0
  185. package/src/components/stream/overlays/built-in/ThoughtBubbleWidget.tsx +77 -0
  186. package/src/components/stream/overlays/built-in/ViewerCountWidget.tsx +46 -0
  187. package/src/components/stream/overlays/built-in/index.ts +13 -0
  188. package/src/components/stream/overlays/registry.ts +22 -0
  189. package/src/components/stream/overlays/types.ts +90 -0
  190. package/src/components/stream/overlays/useOverlayLayout.ts +218 -0
  191. package/src/components/trajectory-format.ts +50 -0
  192. package/src/components/ui-badges.tsx +109 -0
  193. package/src/components/ui-switch.tsx +57 -0
  194. package/src/components/vector-browser-three.ts +27 -0
  195. package/src/config/config-catalog.ts +1092 -0
  196. package/src/config/config-field.tsx +1901 -0
  197. package/src/config/config-renderer.tsx +730 -0
  198. package/src/config/index.ts +11 -0
  199. package/src/config/ui-renderer.tsx +1751 -0
  200. package/src/config/ui-spec.ts +256 -0
  201. package/src/events/index.ts +89 -0
  202. package/src/hooks/index.ts +13 -0
  203. package/src/hooks/useBugReport.tsx +43 -0
  204. package/src/hooks/useCanvasWindow.ts +372 -0
  205. package/src/hooks/useChatAvatarVoice.ts +111 -0
  206. package/src/hooks/useContextMenu.ts +127 -0
  207. package/src/hooks/useKeyboardShortcuts.ts +86 -0
  208. package/src/hooks/useLifoSync.ts +143 -0
  209. package/src/hooks/useMemoryMonitor.ts +334 -0
  210. package/src/hooks/useRenderGuard.ts +43 -0
  211. package/src/hooks/useRetakeCapture.ts +67 -0
  212. package/src/hooks/useStreamPopoutNavigation.ts +27 -0
  213. package/src/hooks/useTimeout.ts +37 -0
  214. package/src/hooks/useVoiceChat.ts +1441 -0
  215. package/src/hooks/useWhatsAppPairing.ts +123 -0
  216. package/src/i18n/index.ts +76 -0
  217. package/src/i18n/locales/en.json +1194 -0
  218. package/src/i18n/locales/es.json +1194 -0
  219. package/src/i18n/locales/ko.json +1194 -0
  220. package/src/i18n/locales/pt.json +1194 -0
  221. package/src/i18n/locales/zh-CN.json +1194 -0
  222. package/src/i18n/messages.ts +21 -0
  223. package/src/index.ts +6 -0
  224. package/src/navigation/index.ts +282 -0
  225. package/src/navigation.test.ts +189 -0
  226. package/src/onboarding-config.test.ts +104 -0
  227. package/src/onboarding-config.ts +114 -0
  228. package/src/platform/browser-launch.test.ts +94 -0
  229. package/src/platform/browser-launch.ts +149 -0
  230. package/src/platform/index.ts +58 -0
  231. package/src/platform/init.ts +236 -0
  232. package/src/platform/lifo.ts +215 -0
  233. package/src/providers/index.ts +99 -0
  234. package/src/state/AppContext.tsx +5846 -0
  235. package/src/state/index.ts +6 -0
  236. package/src/state/internal.ts +86 -0
  237. package/src/state/onboarding-resume.test.ts +135 -0
  238. package/src/state/onboarding-resume.ts +263 -0
  239. package/src/state/parsers.test.ts +124 -0
  240. package/src/state/parsers.ts +308 -0
  241. package/src/state/persistence.ts +321 -0
  242. package/src/state/shell-routing.ts +32 -0
  243. package/src/state/types.ts +701 -0
  244. package/src/state/ui-preferences.ts +3 -0
  245. package/src/state/useApp.ts +23 -0
  246. package/src/state/vrm.ts +76 -0
  247. package/src/stories/AppMockProvider.tsx +32 -0
  248. package/src/stories/ChatEmptyState.stories.tsx +27 -0
  249. package/src/stories/ChatMessage.stories.tsx +115 -0
  250. package/src/stories/CompanionHeader.stories.tsx +74 -0
  251. package/src/stories/CompanionView.stories.tsx +33 -0
  252. package/src/stories/ConversationListItem.stories.tsx +102 -0
  253. package/src/stories/TypingIndicator.stories.tsx +28 -0
  254. package/src/styles/anime.css +6324 -0
  255. package/src/styles/base.css +196 -0
  256. package/src/styles/onboarding-game.css +738 -0
  257. package/src/styles/styles.css +2087 -0
  258. package/src/styles/xterm.css +241 -0
  259. package/src/types/index.ts +715 -0
  260. package/src/types/react-test-renderer.d.ts +45 -0
  261. package/src/utils/asset-url.ts +110 -0
  262. package/src/utils/assistant-text.ts +172 -0
  263. package/src/utils/clipboard.ts +41 -0
  264. package/src/utils/desktop-dialogs.ts +80 -0
  265. package/src/utils/index.ts +6 -0
  266. package/src/utils/number-parsing.ts +125 -0
  267. package/src/utils/openExternalUrl.ts +20 -0
  268. package/src/utils/spoken-text.ts +65 -0
  269. package/src/utils/streaming-text.ts +120 -0
  270. package/src/voice/index.ts +1 -0
  271. package/src/voice/types.ts +197 -0
  272. package/src/wallet-rpc.ts +176 -0
  273. package/test/app/AppContext.pty-sessions.test.tsx +143 -0
  274. package/test/app/MessageContent.test.tsx +326 -0
  275. package/test/app/PermissionsOnboarding.test.tsx +356 -0
  276. package/test/app/PermissionsSection.test.tsx +573 -0
  277. package/test/app/advanced-trajectory-fine-tuning.e2e.test.ts +393 -0
  278. package/test/app/agent-activity-box.test.tsx +132 -0
  279. package/test/app/agent-transfer-lock.test.ts +274 -0
  280. package/test/app/api-client-electron-fallback.test.ts +139 -0
  281. package/test/app/api-client-timeout.test.ts +75 -0
  282. package/test/app/api-client-ws.test.ts +98 -0
  283. package/test/app/api-client.ws-max-reconnect.test.ts +139 -0
  284. package/test/app/api-client.ws-reconnect.test.ts +157 -0
  285. package/test/app/app-context-autonomy-events.test.ts +478 -0
  286. package/test/app/apps-page-view.test.ts +114 -0
  287. package/test/app/apps-view.test.ts +769 -0
  288. package/test/app/autonomous-workflows.e2e.test.ts +765 -0
  289. package/test/app/autonomy-events.test.ts +150 -0
  290. package/test/app/avatar-selector.test.tsx +52 -0
  291. package/test/app/bsc-trade-panel.test.tsx +134 -0
  292. package/test/app/bug-report-modal.test.tsx +353 -0
  293. package/test/app/character-customization.e2e.test.ts +1199 -0
  294. package/test/app/chat-advanced-features.e2e.test.ts +706 -0
  295. package/test/app/chat-composer.test.tsx +181 -0
  296. package/test/app/chat-language-header.test.ts +64 -0
  297. package/test/app/chat-message.test.tsx +222 -0
  298. package/test/app/chat-modal-view.test.tsx +191 -0
  299. package/test/app/chat-routine-filter.test.ts +96 -0
  300. package/test/app/chat-send-lock.test.ts +1465 -0
  301. package/test/app/chat-stream-api-client.test.tsx +390 -0
  302. package/test/app/chat-view-game-modal.test.tsx +661 -0
  303. package/test/app/chat-view.test.tsx +877 -0
  304. package/test/app/cloud-api.e2e.test.ts +258 -0
  305. package/test/app/cloud-login-flow.e2e.test.ts +494 -0
  306. package/test/app/cloud-login-lock.test.ts +411 -0
  307. package/test/app/command-palette.test.tsx +184 -0
  308. package/test/app/command-registry.test.ts +75 -0
  309. package/test/app/companion-greeting-wave.test.tsx +425 -0
  310. package/test/app/companion-stale-conversation.test.tsx +447 -0
  311. package/test/app/companion-view.test.tsx +686 -0
  312. package/test/app/confirm-delete-control.test.ts +79 -0
  313. package/test/app/confirm-modal.test.tsx +219 -0
  314. package/test/app/connectors-ui.e2e.test.ts +508 -0
  315. package/test/app/conversations-sidebar-game-modal.test.tsx +260 -0
  316. package/test/app/conversations-sidebar.test.tsx +160 -0
  317. package/test/app/custom-actions-smoke.test.ts +387 -0
  318. package/test/app/custom-avatar-api-client.test.ts +207 -0
  319. package/test/app/desktop-utils.test.ts +145 -0
  320. package/test/app/electrobun-rpc-bridge.test.ts +83 -0
  321. package/test/app/events.test.ts +88 -0
  322. package/test/app/export-import-flows.e2e.test.ts +700 -0
  323. package/test/app/fine-tuning-view.test.ts +471 -0
  324. package/test/app/game-view-auth-session.test.tsx +186 -0
  325. package/test/app/game-view.test.ts +444 -0
  326. package/test/app/global-emote-overlay.test.tsx +106 -0
  327. package/test/app/header-status.test.tsx +149 -0
  328. package/test/app/i18n.test.ts +152 -0
  329. package/test/app/inventory-bsc-view.test.ts +940 -0
  330. package/test/app/knowledge-ui.e2e.test.ts +762 -0
  331. package/test/app/knowledge-upload-helpers.test.ts +124 -0
  332. package/test/app/lifecycle-lock.test.ts +267 -0
  333. package/test/app/lifo-popout-utils.test.ts +208 -0
  334. package/test/app/lifo-safe-endpoint.test.ts +34 -0
  335. package/test/app/loading-screen.test.tsx +45 -0
  336. package/test/app/memory-monitor.test.ts +332 -0
  337. package/test/app/navigation.test.tsx +22 -0
  338. package/test/app/onboarding-finish-lock.test.ts +663 -0
  339. package/test/app/onboarding-language.test.tsx +160 -0
  340. package/test/app/onboarding-steps.test.tsx +375 -0
  341. package/test/app/open-external-url.test.ts +65 -0
  342. package/test/app/pages-navigation-smoke.e2e.test.ts +633 -0
  343. package/test/app/pairing-lock.test.ts +260 -0
  344. package/test/app/pairing-view.test.tsx +74 -0
  345. package/test/app/permissions-section.test.ts +432 -0
  346. package/test/app/plugin-bridge.test.ts +109 -0
  347. package/test/app/plugins-ui.e2e.test.ts +605 -0
  348. package/test/app/plugins-view-game-modal.test.tsx +650 -0
  349. package/test/app/plugins-view-toggle-restart.test.ts +129 -0
  350. package/test/app/provider-dropdown-default.test.tsx +302 -0
  351. package/test/app/restart-banner.test.tsx +197 -0
  352. package/test/app/retake-capture.test.ts +84 -0
  353. package/test/app/sandbox-api-client.test.ts +108 -0
  354. package/test/app/save-command-modal.test.tsx +109 -0
  355. package/test/app/secrets-view.test.tsx +92 -0
  356. package/test/app/settings-control-styles.test.tsx +142 -0
  357. package/test/app/settings-reset.e2e.test.ts +726 -0
  358. package/test/app/settings-sections.e2e.test.ts +614 -0
  359. package/test/app/shared-format.test.ts +44 -0
  360. package/test/app/shared-switch.test.ts +69 -0
  361. package/test/app/shell-mode-switching.e2e.test.ts +829 -0
  362. package/test/app/shell-mode-tab-memory.test.tsx +58 -0
  363. package/test/app/shell-overlays.test.tsx +50 -0
  364. package/test/app/shortcuts-overlay.test.tsx +111 -0
  365. package/test/app/sse-interruption.test.ts +122 -0
  366. package/test/app/startup-asset-missing.e2e.test.ts +126 -0
  367. package/test/app/startup-backend-missing.e2e.test.ts +118 -0
  368. package/test/app/startup-chat.e2e.test.ts +305 -0
  369. package/test/app/startup-conversation-restore.test.tsx +344 -0
  370. package/test/app/startup-failure-view.test.tsx +103 -0
  371. package/test/app/startup-onboarding.e2e.test.ts +618 -0
  372. package/test/app/startup-timeout.test.tsx +80 -0
  373. package/test/app/startup-token-401.e2e.test.ts +103 -0
  374. package/test/app/stream-helpers.test.ts +46 -0
  375. package/test/app/stream-popout-navigation.test.tsx +41 -0
  376. package/test/app/stream-status-bar.test.tsx +89 -0
  377. package/test/app/theme-toggle.test.tsx +33 -0
  378. package/test/app/training-api-client.test.ts +128 -0
  379. package/test/app/trajectories-view.test.tsx +220 -0
  380. package/test/app/triggers-api-client.test.ts +77 -0
  381. package/test/app/triggers-navigation.test.ts +113 -0
  382. package/test/app/triggers-view.e2e.test.ts +674 -0
  383. package/test/app/update-channel-lock.test.ts +259 -0
  384. package/test/app/vector-browser.async-cleanup.test.tsx +367 -0
  385. package/test/app/vector-browser.e2e.test.ts +653 -0
  386. package/test/app/vrm-stage.test.tsx +351 -0
  387. package/test/app/vrm-viewer.test.tsx +298 -0
  388. package/test/app/wallet-api-save-lock.test.ts +298 -0
  389. package/test/app/wallet-hooks.test.ts +405 -0
  390. package/test/app/wallet-ui-flows.e2e.test.ts +556 -0
  391. package/test/avatar/asset-url.test.ts +90 -0
  392. package/test/avatar/avatar-selector.test.ts +173 -0
  393. package/test/avatar/mixamo-vrm-rig-map.test.ts +111 -0
  394. package/test/avatar/voice-chat-streaming-text.test.ts +96 -0
  395. package/test/avatar/voice-chat.test.ts +391 -0
  396. package/test/ui/command-palette-commands.test.ts +57 -0
  397. package/test/ui/ui-renderer.test.ts +39 -0
  398. package/tsconfig.build.json +19 -0
  399. package/tsconfig.json +20 -0
@@ -0,0 +1,298 @@
1
+ // @vitest-environment jsdom
2
+ import React, { useEffect } from "react";
3
+ import TestRenderer, { act } from "react-test-renderer";
4
+ import { beforeEach, describe, expect, it, vi } from "vitest";
5
+ import type { WalletConfigUpdateRequest } from "@elizaos/autonomous/contracts/wallet";
6
+
7
+ const { mockClient } = vi.hoisted(() => ({
8
+ mockClient: {
9
+ hasToken: vi.fn(() => false),
10
+ getAuthStatus: vi.fn(async () => ({
11
+ required: false,
12
+ pairingEnabled: false,
13
+ expiresAt: null,
14
+ })),
15
+ getOnboardingStatus: vi.fn(async () => ({ complete: true })),
16
+ listConversations: vi.fn(async () => ({
17
+ conversations: [
18
+ {
19
+ id: "conv-1",
20
+ title: "Chat",
21
+ roomId: "room-1",
22
+ createdAt: "2026-02-01T00:00:00.000Z",
23
+ updatedAt: "2026-02-01T00:00:00.000Z",
24
+ },
25
+ ],
26
+ })),
27
+ getConversationMessages: vi.fn(async () => ({
28
+ messages: [
29
+ {
30
+ id: "msg-1",
31
+ role: "assistant",
32
+ text: "hello",
33
+ timestamp: Date.now(),
34
+ },
35
+ ],
36
+ })),
37
+ sendWsMessage: vi.fn(),
38
+ connectWs: vi.fn(),
39
+ disconnectWs: vi.fn(),
40
+ onWsEvent: vi.fn(() => () => {}),
41
+ getAgentEvents: vi.fn(async () => ({ events: [], latestEventId: null })),
42
+ getStatus: vi.fn(async () => ({
43
+ state: "running",
44
+ agentName: "Milady",
45
+ model: undefined,
46
+ startedAt: undefined,
47
+ uptime: undefined,
48
+ })),
49
+ getWalletAddresses: vi.fn(async () => null),
50
+ getConfig: vi.fn(async () => ({})),
51
+ getCloudStatus: vi.fn(async () => ({ enabled: false, connected: false })),
52
+ getCodingAgentStatus: vi.fn(async () => null),
53
+ getWorkbenchOverview: vi.fn(async () => ({
54
+ tasks: [],
55
+ triggers: [],
56
+ todos: [],
57
+ })),
58
+ updateWalletConfig: vi.fn(async () => ({ ok: true })),
59
+ restartAgent: vi.fn(async () => ({
60
+ state: "running",
61
+ agentName: "Milady",
62
+ model: undefined,
63
+ startedAt: undefined,
64
+ uptime: undefined,
65
+ })),
66
+ getWalletConfig: vi.fn(async () => ({
67
+ evmAddress: "0x0000000000000000000000000000000000000001",
68
+ solanaAddress: "So11111111111111111111111111111111111111112",
69
+ })),
70
+ getWalletBalances: vi.fn(async () => ({
71
+ totalUsdValue: 0,
72
+ chains: [],
73
+ tokens: [],
74
+ })),
75
+ },
76
+ }));
77
+
78
+ vi.mock("@elizaos/app-core/api", () => ({
79
+ client: mockClient,
80
+ SkillScanReportSummary: {},
81
+ }));
82
+
83
+ import { AppProvider, useApp } from "@elizaos/app-core/state";
84
+
85
+ function createDeferred<T>() {
86
+ let resolve!: (value: T | PromiseLike<T>) => void;
87
+ const promise = new Promise<T>((res) => {
88
+ resolve = res;
89
+ });
90
+ return { promise, resolve };
91
+ }
92
+
93
+ type ProbeApi = {
94
+ handleWalletApiKeySave: (config: WalletConfigUpdateRequest) => Promise<void>;
95
+ };
96
+
97
+ function Probe(props: { onReady: (api: ProbeApi) => void }) {
98
+ const { onReady } = props;
99
+ const app = useApp();
100
+
101
+ useEffect(() => {
102
+ onReady({ handleWalletApiKeySave: app.handleWalletApiKeySave });
103
+ }, [app, onReady]);
104
+
105
+ return null;
106
+ }
107
+
108
+ describe("wallet api key save locking", () => {
109
+ beforeEach(() => {
110
+ Object.assign(window.location, { protocol: "file:", pathname: "/chat" });
111
+ Object.assign(window, {
112
+ setTimeout: globalThis.setTimeout,
113
+ clearTimeout: globalThis.clearTimeout,
114
+ setInterval: globalThis.setInterval,
115
+ clearInterval: globalThis.clearInterval,
116
+ });
117
+ Object.assign(document.documentElement, { setAttribute: vi.fn() });
118
+
119
+ for (const fn of Object.values(mockClient)) {
120
+ if (typeof fn === "function" && "mockReset" in fn) {
121
+ (fn as { mockReset: () => void }).mockReset();
122
+ }
123
+ }
124
+
125
+ mockClient.hasToken.mockReturnValue(false);
126
+ mockClient.getAuthStatus.mockResolvedValue({
127
+ required: false,
128
+ pairingEnabled: false,
129
+ expiresAt: null,
130
+ });
131
+ mockClient.getOnboardingStatus.mockResolvedValue({ complete: true });
132
+ mockClient.listConversations.mockResolvedValue({
133
+ conversations: [
134
+ {
135
+ id: "conv-1",
136
+ title: "Chat",
137
+ roomId: "room-1",
138
+ createdAt: "2026-02-01T00:00:00.000Z",
139
+ updatedAt: "2026-02-01T00:00:00.000Z",
140
+ },
141
+ ],
142
+ });
143
+ mockClient.getConversationMessages.mockResolvedValue({
144
+ messages: [
145
+ {
146
+ id: "msg-1",
147
+ role: "assistant",
148
+ text: "hello",
149
+ timestamp: Date.now(),
150
+ },
151
+ ],
152
+ });
153
+ mockClient.sendWsMessage.mockImplementation(() => {});
154
+ mockClient.connectWs.mockImplementation(() => {});
155
+ mockClient.disconnectWs.mockImplementation(() => {});
156
+ mockClient.onWsEvent.mockReturnValue(() => {});
157
+ mockClient.getAgentEvents.mockResolvedValue({
158
+ events: [],
159
+ latestEventId: null,
160
+ });
161
+ mockClient.getStatus.mockResolvedValue({
162
+ state: "running",
163
+ agentName: "Milady",
164
+ model: undefined,
165
+ startedAt: undefined,
166
+ uptime: undefined,
167
+ });
168
+ mockClient.getWalletAddresses.mockResolvedValue(null);
169
+ mockClient.getConfig.mockResolvedValue({});
170
+ mockClient.getCloudStatus.mockResolvedValue({
171
+ enabled: false,
172
+ connected: false,
173
+ });
174
+ mockClient.getCodingAgentStatus.mockResolvedValue(null);
175
+ mockClient.getWorkbenchOverview.mockResolvedValue({
176
+ tasks: [],
177
+ triggers: [],
178
+ todos: [],
179
+ });
180
+ mockClient.updateWalletConfig.mockResolvedValue({ ok: true });
181
+ mockClient.restartAgent.mockResolvedValue({
182
+ state: "running",
183
+ agentName: "Milady",
184
+ model: undefined,
185
+ startedAt: undefined,
186
+ uptime: undefined,
187
+ });
188
+ mockClient.getWalletConfig.mockResolvedValue({
189
+ evmAddress: "0x0000000000000000000000000000000000000001",
190
+ solanaAddress: "So11111111111111111111111111111111111111112",
191
+ });
192
+ mockClient.getWalletBalances.mockResolvedValue({
193
+ totalUsdValue: 0,
194
+ chains: [],
195
+ tokens: [],
196
+ });
197
+ });
198
+
199
+ it("allows only one same-tick wallet API key save call", async () => {
200
+ const deferred = createDeferred<{ ok: true }>();
201
+ mockClient.updateWalletConfig.mockReturnValue(deferred.promise);
202
+
203
+ let api: ProbeApi | null = null;
204
+ let tree: TestRenderer.ReactTestRenderer;
205
+ await act(async () => {
206
+ tree = TestRenderer.create(
207
+ React.createElement(
208
+ AppProvider,
209
+ null,
210
+ React.createElement(Probe, {
211
+ onReady: (nextApi) => {
212
+ api = nextApi;
213
+ },
214
+ }),
215
+ ),
216
+ );
217
+ });
218
+
219
+ expect(api).not.toBeNull();
220
+
221
+ const config: WalletConfigUpdateRequest = {
222
+ selections: {
223
+ evm: "eliza-cloud",
224
+ bsc: "eliza-cloud",
225
+ solana: "helius-birdeye",
226
+ },
227
+ credentials: {
228
+ HELIUS_API_KEY: "k_123",
229
+ BIRDEYE_API_KEY: "bird_123",
230
+ },
231
+ };
232
+
233
+ await act(async () => {
234
+ void api?.handleWalletApiKeySave(config);
235
+ void api?.handleWalletApiKeySave(config);
236
+ });
237
+
238
+ expect(mockClient.updateWalletConfig).toHaveBeenCalledTimes(1);
239
+
240
+ await act(async () => {
241
+ deferred.resolve({ ok: true });
242
+ await deferred.promise;
243
+ });
244
+
245
+ await act(async () => {
246
+ tree?.unmount();
247
+ });
248
+ });
249
+
250
+ it("releases lock after failed save so retry can run", async () => {
251
+ mockClient.updateWalletConfig
252
+ .mockRejectedValueOnce(new Error("boom"))
253
+ .mockRejectedValueOnce(new Error("boom-2"));
254
+
255
+ let api: ProbeApi | null = null;
256
+ let tree: TestRenderer.ReactTestRenderer;
257
+ await act(async () => {
258
+ tree = TestRenderer.create(
259
+ React.createElement(
260
+ AppProvider,
261
+ null,
262
+ React.createElement(Probe, {
263
+ onReady: (nextApi) => {
264
+ api = nextApi;
265
+ },
266
+ }),
267
+ ),
268
+ );
269
+ });
270
+
271
+ expect(api).not.toBeNull();
272
+
273
+ const config: WalletConfigUpdateRequest = {
274
+ selections: {
275
+ evm: "eliza-cloud",
276
+ bsc: "eliza-cloud",
277
+ solana: "helius-birdeye",
278
+ },
279
+ credentials: {
280
+ HELIUS_API_KEY: "k_123",
281
+ BIRDEYE_API_KEY: "bird_123",
282
+ },
283
+ };
284
+
285
+ await act(async () => {
286
+ await api?.handleWalletApiKeySave(config);
287
+ });
288
+ await act(async () => {
289
+ await api?.handleWalletApiKeySave(config);
290
+ });
291
+
292
+ expect(mockClient.updateWalletConfig).toHaveBeenCalledTimes(2);
293
+
294
+ await act(async () => {
295
+ tree?.unmount();
296
+ });
297
+ });
298
+ });
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Unit tests for wallet companion hook logic and security helpers.
3
+ *
4
+ * Tests cover:
5
+ * - safeExplorerHref URL validation (security)
6
+ * - useWalletSwapState quote/execute validation logic
7
+ * - useWalletSendState address/amount validation and transfer flow
8
+ * - useWalletTradeHistory ledger sync merge/dedup and status refresh
9
+ *
10
+ * These exercise the financial transaction logic paths that the hooks
11
+ * encapsulate, without requiring a React rendering environment.
12
+ */
13
+ import { describe, expect, it, vi } from "vitest";
14
+
15
+ import {
16
+ HEX_ADDRESS_RE,
17
+ loadRecentTrades,
18
+ MAX_WALLET_RECENT_TRADES,
19
+ mapWalletTradeError,
20
+ persistRecentTrades,
21
+ safeExplorerHref,
22
+ type TranslatorFn,
23
+ type WalletRecentTrade,
24
+ } from "../../src/components/companion/walletUtils";
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Helpers
28
+ // ---------------------------------------------------------------------------
29
+
30
+ function mockT(overrides: Record<string, string> = {}): TranslatorFn {
31
+ return (key: string) => overrides[key] ?? key;
32
+ }
33
+
34
+ const VALID_TOKEN = `0x${"a".repeat(40)}`;
35
+ const VALID_HASH = `0x${"f".repeat(64)}`;
36
+
37
+ function makeTrade(
38
+ partial: Partial<WalletRecentTrade> = {},
39
+ ): WalletRecentTrade {
40
+ return {
41
+ hash: VALID_HASH,
42
+ side: "buy",
43
+ tokenAddress: VALID_TOKEN,
44
+ amount: "0.01",
45
+ inputSymbol: "BNB",
46
+ outputSymbol: "MILADY",
47
+ createdAt: Date.now(),
48
+ status: "pending",
49
+ confirmations: 0,
50
+ nonce: null,
51
+ reason: null,
52
+ explorerUrl: `https://bscscan.com/tx/${VALID_HASH}`,
53
+ ...partial,
54
+ };
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // safeExplorerHref — security validation
59
+ // ---------------------------------------------------------------------------
60
+
61
+ describe("safeExplorerHref", () => {
62
+ it("returns the explorerUrl when it uses https", () => {
63
+ expect(safeExplorerHref("https://bscscan.com/tx/0x123", "0x123")).toBe(
64
+ "https://bscscan.com/tx/0x123",
65
+ );
66
+ });
67
+
68
+ it("returns the explorerUrl when it uses http", () => {
69
+ expect(safeExplorerHref("http://bscscan.com/tx/0x123", "0x123")).toBe(
70
+ "http://bscscan.com/tx/0x123",
71
+ );
72
+ });
73
+
74
+ it("is case-insensitive for scheme", () => {
75
+ expect(safeExplorerHref("HTTPS://bscscan.com/tx/0x1", "0x1")).toBe(
76
+ "HTTPS://bscscan.com/tx/0x1",
77
+ );
78
+ });
79
+
80
+ it("rejects javascript: URIs and returns bscscan fallback", () => {
81
+ expect(safeExplorerHref("javascript:alert(1)", "0xabc")).toBe(
82
+ "https://bscscan.com/tx/0xabc",
83
+ );
84
+ });
85
+
86
+ it("rejects javascript: with mixed case", () => {
87
+ expect(safeExplorerHref("JavaScript:void(0)", "0xabc")).toBe(
88
+ "https://bscscan.com/tx/0xabc",
89
+ );
90
+ });
91
+
92
+ it("rejects data: URIs and returns fallback", () => {
93
+ expect(safeExplorerHref("data:text/html,<h1>hi</h1>", "0xabc")).toBe(
94
+ "https://bscscan.com/tx/0xabc",
95
+ );
96
+ });
97
+
98
+ it("rejects vbscript: URIs", () => {
99
+ expect(safeExplorerHref("vbscript:MsgBox(1)", "0xabc")).toBe(
100
+ "https://bscscan.com/tx/0xabc",
101
+ );
102
+ });
103
+
104
+ it("returns fallback when explorerUrl is null", () => {
105
+ expect(safeExplorerHref(null, "0xabc")).toBe(
106
+ "https://bscscan.com/tx/0xabc",
107
+ );
108
+ });
109
+
110
+ it("returns fallback when explorerUrl is undefined", () => {
111
+ expect(safeExplorerHref(undefined, "0xabc")).toBe(
112
+ "https://bscscan.com/tx/0xabc",
113
+ );
114
+ });
115
+
116
+ it("returns fallback when explorerUrl is empty string", () => {
117
+ expect(safeExplorerHref("", "0xabc")).toBe("https://bscscan.com/tx/0xabc");
118
+ });
119
+ });
120
+
121
+ // ---------------------------------------------------------------------------
122
+ // Swap validation logic (from useWalletSwapState)
123
+ // ---------------------------------------------------------------------------
124
+
125
+ describe("swap validation logic", () => {
126
+ it("rejects non-hex token addresses", () => {
127
+ expect(HEX_ADDRESS_RE.test("not-hex")).toBe(false);
128
+ expect(HEX_ADDRESS_RE.test("0x123")).toBe(false); // too short
129
+ expect(HEX_ADDRESS_RE.test(`0x${"g".repeat(40)}`)).toBe(false);
130
+ });
131
+
132
+ it("accepts valid hex token addresses", () => {
133
+ expect(HEX_ADDRESS_RE.test(VALID_TOKEN)).toBe(true);
134
+ expect(HEX_ADDRESS_RE.test(`0x${"A".repeat(40)}`)).toBe(true);
135
+ });
136
+
137
+ it("rejects zero or negative swap amounts", () => {
138
+ const validateAmount = (input: string) => {
139
+ const num = Number.parseFloat(input);
140
+ return Number.isFinite(num) && num > 0;
141
+ };
142
+ expect(validateAmount("0")).toBe(false);
143
+ expect(validateAmount("-1")).toBe(false);
144
+ expect(validateAmount("abc")).toBe(false);
145
+ expect(validateAmount("")).toBe(false);
146
+ expect(validateAmount("NaN")).toBe(false);
147
+ });
148
+
149
+ it("accepts valid swap amounts", () => {
150
+ const validateAmount = (input: string) => {
151
+ const num = Number.parseFloat(input);
152
+ return Number.isFinite(num) && num > 0;
153
+ };
154
+ expect(validateAmount("0.01")).toBe(true);
155
+ expect(validateAmount("100")).toBe(true);
156
+ expect(validateAmount("0.000001")).toBe(true);
157
+ });
158
+
159
+ it("computes slippage BPS correctly", () => {
160
+ const computeSlippageBps = (input: string) => {
161
+ const parsed = Number.parseFloat(input);
162
+ if (!Number.isFinite(parsed) || parsed <= 0) return 100;
163
+ return Math.min(5000, Math.round(parsed * 100));
164
+ };
165
+ expect(computeSlippageBps("1.0")).toBe(100);
166
+ expect(computeSlippageBps("0.5")).toBe(50);
167
+ expect(computeSlippageBps("50")).toBe(5000); // capped at 5000
168
+ expect(computeSlippageBps("100")).toBe(5000); // capped
169
+ expect(computeSlippageBps("abc")).toBe(100); // fallback
170
+ expect(computeSlippageBps("-1")).toBe(100); // fallback
171
+ });
172
+
173
+ it("maps trade errors to human-readable messages", () => {
174
+ const t = mockT({ "wallet.failedFetchQuote": "Quote failed" });
175
+ expect(
176
+ mapWalletTradeError(new Error("Bad token"), t, "wallet.failedFetchQuote"),
177
+ ).toBe("Bad token");
178
+ expect(
179
+ mapWalletTradeError("String error", t, "wallet.failedFetchQuote"),
180
+ ).toBe("String error");
181
+ expect(mapWalletTradeError(null, t, "wallet.failedFetchQuote")).toBe(
182
+ "Quote failed",
183
+ );
184
+ expect(mapWalletTradeError(undefined, t, "wallet.failedFetchQuote")).toBe(
185
+ "Quote failed",
186
+ );
187
+ });
188
+ });
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Send validation logic (from useWalletSendState)
192
+ // ---------------------------------------------------------------------------
193
+
194
+ describe("send validation logic", () => {
195
+ it("validates destination address is 0x-prefixed 40-char hex", () => {
196
+ expect(HEX_ADDRESS_RE.test(`0x${"b".repeat(40)}`)).toBe(true);
197
+ expect(HEX_ADDRESS_RE.test("not-an-address")).toBe(false);
198
+ expect(HEX_ADDRESS_RE.test("")).toBe(false);
199
+ expect(HEX_ADDRESS_RE.test("0x")).toBe(false);
200
+ });
201
+
202
+ it("computes sendReady correctly", () => {
203
+ const computeSendReady = (
204
+ evmAddress: string | null,
205
+ toValid: boolean,
206
+ amountValid: boolean,
207
+ ) => Boolean(evmAddress && toValid && amountValid);
208
+
209
+ expect(computeSendReady(`0x${"c".repeat(40)}`, true, true)).toBe(true);
210
+ expect(computeSendReady(null, true, true)).toBe(false);
211
+ expect(computeSendReady(`0x${"c".repeat(40)}`, false, true)).toBe(false);
212
+ expect(computeSendReady(`0x${"c".repeat(40)}`, true, false)).toBe(false);
213
+ });
214
+ });
215
+
216
+ // ---------------------------------------------------------------------------
217
+ // Trade history logic (from useWalletTradeHistory)
218
+ // ---------------------------------------------------------------------------
219
+
220
+ describe("trade history logic", () => {
221
+ it("deduplicates trades by hash — newer entry wins", () => {
222
+ const existing = [
223
+ makeTrade({ hash: "0x001", status: "pending", createdAt: 1000 }),
224
+ makeTrade({ hash: "0x002", status: "success", createdAt: 900 }),
225
+ ];
226
+ const incoming = makeTrade({
227
+ hash: "0x001",
228
+ status: "success",
229
+ createdAt: 1100,
230
+ });
231
+
232
+ // Simulates addRecentTrade logic
233
+ const next = [
234
+ incoming,
235
+ ...existing.filter((entry) => entry.hash !== incoming.hash),
236
+ ].slice(0, MAX_WALLET_RECENT_TRADES);
237
+
238
+ expect(next).toHaveLength(2);
239
+ expect(next[0].hash).toBe("0x001");
240
+ expect(next[0].status).toBe("success");
241
+ });
242
+
243
+ it("limits stored trades to MAX_WALLET_RECENT_TRADES", () => {
244
+ const trades: WalletRecentTrade[] = [];
245
+ for (let i = 0; i < MAX_WALLET_RECENT_TRADES + 5; i++) {
246
+ trades.push(makeTrade({ hash: `0x${i.toString(16).padStart(64, "0")}` }));
247
+ }
248
+ const trimmed = trades.slice(0, MAX_WALLET_RECENT_TRADES);
249
+ expect(trimmed).toHaveLength(MAX_WALLET_RECENT_TRADES);
250
+ });
251
+
252
+ it("merges ledger swaps without duplicating existing local entries", () => {
253
+ const localTrades = [
254
+ makeTrade({ hash: "0xlocal1", createdAt: 2000 }),
255
+ makeTrade({ hash: "0xlocal2", createdAt: 1500 }),
256
+ ];
257
+ const ledgerSwaps = [
258
+ { hash: "0xlocal1" }, // duplicate
259
+ { hash: "0xledger1" }, // new
260
+ ];
261
+
262
+ const existingHashes = new Set(localTrades.map((e) => e.hash));
263
+ const newEntries: WalletRecentTrade[] = [];
264
+ for (const swap of ledgerSwaps) {
265
+ if (existingHashes.has(swap.hash)) continue;
266
+ newEntries.push(makeTrade({ hash: swap.hash, createdAt: 1800 }));
267
+ }
268
+
269
+ const merged = [...newEntries, ...localTrades]
270
+ .sort((a, b) => b.createdAt - a.createdAt)
271
+ .slice(0, MAX_WALLET_RECENT_TRADES);
272
+
273
+ expect(merged).toHaveLength(3);
274
+ // No duplicates
275
+ const hashes = merged.map((e) => e.hash);
276
+ expect(new Set(hashes).size).toBe(hashes.length);
277
+ // Sorted by createdAt desc
278
+ expect(merged[0].createdAt).toBeGreaterThanOrEqual(merged[1].createdAt);
279
+ expect(merged[1].createdAt).toBeGreaterThanOrEqual(merged[2].createdAt);
280
+ });
281
+
282
+ it("updates trade status from API response", () => {
283
+ const trades = [
284
+ makeTrade({ hash: VALID_HASH, status: "pending", confirmations: 0 }),
285
+ ];
286
+
287
+ const statusResponse = {
288
+ status: "success" as const,
289
+ confirmations: 12,
290
+ nonce: 42,
291
+ explorerUrl: `https://bscscan.com/tx/${VALID_HASH}`,
292
+ };
293
+
294
+ // Simulates refreshRecentTradeStatus logic
295
+ const next = trades.map((entry) => {
296
+ if (entry.hash !== VALID_HASH) return entry;
297
+ return {
298
+ ...entry,
299
+ status: statusResponse.status,
300
+ confirmations: statusResponse.confirmations,
301
+ nonce: statusResponse.nonce,
302
+ explorerUrl: statusResponse.explorerUrl || entry.explorerUrl,
303
+ };
304
+ });
305
+
306
+ expect(next[0].status).toBe("success");
307
+ expect(next[0].confirmations).toBe(12);
308
+ expect(next[0].nonce).toBe(42);
309
+ });
310
+
311
+ it("filters trades by status", () => {
312
+ const trades = [
313
+ makeTrade({ hash: "0x1", status: "pending" }),
314
+ makeTrade({ hash: "0x2", status: "success" }),
315
+ makeTrade({ hash: "0x3", status: "reverted" }),
316
+ makeTrade({ hash: "0x4", status: "pending" }),
317
+ ];
318
+
319
+ const filterByStatus = (items: WalletRecentTrade[], filter: string) => {
320
+ if (filter === "all") return items;
321
+ return items.filter((e) => e.status === filter);
322
+ };
323
+
324
+ expect(filterByStatus(trades, "all")).toHaveLength(4);
325
+ expect(filterByStatus(trades, "pending")).toHaveLength(2);
326
+ expect(filterByStatus(trades, "success")).toHaveLength(1);
327
+ expect(filterByStatus(trades, "reverted")).toHaveLength(1);
328
+ expect(filterByStatus(trades, "not_found")).toHaveLength(0);
329
+ });
330
+
331
+ it("identifies pending hashes for polling", () => {
332
+ const trades = [
333
+ makeTrade({ hash: "0x1", status: "pending" }),
334
+ makeTrade({ hash: "0x2", status: "success" }),
335
+ makeTrade({ hash: "0x3", status: "pending" }),
336
+ ];
337
+
338
+ const pendingHashes = trades
339
+ .filter((e) => e.status === "pending")
340
+ .map((e) => e.hash);
341
+
342
+ expect(pendingHashes).toEqual(["0x1", "0x3"]);
343
+ });
344
+
345
+ describe("localStorage persistence", () => {
346
+ it("loadRecentTrades returns empty array when localStorage is empty", () => {
347
+ vi.stubGlobal("localStorage", {
348
+ getItem: vi.fn().mockReturnValue(null),
349
+ setItem: vi.fn(),
350
+ });
351
+ expect(loadRecentTrades()).toEqual([]);
352
+ vi.unstubAllGlobals();
353
+ });
354
+
355
+ it("loadRecentTrades parses valid entries", () => {
356
+ const stored = [makeTrade({ hash: "0xtest" })];
357
+ vi.stubGlobal("localStorage", {
358
+ getItem: vi.fn().mockReturnValue(JSON.stringify(stored)),
359
+ setItem: vi.fn(),
360
+ });
361
+ const result = loadRecentTrades();
362
+ expect(result).toHaveLength(1);
363
+ expect(result[0].hash).toBe("0xtest");
364
+ vi.unstubAllGlobals();
365
+ });
366
+
367
+ it("loadRecentTrades filters out invalid entries", () => {
368
+ const stored = [
369
+ makeTrade({ hash: "0xvalid" }),
370
+ { hash: 123 }, // invalid: hash not string
371
+ null,
372
+ { hash: "0xbad", side: "invalid" }, // invalid side
373
+ ];
374
+ vi.stubGlobal("localStorage", {
375
+ getItem: vi.fn().mockReturnValue(JSON.stringify(stored)),
376
+ setItem: vi.fn(),
377
+ });
378
+ const result = loadRecentTrades();
379
+ expect(result).toHaveLength(1);
380
+ expect(result[0].hash).toBe("0xvalid");
381
+ vi.unstubAllGlobals();
382
+ });
383
+
384
+ it("persistRecentTrades stores trimmed entries", () => {
385
+ const setItem = vi.fn();
386
+ vi.stubGlobal("localStorage", { getItem: vi.fn(), setItem });
387
+ const trades = Array.from({ length: 15 }, (_, i) =>
388
+ makeTrade({ hash: `0x${i}` }),
389
+ );
390
+ persistRecentTrades(trades);
391
+ const stored = JSON.parse(setItem.mock.calls[0][1]);
392
+ expect(stored).toHaveLength(MAX_WALLET_RECENT_TRADES);
393
+ vi.unstubAllGlobals();
394
+ });
395
+
396
+ it("loadRecentTrades handles corrupted JSON gracefully", () => {
397
+ vi.stubGlobal("localStorage", {
398
+ getItem: vi.fn().mockReturnValue("not valid json{{{"),
399
+ setItem: vi.fn(),
400
+ });
401
+ expect(loadRecentTrades()).toEqual([]);
402
+ vi.unstubAllGlobals();
403
+ });
404
+ });
405
+ });