feat(sessions): add create session functionality to agent api and hook

Implement session creation in the agent API client and expose it through the useSessions hook. The hook now provides a createSession method that updates the session list upon successful creation.
This commit is contained in:
icarus 2025-09-18 22:19:52 +08:00
parent 7b428be93d
commit 9810f01330
2 changed files with 35 additions and 3 deletions

View File

@ -6,6 +6,10 @@ import {
CreateAgentRequest,
CreateAgentResponse,
CreateAgentResponseSchema,
CreateSessionForm,
CreateSessionRequest,
CreateSessionResponse,
CreateSessionResponseSchema,
GetAgentResponse,
GetAgentResponseSchema,
ListAgentSessionsResponse,
@ -138,4 +142,16 @@ export class AgentApiClient {
throw processError(error, 'Failed to list sessions.')
}
}
public async createSession(agentId: string, session: CreateSessionForm): Promise<CreateSessionResponse> {
const url = this.getSessionPaths(agentId).base
try {
const payload = session satisfies CreateSessionRequest
const response = await this.axios.post(url, payload)
const data = CreateSessionResponseSchema.parse(response.data)
return data
} catch (error) {
throw processError(error, 'Failed to add session.')
}
}
}

View File

@ -1,20 +1,36 @@
import { AgentEntity } from '@renderer/types'
import { AgentEntity, CreateSessionForm } from '@renderer/types'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import useSWR from 'swr'
import { useAgentClient } from './useAgentClient'
export const useSessions = (agent: AgentEntity) => {
const { t } = useTranslation()
const client = useAgentClient()
const key = client.agentPaths.base
const fetcher = async () => {
const data = await client.listSessions(agent.id)
return data.data
}
const { data, error, isLoading } = useSWR(key, fetcher)
const { data, error, isLoading, mutate } = useSWR(key, fetcher)
const createSession = useCallback(
async (form: CreateSessionForm) => {
try {
const result = await client.createSession(agent.id, form)
mutate((prev) => [...(prev ?? []), result])
} catch (error) {
window.toast.error(t('agent.session.create.error.failed'))
}
},
[agent.id, client, mutate, t]
)
return {
sessions: data ?? [],
error,
isLoading
isLoading,
createSession
}
}