feat(agents): add update agent functionality and error message

Add updateAgent method to useAgents hook and update agent API client
This commit is contained in:
icarus 2025-09-18 21:20:58 +08:00
parent a4c2a1d435
commit 34c95ca787
2 changed files with 27 additions and 10 deletions

View File

@ -79,10 +79,10 @@ export class AgentApiClient {
}
}
public async createAgent(agent: AddAgentForm): Promise<CreateAgentResponse> {
public async createAgent(form: AddAgentForm): Promise<CreateAgentResponse> {
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<UpdateAgentResponse> {
const url = this.agentPaths.withId(id)
public async updateAgent(form: UpdateAgentForm): Promise<UpdateAgentResponse> {
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

View File

@ -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
}
}