nolo-cli 0.1.40 → 0.1.41

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 (412) hide show
  1. package/agent-runtime/hybridRecordStore.ts +5 -3
  2. package/ai/agent/_executeModel.ts +146 -0
  3. package/ai/agent/agentSlice.ts +556 -1
  4. package/ai/agent/appWorkingMemory.ts +126 -0
  5. package/ai/agent/buildEditingContext.ts +378 -0
  6. package/ai/agent/buildSystemPrompt.ts +585 -0
  7. package/ai/agent/canvasEditingContext.ts +49 -0
  8. package/ai/agent/cleanAgentMessages.ts +140 -0
  9. package/ai/agent/cliChatClient.ts +153 -0
  10. package/ai/agent/cliExecutor.ts +65 -6
  11. package/ai/agent/contextCompiler.ts +107 -0
  12. package/ai/agent/contextLayerContract.ts +44 -0
  13. package/ai/agent/createAgentSchema.ts +272 -0
  14. package/ai/agent/currentTimeContext.ts +65 -0
  15. package/ai/agent/executeToolCall.ts +58 -0
  16. package/ai/agent/fetchAgentContexts.ts +42 -0
  17. package/ai/agent/generatePrompt.ts +3 -0
  18. package/ai/agent/getFullChatContextKeys.ts +168 -0
  19. package/ai/agent/guidedCreation/capabilities.ts +84 -0
  20. package/ai/agent/guidedCreation/types.ts +38 -0
  21. package/ai/agent/isLiveAudioOnlyAgent.ts +26 -0
  22. package/ai/agent/liveAudioModel.ts +2 -0
  23. package/ai/agent/pageBuilderHandoffRules.ts +75 -0
  24. package/ai/agent/persistMessageWithFixedId.ts +37 -0
  25. package/ai/agent/planSlice.ts +259 -0
  26. package/ai/agent/referenceUtils.ts +229 -0
  27. package/ai/agent/runAgentBackground.ts +310 -0
  28. package/ai/agent/runAgentClientLoop.ts +164 -0
  29. package/ai/agent/runtimeGuidance.ts +116 -0
  30. package/ai/agent/serverOrigin.ts +7 -0
  31. package/ai/agent/startParallelAgentStreams.ts +424 -0
  32. package/ai/agent/startupProtocol.ts +53 -0
  33. package/ai/agent/streamAgentChatTurn.ts +2001 -0
  34. package/ai/agent/streamAgentChatTurnUtils.ts +860 -0
  35. package/ai/agent/toolFailureGuard.ts +99 -0
  36. package/ai/agent/types.ts +73 -0
  37. package/ai/agent/utils/imageOutput.ts +37 -0
  38. package/ai/agent/utils/publicImageAgentMode.ts +26 -0
  39. package/ai/ai.locale.ts +1095 -0
  40. package/ai/chat/accumulateToolCallChunks.ts +126 -0
  41. package/ai/chat/fetchUtils.ts +143 -0
  42. package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
  43. package/ai/chat/parseApiError.ts +67 -0
  44. package/ai/chat/parseMultilineSSE.ts +95 -0
  45. package/ai/chat/sendOpenAICompletionsRequest.ts +897 -0
  46. package/ai/chat/sendOpenAIResponseRequest.ts +720 -0
  47. package/ai/chat/serverProxyRetry.ts +102 -0
  48. package/ai/chat/shouldUseServerProxy.ts +18 -0
  49. package/ai/chat/streamRetry.ts +46 -0
  50. package/ai/chat/updateTotalUsage.ts +89 -0
  51. package/ai/context/buildReferenceContext.ts +437 -0
  52. package/ai/context/retention.ts +165 -0
  53. package/ai/context/tokenUtils.ts +78 -0
  54. package/ai/llm/agentCapabilities.ts +74 -0
  55. package/ai/llm/deepinfra.ts +79 -0
  56. package/ai/llm/fireworks.ts +68 -0
  57. package/ai/llm/generateRequestBody.ts +165 -0
  58. package/ai/llm/getModelContextWindow.ts +93 -0
  59. package/ai/llm/getPricing.ts +252 -0
  60. package/ai/llm/imagePricing.ts +66 -0
  61. package/ai/llm/isResponseAPIModel.ts +13 -0
  62. package/ai/llm/kimi.ts +23 -0
  63. package/ai/llm/mimo.ts +99 -0
  64. package/ai/llm/mistral.ts +21 -0
  65. package/ai/llm/models.ts +45 -0
  66. package/ai/llm/openrouterModels.ts +6 -0
  67. package/ai/llm/providers.ts +313 -0
  68. package/ai/llm/reasoningModels.ts +27 -0
  69. package/ai/llm/types.ts +82 -0
  70. package/ai/llm/usageRequestOptions.ts +59 -0
  71. package/ai/memory/queryShared.ts +161 -0
  72. package/ai/memory/recentRelationshipRecap.ts +247 -0
  73. package/ai/memory/remember.ts +167 -0
  74. package/ai/memory/store.ts +20 -0
  75. package/ai/memory/storeShared.ts +76 -0
  76. package/ai/memory/types.ts +46 -0
  77. package/ai/memory/understanding.ts +349 -0
  78. package/ai/memory/understandingGreeting.ts +264 -0
  79. package/ai/policy/personalizationDialog.ts +333 -0
  80. package/ai/policy/runtimePolicy.ts +454 -0
  81. package/ai/policy/selfUpdateFields.ts +48 -0
  82. package/ai/policy/types.ts +64 -0
  83. package/ai/skills/referenceRuntime.ts +274 -0
  84. package/ai/skills/skillDiagnostics.ts +251 -0
  85. package/ai/skills/skillDocBuilder.ts +139 -0
  86. package/ai/skills/skillSummaryMarker.ts +26 -0
  87. package/ai/token/calculatePrice.ts +576 -0
  88. package/ai/token/missingUsageEstimate.ts +42 -0
  89. package/ai/token/normalizeUsage.ts +124 -0
  90. package/ai/token/openaiImageGenerationUsage.ts +56 -0
  91. package/ai/token/prepareTokenUsageData.ts +93 -0
  92. package/ai/token/resolveBillingTarget.ts +52 -0
  93. package/ai/token/saveTokenRecord.ts +53 -0
  94. package/ai/token/types.ts +103 -0
  95. package/ai/tools/agent/agentTools.ts +235 -0
  96. package/ai/tools/agent/agentUpdateShared.ts +311 -0
  97. package/ai/tools/agent/callAgentTool.ts +139 -0
  98. package/ai/tools/agent/createAgentTool.ts +512 -0
  99. package/ai/tools/agent/createDialogTool.ts +69 -0
  100. package/ai/tools/agent/createSkillAgentTool.ts +62 -0
  101. package/ai/tools/agent/parallelBudget.ts +221 -0
  102. package/ai/tools/agent/prepareAgentDraftTool.ts +159 -0
  103. package/ai/tools/agent/presets/appBuilderPreset.ts +154 -0
  104. package/ai/tools/agent/runLlmTool.ts +96 -0
  105. package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
  106. package/ai/tools/agent/skillAgentArgs.ts +106 -0
  107. package/ai/tools/agent/startAgentDialogTool.ts +53 -0
  108. package/ai/tools/agent/streamParallelAgentsTool.ts +123 -0
  109. package/ai/tools/agent/updateAgentTool.ts +96 -0
  110. package/ai/tools/agent/updateSelfTool.ts +113 -0
  111. package/ai/tools/amazonProductScraperTool.ts +86 -0
  112. package/ai/tools/apifyActorClient.ts +45 -0
  113. package/ai/tools/appEditGuard.ts +372 -0
  114. package/ai/tools/appReadSnapshot.ts +153 -0
  115. package/ai/tools/appTools.ts +1549 -0
  116. package/ai/tools/applyEditTool.ts +259 -0
  117. package/ai/tools/applyLineEditsTool.ts +315 -0
  118. package/ai/tools/browserTools/click.ts +33 -0
  119. package/ai/tools/browserTools/closeSession.ts +29 -0
  120. package/ai/tools/browserTools/common.ts +27 -0
  121. package/ai/tools/browserTools/openSession.ts +48 -0
  122. package/ai/tools/browserTools/readContent.ts +38 -0
  123. package/ai/tools/browserTools/selectOption.ts +46 -0
  124. package/ai/tools/browserTools/typeText.ts +42 -0
  125. package/ai/tools/category/createCategoryTool.ts +66 -0
  126. package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
  127. package/ai/tools/category/updateContentCategoryTool.ts +75 -0
  128. package/ai/tools/cfBrowserTools.ts +319 -0
  129. package/ai/tools/cfSpeechToTextTool.ts +49 -0
  130. package/ai/tools/checkEnvTool.ts +102 -0
  131. package/ai/tools/cloudflareCrawlTool.ts +289 -0
  132. package/ai/tools/codeSearchTool.ts +123 -0
  133. package/ai/tools/codeTools.ts +101 -0
  134. package/ai/tools/convertMarxistsBookTool.ts +103 -0
  135. package/ai/tools/createDocTool.ts +132 -0
  136. package/ai/tools/createSkillDocTool.ts +155 -0
  137. package/ai/tools/createWorkflowTool.ts +154 -0
  138. package/ai/tools/delayTool.ts +31 -0
  139. package/ai/tools/deleteSpacesTool.ts +325 -0
  140. package/ai/tools/deleteSpacesToolModel.ts +159 -0
  141. package/ai/tools/devReloadUtils.ts +29 -0
  142. package/ai/tools/dialogMessageSearch.ts +137 -0
  143. package/ai/tools/doctorSkillTool.ts +72 -0
  144. package/ai/tools/ecommerceScraperTool.ts +86 -0
  145. package/ai/tools/emailTools.ts +549 -0
  146. package/ai/tools/evalSkillTool.ts +92 -0
  147. package/ai/tools/exaSearchTool.ts +63 -0
  148. package/ai/tools/execShellTool.ts +266 -0
  149. package/ai/tools/executeSqlTool.ts +192 -0
  150. package/ai/tools/fetchWebpageSupport.ts +333 -0
  151. package/ai/tools/fetchWebpageTool.ts +97 -0
  152. package/ai/tools/geminiImagePreviewTool.ts +386 -0
  153. package/ai/tools/generateDocxTool.ts +215 -0
  154. package/ai/tools/googleSearchScraperTool.ts +106 -0
  155. package/ai/tools/importDataTool.ts +133 -0
  156. package/ai/tools/importSkillTool.ts +162 -0
  157. package/ai/tools/index.ts +2308 -0
  158. package/ai/tools/jdProductScraperTool.ts +821 -0
  159. package/ai/tools/listUserSpacesTool.ts +113 -0
  160. package/ai/tools/localFilesTool.ts +276 -0
  161. package/ai/tools/marxistsOfflineBook.ts +253 -0
  162. package/ai/tools/modelUsageTools.ts +206 -0
  163. package/ai/tools/noloWorkspaceReadTools.ts +467 -0
  164. package/ai/tools/olmOcrTool.ts +33 -0
  165. package/ai/tools/openaiImageTool.ts +267 -0
  166. package/ai/tools/prepareTools.ts +23 -0
  167. package/ai/tools/readDocTool.ts +88 -0
  168. package/ai/tools/readFileTool.ts +214 -0
  169. package/ai/tools/readTool.ts +194 -0
  170. package/ai/tools/readXPostTool.ts +229 -0
  171. package/ai/tools/readXhsProfileTool.ts +627 -0
  172. package/ai/tools/rememberMemoryTool.ts +84 -0
  173. package/ai/tools/remotionVideoTool.ts +151 -0
  174. package/ai/tools/searchDialogMessagesTool.ts +222 -0
  175. package/ai/tools/searchWorkspaceTool.ts +259 -0
  176. package/ai/tools/skillFollowup.ts +86 -0
  177. package/ai/tools/surfWeatherTool.ts +169 -0
  178. package/ai/tools/table/addTableRowTool.ts +217 -0
  179. package/ai/tools/table/createTableTool.ts +315 -0
  180. package/ai/tools/table/rowTools.ts +386 -0
  181. package/ai/tools/table/schemaTools.ts +244 -0
  182. package/ai/tools/table/shareTableTool.ts +148 -0
  183. package/ai/tools/table/toolShared.ts +129 -0
  184. package/ai/tools/taobaoTmallProductScraperTool.ts +49 -0
  185. package/ai/tools/toolApiClient.ts +279 -0
  186. package/ai/tools/toolResultError.ts +42 -0
  187. package/ai/tools/toolRunSlice.ts +303 -0
  188. package/ai/tools/toolSchemaCompatibility.ts +53 -0
  189. package/ai/tools/uiAskChoiceTool.ts +104 -0
  190. package/ai/tools/updateContentTitleTool.ts +84 -0
  191. package/ai/tools/updateDocTool.ts +105 -0
  192. package/ai/tools/updateUserPreferenceProfileTool.ts +153 -0
  193. package/ai/tools/wereadGatewayTool.ts +152 -0
  194. package/ai/tools/whisperTool.ts +76 -0
  195. package/ai/tools/writeFileTool.ts +213 -0
  196. package/ai/tools/youtubeScraperTool.ts +116 -0
  197. package/ai/tools/ziweiChartTool.ts +678 -0
  198. package/ai/types.ts +55 -0
  199. package/ai/workflow/workflowExecutor.ts +323 -0
  200. package/ai/workflow/workflowSlice.ts +73 -0
  201. package/ai/workflow/workflowTypes.ts +106 -0
  202. package/app/actions/syncAppRecord.ts +73 -0
  203. package/app/constants/animationSets.ts +21 -0
  204. package/app/constants/appEditor.ts +99 -0
  205. package/app/favorite/favoriteSlice.ts +690 -0
  206. package/app/favorite/type.ts +43 -0
  207. package/app/hooks/deleteDbKey.ts +233 -0
  208. package/app/i18n/client.ts +13 -0
  209. package/app/i18n/i18n.base.ts +14 -0
  210. package/app/i18n/i18n.config.ts +77 -0
  211. package/app/i18n/index.ts +15 -0
  212. package/app/i18n/mapLanguage.ts +11 -0
  213. package/app/i18n/translations/appBuilder.locale.ts +453 -0
  214. package/app/i18n/translations/error.locale.ts +246 -0
  215. package/app/i18n/translations/interface.locale.ts +2174 -0
  216. package/app/i18n/translations/pricing.locale.ts +397 -0
  217. package/app/i18n/translations/privacy.locale.ts +168 -0
  218. package/app/i18n/translations/seo.locale.ts +129 -0
  219. package/app/i18n/translations/terms.locale.ts +124 -0
  220. package/app/i18n/types.ts +6 -0
  221. package/app/notifications/model.ts +77 -0
  222. package/app/notifications/notificationSlice.ts +141 -0
  223. package/app/reducer.ts +36 -0
  224. package/app/settings/dbActionThunks.ts +34 -0
  225. package/app/settings/defaultSpacePreference.ts +87 -0
  226. package/app/settings/settingSlice.tsx +1212 -0
  227. package/app/settings/settingsRecord.ts +8 -0
  228. package/app/stateViews/runtime.ts +90 -0
  229. package/app/store.ts +55 -0
  230. package/app/theme/colors.ts +280 -0
  231. package/app/theme/fontPreference.ts +77 -0
  232. package/app/theme/theme.config.ts +120 -0
  233. package/app/theme/themeModeBootstrap.ts +123 -0
  234. package/app/types/appSummary.ts +114 -0
  235. package/app/types.ts +358 -0
  236. package/app/utils/appKeys.ts +55 -0
  237. package/app/utils/async.ts +28 -0
  238. package/app/utils/desktopAgentRuntimeTurnClient.ts +73 -0
  239. package/app/utils/env.ts +17 -0
  240. package/app/utils/fileUtils.ts +229 -0
  241. package/app/utils/imageUtils.ts +274 -0
  242. package/app/utils/myContentItems.ts +289 -0
  243. package/app/utils/retryAfter.ts +36 -0
  244. package/app/utils/retryFetch.ts +61 -0
  245. package/app/utils/toast.ts +3 -0
  246. package/auth/action/signUpAction.ts +227 -0
  247. package/auth/adminPermissions.ts +18 -0
  248. package/auth/authSlice.ts +531 -0
  249. package/auth/client/loginRequest.ts +14 -0
  250. package/auth/resetAuthScopedClientState.ts +27 -0
  251. package/auth/routes.ts +178 -0
  252. package/auth/token.ts +63 -0
  253. package/auth/types.ts +40 -0
  254. package/chat/chat.locale.ts +813 -0
  255. package/chat/dialog/actions/addCybotAction.ts +52 -0
  256. package/chat/dialog/actions/addReferenceKeysAction.ts +62 -0
  257. package/chat/dialog/actions/builtinDialogLlm.ts +35 -0
  258. package/chat/dialog/actions/cleanupCliSession.ts +40 -0
  259. package/chat/dialog/actions/createDialogAction.ts +379 -0
  260. package/chat/dialog/actions/createScheduledTaskAction.ts +78 -0
  261. package/chat/dialog/actions/handleSendMessageAction.ts +197 -0
  262. package/chat/dialog/actions/handleSendMessageResolver.ts +27 -0
  263. package/chat/dialog/actions/removeCybotAction.ts +6 -0
  264. package/chat/dialog/actions/removeDialogAgentAction.ts +44 -0
  265. package/chat/dialog/actions/replacePrimaryCybotAction.ts +6 -0
  266. package/chat/dialog/actions/setPrimaryDialogAgentAction.ts +52 -0
  267. package/chat/dialog/actions/updateDialogSummaryAction.ts +430 -0
  268. package/chat/dialog/actions/updateDialogTitleAction.ts +151 -0
  269. package/chat/dialog/actions/updateDialogTitlePolicy.ts +30 -0
  270. package/chat/dialog/actions/updateTokensAction.ts +233 -0
  271. package/chat/dialog/dialogAgents.ts +72 -0
  272. package/chat/dialog/dialogSlice.ts +872 -0
  273. package/chat/dialog/dialogTitle.ts +81 -0
  274. package/chat/dialog/dialogTokenStats.ts +12 -0
  275. package/chat/dialog/dialogUrl.ts +6 -0
  276. package/chat/dialog/goal.ts +108 -0
  277. package/chat/dialog/objectAssistantRegistry.ts +286 -0
  278. package/chat/dialog/schedule.ts +17 -0
  279. package/chat/messages/fetchAndCacheMessages.ts +119 -0
  280. package/chat/messages/fetchConvMsgs.ts +51 -0
  281. package/chat/messages/fileUrl.ts +13 -0
  282. package/chat/messages/messageAgent.ts +8 -0
  283. package/chat/messages/messageContent.ts +199 -0
  284. package/chat/messages/messageContract.ts +88 -0
  285. package/chat/messages/messageSlice.ts +1367 -0
  286. package/chat/messages/toolThunks.ts +625 -0
  287. package/cli/client/agentRun.ts +27 -8
  288. package/cli/client/localRuntimeAdapter.ts +144 -28
  289. package/client/agentRun.test.ts +52 -0
  290. package/client/agentRun.ts +27 -8
  291. package/client/localRuntimeAdapter.test.ts +437 -6
  292. package/client/localRuntimeAdapter.ts +144 -28
  293. package/core/builtinAgents.ts +209 -0
  294. package/core/config.ts +15 -0
  295. package/core/crypto.ts +51 -0
  296. package/core/generateKeyPairFromSeedV1.ts +15 -0
  297. package/core/generateMainKey.ts +22 -0
  298. package/core/init.ts +41 -0
  299. package/core/localOrigins.ts +8 -0
  300. package/core/password.ts +13 -0
  301. package/core/prefix.ts +23 -0
  302. package/create/editor/transforms/fromMarkdown/index.ts +260 -0
  303. package/create/editor/transforms/fromMarkdown/inline.ts +285 -0
  304. package/create/editor/transforms/fromMarkdown/table.ts +130 -0
  305. package/create/editor/transforms/markdownToSlate.ts +24 -0
  306. package/create/editor/transforms/slateToRenderMarkdown.ts +218 -0
  307. package/create/editor/transforms/slateToSimplifiedMarkdown.ts +224 -0
  308. package/create/editor/transforms/slateToText.ts +33 -0
  309. package/create/editor/utils/slateUtils.ts +233 -0
  310. package/create/space/addSpaceAction.ts +193 -0
  311. package/create/space/category/categoryActions.ts +427 -0
  312. package/create/space/changeSpaceAction.ts +36 -0
  313. package/create/space/constants.ts +8 -0
  314. package/create/space/content/addContentAction.ts +116 -0
  315. package/create/space/content/contentThunks.ts +90 -0
  316. package/create/space/content/deleteContentFromSpaceAction.ts +187 -0
  317. package/create/space/content/deleteMultipleContentAction.ts +112 -0
  318. package/create/space/content/moveContentAction.ts +285 -0
  319. package/create/space/content/updateContentCategoryAction.ts +154 -0
  320. package/create/space/content/updateContentTitleAction.ts +151 -0
  321. package/create/space/content/uploadAndAddFileToSpaceAction.ts +98 -0
  322. package/create/space/contentKeyUtils.ts +117 -0
  323. package/create/space/deleteSpaceAction.ts +276 -0
  324. package/create/space/fetchSpaceAction.ts +70 -0
  325. package/create/space/fetchSpaceSidebarStateAction.ts +26 -0
  326. package/create/space/loadDefaultSpaceAction.ts +57 -0
  327. package/create/space/member/addMemberAction.ts +79 -0
  328. package/create/space/member/fetchUserSpaceMembershipsAction.ts +386 -0
  329. package/create/space/member/memberThunks.ts +47 -0
  330. package/create/space/member/removeMemberAction.ts +67 -0
  331. package/create/space/resolvePreferredSpaceId.ts +113 -0
  332. package/create/space/sidebarVisibleTypes.ts +241 -0
  333. package/create/space/space.locale.ts +1087 -0
  334. package/create/space/spaceAccess.ts +182 -0
  335. package/create/space/spaceCollapsedState.ts +54 -0
  336. package/create/space/spaceKeys.ts +65 -0
  337. package/create/space/spaceSlice.ts +328 -0
  338. package/create/space/spaceThunks.ts +410 -0
  339. package/create/space/types.ts +27 -0
  340. package/create/space/updateSpaceAction.ts +107 -0
  341. package/create/space/utils/permissions.ts +47 -0
  342. package/create/types.ts +21 -0
  343. package/database/actions/agentReadResolution.ts +33 -0
  344. package/database/actions/common.ts +243 -0
  345. package/database/actions/deleteFile.ts +40 -0
  346. package/database/actions/fileContent.ts +125 -0
  347. package/database/actions/patch.ts +155 -0
  348. package/database/actions/read.ts +358 -0
  349. package/database/actions/readAndWait.ts +260 -0
  350. package/database/actions/readRequestManager.ts +120 -0
  351. package/database/actions/readResolution.ts +125 -0
  352. package/database/actions/remove.ts +94 -0
  353. package/database/actions/replication.ts +477 -0
  354. package/database/actions/upload.ts +186 -0
  355. package/database/actions/upsert.ts +56 -0
  356. package/database/actions/write.ts +146 -0
  357. package/database/authority/ownerKey.ts +80 -0
  358. package/database/authority/recordAuthority.ts +67 -0
  359. package/database/authority/userAuthorityRegistry.ts +54 -0
  360. package/database/client/fetchUserData.ts +61 -0
  361. package/database/dbActionThunks.ts +1 -0
  362. package/database/dbSlice.ts +149 -0
  363. package/database/fileRing.ts +51 -0
  364. package/database/fileStorage.ts +232 -0
  365. package/database/fileUrl.ts +34 -0
  366. package/database/keys.ts +767 -0
  367. package/database/queryPrefixes.ts +14 -0
  368. package/database/requests.ts +443 -0
  369. package/database/runtimeServerContext.ts +54 -0
  370. package/database/tenantPlacement.ts +57 -0
  371. package/database/userPreferenceRegister.ts +131 -0
  372. package/database/utils/ulid.ts +1 -0
  373. package/integrations/anthropic/anthropicModels.ts +47 -0
  374. package/integrations/deepseek/models.ts +37 -0
  375. package/integrations/google/models.ts +341 -0
  376. package/integrations/openai/chatCompletionStreamMode.ts +10 -0
  377. package/integrations/openai/filterAndCleanMessages.ts +284 -0
  378. package/integrations/openai/flexTier.ts +102 -0
  379. package/integrations/openai/generateOpenAIRequestBody.ts +274 -0
  380. package/integrations/openai/generateResponseRequestBody.ts +77 -0
  381. package/integrations/openai/models.ts +271 -0
  382. package/integrations/openai/providerBodyCompatibility.ts +23 -0
  383. package/integrations/openai/responsesHelpers.ts +297 -0
  384. package/integrations/x-reader/types.ts +109 -0
  385. package/integrations/xai/models.ts +13 -0
  386. package/integrations/xhs-reader/analyze/profileAnalyzer.ts +205 -0
  387. package/integrations/xhs-reader/backends/playwrightProfileCollector.ts +624 -0
  388. package/integrations/xhs-reader/bridge/readXhsProfileWithBridge.ts +227 -0
  389. package/integrations/xhs-reader/client/xhsWebApiClient.ts +229 -0
  390. package/integrations/xhs-reader/normalize.ts +390 -0
  391. package/integrations/xhs-reader/orchestrator.ts +178 -0
  392. package/integrations/xhs-reader/redaction.ts +68 -0
  393. package/integrations/xhs-reader/types.ts +244 -0
  394. package/integrations/xhs-reader/url.ts +57 -0
  395. package/package.json +430 -4
  396. package/render/page/createPageAction.ts +183 -0
  397. package/render/page/docSlice.ts +468 -0
  398. package/render/page/types.ts +17 -0
  399. package/render/table/createTableAction.ts +270 -0
  400. package/render/table/deleteTableAction.ts +193 -0
  401. package/render/table/fetchAndCacheTableRows.ts +174 -0
  402. package/render/table/tableSlice.ts +1106 -0
  403. package/render/table/toolValueUtils.ts +363 -0
  404. package/render/table/types.ts +252 -0
  405. package/render/table/utils/tableSerialization.ts +50 -0
  406. package/server/handlers/agentRun/types.ts +104 -0
  407. package/share/action.ts +225 -0
  408. package/share/helpers.ts +302 -0
  409. package/share/keys.ts +243 -0
  410. package/share/publicSharePolicy.ts +27 -0
  411. package/share/shareSlice.ts +53 -0
  412. package/share/types.ts +100 -0
