use-plugins.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import { useCallback, useEffect } from 'react'
  2. import type {
  3. ModelProvider,
  4. } from '@/app/components/header/account-setting/model-provider-page/declarations'
  5. import { fetchModelProviderModelList } from '@/service/common'
  6. import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
  7. import type {
  8. DebugInfo as DebugInfoTypes,
  9. Dependency,
  10. GitHubItemAndMarketPlaceDependency,
  11. InstallPackageResponse,
  12. InstalledPluginListResponse,
  13. PackageDependency,
  14. Permissions,
  15. Plugin,
  16. PluginDetail,
  17. PluginInfoFromMarketPlace,
  18. PluginTask,
  19. PluginType,
  20. PluginsFromMarketplaceByInfoResponse,
  21. PluginsFromMarketplaceResponse,
  22. VersionInfo,
  23. VersionListResponse,
  24. uploadGitHubResponse,
  25. } from '@/app/components/plugins/types'
  26. import { TaskStatus } from '@/app/components/plugins/types'
  27. import { PluginType as PluginTypeEnum } from '@/app/components/plugins/types'
  28. import type {
  29. PluginsSearchParams,
  30. } from '@/app/components/plugins/marketplace/types'
  31. import { get, getMarketplace, post, postMarketplace } from './base'
  32. import type { MutateOptions, QueryOptions } from '@tanstack/react-query'
  33. import {
  34. useMutation,
  35. useQuery,
  36. useQueryClient,
  37. } from '@tanstack/react-query'
  38. import { useInvalidateAllBuiltInTools } from './use-tools'
  39. import usePermission from '@/app/components/plugins/plugin-page/use-permission'
  40. import { uninstallPlugin } from '@/service/plugins'
  41. import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
  42. import { cloneDeep } from 'lodash-es'
  43. const NAME_SPACE = 'plugins'
  44. const useInstalledPluginListKey = [NAME_SPACE, 'installedPluginList']
  45. export const useCheckInstalled = ({
  46. pluginIds,
  47. enabled,
  48. }: {
  49. pluginIds: string[],
  50. enabled: boolean
  51. }) => {
  52. return useQuery<{ plugins: PluginDetail[] }>({
  53. queryKey: [NAME_SPACE, 'checkInstalled', pluginIds],
  54. queryFn: () => post<{ plugins: PluginDetail[] }>('/workspaces/current/plugin/list/installations/ids', {
  55. body: {
  56. plugin_ids: pluginIds,
  57. },
  58. }),
  59. enabled,
  60. staleTime: 0, // always fresh
  61. })
  62. }
  63. export const useInstalledPluginList = (disable?: boolean) => {
  64. return useQuery<InstalledPluginListResponse>({
  65. queryKey: useInstalledPluginListKey,
  66. queryFn: () => get<InstalledPluginListResponse>('/workspaces/current/plugin/list'),
  67. enabled: !disable,
  68. initialData: !disable ? undefined : { plugins: [] },
  69. })
  70. }
  71. export const useInvalidateInstalledPluginList = () => {
  72. const queryClient = useQueryClient()
  73. const invalidateAllBuiltInTools = useInvalidateAllBuiltInTools()
  74. return () => {
  75. queryClient.invalidateQueries(
  76. {
  77. queryKey: useInstalledPluginListKey,
  78. })
  79. invalidateAllBuiltInTools()
  80. }
  81. }
  82. export const useInstallPackageFromMarketPlace = (options?: MutateOptions<InstallPackageResponse, Error, string>) => {
  83. return useMutation({
  84. ...options,
  85. mutationFn: (uniqueIdentifier: string) => {
  86. return post<InstallPackageResponse>('/workspaces/current/plugin/install/marketplace', { body: { plugin_unique_identifiers: [uniqueIdentifier] } })
  87. },
  88. })
  89. }
  90. export const useUpdatePackageFromMarketPlace = (options?: MutateOptions<InstallPackageResponse, Error, object>) => {
  91. return useMutation({
  92. ...options,
  93. mutationFn: (body: object) => {
  94. return post<InstallPackageResponse>('/workspaces/current/plugin/upgrade/marketplace', {
  95. body,
  96. })
  97. },
  98. })
  99. }
  100. export const useVersionListOfPlugin = (pluginID: string) => {
  101. return useQuery<{ data: VersionListResponse }>({
  102. enabled: !!pluginID,
  103. queryKey: [NAME_SPACE, 'versions', pluginID],
  104. queryFn: () => getMarketplace<{ data: VersionListResponse }>(`/plugins/${pluginID}/versions`, { params: { page: 1, page_size: 100 } }),
  105. })
  106. }
  107. export const useInvalidateVersionListOfPlugin = () => {
  108. const queryClient = useQueryClient()
  109. return (pluginID: string) => {
  110. queryClient.invalidateQueries({ queryKey: [NAME_SPACE, 'versions', pluginID] })
  111. }
  112. }
  113. export const useInstallPackageFromLocal = () => {
  114. return useMutation({
  115. mutationFn: (uniqueIdentifier: string) => {
  116. return post<InstallPackageResponse>('/workspaces/current/plugin/install/pkg', {
  117. body: { plugin_unique_identifiers: [uniqueIdentifier] },
  118. })
  119. },
  120. })
  121. }
  122. export const useInstallPackageFromGitHub = () => {
  123. return useMutation({
  124. mutationFn: ({ repoUrl, selectedVersion, selectedPackage, uniqueIdentifier }: {
  125. repoUrl: string
  126. selectedVersion: string
  127. selectedPackage: string
  128. uniqueIdentifier: string
  129. }) => {
  130. return post<InstallPackageResponse>('/workspaces/current/plugin/install/github', {
  131. body: {
  132. repo: repoUrl,
  133. version: selectedVersion,
  134. package: selectedPackage,
  135. plugin_unique_identifier: uniqueIdentifier,
  136. },
  137. })
  138. },
  139. })
  140. }
  141. export const useUploadGitHub = (payload: {
  142. repo: string
  143. version: string
  144. package: string
  145. }) => {
  146. return useQuery({
  147. queryKey: [NAME_SPACE, 'uploadGitHub', payload],
  148. queryFn: () => post<uploadGitHubResponse>('/workspaces/current/plugin/upload/github', {
  149. body: payload,
  150. }),
  151. retry: 0,
  152. })
  153. }
  154. export const useInstallOrUpdate = ({
  155. onSuccess,
  156. }: {
  157. onSuccess?: (res: { success: boolean }[]) => void
  158. }) => {
  159. const { mutateAsync: updatePackageFromMarketPlace } = useUpdatePackageFromMarketPlace()
  160. return useMutation({
  161. mutationFn: (data: {
  162. payload: Dependency[],
  163. plugin: Plugin[],
  164. installedInfo: Record<string, VersionInfo>
  165. }) => {
  166. const { payload, plugin, installedInfo } = data
  167. return Promise.all(payload.map(async (item, i) => {
  168. try {
  169. const orgAndName = `${plugin[i]?.org || plugin[i]?.author}/${plugin[i]?.name}`
  170. const installedPayload = installedInfo[orgAndName]
  171. const isInstalled = !!installedPayload
  172. let uniqueIdentifier = ''
  173. if (item.type === 'github') {
  174. const data = item as GitHubItemAndMarketPlaceDependency
  175. // From local bundle don't have data.value.github_plugin_unique_identifier
  176. if (!data.value.github_plugin_unique_identifier) {
  177. const { unique_identifier } = await post<uploadGitHubResponse>('/workspaces/current/plugin/upload/github', {
  178. body: {
  179. repo: data.value.repo!,
  180. version: data.value.release! || data.value.version!,
  181. package: data.value.packages! || data.value.package!,
  182. },
  183. })
  184. uniqueIdentifier = data.value.github_plugin_unique_identifier! || unique_identifier
  185. // has the same version, but not installed
  186. if (uniqueIdentifier === installedPayload?.uniqueIdentifier) {
  187. return {
  188. success: true,
  189. }
  190. }
  191. }
  192. if (!isInstalled) {
  193. await post<InstallPackageResponse>('/workspaces/current/plugin/install/github', {
  194. body: {
  195. repo: data.value.repo!,
  196. version: data.value.release! || data.value.version!,
  197. package: data.value.packages! || data.value.package!,
  198. plugin_unique_identifier: uniqueIdentifier,
  199. },
  200. })
  201. }
  202. }
  203. if (item.type === 'marketplace') {
  204. const data = item as GitHubItemAndMarketPlaceDependency
  205. uniqueIdentifier = data.value.marketplace_plugin_unique_identifier! || plugin[i]?.plugin_id
  206. if (uniqueIdentifier === installedPayload?.uniqueIdentifier) {
  207. return {
  208. success: true,
  209. }
  210. }
  211. if (!isInstalled) {
  212. await post<InstallPackageResponse>('/workspaces/current/plugin/install/marketplace', {
  213. body: {
  214. plugin_unique_identifiers: [uniqueIdentifier],
  215. },
  216. })
  217. }
  218. }
  219. if (item.type === 'package') {
  220. const data = item as PackageDependency
  221. uniqueIdentifier = data.value.unique_identifier
  222. if (uniqueIdentifier === installedPayload?.uniqueIdentifier) {
  223. return {
  224. success: true,
  225. }
  226. }
  227. if (!isInstalled) {
  228. await post<InstallPackageResponse>('/workspaces/current/plugin/install/pkg', {
  229. body: {
  230. plugin_unique_identifiers: [uniqueIdentifier],
  231. },
  232. })
  233. }
  234. }
  235. if (isInstalled) {
  236. if (item.type === 'package') {
  237. await uninstallPlugin(installedPayload.installedId)
  238. await post<InstallPackageResponse>('/workspaces/current/plugin/install/pkg', {
  239. body: {
  240. plugin_unique_identifiers: [uniqueIdentifier],
  241. },
  242. })
  243. }
  244. else {
  245. await updatePackageFromMarketPlace({
  246. original_plugin_unique_identifier: installedPayload?.uniqueIdentifier,
  247. new_plugin_unique_identifier: uniqueIdentifier,
  248. })
  249. }
  250. }
  251. return ({ success: true })
  252. }
  253. // eslint-disable-next-line unused-imports/no-unused-vars
  254. catch (e) {
  255. return Promise.resolve({ success: false })
  256. }
  257. }))
  258. },
  259. onSuccess,
  260. })
  261. }
  262. export const useDebugKey = () => {
  263. return useQuery({
  264. queryKey: [NAME_SPACE, 'debugKey'],
  265. queryFn: () => get<DebugInfoTypes>('/workspaces/current/plugin/debugging-key'),
  266. })
  267. }
  268. const usePermissionsKey = [NAME_SPACE, 'permissions']
  269. export const usePermissions = () => {
  270. return useQuery({
  271. queryKey: usePermissionsKey,
  272. queryFn: () => get<Permissions>('/workspaces/current/plugin/permission/fetch'),
  273. })
  274. }
  275. export const useInvalidatePermissions = () => {
  276. const queryClient = useQueryClient()
  277. return () => {
  278. queryClient.invalidateQueries(
  279. {
  280. queryKey: usePermissionsKey,
  281. })
  282. }
  283. }
  284. export const useMutationPermissions = ({
  285. onSuccess,
  286. }: {
  287. onSuccess?: () => void
  288. }) => {
  289. return useMutation({
  290. mutationFn: (payload: Permissions) => {
  291. return post('/workspaces/current/plugin/permission/change', { body: payload })
  292. },
  293. onSuccess,
  294. })
  295. }
  296. export const useMutationPluginsFromMarketplace = () => {
  297. return useMutation({
  298. mutationFn: (pluginsSearchParams: PluginsSearchParams) => {
  299. const {
  300. query,
  301. sortBy,
  302. sortOrder,
  303. category,
  304. tags,
  305. exclude,
  306. type,
  307. page = 1,
  308. pageSize = 40,
  309. } = pluginsSearchParams
  310. const pluginOrBundle = type === 'bundle' ? 'bundles' : 'plugins'
  311. return postMarketplace<{ data: PluginsFromMarketplaceResponse }>(`/${pluginOrBundle}/search/advanced`, {
  312. body: {
  313. page,
  314. page_size: pageSize,
  315. query,
  316. sort_by: sortBy,
  317. sort_order: sortOrder,
  318. category: category !== 'all' ? category : '',
  319. tags,
  320. exclude,
  321. type,
  322. },
  323. })
  324. },
  325. })
  326. }
  327. export const useFetchPluginsInMarketPlaceByIds = (unique_identifiers: string[], options?: QueryOptions<{ data: PluginsFromMarketplaceResponse }>) => {
  328. return useQuery({
  329. ...options,
  330. queryKey: [NAME_SPACE, 'fetchPluginsInMarketPlaceByIds', unique_identifiers],
  331. queryFn: () => postMarketplace<{ data: PluginsFromMarketplaceResponse }>('/plugins/identifier/batch', {
  332. body: {
  333. unique_identifiers,
  334. },
  335. }),
  336. enabled: unique_identifiers?.filter(i => !!i).length > 0,
  337. retry: 0,
  338. })
  339. }
  340. export const useFetchPluginsInMarketPlaceByInfo = (infos: Record<string, any>[]) => {
  341. return useQuery({
  342. queryKey: [NAME_SPACE, 'fetchPluginsInMarketPlaceByInfo', infos],
  343. queryFn: () => postMarketplace<{ data: PluginsFromMarketplaceByInfoResponse }>('/plugins/versions/batch', {
  344. body: {
  345. plugin_tuples: infos.map(info => ({
  346. org: info.organization,
  347. name: info.plugin,
  348. version: info.version,
  349. })),
  350. },
  351. }),
  352. enabled: infos?.filter(i => !!i).length > 0,
  353. retry: 0,
  354. })
  355. }
  356. const usePluginTaskListKey = [NAME_SPACE, 'pluginTaskList']
  357. export const usePluginTaskList = (category?: PluginType) => {
  358. const {
  359. canManagement,
  360. } = usePermission()
  361. const { refreshPluginList } = useRefreshPluginList()
  362. const {
  363. data,
  364. isFetched,
  365. isRefetching,
  366. refetch,
  367. ...rest
  368. } = useQuery({
  369. enabled: canManagement,
  370. queryKey: usePluginTaskListKey,
  371. queryFn: () => get<{ tasks: PluginTask[] }>('/workspaces/current/plugin/tasks?page=1&page_size=100'),
  372. refetchInterval: (lastQuery) => {
  373. const lastData = lastQuery.state.data
  374. const taskDone = lastData?.tasks.every(task => task.status === TaskStatus.success || task.status === TaskStatus.failed)
  375. return taskDone ? false : 5000
  376. },
  377. })
  378. useEffect(() => {
  379. // After first fetch, refresh plugin list each time all tasks are done
  380. if (!isRefetching) {
  381. const lastData = cloneDeep(data)
  382. const taskDone = lastData?.tasks.every(task => task.status === TaskStatus.success || task.status === TaskStatus.failed)
  383. const taskAllFailed = lastData?.tasks.every(task => task.status === TaskStatus.failed)
  384. if (taskDone) {
  385. if (lastData?.tasks.length && !taskAllFailed)
  386. refreshPluginList(category ? { category } as any : undefined, !category)
  387. }
  388. }
  389. // eslint-disable-next-line react-hooks/exhaustive-deps
  390. }, [isRefetching])
  391. const handleRefetch = useCallback(() => {
  392. refetch()
  393. }, [refetch])
  394. return {
  395. data,
  396. pluginTasks: data?.tasks || [],
  397. isFetched,
  398. handleRefetch,
  399. ...rest,
  400. }
  401. }
  402. export const useMutationClearTaskPlugin = () => {
  403. return useMutation({
  404. mutationFn: ({ taskId, pluginId }: { taskId: string; pluginId: string }) => {
  405. return post<{ success: boolean }>(`/workspaces/current/plugin/tasks/${taskId}/delete/${pluginId}`)
  406. },
  407. })
  408. }
  409. export const useMutationClearAllTaskPlugin = () => {
  410. return useMutation({
  411. mutationFn: () => {
  412. return post<{ success: boolean }>('/workspaces/current/plugin/tasks/delete_all')
  413. },
  414. })
  415. }
  416. export const usePluginManifestInfo = (pluginUID: string) => {
  417. return useQuery({
  418. enabled: !!pluginUID,
  419. queryKey: [[NAME_SPACE, 'manifest', pluginUID]],
  420. queryFn: () => getMarketplace<{ data: { plugin: PluginInfoFromMarketPlace, version: { version: string } } }>(`/plugins/${pluginUID}`),
  421. retry: 0,
  422. })
  423. }
  424. export const useDownloadPlugin = (info: { organization: string; pluginName: string; version: string }, needDownload: boolean) => {
  425. return useQuery({
  426. queryKey: [NAME_SPACE, 'downloadPlugin', info],
  427. queryFn: () => getMarketplace<Blob>(`/plugins/${info.organization}/${info.pluginName}/${info.version}/download`),
  428. enabled: needDownload,
  429. retry: 0,
  430. })
  431. }
  432. export const useMutationCheckDependencies = () => {
  433. return useMutation({
  434. mutationFn: (appId: string) => {
  435. return get<{ leaked_dependencies: Dependency[] }>(`/apps/imports/${appId}/check-dependencies`)
  436. },
  437. })
  438. }
  439. export const useModelInList = (currentProvider?: ModelProvider, modelId?: string) => {
  440. return useQuery({
  441. queryKey: ['modelInList', currentProvider?.provider, modelId],
  442. queryFn: async () => {
  443. if (!modelId || !currentProvider) return false
  444. try {
  445. const modelsData = await fetchModelProviderModelList(`/workspaces/current/model-providers/${currentProvider?.provider}/models`)
  446. return !!modelId && !!modelsData.data.find(item => item.model === modelId)
  447. }
  448. catch (error) {
  449. return false
  450. }
  451. },
  452. enabled: !!modelId && !!currentProvider,
  453. })
  454. }
  455. export const usePluginInfo = (providerName?: string) => {
  456. return useQuery({
  457. queryKey: ['pluginInfo', providerName],
  458. queryFn: async () => {
  459. if (!providerName) return null
  460. const parts = providerName.split('/')
  461. const org = parts[0]
  462. const name = parts[1]
  463. try {
  464. const response = await fetchPluginInfoFromMarketPlace({ org, name })
  465. return response.data.plugin.category === PluginTypeEnum.model ? response.data.plugin : null
  466. }
  467. catch (error) {
  468. return null
  469. }
  470. },
  471. enabled: !!providerName,
  472. })
  473. }