You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

use-plugins.ts 18KB

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