@lobehub/chat 1.98.2 → 1.99.0

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 (456) hide show
  1. package/.cursor/rules/backend-architecture.mdc +93 -17
  2. package/.cursor/rules/cursor-ux.mdc +45 -35
  3. package/.cursor/rules/project-introduce.mdc +72 -6
  4. package/.cursor/rules/rules-attach.mdc +16 -7
  5. package/.eslintrc.js +10 -0
  6. package/CHANGELOG.md +27 -0
  7. package/apps/desktop/README.md +7 -0
  8. package/apps/desktop/electron-builder.js +5 -0
  9. package/apps/desktop/package.json +2 -1
  10. package/apps/desktop/src/main/const/dir.ts +3 -0
  11. package/apps/desktop/src/main/controllers/UploadFileCtr.ts +13 -8
  12. package/apps/desktop/src/main/core/App.ts +8 -0
  13. package/apps/desktop/src/main/core/StaticFileServerManager.ts +221 -0
  14. package/apps/desktop/src/main/services/fileSrv.ts +231 -44
  15. package/apps/desktop/src/main/utils/next-electron-rsc.ts +36 -5
  16. package/changelog/v1.json +9 -0
  17. package/docs/development/database-schema.dbml +70 -0
  18. package/locales/ar/common.json +2 -0
  19. package/locales/ar/components.json +35 -0
  20. package/locales/ar/error.json +2 -0
  21. package/locales/ar/image.json +100 -0
  22. package/locales/ar/metadata.json +4 -0
  23. package/locales/ar/modelProvider.json +1 -0
  24. package/locales/ar/models.json +15 -0
  25. package/locales/ar/plugin.json +22 -0
  26. package/locales/ar/providers.json +3 -0
  27. package/locales/ar/setting.json +5 -0
  28. package/locales/bg-BG/common.json +2 -0
  29. package/locales/bg-BG/components.json +35 -0
  30. package/locales/bg-BG/error.json +2 -0
  31. package/locales/bg-BG/image.json +100 -0
  32. package/locales/bg-BG/metadata.json +4 -0
  33. package/locales/bg-BG/modelProvider.json +1 -0
  34. package/locales/bg-BG/models.json +15 -0
  35. package/locales/bg-BG/plugin.json +22 -0
  36. package/locales/bg-BG/providers.json +3 -0
  37. package/locales/bg-BG/setting.json +5 -0
  38. package/locales/de-DE/common.json +2 -0
  39. package/locales/de-DE/components.json +35 -0
  40. package/locales/de-DE/error.json +2 -0
  41. package/locales/de-DE/image.json +100 -0
  42. package/locales/de-DE/metadata.json +4 -0
  43. package/locales/de-DE/modelProvider.json +1 -0
  44. package/locales/de-DE/models.json +15 -0
  45. package/locales/de-DE/plugin.json +22 -0
  46. package/locales/de-DE/providers.json +3 -0
  47. package/locales/de-DE/setting.json +5 -0
  48. package/locales/en-US/common.json +2 -0
  49. package/locales/en-US/components.json +35 -0
  50. package/locales/en-US/error.json +2 -0
  51. package/locales/en-US/image.json +100 -0
  52. package/locales/en-US/metadata.json +4 -0
  53. package/locales/en-US/modelProvider.json +1 -0
  54. package/locales/en-US/models.json +15 -0
  55. package/locales/en-US/plugin.json +22 -0
  56. package/locales/en-US/providers.json +3 -0
  57. package/locales/en-US/setting.json +5 -0
  58. package/locales/es-ES/common.json +2 -0
  59. package/locales/es-ES/components.json +35 -0
  60. package/locales/es-ES/error.json +2 -0
  61. package/locales/es-ES/image.json +100 -0
  62. package/locales/es-ES/metadata.json +4 -0
  63. package/locales/es-ES/modelProvider.json +1 -0
  64. package/locales/es-ES/models.json +15 -0
  65. package/locales/es-ES/plugin.json +22 -0
  66. package/locales/es-ES/providers.json +3 -0
  67. package/locales/es-ES/setting.json +5 -0
  68. package/locales/fa-IR/common.json +2 -0
  69. package/locales/fa-IR/components.json +35 -0
  70. package/locales/fa-IR/error.json +2 -0
  71. package/locales/fa-IR/image.json +100 -0
  72. package/locales/fa-IR/metadata.json +4 -0
  73. package/locales/fa-IR/modelProvider.json +1 -0
  74. package/locales/fa-IR/models.json +15 -0
  75. package/locales/fa-IR/plugin.json +22 -0
  76. package/locales/fa-IR/providers.json +3 -0
  77. package/locales/fa-IR/setting.json +5 -0
  78. package/locales/fr-FR/common.json +2 -0
  79. package/locales/fr-FR/components.json +35 -0
  80. package/locales/fr-FR/error.json +2 -0
  81. package/locales/fr-FR/image.json +100 -0
  82. package/locales/fr-FR/metadata.json +4 -0
  83. package/locales/fr-FR/modelProvider.json +1 -0
  84. package/locales/fr-FR/models.json +15 -0
  85. package/locales/fr-FR/plugin.json +22 -0
  86. package/locales/fr-FR/providers.json +3 -0
  87. package/locales/fr-FR/setting.json +5 -0
  88. package/locales/it-IT/common.json +2 -0
  89. package/locales/it-IT/components.json +35 -0
  90. package/locales/it-IT/error.json +2 -0
  91. package/locales/it-IT/image.json +100 -0
  92. package/locales/it-IT/metadata.json +4 -0
  93. package/locales/it-IT/modelProvider.json +1 -0
  94. package/locales/it-IT/models.json +15 -0
  95. package/locales/it-IT/plugin.json +22 -0
  96. package/locales/it-IT/providers.json +3 -0
  97. package/locales/it-IT/setting.json +5 -0
  98. package/locales/ja-JP/common.json +2 -0
  99. package/locales/ja-JP/components.json +35 -0
  100. package/locales/ja-JP/error.json +2 -0
  101. package/locales/ja-JP/image.json +100 -0
  102. package/locales/ja-JP/metadata.json +4 -0
  103. package/locales/ja-JP/modelProvider.json +1 -0
  104. package/locales/ja-JP/models.json +15 -0
  105. package/locales/ja-JP/plugin.json +22 -0
  106. package/locales/ja-JP/providers.json +3 -0
  107. package/locales/ja-JP/setting.json +5 -0
  108. package/locales/ko-KR/common.json +2 -0
  109. package/locales/ko-KR/components.json +35 -0
  110. package/locales/ko-KR/error.json +2 -0
  111. package/locales/ko-KR/image.json +100 -0
  112. package/locales/ko-KR/metadata.json +4 -0
  113. package/locales/ko-KR/modelProvider.json +1 -0
  114. package/locales/ko-KR/models.json +15 -0
  115. package/locales/ko-KR/plugin.json +22 -0
  116. package/locales/ko-KR/providers.json +3 -0
  117. package/locales/ko-KR/setting.json +5 -0
  118. package/locales/nl-NL/common.json +2 -0
  119. package/locales/nl-NL/components.json +35 -0
  120. package/locales/nl-NL/error.json +2 -0
  121. package/locales/nl-NL/image.json +100 -0
  122. package/locales/nl-NL/metadata.json +4 -0
  123. package/locales/nl-NL/modelProvider.json +1 -0
  124. package/locales/nl-NL/models.json +15 -0
  125. package/locales/nl-NL/plugin.json +22 -0
  126. package/locales/nl-NL/providers.json +3 -0
  127. package/locales/nl-NL/setting.json +5 -0
  128. package/locales/pl-PL/common.json +2 -0
  129. package/locales/pl-PL/components.json +35 -0
  130. package/locales/pl-PL/error.json +2 -0
  131. package/locales/pl-PL/image.json +100 -0
  132. package/locales/pl-PL/metadata.json +4 -0
  133. package/locales/pl-PL/modelProvider.json +1 -0
  134. package/locales/pl-PL/models.json +15 -0
  135. package/locales/pl-PL/plugin.json +22 -0
  136. package/locales/pl-PL/providers.json +3 -0
  137. package/locales/pl-PL/setting.json +5 -0
  138. package/locales/pt-BR/common.json +2 -0
  139. package/locales/pt-BR/components.json +35 -0
  140. package/locales/pt-BR/error.json +2 -0
  141. package/locales/pt-BR/image.json +100 -0
  142. package/locales/pt-BR/metadata.json +4 -0
  143. package/locales/pt-BR/modelProvider.json +1 -0
  144. package/locales/pt-BR/models.json +15 -0
  145. package/locales/pt-BR/plugin.json +22 -0
  146. package/locales/pt-BR/providers.json +3 -0
  147. package/locales/pt-BR/setting.json +5 -0
  148. package/locales/ru-RU/common.json +2 -0
  149. package/locales/ru-RU/components.json +35 -0
  150. package/locales/ru-RU/error.json +2 -0
  151. package/locales/ru-RU/image.json +100 -0
  152. package/locales/ru-RU/metadata.json +4 -0
  153. package/locales/ru-RU/modelProvider.json +1 -0
  154. package/locales/ru-RU/models.json +15 -0
  155. package/locales/ru-RU/plugin.json +22 -0
  156. package/locales/ru-RU/providers.json +3 -0
  157. package/locales/ru-RU/setting.json +5 -0
  158. package/locales/tr-TR/common.json +2 -0
  159. package/locales/tr-TR/components.json +35 -0
  160. package/locales/tr-TR/error.json +2 -0
  161. package/locales/tr-TR/image.json +100 -0
  162. package/locales/tr-TR/metadata.json +4 -0
  163. package/locales/tr-TR/modelProvider.json +1 -0
  164. package/locales/tr-TR/models.json +15 -0
  165. package/locales/tr-TR/plugin.json +22 -0
  166. package/locales/tr-TR/providers.json +3 -0
  167. package/locales/tr-TR/setting.json +5 -0
  168. package/locales/vi-VN/common.json +2 -0
  169. package/locales/vi-VN/components.json +35 -0
  170. package/locales/vi-VN/error.json +2 -0
  171. package/locales/vi-VN/image.json +100 -0
  172. package/locales/vi-VN/metadata.json +4 -0
  173. package/locales/vi-VN/modelProvider.json +1 -0
  174. package/locales/vi-VN/models.json +15 -0
  175. package/locales/vi-VN/plugin.json +22 -0
  176. package/locales/vi-VN/providers.json +3 -0
  177. package/locales/vi-VN/setting.json +5 -0
  178. package/locales/zh-CN/common.json +2 -0
  179. package/locales/zh-CN/components.json +35 -0
  180. package/locales/zh-CN/error.json +2 -0
  181. package/locales/zh-CN/image.json +100 -0
  182. package/locales/zh-CN/metadata.json +4 -0
  183. package/locales/zh-CN/modelProvider.json +1 -0
  184. package/locales/zh-CN/models.json +15 -0
  185. package/locales/zh-CN/plugin.json +22 -0
  186. package/locales/zh-CN/providers.json +3 -0
  187. package/locales/zh-CN/setting.json +5 -0
  188. package/locales/zh-TW/common.json +2 -0
  189. package/locales/zh-TW/components.json +35 -0
  190. package/locales/zh-TW/error.json +2 -0
  191. package/locales/zh-TW/image.json +100 -0
  192. package/locales/zh-TW/metadata.json +4 -0
  193. package/locales/zh-TW/modelProvider.json +1 -0
  194. package/locales/zh-TW/models.json +15 -0
  195. package/locales/zh-TW/plugin.json +22 -0
  196. package/locales/zh-TW/providers.json +3 -0
  197. package/locales/zh-TW/setting.json +5 -0
  198. package/package.json +11 -4
  199. package/packages/electron-server-ipc/src/events/file.ts +3 -1
  200. package/packages/electron-server-ipc/src/types/file.ts +15 -0
  201. package/src/app/[variants]/(main)/_layout/Desktop/SideBar/TopActions.tsx +11 -1
  202. package/src/app/[variants]/(main)/image/@menu/components/AspectRatioSelect/index.tsx +73 -0
  203. package/src/app/[variants]/(main)/image/@menu/components/SeedNumberInput/index.tsx +39 -0
  204. package/src/app/[variants]/(main)/image/@menu/components/SizeSelect/index.tsx +89 -0
  205. package/src/app/[variants]/(main)/image/@menu/default.tsx +11 -0
  206. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/AspectRatioSelect.tsx +24 -0
  207. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/DimensionControlGroup.tsx +107 -0
  208. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageNum.tsx +290 -0
  209. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageUpload.tsx +504 -0
  210. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageUrl.tsx +18 -0
  211. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ImageUrlsUpload.tsx +19 -0
  212. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/ModelSelect.tsx +155 -0
  213. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/MultiImagesUpload/ImageManageModal.tsx +415 -0
  214. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/MultiImagesUpload/index.tsx +732 -0
  215. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/SeedNumberInput.tsx +24 -0
  216. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/SizeSelect.tsx +17 -0
  217. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/SizeSliderInput.tsx +15 -0
  218. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/components/StepsSliderInput.tsx +11 -0
  219. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/constants.ts +1 -0
  220. package/src/app/[variants]/(main)/image/@menu/features/ConfigPanel/index.tsx +93 -0
  221. package/src/app/[variants]/(main)/image/@topic/default.tsx +17 -0
  222. package/src/app/[variants]/(main)/image/@topic/features/Topics/NewTopicButton.tsx +64 -0
  223. package/src/app/[variants]/(main)/image/@topic/features/Topics/SkeletonList.tsx +34 -0
  224. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicItem.tsx +136 -0
  225. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicItemContainer.tsx +91 -0
  226. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicList.tsx +57 -0
  227. package/src/app/[variants]/(main)/image/@topic/features/Topics/TopicUrlSync.tsx +37 -0
  228. package/src/app/[variants]/(main)/image/@topic/features/Topics/index.tsx +19 -0
  229. package/src/app/[variants]/(main)/image/NotSupportClient.tsx +153 -0
  230. package/src/app/[variants]/(main)/image/_layout/Desktop/Container.tsx +35 -0
  231. package/src/app/[variants]/(main)/image/_layout/Desktop/RegisterHotkeys.tsx +10 -0
  232. package/src/app/[variants]/(main)/image/_layout/Desktop/index.tsx +30 -0
  233. package/src/app/[variants]/(main)/image/_layout/Mobile/index.tsx +14 -0
  234. package/src/app/[variants]/(main)/image/_layout/type.ts +7 -0
  235. package/src/app/[variants]/(main)/image/features/GenerationFeed/BatchItem.tsx +196 -0
  236. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/ActionButtons.tsx +60 -0
  237. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/ElapsedTime.tsx +90 -0
  238. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/ErrorState.tsx +65 -0
  239. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/LoadingState.tsx +43 -0
  240. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/SuccessState.tsx +49 -0
  241. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/index.tsx +156 -0
  242. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/styles.ts +51 -0
  243. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/types.ts +39 -0
  244. package/src/app/[variants]/(main)/image/features/GenerationFeed/GenerationItem/utils.ts +11 -0
  245. package/src/app/[variants]/(main)/image/features/GenerationFeed/index.tsx +97 -0
  246. package/src/app/[variants]/(main)/image/features/ImageWorkspace/Content.tsx +48 -0
  247. package/src/app/[variants]/(main)/image/features/ImageWorkspace/EmptyState.tsx +37 -0
  248. package/src/app/[variants]/(main)/image/features/ImageWorkspace/SkeletonList.tsx +50 -0
  249. package/src/app/[variants]/(main)/image/features/ImageWorkspace/index.tsx +23 -0
  250. package/src/app/[variants]/(main)/image/features/PromptInput/Title.tsx +38 -0
  251. package/src/app/[variants]/(main)/image/features/PromptInput/index.tsx +114 -0
  252. package/src/app/[variants]/(main)/image/layout.tsx +19 -0
  253. package/src/app/[variants]/(main)/image/loading.tsx +3 -0
  254. package/src/app/[variants]/(main)/image/page.tsx +47 -0
  255. package/src/app/[variants]/(main)/settings/system-agent/index.tsx +2 -1
  256. package/src/chains/summaryGenerationTitle.ts +25 -0
  257. package/src/components/ImageItem/index.tsx +9 -6
  258. package/src/{features/Conversation/Error → components/InvalidAPIKey}/APIKeyForm/Bedrock.tsx +3 -4
  259. package/src/{features/Conversation/Error → components/InvalidAPIKey}/APIKeyForm/ProviderApiKeyForm.tsx +5 -4
  260. package/src/components/InvalidAPIKey/APIKeyForm/index.tsx +108 -0
  261. package/src/{features/Conversation/Error → components/InvalidAPIKey}/APIKeyForm/useApiKey.ts +2 -1
  262. package/src/components/InvalidAPIKey/index.tsx +30 -0
  263. package/src/components/KeyValueEditor/index.tsx +203 -0
  264. package/src/components/KeyValueEditor/utils.ts +42 -0
  265. package/src/config/aiModels/fal.ts +52 -0
  266. package/src/config/aiModels/index.ts +3 -0
  267. package/src/config/aiModels/openai.ts +20 -6
  268. package/src/config/llm.ts +6 -0
  269. package/src/config/modelProviders/fal.ts +21 -0
  270. package/src/config/modelProviders/index.ts +3 -0
  271. package/src/config/paramsSchemas/fal/flux-kontext-dev.ts +8 -0
  272. package/src/config/paramsSchemas/fal/flux-pro-kontext.ts +11 -0
  273. package/src/config/paramsSchemas/fal/flux-schnell.ts +9 -0
  274. package/src/config/paramsSchemas/fal/imagen4.ts +10 -0
  275. package/src/config/paramsSchemas/openai/gpt-image-1.ts +10 -0
  276. package/src/const/hotkeys.ts +2 -2
  277. package/src/const/image.ts +6 -0
  278. package/src/const/settings/systemAgent.ts +1 -0
  279. package/src/database/client/migrations.json +27 -0
  280. package/src/database/migrations/0026_add_autovacuum_tuning.sql +2 -0
  281. package/src/database/migrations/0027_ai_image.sql +47 -0
  282. package/src/database/migrations/meta/0027_snapshot.json +6003 -0
  283. package/src/database/migrations/meta/_journal.json +7 -0
  284. package/src/database/models/__tests__/asyncTask.test.ts +7 -5
  285. package/src/database/models/__tests__/file.test.ts +287 -0
  286. package/src/database/models/__tests__/generation.test.ts +786 -0
  287. package/src/database/models/__tests__/generationBatch.test.ts +614 -0
  288. package/src/database/models/__tests__/generationTopic.test.ts +411 -0
  289. package/src/database/models/aiModel.ts +2 -0
  290. package/src/database/models/asyncTask.ts +1 -1
  291. package/src/database/models/file.ts +28 -20
  292. package/src/database/models/generation.ts +197 -0
  293. package/src/database/models/generationBatch.ts +212 -0
  294. package/src/database/models/generationTopic.ts +131 -0
  295. package/src/database/repositories/aiInfra/index.test.ts +151 -1
  296. package/src/database/repositories/aiInfra/index.ts +28 -19
  297. package/src/database/repositories/tableViewer/index.test.ts +1 -1
  298. package/src/database/schemas/file.ts +8 -0
  299. package/src/database/schemas/generation.ts +127 -0
  300. package/src/database/schemas/index.ts +1 -0
  301. package/src/database/schemas/relations.ts +45 -1
  302. package/src/database/type.ts +2 -0
  303. package/src/database/utils/idGenerator.ts +3 -0
  304. package/src/features/Conversation/Error/ChatInvalidApiKey.tsx +39 -0
  305. package/src/features/Conversation/Error/InvalidAccessCode.tsx +2 -2
  306. package/src/features/Conversation/Error/index.tsx +3 -3
  307. package/src/features/ImageSidePanel/index.tsx +83 -0
  308. package/src/features/ImageTopicPanel/index.tsx +79 -0
  309. package/src/features/PluginDevModal/MCPManifestForm/CollapsibleSection.tsx +62 -0
  310. package/src/features/PluginDevModal/MCPManifestForm/QuickImportSection.tsx +158 -0
  311. package/src/features/PluginDevModal/MCPManifestForm/index.tsx +99 -155
  312. package/src/features/PluginStore/McpList/Detail/Settings/index.tsx +5 -2
  313. package/src/hooks/useDownloadImage.ts +31 -0
  314. package/src/hooks/useFetchGenerationTopics.ts +13 -0
  315. package/src/hooks/useHotkeys/imageScope.ts +48 -0
  316. package/src/libs/mcp/client.ts +55 -22
  317. package/src/libs/mcp/types.ts +42 -6
  318. package/src/libs/model-runtime/BaseAI.ts +3 -1
  319. package/src/libs/model-runtime/ModelRuntime.test.ts +80 -0
  320. package/src/libs/model-runtime/ModelRuntime.ts +15 -1
  321. package/src/libs/model-runtime/UniformRuntime/index.ts +4 -1
  322. package/src/libs/model-runtime/fal/index.test.ts +442 -0
  323. package/src/libs/model-runtime/fal/index.ts +88 -0
  324. package/src/libs/model-runtime/openai/index.test.ts +396 -2
  325. package/src/libs/model-runtime/openai/index.ts +129 -3
  326. package/src/libs/model-runtime/runtimeMap.ts +2 -0
  327. package/src/libs/model-runtime/types/image.ts +25 -0
  328. package/src/libs/model-runtime/types/type.ts +1 -0
  329. package/src/libs/model-runtime/utils/openaiCompatibleFactory/index.ts +10 -0
  330. package/src/libs/standard-parameters/index.ts +1 -0
  331. package/src/libs/standard-parameters/meta-schema.test.ts +214 -0
  332. package/src/libs/standard-parameters/meta-schema.ts +147 -0
  333. package/src/libs/swr/index.ts +1 -0
  334. package/src/libs/trpc/async/asyncAuth.ts +29 -8
  335. package/src/libs/trpc/async/context.ts +42 -4
  336. package/src/libs/trpc/async/index.ts +17 -4
  337. package/src/libs/trpc/async/init.ts +8 -0
  338. package/src/libs/trpc/client/lambda.ts +19 -2
  339. package/src/locales/default/common.ts +2 -0
  340. package/src/locales/default/components.ts +35 -0
  341. package/src/locales/default/error.ts +2 -0
  342. package/src/locales/default/image.ts +100 -0
  343. package/src/locales/default/index.ts +2 -0
  344. package/src/locales/default/metadata.ts +4 -0
  345. package/src/locales/default/modelProvider.ts +2 -0
  346. package/src/locales/default/plugin.ts +22 -0
  347. package/src/locales/default/setting.ts +5 -0
  348. package/src/middleware.ts +1 -0
  349. package/src/server/modules/ElectronIPCClient/index.ts +9 -1
  350. package/src/server/modules/S3/index.ts +15 -0
  351. package/src/server/routers/async/caller.ts +9 -1
  352. package/src/server/routers/async/image.ts +253 -0
  353. package/src/server/routers/async/index.ts +2 -0
  354. package/src/server/routers/lambda/aiProvider.test.ts +1 -0
  355. package/src/server/routers/lambda/generation.test.ts +267 -0
  356. package/src/server/routers/lambda/generation.ts +86 -0
  357. package/src/server/routers/lambda/generationBatch.test.ts +376 -0
  358. package/src/server/routers/lambda/generationBatch.ts +56 -0
  359. package/src/server/routers/lambda/generationTopic.test.ts +508 -0
  360. package/src/server/routers/lambda/generationTopic.ts +93 -0
  361. package/src/server/routers/lambda/image.ts +248 -0
  362. package/src/server/routers/lambda/index.ts +8 -0
  363. package/src/server/routers/tools/mcp.ts +15 -0
  364. package/src/server/services/file/__tests__/index.test.ts +135 -0
  365. package/src/server/services/file/impls/local.test.ts +153 -52
  366. package/src/server/services/file/impls/local.ts +70 -46
  367. package/src/server/services/file/impls/s3.test.ts +114 -0
  368. package/src/server/services/file/impls/s3.ts +40 -0
  369. package/src/server/services/file/impls/type.ts +10 -0
  370. package/src/server/services/file/index.ts +14 -0
  371. package/src/server/services/generation/index.ts +239 -0
  372. package/src/server/services/mcp/index.ts +20 -2
  373. package/src/services/__tests__/generation.test.ts +40 -0
  374. package/src/services/__tests__/generationBatch.test.ts +36 -0
  375. package/src/services/__tests__/generationTopic.test.ts +72 -0
  376. package/src/services/electron/file.ts +3 -1
  377. package/src/services/generation.ts +16 -0
  378. package/src/services/generationBatch.ts +25 -0
  379. package/src/services/generationTopic.ts +28 -0
  380. package/src/services/image.ts +33 -0
  381. package/src/services/mcp.ts +12 -7
  382. package/src/services/upload.ts +43 -9
  383. package/src/store/aiInfra/slices/aiProvider/action.ts +25 -5
  384. package/src/store/aiInfra/slices/aiProvider/initialState.ts +1 -0
  385. package/src/store/aiInfra/slices/aiProvider/selectors.ts +3 -0
  386. package/src/store/chat/slices/aiChat/actions/generateAIChat.ts +5 -5
  387. package/src/store/chat/slices/message/action.ts +2 -2
  388. package/src/store/chat/slices/translate/action.ts +1 -1
  389. package/src/store/global/initialState.ts +9 -0
  390. package/src/store/global/selectors/systemStatus.ts +8 -0
  391. package/src/store/image/index.ts +2 -0
  392. package/src/store/image/initialState.ts +25 -0
  393. package/src/store/image/selectors.ts +4 -0
  394. package/src/store/image/slices/createImage/action.test.ts +330 -0
  395. package/src/store/image/slices/createImage/action.ts +134 -0
  396. package/src/store/image/slices/createImage/initialState.ts +9 -0
  397. package/src/store/image/slices/createImage/selectors.test.ts +114 -0
  398. package/src/store/image/slices/createImage/selectors.ts +9 -0
  399. package/src/store/image/slices/generationBatch/action.test.ts +495 -0
  400. package/src/store/image/slices/generationBatch/action.ts +303 -0
  401. package/src/store/image/slices/generationBatch/initialState.ts +13 -0
  402. package/src/store/image/slices/generationBatch/reducer.test.ts +568 -0
  403. package/src/store/image/slices/generationBatch/reducer.ts +101 -0
  404. package/src/store/image/slices/generationBatch/selectors.test.ts +307 -0
  405. package/src/store/image/slices/generationBatch/selectors.ts +36 -0
  406. package/src/store/image/slices/generationConfig/action.test.ts +351 -0
  407. package/src/store/image/slices/generationConfig/action.ts +295 -0
  408. package/src/store/image/slices/generationConfig/hooks.test.ts +304 -0
  409. package/src/store/image/slices/generationConfig/hooks.ts +118 -0
  410. package/src/store/image/slices/generationConfig/index.ts +1 -0
  411. package/src/store/image/slices/generationConfig/initialState.ts +37 -0
  412. package/src/store/image/slices/generationConfig/selectors.test.ts +204 -0
  413. package/src/store/image/slices/generationConfig/selectors.ts +25 -0
  414. package/src/store/image/slices/generationTopic/action.test.ts +687 -0
  415. package/src/store/image/slices/generationTopic/action.ts +319 -0
  416. package/src/store/image/slices/generationTopic/index.ts +2 -0
  417. package/src/store/image/slices/generationTopic/initialState.ts +14 -0
  418. package/src/store/image/slices/generationTopic/reducer.test.ts +198 -0
  419. package/src/store/image/slices/generationTopic/reducer.ts +66 -0
  420. package/src/store/image/slices/generationTopic/selectors.test.ts +103 -0
  421. package/src/store/image/slices/generationTopic/selectors.ts +15 -0
  422. package/src/store/image/store.ts +42 -0
  423. package/src/store/image/utils/size.ts +51 -0
  424. package/src/store/tool/slices/customPlugin/action.ts +10 -1
  425. package/src/store/tool/slices/mcpStore/action.ts +6 -4
  426. package/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap +4 -0
  427. package/src/store/user/slices/settings/selectors/systemAgent.ts +2 -0
  428. package/src/types/aiModel.ts +8 -3
  429. package/src/types/aiProvider.ts +1 -0
  430. package/src/types/asyncTask.ts +2 -0
  431. package/src/types/files/index.ts +5 -0
  432. package/src/types/generation/index.ts +80 -0
  433. package/src/types/hotkey.ts +2 -0
  434. package/src/types/plugins/mcp.ts +2 -6
  435. package/src/types/tool/plugin.ts +8 -0
  436. package/src/types/user/settings/keyVaults.ts +5 -0
  437. package/src/types/user/settings/systemAgent.ts +1 -0
  438. package/src/utils/client/downloadFile.ts +33 -4
  439. package/src/utils/number.test.ts +105 -0
  440. package/src/utils/number.ts +25 -0
  441. package/src/utils/server/__tests__/geo.test.ts +6 -3
  442. package/src/utils/storeDebug.test.ts +152 -0
  443. package/src/utils/storeDebug.ts +16 -7
  444. package/src/utils/time.test.ts +259 -0
  445. package/src/utils/time.ts +18 -0
  446. package/src/utils/units.ts +61 -0
  447. package/src/utils/url.test.ts +358 -9
  448. package/src/utils/url.ts +105 -3
  449. package/{vitest.server.config.ts → vitest.config.server.ts} +3 -0
  450. package/.cursor/rules/i18n/i18n-auto-attached.mdc +0 -6
  451. package/src/features/Conversation/Error/APIKeyForm/index.tsx +0 -105
  452. package/src/features/Conversation/Error/InvalidAPIKey.tsx +0 -16
  453. package/src/features/PluginDevModal/MCPManifestForm/EnvEditor.tsx +0 -227
  454. /package/.cursor/rules/{i18n/i18n.mdc → i18n.mdc} +0 -0
  455. /package/src/app/[variants]/(main)/settings/system-agent/features/{createForm.tsx → SystemAgentForm.tsx} +0 -0
  456. /package/src/{features/Conversation/Error → components/InvalidAPIKey}/APIKeyForm/LoadingContext.ts +0 -0
