Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

use-plugins.ts 16KB

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