diff --git a/src/renderer/src/api/agent.ts b/src/renderer/src/api/agent.ts index 4847ff99ec..39386b5946 100644 --- a/src/renderer/src/api/agent.ts +++ b/src/renderer/src/api/agent.ts @@ -79,10 +79,10 @@ export class AgentApiClient { } } - public async createAgent(agent: AddAgentForm): Promise { + public async createAgent(form: AddAgentForm): Promise { const url = this.agentPaths.base try { - const payload = agent satisfies CreateAgentRequest + const payload = form satisfies CreateAgentRequest const response = await this.axios.post(url, payload) const data = CreateAgentResponseSchema.parse(response.data) return data @@ -111,10 +111,10 @@ export class AgentApiClient { } } - public async updateAgent(id: string, agent: UpdateAgentForm): Promise { - const url = this.agentPaths.withId(id) + public async updateAgent(form: UpdateAgentForm): Promise { + const url = this.agentPaths.withId(form.id) try { - const payload = agent satisfies UpdateAgentRequest + const payload = form satisfies UpdateAgentRequest const response = await this.axios.patch(url, payload) const data = UpdateAgentResponseSchema.parse(response.data) return data diff --git a/src/renderer/src/hooks/agents/useAgents.ts b/src/renderer/src/hooks/agents/useAgents.ts index 7fe31b4584..7dbe22511c 100644 --- a/src/renderer/src/hooks/agents/useAgents.ts +++ b/src/renderer/src/hooks/agents/useAgents.ts @@ -1,4 +1,4 @@ -import { AddAgentForm } from '@renderer/types' +import { AddAgentForm, UpdateAgentForm } from '@renderer/types' import { formatErrorMessageWithPrefix } from '@renderer/utils/error' import { useCallback } from 'react' import { useTranslation } from 'react-i18next' @@ -13,10 +13,10 @@ export const useAgents = () => { const { data, error, isLoading, mutate } = useSWR(key, () => client.listAgents()) const addAgent = useCallback( - async (agent: AddAgentForm) => { + async (form: AddAgentForm) => { try { - const result = await client.createAgent(agent) - mutate((prev) => ({ agents: [...(prev?.agents ?? []), result], total: 0 })) + const result = await client.createAgent(form) + mutate((prev) => ({ agents: [...(prev?.agents ?? []), result], total: prev ? prev.total + 1 : 1 })) } catch (error) { window.toast.error(formatErrorMessageWithPrefix(error, t('agent.add.error.failed'))) } @@ -24,10 +24,27 @@ export const useAgents = () => { [client, mutate, t] ) + const updateAgent = useCallback( + async (form: UpdateAgentForm) => { + try { + // may change to optimistic update + const result = await client.updateAgent(form) + mutate((prev) => ({ + agents: prev?.agents.map((a) => (a.id === form.id ? result : a)) ?? [], + total: prev?.total ?? 0 + })) + } catch (error) { + window.toast.error(formatErrorMessageWithPrefix(error, t('agent.update.error.failed'))) + } + }, + [client, mutate, t] + ) + return { agents: data?.agents ?? [], error, isLoading, - addAgent + addAgent, + updateAgent } }