@@ -0,0 +1,319 @@
1
+ import isEqual from 'fast-deep-equal';
2
+ import { SWRResponse, mutate } from 'swr';
3
+ import { StateCreator } from 'zustand/vanilla';
4
+
5
+ import { chainSummaryGenerationTitle } from '@/chains/summaryGenerationTitle';
6
+ import { LOADING_FLAT } from '@/const/message';
7
+ import { useClientDataSWR } from '@/libs/swr';
8
+ import { UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
9
+ import { chatService } from '@/services/chat';
10
+ import { generationTopicService } from '@/services/generationTopic';
11
+ import { useUserStore } from '@/store/user';
12
+ import { systemAgentSelectors } from '@/store/user/selectors';
13
+ import { ImageGenerationTopic } from '@/types/generation';
14
+ import { merge } from '@/utils/merge';
15
+ import { setNamespace } from '@/utils/storeDebug';
16
+
17
+ import type { ImageStore } from '../../store';
18
+ import { GenerationTopicDispatch, generationTopicReducer } from './reducer';
19
+ import { generationTopicSelectors } from './selectors';
20
+
21
+ const FETCH_GENERATION_TOPICS_KEY = 'fetchGenerationTopics';
22
+
23
+ const n = setNamespace('generationTopic');
24
+
25
+ export interface GenerationTopicAction {
26
+ createGenerationTopic: (prompts: string[]) => Promise<string>;
27
+ removeGenerationTopic: (id: string) => Promise<void>;
28
+ useFetchGenerationTopics: (
29
+ enabled: boolean,
30
+ isLogin: boolean | undefined,
31
+ ) => SWRResponse<ImageGenerationTopic[]>;
32
+ summaryGenerationTopicTitle: (topicId: string, prompts: string[]) => Promise<string>;
33
+ refreshGenerationTopics: () => Promise<void>;
34
+ switchGenerationTopic: (topicId: string) => void;
35
+ openNewGenerationTopic: () => void;
36
+ updateGenerationTopicCover: (topicId: string, imageUrl: string) => Promise<void>;
37
+
38
+ internal_updateGenerationTopicLoading: (id: string, loading: boolean) => void;
39
+ internal_dispatchGenerationTopic: (payload: GenerationTopicDispatch, action?: any) => void;
40
+ internal_createGenerationTopic: () => Promise<string>;
41
+ internal_updateGenerationTopic: (id: string, data: UpdateTopicValue) => Promise<void>;
42
+ internal_updateGenerationTopicTitleInSummary: (id: string, title: string) => void;
43
+ internal_removeGenerationTopic: (id: string) => Promise<void>;
44
+ internal_updateGenerationTopicCover: (topicId: string, coverUrl: string) => Promise<void>;
45
+ }
46
+
47
+ export const createGenerationTopicSlice: StateCreator<
48
+ ImageStore,
49
+ [['zustand/devtools', never]],
50
+ [],
51
+ GenerationTopicAction
52
+ > = (set, get) => ({
53
+ createGenerationTopic: async (prompts: string[]) => {
54
+ // Validate prompts - cannot be empty
55
+ if (!prompts || prompts.length === 0) {
56
+ throw new Error('Prompts cannot be empty when creating a generation topic');
57
+ }
58
+
59
+ const { internal_createGenerationTopic, summaryGenerationTopicTitle } = get();
60
+
61
+ // Create topic with default title
62
+ const topicId = await internal_createGenerationTopic();
63
+
64
+ // Auto-generate title from prompts
65
+ summaryGenerationTopicTitle(topicId, prompts);
66
+
67
+ return topicId;
68
+ },
69
+
70
+ switchGenerationTopic: (topicId: string) => {
71
+ // Check if topic exists
72
+ const currentTopics = get().generationTopics;
73
+ const targetTopic = currentTopics.find((topic) => topic.id === topicId);
74
+
75
+ if (!targetTopic) {
76
+ console.warn(`Generation topic with id ${topicId} not found`);
77
+ return;
78
+ }
79
+
80
+ // Don't update if already active
81
+ if (get().activeGenerationTopicId === topicId) return;
82
+
83
+ set({ activeGenerationTopicId: topicId }, false, n('switchGenerationTopic'));
84
+ },
85
+
86
+ openNewGenerationTopic: () => {
87
+ set({ activeGenerationTopicId: null }, false, n('openNewGenerationTopic'));
88
+ },
89
+
90
+ summaryGenerationTopicTitle: async (topicId: string, prompts: string[]) => {
91
+ const topic = generationTopicSelectors.getGenerationTopicById(topicId)(get());
92
+ if (!topic) throw new Error(`Topic ${topicId} not found`);
93
+
94
+ const { internal_updateGenerationTopicTitleInSummary, internal_updateGenerationTopicLoading } =
95
+ get();
96
+
97
+ internal_updateGenerationTopicLoading(topicId, true);
98
+ internal_updateGenerationTopicTitleInSummary(topicId, LOADING_FLAT);
99
+
100
+ let output = '';
101
+
102
+ // Helper function to generate fallback title from prompts
103
+ const generateFallbackTitle = () => {
104
+ // Extract title from the first prompt content
105
+ const title = prompts[0]
106
+ .replaceAll(/[^\s\w\u4E00-\u9FFF]/g, '') // Remove punctuation, keep Chinese characters
107
+ .trim()
108
+ .split(/\s+/) // Split by whitespace
109
+ .slice(0, 3) // Take first 3 words
110
+ .join(' ')
111
+ .slice(0, 10); // Limit to 10 characters
112
+
113
+ return title;
114
+ };
115
+
116
+ const generationTopicAgentConfig = systemAgentSelectors.generationTopic(
117
+ useUserStore.getState(),
118
+ );
119
+ // Auto generate topic title from prompt by AI
120
+ await chatService.fetchPresetTaskResult({
121
+ params: merge(generationTopicAgentConfig, chainSummaryGenerationTitle(prompts, 'image')),
122
+ onError: async () => {
123
+ const fallbackTitle = generateFallbackTitle();
124
+ internal_updateGenerationTopicTitleInSummary(topicId, fallbackTitle);
125
+ // Update the topic with fallback title
126
+ await get().internal_updateGenerationTopic(topicId, { title: fallbackTitle });
127
+ },
128
+ onFinish: async (text) => {
129
+ await get().internal_updateGenerationTopic(topicId, { title: text });
130
+ },
131
+ onLoadingChange: (loading) => {
132
+ internal_updateGenerationTopicLoading(topicId, loading);
133
+ },
134
+ onMessageHandle: (chunk) => {
135
+ switch (chunk.type) {
136
+ case 'text': {
137
+ output += chunk.text;
138
+ internal_updateGenerationTopicTitleInSummary(topicId, output);
139
+ }
140
+ }
141
+ },
142
+ });
143
+
144
+ return output;
145
+ },
146
+
147
+ internal_createGenerationTopic: async () => {
148
+ const tmpId = Date.now().toString();
149
+
150
+ // 1. Optimistic update - add temporary topic
151
+ get().internal_dispatchGenerationTopic(
152
+ { type: 'addTopic', value: { id: tmpId, title: '' } },
153
+ 'internal_createGenerationTopic',
154
+ );
155
+
156
+ get().internal_updateGenerationTopicLoading(tmpId, true);
157
+
158
+ // 2. Call backend service
159
+ const topicId = await generationTopicService.createTopic();
160
+ get().internal_updateGenerationTopicLoading(tmpId, false);
161
+
162
+ // 3. Refresh data to ensure consistency
163
+ get().internal_updateGenerationTopicLoading(topicId, true);
164
+ await get().refreshGenerationTopics();
165
+ get().internal_updateGenerationTopicLoading(topicId, false);
166
+
167
+ return topicId;
168
+ },
169
+
170
+ internal_updateGenerationTopic: async (id, data) => {
171
+ // 1. Optimistic update
172
+ get().internal_dispatchGenerationTopic({ type: 'updateTopic', id, value: data });
173
+
174
+ // 2. Update loading state
175
+ get().internal_updateGenerationTopicLoading(id, true);
176
+
177
+ // 3. Call backend service
178
+ await generationTopicService.updateTopic(id, data);
179
+
180
+ // 4. Refresh data and clear loading
181
+ await get().refreshGenerationTopics();
182
+ get().internal_updateGenerationTopicLoading(id, false);
183
+ },
184
+
185
+ internal_updateGenerationTopicTitleInSummary: (id, title) => {
186
+ get().internal_dispatchGenerationTopic(
187
+ { type: 'updateTopic', id, value: { title } },
188
+ 'updateGenerationTopicTitleInSummary',
189
+ );
190
+ },
191
+
192
+ internal_updateGenerationTopicLoading: (id, loading) => {
193
+ set(
194
+ (state) => {
195
+ if (loading) return { loadingGenerationTopicIds: [...state.loadingGenerationTopicIds, id] };
196
+
197
+ return {
198
+ loadingGenerationTopicIds: state.loadingGenerationTopicIds.filter((i) => i !== id),
199
+ };
200
+ },
201
+ false,
202
+ n('updateGenerationTopicLoading'),
203
+ );
204
+ },
205
+
206
+ internal_dispatchGenerationTopic: (payload, action) => {
207
+ const nextTopics = generationTopicReducer(get().generationTopics, payload);
208
+
209
+ // No need to update if the topics are the same
210
+ if (isEqual(nextTopics, get().generationTopics)) return;
211
+
212
+ set(
213
+ { generationTopics: nextTopics },
214
+ false,
215
+ action ?? n(`dispatchGenerationTopic/${payload.type}`),
216
+ );
217
+ },
218
+
219
+ useFetchGenerationTopics: (enabled, isLogin) =>
220
+ useClientDataSWR<ImageGenerationTopic[]>(
221
+ enabled ? [FETCH_GENERATION_TOPICS_KEY, isLogin] : null,
222
+ () => generationTopicService.getAllGenerationTopics(),
223
+ {
224
+ suspense: true,
225
+ onSuccess: (data) => {
226
+ // No need to update if data is the same
227
+ if (isEqual(data, get().generationTopics)) return;
228
+ set({ generationTopics: data }, false, n('useFetchGenerationTopics'));
229
+ },
230
+ },
231
+ ),
232
+
233
+ refreshGenerationTopics: async () => {
234
+ await mutate([FETCH_GENERATION_TOPICS_KEY, true]);
235
+ },
236
+
237
+ removeGenerationTopic: async (id: string) => {
238
+ const {
239
+ internal_removeGenerationTopic,
240
+ generationTopics,
241
+ activeGenerationTopicId,
242
+ switchGenerationTopic,
243
+ openNewGenerationTopic,
244
+ } = get();
245
+
246
+ const isRemovingActiveTopic = activeGenerationTopicId === id;
247
+ let topicIndexToRemove = -1;
248
+
249
+ if (isRemovingActiveTopic) {
250
+ topicIndexToRemove = generationTopics.findIndex((topic) => topic.id === id);
251
+ }
252
+
253
+ await internal_removeGenerationTopic(id);
254
+
255
+ // if the active topic is the one being deleted, switch to the next topic
256
+ if (isRemovingActiveTopic) {
257
+ const newTopics = get().generationTopics;
258
+
259
+ if (newTopics.length > 0) {
260
+ // try to select the topic at the same index, if not, select the last one
261
+ const newActiveIndex = Math.min(topicIndexToRemove, newTopics.length - 1);
262
+ const newActiveTopic = newTopics[newActiveIndex];
263
+
264
+ if (newActiveTopic) {
265
+ switchGenerationTopic(newActiveTopic.id);
266
+ } else {
267
+ // fallback to open new topic, should not happen in this branch
268
+ openNewGenerationTopic();
269
+ }
270
+ } else {
271
+ // if no topics left, open a new one
272
+ openNewGenerationTopic();
273
+ }
274
+ }
275
+ },
276
+
277
+ internal_removeGenerationTopic: async (id: string) => {
278
+ get().internal_updateGenerationTopicLoading(id, true);
279
+ try {
280
+ await generationTopicService.deleteTopic(id);
281
+ await get().refreshGenerationTopics();
282
+ } finally {
283
+ get().internal_updateGenerationTopicLoading(id, false);
284
+ }
285
+ },
286
+
287
+ updateGenerationTopicCover: async (topicId: string, coverUrl: string) => {
288
+ const { internal_updateGenerationTopicCover } = get();
289
+ await internal_updateGenerationTopicCover(topicId, coverUrl);
290
+ },
291
+
292
+ internal_updateGenerationTopicCover: async (topicId: string, coverUrl: string) => {
293
+ const {
294
+ internal_dispatchGenerationTopic,
295
+ internal_updateGenerationTopicLoading,
296
+ refreshGenerationTopics,
297
+ } = get();
298
+
299
+ // 1. Optimistic update - immediately show the new cover URL in UI
300
+ internal_dispatchGenerationTopic(
301
+ { type: 'updateTopic', id: topicId, value: { coverUrl } },
302
+ 'internal_updateGenerationTopicCover/optimistic',
303
+ );
304
+
305
+ // 2. Set loading state
306
+ internal_updateGenerationTopicLoading(topicId, true);
307
+
308
+ try {
309
+ // 3. Call backend service to process and upload cover image
310
+ await generationTopicService.updateTopicCover(topicId, coverUrl);
311
+
312
+ // 4. Refresh data to get the final processed cover URL from S3
313
+ await refreshGenerationTopics();
314
+ } finally {
315
+ // 5. Clear loading state
316
+ internal_updateGenerationTopicLoading(topicId, false);
317
+ }
318
+ },
319
+ });
@@ -0,0 +1,2 @@
1
+ export * from './action';
2
+ export * from './selectors';
@@ -0,0 +1,14 @@
1
+ import { ImageGenerationTopic } from '@/types/generation';
2
+
3
+ export interface GenerationTopicState {
4
+ activeGenerationTopicId: string | null;
5
+ loadingGenerationTopicIds: string[];
6
+ generationTopics: ImageGenerationTopic[];
7
+ }
8
+
9
+ export const initialGenerationTopicState: GenerationTopicState = {
10
+ activeGenerationTopicId:
11
+ typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('topic') : null,
12
+ loadingGenerationTopicIds: [],
13
+ generationTopics: [],
14
+ };
@@ -0,0 +1,198 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { ImageGenerationTopic } from '@/types/generation';
4
+
5
+ import { GenerationTopicDispatch, generationTopicReducer } from './reducer';
6
+
7
+ describe('generationTopicReducer', () => {
8
+ let state: ImageGenerationTopic[];
9
+
10
+ beforeEach(() => {
11
+ state = [];
12
+ });
13
+
14
+ describe('addTopic', () => {
15
+ it('should add a new topic to the state', () => {
16
+ const newTopic: Partial<ImageGenerationTopic> & { id: string } = {
17
+ id: 'gt_new_topic',
18
+ title: 'New Topic',
19
+ };
20
+ const payload: GenerationTopicDispatch = { type: 'addTopic', value: newTopic };
21
+
22
+ const newState = generationTopicReducer(state, payload);
23
+
24
+ expect(newState).toHaveLength(1);
25
+ expect(newState[0]).toMatchObject(newTopic);
26
+ expect(newState[0].createdAt).toBeInstanceOf(Date);
27
+ expect(newState[0].updatedAt).toBeInstanceOf(Date);
28
+ });
29
+
30
+ it('should prepend the new topic to the beginning of the array', () => {
31
+ const initialTopic: ImageGenerationTopic = {
32
+ id: 'gt_initial_topic',
33
+ title: 'Initial Topic',
34
+ createdAt: new Date('2023-01-01'),
35
+ updatedAt: new Date('2023-01-01'),
36
+ };
37
+ state = [initialTopic];
38
+
39
+ const newTopic: Partial<ImageGenerationTopic> & { id: string } = {
40
+ id: 'gt_new_topic',
41
+ title: 'New Topic',
42
+ };
43
+ const payload: GenerationTopicDispatch = { type: 'addTopic', value: newTopic };
44
+
45
+ const newState = generationTopicReducer(state, payload);
46
+
47
+ expect(newState).toHaveLength(2);
48
+ expect(newState[0].id).toBe('gt_new_topic');
49
+ expect(newState[1].id).toBe('gt_initial_topic');
50
+ });
51
+ });
52
+
53
+ describe('updateTopic', () => {
54
+ beforeEach(() => {
55
+ state = [
56
+ {
57
+ id: 'gt_topic_to_update',
58
+ title: 'Original Title',
59
+ coverUrl: 'original_url',
60
+ createdAt: new Date('2023-01-01'),
61
+ updatedAt: new Date('2023-01-01'),
62
+ },
63
+ ];
64
+ });
65
+
66
+ it('should update the title of a specific topic', () => {
67
+ const payload: GenerationTopicDispatch = {
68
+ type: 'updateTopic',
69
+ id: 'gt_topic_to_update',
70
+ value: { title: 'Updated Title' },
71
+ };
72
+
73
+ const newState = generationTopicReducer(state, payload);
74
+
75
+ expect(newState[0].title).toBe('Updated Title');
76
+ expect(newState[0].coverUrl).toBe('original_url'); // Should not change
77
+ expect(newState[0].updatedAt.valueOf()).toBeGreaterThan(state[0].updatedAt.valueOf());
78
+ });
79
+
80
+ it('should update the coverUrl of a specific topic', () => {
81
+ const payload: GenerationTopicDispatch = {
82
+ type: 'updateTopic',
83
+ id: 'gt_topic_to_update',
84
+ value: { coverUrl: 'updated_url' },
85
+ };
86
+
87
+ const newState = generationTopicReducer(state, payload);
88
+
89
+ expect(newState[0].coverUrl).toBe('updated_url');
90
+ expect(newState[0].title).toBe('Original Title'); // Should not change
91
+ });
92
+
93
+ it('should not change state if topic id is not found', () => {
94
+ const payload: GenerationTopicDispatch = {
95
+ type: 'updateTopic',
96
+ id: 'gt_non_existent_topic',
97
+ value: { title: 'Updated Title' },
98
+ };
99
+
100
+ const newState = generationTopicReducer(state, payload);
101
+
102
+ expect(newState).toEqual(state);
103
+ });
104
+ });
105
+
106
+ describe('deleteTopic', () => {
107
+ beforeEach(() => {
108
+ state = [
109
+ {
110
+ id: 'gt_topic_1',
111
+ title: 'Topic 1',
112
+ createdAt: new Date(),
113
+ updatedAt: new Date(),
114
+ },
115
+ {
116
+ id: 'gt_topic_2',
117
+ title: 'Topic 2',
118
+ createdAt: new Date(),
119
+ updatedAt: new Date(),
120
+ },
121
+ ];
122
+ });
123
+
124
+ it('should delete the specified topic from the state', () => {
125
+ const payload: GenerationTopicDispatch = { type: 'deleteTopic', id: 'gt_topic_1' };
126
+
127
+ const newState = generationTopicReducer(state, payload);
128
+
129
+ expect(newState).toHaveLength(1);
130
+ expect(newState.find((t) => t.id === 'gt_topic_1')).toBeUndefined();
131
+ expect(newState[0].id).toBe('gt_topic_2');
132
+ });
133
+
134
+ it('should not modify state if topic id is not found', () => {
135
+ const payload: GenerationTopicDispatch = { type: 'deleteTopic', id: 'gt_non_existent' };
136
+
137
+ const newState = generationTopicReducer(state, payload);
138
+
139
+ expect(newState).toHaveLength(2);
140
+ expect(newState).toEqual(state);
141
+ });
142
+ });
143
+
144
+ describe('default case', () => {
145
+ it('should return the original state for an unknown action type', () => {
146
+ const payload = { type: 'unknown' } as any;
147
+
148
+ const newState = generationTopicReducer(state, payload);
149
+
150
+ expect(newState).toBe(state);
151
+ });
152
+ });
153
+
154
+ describe('immutability', () => {
155
+ it('should return a new state object for addTopic', () => {
156
+ const payload: GenerationTopicDispatch = {
157
+ type: 'addTopic',
158
+ value: { id: 'test', title: 'Test' },
159
+ };
160
+ const newState = generationTopicReducer(state, payload);
161
+ expect(newState).not.toBe(state);
162
+ });
163
+
164
+ it('should return a new state object for updateTopic', () => {
165
+ state = [{ id: 'test', title: 'Test', createdAt: new Date(), updatedAt: new Date() }];
166
+ const payload: GenerationTopicDispatch = {
167
+ type: 'updateTopic',
168
+ id: 'test',
169
+ value: { title: 'Updated' },
170
+ };
171
+ const newState = generationTopicReducer(state, payload);
172
+ expect(newState).not.toBe(state);
173
+ });
174
+
175
+ it('should return a new state object for deleteTopic', () => {
176
+ state = [{ id: 'test', title: 'Test', createdAt: new Date(), updatedAt: new Date() }];
177
+ const payload: GenerationTopicDispatch = { type: 'deleteTopic', id: 'test' };
178
+ const newState = generationTopicReducer(state, payload);
179
+ expect(newState).not.toBe(state);
180
+ });
181
+
182
+ it('should not modify the original state object', () => {
183
+ const date = new Date();
184
+ const originalState = [{ id: 'a', title: 'A', createdAt: date, updatedAt: date }];
185
+ const stateCopy = [{ id: 'a', title: 'A', createdAt: date, updatedAt: date }];
186
+ const stateRef = originalState;
187
+
188
+ const payload: GenerationTopicDispatch = {
189
+ type: 'addTopic',
190
+ value: { id: 'b', title: 'B' },
191
+ };
192
+ generationTopicReducer(originalState, payload);
193
+
194
+ expect(originalState).toEqual(stateCopy);
195
+ expect(originalState).toBe(stateRef);
196
+ });
197
+ });
198
+ });
@@ -0,0 +1,66 @@
1
+ import { produce } from 'immer';
2
+
3
+ import { UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
4
+ import { ImageGenerationTopic } from '@/types/generation';
5
+
6
+ interface AddGenerationTopicAction {
7
+ type: 'addTopic';
8
+ value: Partial<ImageGenerationTopic> & { id: string };
9
+ }
10
+
11
+ interface UpdateGenerationTopicAction {
12
+ id: string;
13
+ type: 'updateTopic';
14
+ value: UpdateTopicValue;
15
+ }
16
+
17
+ interface DeleteGenerationTopicAction {
18
+ id: string;
19
+ type: 'deleteTopic';
20
+ }
21
+
22
+ export type GenerationTopicDispatch =
23
+ | AddGenerationTopicAction
24
+ | UpdateGenerationTopicAction
25
+ | DeleteGenerationTopicAction;
26
+
27
+ export const generationTopicReducer = (
28
+ state: ImageGenerationTopic[] = [],
29
+ payload: GenerationTopicDispatch,
30
+ ): ImageGenerationTopic[] => {
31
+ switch (payload.type) {
32
+ case 'addTopic': {
33
+ return produce(state, (draftState) => {
34
+ const now = new Date();
35
+ draftState.unshift({
36
+ title: payload.value.title || null,
37
+ coverUrl: payload.value.coverUrl || null,
38
+ createdAt: payload.value.createdAt || now,
39
+ updatedAt: payload.value.updatedAt || now,
40
+ ...payload.value,
41
+ });
42
+ });
43
+ }
44
+
45
+ case 'updateTopic': {
46
+ return produce(state, (draftState) => {
47
+ const index = draftState.findIndex((topic) => topic.id === payload.id);
48
+ if (index !== -1) {
49
+ draftState[index] = {
50
+ ...draftState[index],
51
+ ...payload.value,
52
+ updatedAt: new Date(),
53
+ };
54
+ }
55
+ });
56
+ }
57
+
58
+ case 'deleteTopic': {
59
+ return state.filter((topic) => topic.id !== payload.id);
60
+ }
61
+
62
+ default: {
63
+ return state;
64
+ }
65
+ }
66
+ };