feat: configure embedding servers and transcript agents

This commit is contained in:
yiling
2026-12-04 18:54:29 +08:00
parent 72a7f68c92
commit 553269012c
57 changed files with 1686 additions and 271 deletions
@@ -53,7 +53,7 @@ interface AgentFormDialogProps {
const agentFormSchema = z.object({
name: z.string().min(1, m.name_is_required()),
type: z.enum(['chat', 'autofill', 'embedding']),
type: z.enum(['chat', 'autofill', 'embedding', 'transcription']),
permission: z.enum(['owner', 'editor', 'reviewer']),
avatar: z.string().optional(),
providerId: z.string().optional(),
@@ -387,9 +387,12 @@ export function AgentFormDialog({
if (!res.ok) throw new Error('Failed to create agent')
return await res.json()
},
onSuccess: () => {
onSuccess: (_agent, values) => {
onClose()
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
if (values.type === 'transcription') {
void queryClient.invalidateQueries({ queryKey: ['signup-info'] })
}
toast.success(m.agent_created_successfully())
},
onError: (error) => {
@@ -406,9 +409,12 @@ export function AgentFormDialog({
if (!res.ok) throw new Error('Failed to update agent')
return await res.json()
},
onSuccess: () => {
onSuccess: (_agent, { values }) => {
onClose()
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
if (values.type === 'transcription') {
void queryClient.invalidateQueries({ queryKey: ['signup-info'] })
}
toast.success(m.agent_updated_successfully())
},
onError: (error) => {
@@ -502,6 +508,9 @@ export function AgentFormDialog({
<SelectItem value="chat">{m.agent_type_chat()}</SelectItem>
<SelectItem value="autofill">{m.agent_type_autofill()}</SelectItem>
<SelectItem value="embedding">{m.agent_type_embedding()}</SelectItem>
<SelectItem value="transcription">
{m.agent_type_transcription()}
</SelectItem>
</SelectContent>
</Select>
</Field>
@@ -35,6 +35,7 @@ import {
Bot,
ChevronDown,
Cpu,
Captions,
Loader2,
MessageSquare,
MoreVertical,
@@ -49,19 +50,21 @@ import { AgentFormDialog } from './AgentFormDialog'
interface AgentsSettingsProps {
teamId: string
transcriptionAgentManagedByEnv?: boolean
}
const AGENT_TYPES: {
type: AgentType
label: string
title: () => string
icon: React.FC<React.SVGProps<SVGSVGElement>>
}[] = [
{ type: 'chat', label: 'Chat', icon: MessageSquare },
{ type: 'autofill', label: 'Autofill', icon: Zap },
{ type: 'embedding', label: 'Embedding', icon: Cpu },
{ type: 'chat', title: m.chat_agents, icon: MessageSquare },
{ type: 'autofill', title: m.autofill_agent, icon: Zap },
{ type: 'embedding', title: m.embedding_agent, icon: Cpu },
{ type: 'transcription', title: m.transcript_agent, icon: Captions },
]
export function AgentsSettings({ teamId }: AgentsSettingsProps) {
export function AgentsSettings({ teamId, transcriptionAgentManagedByEnv }: AgentsSettingsProps) {
const queryClient = useQueryClient()
const { canAdmin } = usePermissions()
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
@@ -78,6 +81,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
const getSectionLabel = (type: AgentType) => {
if (type === 'chat') return m.agent_type_chat()
if (type === 'autofill') return m.agent_type_autofill()
if (type === 'transcription') return m.agent_type_transcription()
return m.agent_type_embedding()
}
@@ -103,6 +107,9 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
onSuccess: () => {
setIsDeleteDialogOpen(false)
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
if (agentToDelete?.type === 'transcription') {
void queryClient.invalidateQueries({ queryKey: ['signup-info'] })
}
toast.success(m.agent_deleted_successfully())
},
onError: (error) => {
@@ -170,9 +177,12 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
if (!res.ok) throw new Error('failed to update agent')
return res.json()
},
onSuccess: () => {
onSuccess: (_agent, params) => {
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
toast.success(m.agent_updated_successfully())
if (params.type === 'transcription') {
void queryClient.invalidateQueries({ queryKey: ['signup-info'] })
}
},
onError: (error) => {
toast.error(error.message)
@@ -254,7 +264,9 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
{AGENT_TYPES.map((section) => {
const typeAgents = agents.filter((a) => a.type === section.type)
const Icon = section.icon
const isSingleAgentType = section.type === 'autofill' || section.type === 'embedding'
const isSingleAgentType = section.type !== 'chat'
const isManagedTranscriptAgent =
section.type === 'transcription' && transcriptionAgentManagedByEnv
return (
<div
@@ -269,13 +281,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
onClick={!isSingleAgentType ? () => toggleSection(section.type) : undefined}
>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-foreground">
{section.type === 'chat'
? m.chat_agents()
: section.type === 'autofill'
? m.autofill_agent()
: m.embedding_agent()}
</h3>
<h3 className="font-semibold text-foreground">{section.title()}</h3>
{!isSingleAgentType && (
<Badge variant="secondary" className="h-5 px-1.5 min-w-[1.25rem] text-[10px]">
{typeAgents.length}
@@ -283,20 +289,23 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
)}
</div>
<div className="flex items-center gap-2">
{!(isSingleAgentType && typeAgents.length > 0) && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 rounded-full bg-primary/10 text-primary hover:bg-primary/20"
onClick={(e) => {
e.stopPropagation()
setCreateType(section.type)
setIsCreateDialogOpen(true)
}}
>
<Plus className="w-4 h-4" />
</Button>
)}
{canAdmin &&
!isManagedTranscriptAgent &&
!(isSingleAgentType && typeAgents.length > 0) && (
<Button
variant="ghost"
size="icon"
aria-label={m.create_type_agent({ type: getSectionLabel(section.type) })}
className="h-8 w-8 rounded-full bg-primary/10 text-primary hover:bg-primary/20"
onClick={(e) => {
e.stopPropagation()
setCreateType(section.type)
setIsCreateDialogOpen(true)
}}
>
<Plus className="w-4 h-4" />
</Button>
)}
{!isSingleAgentType && (
<ChevronDown
className={cn(
@@ -310,6 +319,13 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
{(isSingleAgentType || expandedSections[section.type]) && (
<div className="px-6 pb-6 pt-2 space-y-3">
{section.type === 'transcription' && (
<p className="text-sm text-muted-foreground">
{isManagedTranscriptAgent && typeAgents.length === 0
? m.agent_managed_by_system_hint()
: m.transcript_agent_description()}
</p>
)}
<div className="grid grid-cols-1 gap-4">
{typeAgents.map((agent) => (
<Card
@@ -0,0 +1,90 @@
// @vitest-environment happy-dom
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { EmbeddingServerSettingsCard } from './EmbeddingServerSettingsCard'
const getSettings = vi.fn()
const saveSettings = vi.fn()
const testConnection = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
'embedding-server-settings': {
$get: (args: unknown) => getSettings(args),
$put: (args: unknown) => saveSettings(args),
test: { $post: (args: unknown) => testConnection(args) },
},
},
},
},
},
}))
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
function renderCard() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<EmbeddingServerSettingsCard teamId="team-1" />
</QueryClientProvider>,
)
}
describe('Embedding server integration card', () => {
afterEach(() => {
cleanup()
vi.resetAllMocks()
})
it('tests a draft URL and saves or clears it', async () => {
getSettings.mockResolvedValue(Response.json({ isEnvConfigured: false }))
const url = 'http://embedding:9379/v1'
testConnection.mockResolvedValue(Response.json({ ok: true }))
saveSettings
.mockResolvedValueOnce(Response.json({ url, isEnvConfigured: false }))
.mockResolvedValueOnce(Response.json({ isEnvConfigured: false }))
renderCard()
const input = (await screen.findByLabelText('Server URL')) as HTMLInputElement
fireEvent.change(input, { target: { value: url } })
fireEvent.click(screen.getByRole('button', { name: 'Test Connection' }))
await screen.findByText('Connected successfully')
const args = { param: { teamId: 'team-1' }, json: { url } }
expect(testConnection).toHaveBeenCalledWith(args)
expect(saveSettings).not.toHaveBeenCalled()
const save = screen.getByRole<HTMLButtonElement>('button', { name: 'Save' })
fireEvent.click(save)
await waitFor(() => expect(save.disabled).toBe(true))
expect(saveSettings).toHaveBeenCalledWith(args)
await waitFor(() => expect(input.disabled).toBe(false))
fireEvent.change(input, { target: { value: '' } })
fireEvent.click(save)
await waitFor(() =>
expect(saveSettings).toHaveBeenLastCalledWith({
param: { teamId: 'team-1' },
json: { url: '' },
}),
)
})
it('shows the environment URL read-only and tests the effective server', async () => {
const url = 'http://embedding-server:9379/v1'
getSettings.mockResolvedValue(Response.json({ url, isEnvConfigured: true }))
testConnection.mockResolvedValue(Response.json({ ok: true }))
renderCard()
const input = (await screen.findByLabelText('Server URL')) as HTMLInputElement
expect(input.value).toBe(url)
expect(input.readOnly).toBe(true)
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save' }).disabled).toBe(true)
fireEvent.click(screen.getByRole('button', { name: 'Test Connection' }))
await screen.findByText('Connected successfully')
expect(testConnection).toHaveBeenCalledWith({ param: { teamId: 'team-1' }, json: {} })
})
})
@@ -0,0 +1,148 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { updateEmbeddingServerSettingsRequestSchema } from '@shumai/dtos'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { client } from '@/ui/api/client'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/ui/components/ui/card'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { m } from '@/ui/paraglide/messages.js'
export function EmbeddingServerSettingsCard({ teamId }: { teamId: string }) {
const queryClient = useQueryClient()
const queryKey = ['teams', teamId, 'embedding-server-settings']
const endpoint = client.api.teams[':teamId']['embedding-server-settings']
const [draft, setDraft] = useState<string | null>(null)
const {
data: settings,
isLoading,
isError,
} = useQuery({
queryKey,
queryFn: async () => {
const response = await endpoint.$get({ param: { teamId } })
if (!response.ok) throw new Error(m.failed_load_settings())
return response.json()
},
})
const isReadOnly = Boolean(settings?.isEnvConfigured)
const url = isReadOnly ? (settings?.url ?? '') : (draft ?? settings?.url ?? '')
const validUrl =
isReadOnly || updateEmbeddingServerSettingsRequestSchema.safeParse({ url }).success
const save = useMutation({
mutationFn: async () => {
const response = await endpoint.$put({ param: { teamId }, json: { url: url.trim() } })
if (!response.ok) throw new Error(m.failed_update_settings())
return response.json()
},
onSuccess: (updated) => {
queryClient.setQueryData(queryKey, updated)
setDraft(null)
test.reset()
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'settings'] })
void queryClient.invalidateQueries({ queryKey: ['signup-info'] })
void queryClient.invalidateQueries({ queryKey: ['transcription-languages'] })
toast.success(m.settings_updated())
},
onError: () => toast.error(m.failed_update_settings()),
})
const test = useMutation({
mutationFn: async () => {
const response = await endpoint.test.$post({
param: { teamId },
json: isReadOnly ? {} : { url: url.trim() },
})
if (!response.ok) throw new Error(m.embedding_server_connection_failed())
return response.json()
},
})
const isBusy = save.isPending || test.isPending
return (
<Card>
<CardHeader>
<div className="flex flex-wrap items-center justify-between gap-2">
<CardTitle>{m.embedding_server_settings()}</CardTitle>
{isReadOnly && <Badge variant="secondary">{m.embedding_server_env_configured()}</Badge>}
</div>
<CardDescription>{m.embedding_server_description()}</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
{isLoading ? (
<Loader2 className="mx-auto my-6 size-6 animate-spin text-muted-foreground" />
) : isError ? (
<p role="alert" className="text-sm text-destructive">
{m.failed_load_settings()}
</p>
) : (
<>
<Label htmlFor="embedding-server-url">{m.embedding_server_url()}</Label>
<Input
id="embedding-server-url"
type="url"
value={url}
placeholder="http://embedding-server:9379/v1"
readOnly={isReadOnly}
disabled={isBusy}
aria-invalid={!validUrl}
aria-describedby={validUrl ? undefined : 'embedding-server-url-error'}
onChange={(event) => {
setDraft(event.target.value)
test.reset()
}}
/>
{!validUrl && (
<p id="embedding-server-url-error" className="text-sm text-destructive">
{m.embedding_server_invalid_url()}
</p>
)}
{test.data?.ok && (
<p role="status" className="text-sm">
{m.embedding_server_connection_success()}
</p>
)}
{(test.data?.ok === false || test.isError) && (
<p role="alert" className="text-sm text-destructive">
{m.embedding_server_connection_failed()}
{test.data?.error && <> — {test.data.error}</>}
</p>
)}
</>
)}
</CardContent>
<CardFooter className="flex justify-between border-t border-border pt-4">
<Button
type="button"
variant="outline"
onClick={() => test.mutate()}
disabled={!settings || isBusy || !validUrl || !url.trim()}
>
{test.isPending && <Loader2 className="size-4 animate-spin" />}
{m.embedding_server_test_connection()}
</Button>
<Button
type="button"
onClick={() => save.mutate()}
disabled={!settings || isReadOnly || isBusy || !validUrl || url === (settings.url ?? '')}
>
{save.isPending && <Loader2 className="size-4 animate-spin" />}
{m.save()}
</Button>
</CardFooter>
</Card>
)
}