Configure embedding servers and add a Transcript Agent (#561)

* feat: configure embedding servers and transcript agents

* fix(agents): guide Transcript Agent setup

* fix(agents): require a configured embedding server URL

* docs: consolidate embedding and transcript changelog entry

* fix(webui): stabilize transcript menu interactions

* test(e2e): verify transcript scroll interruption by position

* test(webui): check transcript following without frame timing races
This commit is contained in:
Yiling-J
2026-12-05 10:17:36 +08:00
committed by GitHub
parent 72a7f68c92
commit 6c74413375
66 changed files with 2021 additions and 325 deletions
@@ -84,6 +84,20 @@ describe('FileBrowserContextMenu', () => {
expect(open).toHaveBeenCalledWith(url, '_blank', 'noopener,noreferrer')
})
it('keeps the menu open when the right button is released over Move to', () => {
const onMoveTo = vi.fn()
renderWithMenu(fileItem, { onMoveTo })
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
const moveTo = screen.getByRole('menuitem', { name: 'Move to' })
fireEvent.pointerUp(moveTo, { button: 2, pointerType: 'mouse' })
expect(onMoveTo).not.toHaveBeenCalled()
expect(screen.getByRole('menu')).toBeTruthy()
fireEvent.click(moveTo)
expect(onMoveTo).toHaveBeenCalledWith([fileItem])
})
it('omits the new-tab action for a multi-item selection', () => {
renderWithMenu(fileItem, {
files: [fileItem, stackItem],
@@ -346,10 +346,6 @@ export function FileBrowserContextMenu({
>
{openInNewTabHref && (
<ContextMenuItem
onPointerUp={(event) => {
// Radix can synthesize a click as the right button that opened the menu is released.
if (event.button !== 0) event.preventDefault()
}}
onSelect={() => window.open(openInNewTabHref, '_blank', 'noopener,noreferrer')}
>
<ExternalLink className="mr-2 h-4 w-4" />
@@ -96,6 +96,17 @@ export function GenerateTranscriptsDialog({
<Combobox
items={choices}
onOpenChange={(isOpen, details) => {
const activeElement = dialogRef.current?.ownerDocument.activeElement
// WebKit can report focus-out after focus has already returned to the input.
if (
!isOpen &&
details.reason === 'focus-out' &&
activeElement === details.event.target
) {
details.cancel()
}
}}
value={choices.find((choice) => choice.code === language)}
onValueChange={(choice) => setLanguage(choice?.code ?? '')}
itemToStringLabel={(choice) => choice.name}
@@ -0,0 +1,73 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useRef } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useTranscriptScroll } from './use-transcript-scroll'
function setup(reducedMotion = false) {
vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] })
vi.stubGlobal('matchMedia', () => ({ matches: reducedMotion }))
const onManualScroll = vi.fn()
function TranscriptViewport() {
const row = useRef<HTMLDivElement>(null)
const { setViewport, scrollTo, onWheel } = useTranscriptScroll(onManualScroll)
return (
<div ref={setViewport} onWheel={onWheel} data-testid="viewport">
<button type="button" onClick={() => scrollTo(row.current, { followPlayback: true })}>
Follow
</button>
<div ref={row} data-testid="segment" />
</div>
)
}
render(<TranscriptViewport />)
const viewport = screen.getByTestId<HTMLDivElement>('viewport')
Object.defineProperties(viewport, {
clientHeight: { value: 500 },
scrollHeight: { value: 2000 },
})
vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 384, 500))
vi.spyOn(screen.getByTestId('segment'), 'getBoundingClientRect').mockImplementation(
() => new DOMRect(0, 800 - viewport.scrollTop, 384, 40),
)
return { viewport, onManualScroll, follow: screen.getByRole('button', { name: 'Follow' }) }
}
describe('useTranscriptScroll', () => {
afterEach(() => {
cleanup()
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('animates toward the active segment, stops on wheel input, and resumes on request', () => {
const { viewport, onManualScroll, follow } = setup()
fireEvent.click(follow)
act(() => vi.advanceTimersByTime(64))
const interruptedTop = viewport.scrollTop
expect(interruptedTop).toBeGreaterThan(0)
expect(interruptedTop).toBeLessThan(570)
fireEvent.wheel(viewport, { deltaY: -120 })
act(() => vi.advanceTimersByTime(300))
expect(onManualScroll).toHaveBeenCalledOnce()
expect(viewport.scrollTop).toBe(interruptedTop)
fireEvent.click(follow)
act(() => vi.advanceTimersByTime(300))
expect(viewport.scrollTop).toBe(570)
})
it('centers the active segment immediately when reduced motion is enabled', () => {
const { viewport, follow } = setup(true)
fireEvent.click(follow)
expect(viewport.scrollTop).toBe(570)
})
})
@@ -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>
@@ -0,0 +1,88 @@
// @vitest-environment happy-dom
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AgentsSettings } from './AgentsSettings'
const getAgents = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: { ':teamId': { agents: { $get: () => getAgents() } } },
},
},
}))
vi.mock('@/ui/hooks/use-permissions', () => ({
usePermissions: () => ({ canAdmin: true }),
}))
vi.mock('./AgentFormDialog', () => ({
AgentFormDialog: ({ title }: { title: string }) => <div role="dialog">{title}</div>,
}))
function renderSettings(initiallyConfigured: boolean) {
const queryClient = new QueryClient()
const onOpenIntegrations = vi.fn()
const view = (configured: boolean) => (
<QueryClientProvider client={queryClient}>
<AgentsSettings
teamId="team"
localEmbeddingProviderConfigured={configured}
onOpenIntegrations={onOpenIntegrations}
/>
</QueryClientProvider>
)
const { rerender } = render(view(initiallyConfigured))
return {
onOpenIntegrations,
updateConfigured: (configured: boolean) => rerender(view(configured)),
}
}
describe('Transcript Agent setup', () => {
afterEach(() => {
cleanup()
vi.resetAllMocks()
})
it('blocks creation and offers to open Integrations when setup is missing', async () => {
getAgents.mockResolvedValue(Response.json([]))
const { onOpenIntegrations, updateConfigured } = renderSettings(false)
await screen.findByText('Set up a local embedding server to use the Transcript Agent.')
const create = screen.getByRole<HTMLButtonElement>('button', {
name: 'Create Transcript Agent',
})
expect(create.disabled).toBe(true)
fireEvent.click(screen.getByRole('button', { name: 'Open Integrations' }))
expect(onOpenIntegrations).toHaveBeenCalledOnce()
updateConfigured(true)
expect(create.disabled).toBe(false)
fireEvent.click(create)
expect(screen.getByRole('dialog')).toBeTruthy()
})
it('keeps an existing Transcript Agent visible with its controls disabled', async () => {
getAgents.mockResolvedValue(
Response.json([
{ id: 'transcriber', name: 'Video Transcriber', type: 'transcription', enabled: true },
]),
)
const { updateConfigured } = renderSettings(false)
const transcriber = await screen.findByText('Video Transcriber')
const enabled = screen.getByRole<HTMLButtonElement>('switch')
expect(enabled.disabled).toBe(true)
fireEvent.click(transcriber)
expect(screen.queryByRole('dialog')).toBeNull()
updateConfigured(true)
expect(enabled.disabled).toBe(false)
fireEvent.click(transcriber)
expect(screen.getByRole('dialog')).toBeTruthy()
})
})
@@ -35,6 +35,7 @@ import {
Bot,
ChevronDown,
Cpu,
Captions,
Loader2,
MessageSquare,
MoreVertical,
@@ -49,19 +50,28 @@ import { AgentFormDialog } from './AgentFormDialog'
interface AgentsSettingsProps {
teamId: string
localEmbeddingProviderConfigured: boolean
transcriptionAgentManagedByEnv?: boolean
onOpenIntegrations: () => void
}
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,
localEmbeddingProviderConfigured,
transcriptionAgentManagedByEnv,
onOpenIntegrations,
}: AgentsSettingsProps) {
const queryClient = useQueryClient()
const { canAdmin } = usePermissions()
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
@@ -78,6 +88,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 +114,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 +184,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 +271,12 @@ 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 isTranscriptSection = section.type === 'transcription'
const requiresEmbeddingServer = isTranscriptSection && !localEmbeddingProviderConfigured
const isManagedTranscriptAgent = isTranscriptSection && transcriptionAgentManagedByEnv
const canCreate =
canAdmin && !isManagedTranscriptAgent && !(isSingleAgentType && typeAgents.length > 0)
return (
<div
@@ -269,13 +291,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,10 +299,12 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
)}
</div>
<div className="flex items-center gap-2">
{!(isSingleAgentType && typeAgents.length > 0) && (
{canCreate && (
<Button
variant="ghost"
size="icon"
aria-label={m.create_type_agent({ type: getSectionLabel(section.type) })}
disabled={requiresEmbeddingServer}
className="h-8 w-8 rounded-full bg-primary/10 text-primary hover:bg-primary/20"
onClick={(e) => {
e.stopPropagation()
@@ -310,12 +328,42 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
{(isSingleAgentType || expandedSections[section.type]) && (
<div className="px-6 pb-6 pt-2 space-y-3">
{requiresEmbeddingServer ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border bg-muted/40 px-4 py-3">
<p className="text-sm text-muted-foreground">
{m.transcript_agent_setup_required()}
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={onOpenIntegrations}
>
{m.transcript_agent_open_integrations()}
</Button>
</div>
) : (
isTranscriptSection && (
<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
key={agent.id}
className="group relative overflow-hidden border-border hover:border-primary/50 transition-all duration-200 cursor-pointer pb-1 pt-1"
onClick={() => setAgentToEdit(agent)}
className={cn(
'group relative overflow-hidden border-border pb-1 pt-1',
requiresEmbeddingServer
? 'opacity-60'
: 'cursor-pointer transition-all duration-200 hover:border-primary/50',
)}
onClick={
requiresEmbeddingServer ? undefined : () => setAgentToEdit(agent)
}
>
<CardContent className="p-4 flex flex-col gap-3">
<div className="flex items-center justify-between">
@@ -356,6 +404,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
<Button
variant="ghost"
size="icon"
disabled={requiresEmbeddingServer}
className="h-8 w-8 text-muted-foreground hover:text-foreground"
>
<MoreVertical className="w-4 h-4" />
@@ -420,7 +469,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
<div onClick={(e) => e.stopPropagation()}>
<Switch
checked={agent.enabled}
disabled={agent.readOnly}
disabled={agent.readOnly || requiresEmbeddingServer}
onCheckedChange={(enabled) => {
updateAgentMutation.mutate({
teamId,
@@ -445,7 +494,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
</CardContent>
</Card>
))}
{typeAgents.length === 0 && (
{typeAgents.length === 0 && !requiresEmbeddingServer && (
<div className="col-span-full py-8 flex flex-col items-center justify-center border-2 border-dashed border-border rounded-xl bg-muted/30">
<div className="w-10 h-10 rounded-full bg-card flex items-center justify-center shadow-sm mb-3">
<Icon className="w-5 h-5 text-muted-foreground" />
@@ -453,17 +502,19 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
<p className="text-sm text-muted-foreground">
{m.no_agents_found({ type: getSectionLabel(section.type) })}
</p>
<Button
variant="link"
size="sm"
className="text-primary font-medium h-auto p-0 mt-1"
onClick={() => {
setCreateType(section.type)
setIsCreateDialogOpen(true)
}}
>
{m.create_one_now()}
</Button>
{canCreate && (
<Button
variant="link"
size="sm"
className="text-primary font-medium h-auto p-0 mt-1"
onClick={() => {
setCreateType(section.type)
setIsCreateDialogOpen(true)
}}
>
{m.create_one_now()}
</Button>
)}
</div>
)}
</div>
@@ -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>
)
}
@@ -95,6 +95,7 @@ function ContextMenuContent({
function ContextMenuItem({
className,
inset,
onPointerUp,
variant = 'default',
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
@@ -106,6 +107,11 @@ function ContextMenuItem({
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
onPointerUp={(event) => {
// Radix can synthesize a click when the button that opened the menu is released.
if (event.button !== 0) event.preventDefault()
onPointerUp?.(event)
}}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className,