diff --git a/src/renderer/src/hooks/agents/useAgent.ts b/src/renderer/src/hooks/agents/useAgent.ts new file mode 100644 index 0000000000..9bc2258635 --- /dev/null +++ b/src/renderer/src/hooks/agents/useAgent.ts @@ -0,0 +1,45 @@ +import { UpdateAgentForm } from '@renderer/types' +import { formatErrorMessageWithPrefix } from '@renderer/utils/error' +import { useCallback } from 'react' +import { useTranslation } from 'react-i18next' +import useSWR from 'swr' + +import { useAgentClient } from './useAgentClient' + +export const useAgent = (id: string | null) => { + const { t } = useTranslation() + const client = useAgentClient() + const key = client.agentPaths.base + const fetcher = useCallback(async () => { + if (id === null) { + return null + } + const result = await client.getAgent(id) + return result + }, [client, id]) + const { data, error, isLoading, mutate } = useSWR(key, fetcher) + + const updateAgent = useCallback( + async (form: UpdateAgentForm) => { + try { + // may change to optimistic update + const result = await client.updateAgent(form) + mutate((prev) => ({ + ...prev, + ...result + })) + window.toast.success(t('common.update_success')) + } catch (error) { + window.toast.error(formatErrorMessageWithPrefix(error, t('agent.update.error.failed'))) + } + }, + [client, mutate, t] + ) + + return { + agent: data, + error, + isLoading, + updateAgent + } +}