@@ -0,0 +1,1367 @@
1
+ // 文件路径: chat/messages/messageSlice.ts
2
+
3
+ /*
4
+ * ==================================================================
5
+ * /chat/messages/messageSlice.ts
6
+ * ==================================================================
7
+ */
8
+
9
+ import {
10
+ asyncThunkCreator,
11
+ buildCreateSlice,
12
+ createSelector,
13
+ createEntityAdapter,
14
+ type PayloadAction,
15
+ type EntityState,
16
+ } from "@reduxjs/toolkit";
17
+ import { addReferenceKeysAction } from "../dialog/actions/addReferenceKeysAction";
18
+ import type { RootState } from "../../app/store";
19
+ import { getRuntimeServerContext } from "../../database/runtimeServerContext";
20
+ import { DataType } from "../../create/types";
21
+ import { remove, write, patch, selectById as selectDbRecordById } from "../../database/dbSlice";
22
+ import type { Message } from "./types";
23
+ import { selectUserId } from "../../auth/authSlice";
24
+ import { fetchAndCacheMessages } from "./fetchAndCacheMessages";
25
+ import { createDialogMessageKeyAndId } from "../../database/keys";
26
+ import { extractCustomId } from "../../core/prefix";
27
+ import type { DialogConfig } from "../../app/types";
28
+ import { updateDialogTitle, updateTokens } from "../dialog/dialogSlice";
29
+ import { updateDialogSummaryAction } from "../dialog/actions/updateDialogSummaryAction";
30
+ import {
31
+ normalizeAssistantContentBuffer,
32
+ serializeMessageContent,
33
+ } from "./messageContent";
34
+ import {
35
+ appendSaveFailureToContent,
36
+ finalizeAssistantMessageContent,
37
+ } from "./messageContract";
38
+ import { estimateMissingUsage } from "../../ai/token/missingUsageEstimate";
39
+ import {
40
+ countImageGenerationOutputsInContent,
41
+ isOpenAIBuiltInImageGenerationAgent,
42
+ withImageGenerationCount,
43
+ } from "../../ai/token/openaiImageGenerationUsage";
44
+ import { resolveHandleSendMessageContext } from "../dialog/actions/handleSendMessageResolver";
45
+
46
+
47
+ const OLDER_LOAD_LIMIT = 30;
48
+
49
+ const isValidMessage = (msg: unknown): msg is Message =>
50
+ !!msg && typeof msg === "object" && typeof (msg as Message).id === "string";
51
+
52
+ export interface MessageSliceState {
53
+ currentDialogId: string | null;
54
+ dialogStateById: Record<string, MessageDialogState>;
55
+ }
56
+
57
+ export interface MessageDialogState {
58
+ msgs: EntityState<Message>;
59
+ firstStreamProcessed: boolean;
60
+ isLoadingInitial: boolean;
61
+ isLoadingOlder: boolean;
62
+ hasMoreOlder: boolean;
63
+ error: Error | null;
64
+ lastStreamTimestamp: number;
65
+ currentInitMsgsRequestId?: string;
66
+ currentLoadOlderRequestId?: string;
67
+ }
68
+
69
+ const createSliceWithThunks = buildCreateSlice({
70
+ creators: { asyncThunk: asyncThunkCreator },
71
+ });
72
+
73
+ const messagesAdapter = createEntityAdapter<Message>({
74
+ selectId: (message) => message.id,
75
+ sortComparer: (a, b) => a.id.localeCompare(b.id),
76
+ });
77
+
78
+ const GLOBAL_MESSAGE_DIALOG_ID = "__global__";
79
+
80
+ const createEmptyMessageDialogState = (): MessageDialogState => ({
81
+ msgs: messagesAdapter.getInitialState(),
82
+ firstStreamProcessed: false,
83
+ isLoadingInitial: false,
84
+ isLoadingOlder: false,
85
+ hasMoreOlder: true,
86
+ error: null,
87
+ lastStreamTimestamp: 0,
88
+ currentInitMsgsRequestId: undefined,
89
+ currentLoadOlderRequestId: undefined,
90
+ });
91
+
92
+ const initialState: MessageSliceState = {
93
+ currentDialogId: null,
94
+ dialogStateById: {
95
+ [GLOBAL_MESSAGE_DIALOG_ID]: createEmptyMessageDialogState(),
96
+ },
97
+ };
98
+
99
+ // messageStreamEnd 的 payload 类型
100
+ interface MessageStreamEndPayload {
101
+ finalContentBuffer: any[];
102
+ totalUsage: any;
103
+ msgKey: string;
104
+ agentConfig: any;
105
+ dialogId: string;
106
+ dialogKey: string;
107
+ messageId: string;
108
+ reasoningBuffer: string;
109
+ spaceId?: string;
110
+ messageMetadata?: Partial<Message>;
111
+ toolCalls?: Array<{
112
+ id: string;
113
+ type: "function";
114
+ function: {
115
+ name: string;
116
+ arguments: string;
117
+ };
118
+ }>;
119
+ }
120
+
121
+ type DialogScopedMessage = Message & { dialogId?: string };
122
+ type DialogScopedStreamingMessage = Partial<Message> & {
123
+ id: string;
124
+ dialogId?: string;
125
+ };
126
+
127
+ type MessageScopePayload = { dialogId?: string; dialogKey?: string; all?: boolean };
128
+
129
+ const getLatestUserInputForUnderstanding = (
130
+ state: RootState,
131
+ dialogId: string
132
+ ): string | null => {
133
+ const messages = selectAllMsgs(state, dialogId);
134
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
135
+ const message = messages[index];
136
+ if (!message || message.role !== "user") continue;
137
+ const serialized = serializeMessageContent(message.content, "[图片]")?.trim();
138
+ if (serialized) return serialized;
139
+ }
140
+ return null;
141
+ };
142
+
143
+ const getDialogSpaceIdForUnderstanding = (
144
+ state: RootState,
145
+ dialogKey?: string
146
+ ): string | undefined => {
147
+ if (!dialogKey) return undefined;
148
+ const dialog = selectDbRecordById(state, dialogKey) as DialogConfig | undefined;
149
+ return typeof dialog?.spaceId === "string" ? dialog.spaceId : undefined;
150
+ };
151
+
152
+ export const captureUnderstandingFromCompletedUiTurn = async (input: {
153
+ state: RootState;
154
+ db?: any;
155
+ agentKey?: string | null;
156
+ dialogId: string;
157
+ dialogKey?: string;
158
+ spaceId?: string;
159
+ assistantText: string;
160
+ toolCalls?: MessageStreamEndPayload["toolCalls"];
161
+ }): Promise<void> => {
162
+ if (input.assistantText.trim() === "") return;
163
+ if (input.toolCalls && input.toolCalls.length > 0) return;
164
+ if (!input.agentKey) return;
165
+
166
+ const latestUserInput = getLatestUserInputForUnderstanding(
167
+ input.state,
168
+ input.dialogId
169
+ );
170
+ if (!latestUserInput) return;
171
+
172
+ const { captureUnderstandingMemoryFromDialog } = await import("../../ai/memory/understanding");
173
+ await captureUnderstandingMemoryFromDialog({
174
+ db: input.db,
175
+ userId: selectUserId(input.state),
176
+ spaceId:
177
+ input.spaceId ??
178
+ getDialogSpaceIdForUnderstanding(input.state, input.dialogKey),
179
+ agentKey: input.agentKey,
180
+ dialogId: input.dialogId,
181
+ userInput: latestUserInput,
182
+ trace: [
183
+ {
184
+ role: "assistant",
185
+ content: input.assistantText,
186
+ } as Message,
187
+ ],
188
+ });
189
+ };
190
+
191
+ const resolveMessageDialogId = (
192
+ state: Pick<MessageSliceState, "currentDialogId">,
193
+ dialogId?: string | null,
194
+ dialogKey?: string | null
195
+ ) =>
196
+ dialogId ??
197
+ (dialogKey ? extractCustomId(dialogKey) : null) ??
198
+ state.currentDialogId ??
199
+ GLOBAL_MESSAGE_DIALOG_ID;
200
+
201
+ const ensureMessageDialogState = (
202
+ state: MessageSliceState,
203
+ dialogId?: string | null,
204
+ dialogKey?: string | null
205
+ ): MessageDialogState => {
206
+ const resolvedDialogId = resolveMessageDialogId(state, dialogId, dialogKey);
207
+ if (!state.dialogStateById) {
208
+ state.dialogStateById = {
209
+ [GLOBAL_MESSAGE_DIALOG_ID]: createEmptyMessageDialogState(),
210
+ };
211
+ }
212
+ if (!state.dialogStateById[resolvedDialogId]) {
213
+ state.dialogStateById[resolvedDialogId] = createEmptyMessageDialogState();
214
+ }
215
+ return state.dialogStateById[resolvedDialogId];
216
+ };
217
+
218
+ const getMessageDialogState = (
219
+ state: MessageSliceState,
220
+ dialogId?: string | null,
221
+ dialogKey?: string | null
222
+ ): MessageDialogState => {
223
+ const dialogStateById = state.dialogStateById ?? {};
224
+ const resolvedDialogId = resolveMessageDialogId(state, dialogId, dialogKey);
225
+ const bucket = dialogStateById[resolvedDialogId];
226
+ if (bucket) return bucket;
227
+
228
+ const legacyMsgs = (state as any).msgs;
229
+ if (legacyMsgs && typeof legacyMsgs === "object") {
230
+ return {
231
+ msgs: legacyMsgs,
232
+ firstStreamProcessed: (state as any).firstStreamProcessed ?? false,
233
+ isLoadingInitial: (state as any).isLoadingInitial ?? false,
234
+ isLoadingOlder: (state as any).isLoadingOlder ?? false,
235
+ hasMoreOlder: (state as any).hasMoreOlder ?? true,
236
+ error: (state as any).error ?? null,
237
+ lastStreamTimestamp: (state as any).lastStreamTimestamp ?? 0,
238
+ currentInitMsgsRequestId: (state as any).currentInitMsgsRequestId,
239
+ currentLoadOlderRequestId: (state as any).currentLoadOlderRequestId,
240
+ };
241
+ }
242
+
243
+ return createEmptyMessageDialogState();
244
+ };
245
+
246
+ const inferDialogIdFromDbKey = (dbKey?: string): string | null => {
247
+ if (!dbKey) return null;
248
+ const parts = dbKey.split("-");
249
+ if (parts.length >= 4 && parts[0] === DataType.DIALOG && parts[2] === "msg") {
250
+ return parts[1];
251
+ }
252
+ return null;
253
+ };
254
+
255
+ const inferDialogIdFromMessage = (
256
+ message: Partial<Message> & { dialogId?: string }
257
+ ): string | null => message.dialogId ?? inferDialogIdFromDbKey(message.dbKey);
258
+
259
+ export const buildEditedMessageContent = (
260
+ originalContent: Message["content"],
261
+ nextText: string
262
+ ): Message["content"] => {
263
+ const trimmedText = nextText.trim();
264
+
265
+ if (typeof originalContent === "string") {
266
+ return trimmedText;
267
+ }
268
+
269
+ if (Array.isArray(originalContent)) {
270
+ const nextParts = originalContent.filter(
271
+ (part) => part && typeof part === "object" && part.type !== "text"
272
+ );
273
+
274
+ if (trimmedText) {
275
+ nextParts.unshift({ type: "text", text: trimmedText } as any);
276
+ }
277
+
278
+ return nextParts;
279
+ }
280
+
281
+ return trimmedText;
282
+ };
283
+
284
+ const findDialogIdByMessageId = (
285
+ state: MessageSliceState,
286
+ messageId: string
287
+ ): string | null => {
288
+ for (const [dialogId, dialogState] of Object.entries(state.dialogStateById)) {
289
+ if (dialogState.msgs.entities[messageId]) {
290
+ return dialogId;
291
+ }
292
+ }
293
+ return null;
294
+ };
295
+
296
+ const findDialogIdByMessageDbKey = (
297
+ state: MessageSliceState,
298
+ dbKey: string
299
+ ): string | null => {
300
+ for (const [dialogId, dialogState] of Object.entries(state.dialogStateById)) {
301
+ const hasDbKey = Object.values(dialogState.msgs.entities).some(
302
+ (message) => message?.dbKey === dbKey
303
+ );
304
+ if (hasDbKey) {
305
+ return dialogId;
306
+ }
307
+ }
308
+ return inferDialogIdFromDbKey(dbKey);
309
+ };
310
+
311
+ const upsertOneMessage = (dialogState: MessageDialogState, message: Message) => {
312
+ dialogState.msgs = messagesAdapter.upsertOne(dialogState.msgs, message);
313
+ };
314
+
315
+ const upsertManyMessages = (
316
+ dialogState: MessageDialogState,
317
+ messages: Message[]
318
+ ) => {
319
+ dialogState.msgs = messagesAdapter.upsertMany(dialogState.msgs, messages);
320
+ };
321
+
322
+ const addOneMessage = (dialogState: MessageDialogState, message: Message) => {
323
+ dialogState.msgs = messagesAdapter.addOne(dialogState.msgs, message);
324
+ };
325
+
326
+ const updateOneMessage = (
327
+ dialogState: MessageDialogState,
328
+ payload: { id: string; changes: Partial<Message> }
329
+ ) => {
330
+ dialogState.msgs = messagesAdapter.updateOne(dialogState.msgs, payload);
331
+ };
332
+
333
+ const updateManyMessages = (
334
+ dialogState: MessageDialogState,
335
+ payload: Array<{ id: string; changes: Partial<Message> }>
336
+ ) => {
337
+ dialogState.msgs = messagesAdapter.updateMany(dialogState.msgs, payload);
338
+ };
339
+
340
+ const removeOneMessage = (dialogState: MessageDialogState, messageId: string) => {
341
+ dialogState.msgs = messagesAdapter.removeOne(dialogState.msgs, messageId);
342
+ };
343
+
344
+ const removeAllMessages = (dialogState: MessageDialogState) => {
345
+ dialogState.msgs = messagesAdapter.removeAll(dialogState.msgs);
346
+ };
347
+
348
+ const setAllMessages = (dialogState: MessageDialogState, messages: Message[]) => {
349
+ dialogState.msgs = messagesAdapter.setAll(dialogState.msgs, messages);
350
+ };
351
+
352
+ export const messageSlice = createSliceWithThunks({
353
+ name: "message",
354
+ initialState,
355
+ reducers: (create) => ({
356
+ addUserMessage: create.reducer<DialogScopedMessage>((state, action) => {
357
+ const { dialogId, ...message } = action.payload;
358
+ const dialogState = ensureMessageDialogState(
359
+ state,
360
+ dialogId ?? inferDialogIdFromMessage(action.payload)
361
+ );
362
+ upsertOneMessage(dialogState, {
363
+ ...message,
364
+ isStreaming: false,
365
+ });
366
+ }),
367
+
368
+ messageStreaming: create.reducer<DialogScopedStreamingMessage>(
369
+ (state, action) => {
370
+ const { dialogId, ...message } = action.payload;
371
+ const dialogState = ensureMessageDialogState(
372
+ state,
373
+ dialogId ?? inferDialogIdFromMessage(action.payload)
374
+ );
375
+ upsertOneMessage(dialogState, {
376
+ isStreaming: true,
377
+ content: "",
378
+ thinkContent: "",
379
+ ...message,
380
+ });
381
+ dialogState.firstStreamProcessed = true;
382
+ dialogState.lastStreamTimestamp = Date.now();
383
+ }
384
+ ),
385
+
386
+ resetMsgs: create.reducer((state, action: PayloadAction<MessageScopePayload | undefined>) => {
387
+ if (action.payload?.all) {
388
+ state.dialogStateById = {
389
+ [GLOBAL_MESSAGE_DIALOG_ID]: createEmptyMessageDialogState(),
390
+ };
391
+ state.currentDialogId = null;
392
+ return;
393
+ }
394
+
395
+ const dialogId = resolveMessageDialogId(
396
+ state,
397
+ action.payload?.dialogId,
398
+ action.payload?.dialogKey
399
+ );
400
+ delete state.dialogStateById[dialogId];
401
+
402
+ if (dialogId === state.currentDialogId) {
403
+ state.currentDialogId = null;
404
+ }
405
+
406
+ if (!state.dialogStateById[GLOBAL_MESSAGE_DIALOG_ID]) {
407
+ state.dialogStateById[GLOBAL_MESSAGE_DIALOG_ID] =
408
+ createEmptyMessageDialogState();
409
+ }
410
+ }),
411
+
412
+ clearAllStreaming: create.reducer((state, action: PayloadAction<MessageScopePayload | undefined>) => {
413
+ const targetStates = action.payload?.all
414
+ ? Object.values(state.dialogStateById)
415
+ : [getMessageDialogState(state, action.payload?.dialogId, action.payload?.dialogKey)];
416
+
417
+ targetStates.forEach((dialogState) => {
418
+ const updates = Object.values(dialogState.msgs.entities)
419
+ .filter((m) => m?.isStreaming)
420
+ .map((m) => ({ id: m!.id, changes: { isStreaming: false } }));
421
+ if (updates.length > 0) {
422
+ updateManyMessages(dialogState, updates);
423
+ }
424
+ });
425
+ }),
426
+
427
+ removeTransientMessage: create.reducer(
428
+ (state, action: PayloadAction<string | { id: string; dialogId?: string }>) => {
429
+ const payload =
430
+ typeof action.payload === "string"
431
+ ? { id: action.payload }
432
+ : action.payload;
433
+ const dialogId =
434
+ payload.dialogId ?? findDialogIdByMessageId(state, payload.id);
435
+ const dialogState = ensureMessageDialogState(state, dialogId);
436
+ removeOneMessage(dialogState, payload.id);
437
+ }
438
+ ),
439
+
440
+ addToolMessage: create.reducer<Message & { dialogId?: string }>((state, action) => {
441
+ const dialogState = ensureMessageDialogState(
442
+ state,
443
+ inferDialogIdFromMessage(action.payload)
444
+ );
445
+ addOneMessage(dialogState, action.payload);
446
+ }),
447
+
448
+ updateToolMessage: create.reducer<{
449
+ id: string;
450
+ changes: Partial<Message>;
451
+ dialogId?: string;
452
+ }>((state, action) => {
453
+ const dialogState = ensureMessageDialogState(
454
+ state,
455
+ action.payload.dialogId ?? findDialogIdByMessageId(state, action.payload.id)
456
+ );
457
+ updateOneMessage(dialogState, action.payload);
458
+ }),
459
+
460
+ removeMessagesByIds: create.reducer<{
461
+ ids: string[];
462
+ dialogId?: string;
463
+ }>((state, action) => {
464
+ const dialogState = ensureMessageDialogState(state, action.payload.dialogId);
465
+ dialogState.msgs = messagesAdapter.removeMany(dialogState.msgs, action.payload.ids);
466
+ }),
467
+
468
+
469
+
470
+ prepareAndPersistMessage: create.asyncThunk(
471
+ async (
472
+ args: {
473
+ message: Omit<Message, "id" | "dbKey" | "userId">;
474
+ dialogConfig: DialogConfig;
475
+ },
476
+ thunkApi
477
+ ) => {
478
+ const { message, dialogConfig } = args;
479
+ const { getState, dispatch, rejectWithValue } = thunkApi;
480
+ const state = getState() as RootState;
481
+
482
+ if (!dialogConfig) {
483
+ return rejectWithValue("Missing dialogConfig");
484
+ }
485
+
486
+ const dialogKey = dialogConfig.dbKey || dialogConfig.id;
487
+ const dialogId = extractCustomId(dialogKey);
488
+ const userId = selectUserId(state);
489
+
490
+ const { key: messageDbKey, messageId } =
491
+ createDialogMessageKeyAndId(dialogId);
492
+
493
+ const fullMessage: Message = {
494
+ ...message,
495
+ id: messageId,
496
+ dbKey: messageDbKey,
497
+ userId,
498
+ };
499
+
500
+ // 提取并保存引用 keys
501
+ dispatch(
502
+ addReferenceKeysAction({
503
+ content: message.content,
504
+ dialogKey,
505
+ })
506
+ ).catch((err) => console.error("Failed to add refs:", err));
507
+
508
+ dispatch(messageSlice.actions.addUserMessage({ ...fullMessage, dialogId }));
509
+
510
+ const { controller, ...messageToWrite } = fullMessage;
511
+ dispatch(
512
+ write({
513
+ data: { ...messageToWrite, type: DataType.MSG },
514
+ customKey: fullMessage.dbKey,
515
+ })
516
+ );
517
+
518
+ return fullMessage;
519
+ }
520
+ ),
521
+
522
+ prepareAndPersistUserMessage: create.asyncThunk(
523
+ async (
524
+ args: { userInput: string; dialogConfig: DialogConfig },
525
+ thunkApi
526
+ ) => {
527
+ const { userInput, dialogConfig } = args;
528
+ const { dispatch } = thunkApi;
529
+
530
+ return dispatch(
531
+ messageSlice.actions.prepareAndPersistMessage({
532
+ message: {
533
+ role: "user",
534
+ content: userInput,
535
+ },
536
+ dialogConfig,
537
+ })
538
+ ).unwrap();
539
+ }
540
+ ),
541
+
542
+ /**
543
+ * 初始化当前对话消息
544
+ */
545
+ initMsgs: create.asyncThunk(
546
+ async (
547
+ {
548
+ dialogId,
549
+ dialogKey,
550
+ limit,
551
+ isNew,
552
+ }: {
553
+ dialogId: string;
554
+ dialogKey?: string;
555
+ limit: number;
556
+ isNew?: boolean;
557
+ },
558
+ thunkApi
559
+ ): Promise<Message[]> => {
560
+ const { db } = thunkApi.extra;
561
+ const { getState, signal } = thunkApi;
562
+
563
+ const state = getState() as RootState;
564
+ const { currentToken: token, remoteServers } =
565
+ getRuntimeServerContext(state);
566
+ const finalMessages = (
567
+ await fetchAndCacheMessages({
568
+ db,
569
+ dialogId,
570
+ dialogKey,
571
+ limit,
572
+ token,
573
+ remoteServers,
574
+ signal,
575
+ })
576
+ ).filter(isValidMessage);
577
+
578
+ // --- Post-fetch check: Resume suspended summary tasks ---
579
+ try {
580
+ // Note: We need to find the dialogKey. We have dialogId.
581
+ // Usually we can query state, but state might be stale if we just loaded.
582
+ // However, dialogConfig should be in 'dbSlice' or 'dialogSlice' state.
583
+ // Let's try to find it from the Redux state.
584
+ const rootState = getState() as RootState;
585
+ const { entities } = rootState.db; // Access raw DB entities if needed, or use selectors
586
+
587
+ const dialogConfig = Object.values(entities).find(
588
+ (entity): entity is DialogConfig => {
589
+ if (!entity || typeof entity !== "object") return false;
590
+ const value = entity as { type?: unknown; id?: unknown };
591
+ return value.type === DataType.DIALOG && value.id === dialogId;
592
+ }
593
+ );
594
+
595
+ if (dialogConfig && dialogConfig.summaryPending && dialogConfig.dbKey) {
596
+ console.log("[initMsgs] Found suspended summary task, resuming...", dialogConfig.dbKey);
597
+ // Clear the flag first to avoid loops (though action has lock)
598
+ thunkApi.dispatch(patch({
599
+ dbKey: dialogConfig.dbKey,
600
+ changes: { summaryPending: false }
601
+ }));
602
+
603
+ // 2. Resume summary update (directly calling async function)
604
+ updateDialogSummaryAction(
605
+ { dialogKey: dialogConfig.dbKey, preFetchedMessages: finalMessages },
606
+ thunkApi
607
+ ).catch(err => console.error("Resume summary failed:", err));
608
+ }
609
+ } catch (e) {
610
+ console.error("[initMsgs] Failed to resume summary:", e);
611
+ }
612
+
613
+ return finalMessages;
614
+ },
615
+ {
616
+ pending: (state, action) => {
617
+ const { dialogId, isNew } = action.meta.arg as {
618
+ dialogId: string;
619
+ limit: number;
620
+ isNew?: boolean;
621
+ };
622
+ const dialogState = ensureMessageDialogState(state, dialogId);
623
+
624
+ // 不在 pending 阶段清空消息,保留旧消息供用户查看,
625
+ // 避免切换对话时出现消息列表短暂变空的闪烁。
626
+ // 新消息将在 fulfilled 阶段原子性替换。
627
+ if (isNew) {
628
+ // 全新对话才需要立即清空(没有历史消息)
629
+ // 只有内存中确实没有任何已有消息时才清空,防止抹除已经 optimistic 抢先写入的首条消息
630
+ if (Object.keys(dialogState.msgs.entities).length === 0) {
631
+ removeAllMessages(dialogState);
632
+ }
633
+ }
634
+
635
+ dialogState.firstStreamProcessed = false;
636
+ dialogState.isLoadingInitial = true;
637
+ dialogState.isLoadingOlder = false;
638
+ dialogState.hasMoreOlder = true;
639
+ dialogState.error = null;
640
+ dialogState.lastStreamTimestamp = 0;
641
+ state.currentDialogId = dialogId;
642
+ dialogState.currentInitMsgsRequestId = action.meta.requestId;
643
+ },
644
+ fulfilled: (state, action) => {
645
+ const dialogState = ensureMessageDialogState(state, action.meta.arg.dialogId);
646
+ if (dialogState.currentInitMsgsRequestId !== action.meta.requestId) {
647
+ return;
648
+ }
649
+
650
+ dialogState.isLoadingInitial = false;
651
+ if (action.meta.arg.isNew) {
652
+ upsertManyMessages(dialogState, action.payload);
653
+ } else {
654
+ // 用从 DB 加载的消息原子性替换,确保不遗留已删除消息或旧的流式消息
655
+ setAllMessages(dialogState, action.payload);
656
+ }
657
+
658
+ // Check for pending summary tasks and resume them
659
+ // We need access to the dialog config. We can try to find it in the store via thunkAPI (not available here)
660
+ // OR we can do a fire-and-forget logic if we had access to dispatch.
661
+ // Since we are in a reducer, we CANNOT dispatch actions or access other slices easily.
662
+ // The correct way is to use a Listener Middleware or AppThunk, but for minimal changes:
663
+ // We can piggyback on the thunk's promise handling if we return extra data, but initMsgs returns Message[].
664
+ // Alternatively, we use `initMsgs.fulfilled` in a separate listener or component.
665
+
666
+ // BETTER: Do it in the component layer or use a thunk wrapper.
667
+ // However, for "minimal changes" requested by user:
668
+ // We can try to do this in the `swallowNonAbortError` or logic inside the thunk?
669
+ // NO, the user moved logic OUT of the thunk body because of P1 error (empty state).
670
+ // user said: "Move to initMsgs.fulfilled IS NOT POSSIBLE because it is a reducer".
671
+ // Actually user said: "Remove from initMsgs async ... and use updateDialogSummaryAction with preFetchedMessages".
672
+ // So we should put it BACK into the thunk body, but pass `allMessages` explicitly!
673
+
674
+ },
675
+ rejected: (state, action) => {
676
+ const dialogState = ensureMessageDialogState(state, action.meta.arg.dialogId);
677
+ if (dialogState.currentInitMsgsRequestId !== action.meta.requestId) {
678
+ return;
679
+ }
680
+
681
+ dialogState.isLoadingInitial = false;
682
+
683
+ if (action.meta?.aborted) {
684
+ return;
685
+ }
686
+
687
+ dialogState.error =
688
+ action.error instanceof Error
689
+ ? action.error
690
+ : new Error(String(action.error));
691
+ console.error(`${action.type} failed:`, action.error);
692
+ },
693
+ }
694
+ ),
695
+
696
+ /**
697
+ * 加载更早的历史消息
698
+ */
699
+ loadOlderMessages: create.asyncThunk(
700
+ async (
701
+ {
702
+ dialogId,
703
+ dialogKey,
704
+ beforeKey,
705
+ limit = OLDER_LOAD_LIMIT,
706
+ }: { dialogId: string; dialogKey?: string; beforeKey?: string; limit?: number },
707
+ thunkApi
708
+ ): Promise<{ messages: Message[]; limit: number }> => {
709
+ const { getState, extra, signal } = thunkApi;
710
+ const { db } = extra;
711
+
712
+ const state = getState() as RootState;
713
+ const { currentToken: token, remoteServers } =
714
+ getRuntimeServerContext(state);
715
+ const messages = (
716
+ await fetchAndCacheMessages({
717
+ db,
718
+ dialogId,
719
+ dialogKey,
720
+ limit,
721
+ beforeKey,
722
+ token,
723
+ remoteServers,
724
+ signal,
725
+ })
726
+ ).filter(isValidMessage);
727
+
728
+ return { messages, limit };
729
+ },
730
+ {
731
+ pending: (state, action) => {
732
+ const dialogState = ensureMessageDialogState(state, action.meta.arg.dialogId);
733
+ dialogState.isLoadingOlder = true;
734
+ dialogState.error = null;
735
+ dialogState.currentLoadOlderRequestId = action.meta.requestId;
736
+ },
737
+ fulfilled: (state, action) => {
738
+ const dialogState = ensureMessageDialogState(state, action.meta.arg.dialogId);
739
+ if (dialogState.currentLoadOlderRequestId !== action.meta.requestId) {
740
+ return;
741
+ }
742
+
743
+ dialogState.isLoadingOlder = false;
744
+ const { messages, limit } = action.payload;
745
+
746
+ if (messages.length > 0) {
747
+ upsertManyMessages(dialogState, messages);
748
+ }
749
+ if (messages.length < limit) {
750
+ dialogState.hasMoreOlder = false;
751
+ }
752
+ },
753
+ rejected: (state, action) => {
754
+ const dialogState = ensureMessageDialogState(state, action.meta.arg.dialogId);
755
+ if (dialogState.currentLoadOlderRequestId !== action.meta.requestId) {
756
+ return;
757
+ }
758
+
759
+ dialogState.isLoadingOlder = false;
760
+
761
+ if (action.meta?.aborted) {
762
+ return;
763
+ }
764
+
765
+ dialogState.error =
766
+ action.error instanceof Error
767
+ ? action.error
768
+ : new Error(String(action.error));
769
+ console.error(`${action.type} failed:`, action.error);
770
+ },
771
+ }
772
+ ),
773
+
774
+ /**
775
+ * 一条流式回复结束
776
+ */
777
+ messageStreamEnd: create.asyncThunk(
778
+ async (payload: MessageStreamEndPayload, { dispatch, getState, extra }) => {
779
+ const {
780
+ finalContentBuffer,
781
+ totalUsage,
782
+ msgKey,
783
+ agentConfig,
784
+ dialogId,
785
+ dialogKey,
786
+ messageId,
787
+ reasoningBuffer,
788
+ toolCalls,
789
+ } = payload;
790
+
791
+ // 1. 先把 contentBuffer 中的 dataURL 图像上传为文件 URL
792
+ const spaceId = payload.spaceId;
793
+ const rawAgentName = typeof agentConfig?.name === "string" ? agentConfig.name.trim() : "";
794
+ const normalizedContentBuffer = await normalizeAssistantContentBuffer(
795
+ finalContentBuffer,
796
+ dialogId,
797
+ messageId,
798
+ dispatch,
799
+ getState,
800
+ spaceId ? { spaceId, agentName: rawAgentName || undefined } : undefined
801
+ );
802
+
803
+ const finalUsageData =
804
+ totalUsage && totalUsage.completion_tokens != null
805
+ ? { completion_tokens: totalUsage.completion_tokens }
806
+ : undefined;
807
+
808
+ const {
809
+ thinkContent,
810
+ textContent,
811
+ visibleContent: finalVisibleContent,
812
+ } =
813
+ finalizeAssistantMessageContent(
814
+ normalizedContentBuffer,
815
+ reasoningBuffer
816
+ );
817
+ const imageGenerationCount = countImageGenerationOutputsInContent(
818
+ finalVisibleContent
819
+ );
820
+ const billedUsage =
821
+ isOpenAIBuiltInImageGenerationAgent(agentConfig)
822
+ ? withImageGenerationCount(totalUsage, imageGenerationCount)
823
+ : totalUsage;
824
+ const estimatedUsage = estimateMissingUsage({
825
+ content: finalVisibleContent,
826
+ });
827
+ const billedEstimatedUsage =
828
+ isOpenAIBuiltInImageGenerationAgent(agentConfig)
829
+ ? withImageGenerationCount(estimatedUsage, imageGenerationCount)
830
+ : estimatedUsage;
831
+
832
+ // 从 Agent 配置里提取名称,写入消息(供后续多 Agent 视角使用)
833
+ const rawName =
834
+ typeof agentConfig?.name === "string"
835
+ ? agentConfig.name.trim()
836
+ : "";
837
+ const agentName = rawName || undefined;
838
+ const { imageGenerationState: _transientImageGenerationState, ...persistedMessageMetadata } =
839
+ payload.messageMetadata ?? {};
840
+
841
+ const finalMessage: Message = {
842
+ id: messageId,
843
+ dbKey: msgKey,
844
+ content: finalVisibleContent,
845
+ thinkContent,
846
+ role: "assistant",
847
+ agentKey: agentConfig.dbKey,
848
+ cybotKey: agentConfig.dbKey,
849
+ usage: finalUsageData,
850
+ isStreaming: false,
851
+ ...persistedMessageMetadata,
852
+ ...(agentName ? { agentName } : {}),
853
+ ...(toolCalls && toolCalls.length > 0
854
+ ? { tool_calls: toolCalls }
855
+ : {}),
856
+ };
857
+
858
+ const { controller, ...messageToWrite } = finalMessage;
859
+
860
+ dispatch(
861
+ write({
862
+ data: { ...messageToWrite, type: DataType.MSG },
863
+ customKey: msgKey,
864
+ })
865
+ );
866
+
867
+ if (totalUsage) {
868
+ dispatch(
869
+ updateTokens({
870
+ dialogId,
871
+ dialogKey,
872
+ usage: billedUsage,
873
+ agentConfig,
874
+ })
875
+ );
876
+ } else if (agentConfig?.provider && agentConfig.provider !== "custom") {
877
+ dispatch(
878
+ updateTokens({
879
+ dialogId,
880
+ dialogKey,
881
+ usage: billedEstimatedUsage,
882
+ agentConfig,
883
+ })
884
+ );
885
+ console.warn("[billing] Missing usage at messageStreamEnd; using estimated token update", {
886
+ dialogId,
887
+ dialogKey,
888
+ provider: agentConfig.provider,
889
+ model: agentConfig.model,
890
+ endpointKey: agentConfig.endpointKey,
891
+ });
892
+ }
893
+
894
+ const titleEligibleContent =
895
+ serializeMessageContent(finalVisibleContent, "[图片]") ?? "";
896
+
897
+ if (titleEligibleContent.trim() !== "") {
898
+ dispatch(updateDialogTitle({ dialogKey, agentConfig }));
899
+ }
900
+
901
+ if (textContent.trim() !== "") {
902
+ const messagesForSummary = [
903
+ ...selectAllMsgs(getState() as RootState, dialogId),
904
+ finalMessage,
905
+ ];
906
+
907
+ // 后台触发摘要更新(fire-and-forget,不阻塞主流程)
908
+ updateDialogSummaryAction(
909
+ {
910
+ dialogKey,
911
+ preFetchedMessages: messagesForSummary,
912
+ force: !toolCalls || toolCalls.length === 0,
913
+ reason:
914
+ !toolCalls || toolCalls.length === 0
915
+ ? "task_completed"
916
+ : "context_budget",
917
+ },
918
+ { dispatch, getState }
919
+ )
920
+ .catch(err => console.error("Summary update failed:", err));
921
+
922
+ // 提取并保存引用 keys (Assistant)
923
+ dispatch(addReferenceKeysAction({
924
+ content: finalVisibleContent,
925
+ dialogKey
926
+ })).catch(err => console.error("Failed to add assistant refs:", err));
927
+ }
928
+
929
+ await captureUnderstandingFromCompletedUiTurn({
930
+ state: getState() as RootState,
931
+ db: extra?.db,
932
+ agentKey: agentConfig?.dbKey,
933
+ dialogId,
934
+ dialogKey,
935
+ spaceId: payload.spaceId,
936
+ assistantText: textContent,
937
+ toolCalls,
938
+ });
939
+
940
+ return {
941
+ id: messageId,
942
+ content: finalMessage.content,
943
+ thinkContent: finalMessage.thinkContent,
944
+ usage: finalMessage.usage,
945
+ agentKey: finalMessage.agentKey,
946
+ cybotKey: finalMessage.cybotKey,
947
+ tool_calls: (finalMessage as any).tool_calls,
948
+ dialogId,
949
+ agentName: finalMessage.agentName,
950
+ };
951
+ },
952
+ {
953
+ fulfilled: (state, action) => {
954
+ const { dialogId, agentName } = action.payload as {
955
+ dialogId: string;
956
+ agentName?: string;
957
+ };
958
+ const dialogState = ensureMessageDialogState(state, dialogId);
959
+ updateOneMessage(dialogState, {
960
+ id: action.payload.id,
961
+ changes: {
962
+ isStreaming: false,
963
+ imageGenerationState: undefined,
964
+ content: action.payload.content,
965
+ thinkContent: action.payload.thinkContent,
966
+ usage: action.payload.usage,
967
+ ...(action.payload.agentKey
968
+ ? { agentKey: action.payload.agentKey }
969
+ : {}),
970
+ cybotKey: action.payload.cybotKey,
971
+ ...(action.payload.tool_calls
972
+ ? { tool_calls: action.payload.tool_calls }
973
+ : {}),
974
+ ...(agentName ? { agentName } : {}),
975
+ },
976
+ });
977
+
978
+ // === 一轮流式回复结束后的 dev-reload 行为(仅限无工具调用的简单轮次)===
979
+ if (
980
+ typeof window !== "undefined" &&
981
+ typeof window.location?.reload === "function"
982
+ ) {
983
+ const w = window as any;
984
+ const isProd = w.__IS_PRODUCTION_BUILD__ === true;
985
+
986
+ // Agent Loop / 工具调用场景下,本轮结束后很可能还会有后续轮次。
987
+ // 为避免在中途刷新打断 Agent Loop,当本条消息包含 tool_calls 时,
988
+ // 仅重置自举保护计数,不做自动 reload。
989
+ const hasToolCalls =
990
+ Array.isArray((action.payload as any).tool_calls) &&
991
+ (action.payload as any).tool_calls.length > 0;
992
+
993
+ // 结束一轮后,无论成败,清空自举保护计数
994
+ if (typeof w.__DEV_RELOAD_SUPPRESS_COUNT__ === "number") {
995
+ w.__DEV_RELOAD_SUPPRESS_COUNT__ = 0;
996
+ }
997
+
998
+ // 开发环境:如果这轮期间有 pending 的新构建,且本轮没有工具调用,自动刷新一次
999
+ if (!hasToolCalls && !isProd && w.__DEV_RELOAD_PENDING__) {
1000
+ w.__DEV_RELOAD_PENDING__ = false;
1001
+ try {
1002
+
1003
+ // 延迟到当前事件循环尾部,避免影响 Redux 自身逻辑
1004
+ setTimeout(() => {
1005
+ window.location.reload();
1006
+ }, 0);
1007
+ } catch (e) {
1008
+ console.error("自动 dev reload 失败:", e);
1009
+ }
1010
+ }
1011
+ }
1012
+ // === dev-reload 逻辑结束 ===
1013
+
1014
+ // === 新增结束 ===
1015
+ },
1016
+ rejected: (state, action) => {
1017
+ const arg = action.meta?.arg as MessageStreamEndPayload | undefined;
1018
+ const messageId = arg?.messageId;
1019
+ const dialogId = arg?.dialogId;
1020
+
1021
+ console.error("messageStreamEnd failed:", action.error);
1022
+ if (messageId && dialogId) {
1023
+ const dialogState = ensureMessageDialogState(state, dialogId);
1024
+ updateOneMessage(dialogState, {
1025
+ id: messageId,
1026
+ changes: {
1027
+ isStreaming: false,
1028
+ imageGenerationState: undefined,
1029
+ content: appendSaveFailureToContent(
1030
+ dialogState.msgs.entities[messageId]?.content
1031
+ ),
1032
+ },
1033
+ });
1034
+ }
1035
+ },
1036
+ }
1037
+ ),
1038
+
1039
+ deleteMessage: create.asyncThunk(
1040
+ async (dbKey: string, { dispatch, getState }) => {
1041
+ const state = getState() as RootState;
1042
+ const dialogId = findDialogIdByMessageDbKey(state.message, dbKey);
1043
+ const dialogState = dialogId
1044
+ ? state.message.dialogStateById[dialogId]
1045
+ : undefined;
1046
+ const entities = dialogState?.msgs.entities ?? {};
1047
+
1048
+ // 找到被删除的这条 message
1049
+ const msg = Object.values(entities).find((m) => m?.dbKey === dbKey);
1050
+ const msgId = msg?.id;
1051
+
1052
+ // 默认只删除当前这条
1053
+ let extraRemoveId: string | undefined;
1054
+ let extraRemoveDbKey: string | undefined;
1055
+
1056
+ // 如果是工具消息,尝试一并清理对应的「assistant tool stub」
1057
+ if (msg?.role === "tool" && msg.parentMessageId) {
1058
+ const parent = entities[msg.parentMessageId];
1059
+
1060
+ if (parent && parent.role === "assistant") {
1061
+ const content = (parent as any).content;
1062
+ const toolCalls = (parent as any).tool_calls;
1063
+
1064
+ const isAssistantToolStub =
1065
+ (
1066
+ content == null ||
1067
+ (typeof content === "string" && content.trim().length === 0) ||
1068
+ (Array.isArray(content) && content.length === 0)
1069
+ ) &&
1070
+ Array.isArray(toolCalls) &&
1071
+ toolCalls.length > 0;
1072
+
1073
+ if (isAssistantToolStub) {
1074
+ const hasOtherToolMsgs = Object.values(entities).some(
1075
+ (m) =>
1076
+ m &&
1077
+ m.role === "tool" &&
1078
+ m.parentMessageId === msg.parentMessageId &&
1079
+ m.dbKey !== dbKey
1080
+ );
1081
+
1082
+ if (!hasOtherToolMsgs) {
1083
+ extraRemoveId = parent.id;
1084
+ extraRemoveDbKey = parent.dbKey as string | undefined;
1085
+ }
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ // 先删当前这条
1091
+ await dispatch(remove(dbKey));
1092
+
1093
+ // 再删 parent stub(如果需要)
1094
+ if (extraRemoveDbKey) {
1095
+ await dispatch(remove(extraRemoveDbKey));
1096
+ }
1097
+
1098
+ return { id: msgId, extraRemoveId, dialogId };
1099
+ },
1100
+ {
1101
+ fulfilled: (state, action) => {
1102
+ const { id, extraRemoveId, dialogId } = action.payload as {
1103
+ id?: string;
1104
+ extraRemoveId?: string;
1105
+ dialogId?: string;
1106
+ };
1107
+ const dialogState = ensureMessageDialogState(state, dialogId);
1108
+
1109
+ if (id) {
1110
+ removeOneMessage(dialogState, id);
1111
+ }
1112
+ if (extraRemoveId) {
1113
+ removeOneMessage(dialogState, extraRemoveId);
1114
+ }
1115
+ },
1116
+ }
1117
+ ),
1118
+
1119
+ editUserMessageAndReplay: create.asyncThunk(
1120
+ async (
1121
+ args: {
1122
+ dialogKey?: string;
1123
+ messageId: string;
1124
+ originalContent: Message["content"];
1125
+ nextText: string;
1126
+ runtimeOptions?: any;
1127
+ targetAgentKey?: string;
1128
+ quickChatPerfStartedAt?: number;
1129
+ },
1130
+ thunkApi
1131
+ ) => {
1132
+ const { dispatch, getState, rejectWithValue } = thunkApi;
1133
+
1134
+ try {
1135
+ const state = getState() as RootState;
1136
+ const dialogKey = args.dialogKey ?? state.dialog?.currentDialogKey;
1137
+ if (!dialogKey) {
1138
+ throw new Error("editUserMessageAndReplay: dialogKey is required.");
1139
+ }
1140
+
1141
+ const dialogConfig = selectDbRecordById(state, dialogKey) as DialogConfig | null;
1142
+ if (!dialogConfig) {
1143
+ throw new Error("editUserMessageAndReplay: dialog config is missing.");
1144
+ }
1145
+
1146
+ const dialogId = dialogConfig.id ?? extractCustomId(dialogKey);
1147
+ const messages = selectAllMsgs(state, dialogId);
1148
+ const targetIndex = messages.findIndex((message) => message.id === args.messageId);
1149
+ if (targetIndex < 0) {
1150
+ throw new Error("editUserMessageAndReplay: target message not found.");
1151
+ }
1152
+
1153
+ const targetMessage = messages[targetIndex];
1154
+ if (!targetMessage || targetMessage.role !== "user") {
1155
+ throw new Error("只能编辑用户消息。");
1156
+ }
1157
+
1158
+ if (messages.some((message) => message.isStreaming)) {
1159
+ throw new Error("请等待当前回复完成后再编辑历史消息。");
1160
+ }
1161
+
1162
+ const nextContent = buildEditedMessageContent(
1163
+ args.originalContent ?? targetMessage.content,
1164
+ args.nextText
1165
+ );
1166
+ const trailingMessages = messages.slice(targetIndex + 1);
1167
+
1168
+ dispatch(
1169
+ messageSlice.actions.updateToolMessage({
1170
+ id: targetMessage.id,
1171
+ dialogId,
1172
+ changes: {
1173
+ content: nextContent,
1174
+ },
1175
+ })
1176
+ );
1177
+
1178
+ if (trailingMessages.length > 0) {
1179
+ dispatch(
1180
+ messageSlice.actions.removeMessagesByIds({
1181
+ dialogId,
1182
+ ids: trailingMessages.map((message) => message.id),
1183
+ })
1184
+ );
1185
+ }
1186
+
1187
+ await dispatch(
1188
+ patch({
1189
+ dbKey: targetMessage.dbKey,
1190
+ changes: {
1191
+ content: nextContent,
1192
+ },
1193
+ })
1194
+ ).unwrap();
1195
+
1196
+ await dispatch(
1197
+ patch({
1198
+ dbKey: dialogKey,
1199
+ changes: {
1200
+ summary: null,
1201
+ summarizedBeforeId: null,
1202
+ proactiveSummary: null,
1203
+ proactiveSummaryBeforeId: null,
1204
+ },
1205
+ })
1206
+ ).unwrap();
1207
+
1208
+ for (const message of trailingMessages) {
1209
+ if (message?.dbKey) {
1210
+ await dispatch(remove(message.dbKey)).unwrap();
1211
+ }
1212
+ }
1213
+
1214
+ const { agentKeyToUse, effectiveRuntimeOptions } =
1215
+ resolveHandleSendMessageContext({
1216
+ dialogConfig,
1217
+ targetAgentKey: args.targetAgentKey,
1218
+ runtimeOptions: args.runtimeOptions,
1219
+ });
1220
+
1221
+ if (agentKeyToUse) {
1222
+ const { streamAgentChatTurn } = await import("../../ai/agent/agentSlice");
1223
+ await dispatch(
1224
+ streamAgentChatTurn({
1225
+ agentKey: agentKeyToUse,
1226
+ userInput: nextContent,
1227
+ dialogKey,
1228
+ parentMessageId: undefined,
1229
+ runtimeOptions: effectiveRuntimeOptions,
1230
+ quickChatPerfStartedAt: args.quickChatPerfStartedAt,
1231
+ })
1232
+ ).unwrap();
1233
+ }
1234
+
1235
+ return {
1236
+ editedMessageId: targetMessage.id,
1237
+ removedMessageIds: trailingMessages.map((message) => message.id),
1238
+ };
1239
+ } catch (error) {
1240
+ return rejectWithValue(
1241
+ error instanceof Error ? error.message : String(error)
1242
+ );
1243
+ }
1244
+ }
1245
+ ),
1246
+ }),
1247
+ selectors: {
1248
+ selectCurrentDialogId: (state) => state.currentDialogId,
1249
+ },
1250
+ });
1251
+
1252
+ const dialogMessageSelectors = messagesAdapter.getSelectors<MessageDialogState>(
1253
+ (dialogState) => dialogState.msgs
1254
+ );
1255
+
1256
+ export const { selectCurrentDialogId } = messageSlice.selectors;
1257
+
1258
+ export const selectMessageState = (state: RootState) => state.message;
1259
+
1260
+ export const selectMessageDialogState = (
1261
+ state: RootState,
1262
+ dialogId?: string | null
1263
+ ) => getMessageDialogState(state.message, dialogId);
1264
+
1265
+ export const selectAllMsgs = (state: RootState, dialogId?: string | null) =>
1266
+ dialogMessageSelectors.selectAll(selectMessageDialogState(state, dialogId));
1267
+
1268
+ export const selectMsgById = (
1269
+ state: RootState,
1270
+ messageId: string,
1271
+ dialogId?: string | null
1272
+ ) => dialogMessageSelectors.selectById(
1273
+ getMessageDialogState(state.message, dialogId),
1274
+ messageId
1275
+ );
1276
+
1277
+ export const selectTotalMsgs = (state: RootState, dialogId?: string | null) =>
1278
+ dialogMessageSelectors.selectTotal(selectMessageDialogState(state, dialogId));
1279
+
1280
+ export const selectFirstStreamProcessed = (
1281
+ state: RootState,
1282
+ dialogId?: string | null
1283
+ ) => selectMessageDialogState(state, dialogId).firstStreamProcessed;
1284
+
1285
+ export const selectIsLoadingInitial = (
1286
+ state: RootState,
1287
+ dialogId?: string | null
1288
+ ) => selectMessageDialogState(state, dialogId).isLoadingInitial;
1289
+
1290
+ export const selectIsLoadingOlder = (
1291
+ state: RootState,
1292
+ dialogId?: string | null
1293
+ ) => selectMessageDialogState(state, dialogId).isLoadingOlder;
1294
+
1295
+ export const selectHasMoreOlder = (
1296
+ state: RootState,
1297
+ dialogId?: string | null
1298
+ ) => selectMessageDialogState(state, dialogId).hasMoreOlder;
1299
+
1300
+ export const selectMessageError = (
1301
+ state: RootState,
1302
+ dialogId?: string | null
1303
+ ) => selectMessageDialogState(state, dialogId).error;
1304
+
1305
+ export const selectLastStreamTimestamp = (
1306
+ state: RootState,
1307
+ dialogId?: string | null
1308
+ ) => selectMessageDialogState(state, dialogId).lastStreamTimestamp;
1309
+
1310
+ export const selectMessagesLoadingState = createSelector(
1311
+ [
1312
+ (state: RootState, dialogId?: string | null) =>
1313
+ selectMessageDialogState(state, dialogId),
1314
+ ],
1315
+ (dialogState) => ({
1316
+ isLoadingInitial: dialogState.isLoadingInitial,
1317
+ isLoadingOlder: dialogState.isLoadingOlder,
1318
+ hasMoreOlder: dialogState.hasMoreOlder,
1319
+ error: dialogState.error,
1320
+ })
1321
+ );
1322
+
1323
+ /**
1324
+ * 是否存在正在流式生成的消息(用于标题 / 状态展示)
1325
+ */
1326
+ export const selectHasStreamingMessage = (
1327
+ state: RootState,
1328
+ dialogId?: string | null
1329
+ ) => selectAllMsgs(state, dialogId).some((m) => m.isStreaming);
1330
+
1331
+ /**
1332
+ * 最后一条 assistant 消息(用于通知)
1333
+ */
1334
+ export const selectLastAssistantMessage = (
1335
+ state: RootState,
1336
+ dialogId?: string | null
1337
+ ) => {
1338
+ const msgs = selectAllMsgs(state, dialogId);
1339
+ for (let i = msgs.length - 1; i >= 0; i -= 1) {
1340
+ const msg = msgs[i];
1341
+ if (msg && msg.role === "assistant") {
1342
+ return msg;
1343
+ }
1344
+ }
1345
+ return undefined;
1346
+ };
1347
+
1348
+ export const {
1349
+ addUserMessage,
1350
+ messageStreaming,
1351
+ resetMsgs,
1352
+ clearAllStreaming,
1353
+ removeTransientMessage,
1354
+ prepareAndPersistMessage,
1355
+ prepareAndPersistUserMessage,
1356
+ initMsgs,
1357
+ loadOlderMessages,
1358
+ messageStreamEnd,
1359
+ deleteMessage,
1360
+ editUserMessageAndReplay,
1361
+ addToolMessage,
1362
+ updateToolMessage,
1363
+ removeMessagesByIds,
1364
+ } = messageSlice.actions;
1365
+
1366
+
1367
+ export default messageSlice.reducer;