mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 12:24:39 +00:00
feat(provider): refresh models per AI provider
This commit is contained in:
@@ -38,17 +38,19 @@ import {
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { providerConfigSchema, KNOWN_APIS, type SyncCheckResponse } from '@shumai/dtos'
|
||||
import {
|
||||
providerConfigSchema,
|
||||
KNOWN_APIS,
|
||||
type ProviderRefreshUnavailableReason,
|
||||
type RefreshedProviderModel,
|
||||
} from '@shumai/dtos'
|
||||
import { useForm } from '@tanstack/react-form'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { InferResponseType } from 'hono/client'
|
||||
import {
|
||||
ChevronRight,
|
||||
Cpu,
|
||||
Globe,
|
||||
Info,
|
||||
Loader2,
|
||||
Maximize2,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
@@ -61,7 +63,7 @@ import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { ModelFormDialog, ModelFormValues } from './ModelFormDialog'
|
||||
import { SyncProvidersDialog } from './SyncProvidersDialog'
|
||||
import { RefreshProviderModelsDialog } from './RefreshProviderModelsDialog'
|
||||
|
||||
const API_PROTOCOL_LABELS: Record<(typeof KNOWN_APIS)[number], string> = {
|
||||
'openai-completions': 'OpenAI Completions',
|
||||
@@ -87,6 +89,12 @@ interface ProvidersSettingsProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
function refreshUnavailableText(reason: ProviderRefreshUnavailableReason) {
|
||||
return reason === 'missing_credentials'
|
||||
? m.provider_refresh_missing_credentials()
|
||||
: m.provider_refresh_unsupported_connection()
|
||||
}
|
||||
|
||||
export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
|
||||
@@ -94,31 +102,34 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [providerToDelete, setProviderToDelete] = useState<Provider | null>(null)
|
||||
const [isSyncDialogOpen, setIsSyncDialogOpen] = useState(false)
|
||||
const [syncData, setSyncData] = useState<SyncCheckResponse | null>(null)
|
||||
const [preview, setPreview] = useState<{
|
||||
provider: Provider
|
||||
models: RefreshedProviderModel[]
|
||||
trigger: HTMLButtonElement
|
||||
} | null>(null)
|
||||
|
||||
// Check updates mutation
|
||||
const syncCheckMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers['sync-check'].$post({
|
||||
param: { teamId },
|
||||
const refreshMutation = useMutation({
|
||||
mutationFn: async ({ provider }: { provider: Provider; trigger: HTMLButtonElement }) => {
|
||||
const res = await client.api.teams[':teamId'].providers[':providerId'].models.refresh.$post({
|
||||
param: { teamId, providerId: provider.id },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: 'Failed to check updates' }))
|
||||
throw new Error((err as { message?: string }).message || 'Failed to check updates')
|
||||
}
|
||||
return await res.json()
|
||||
if (!res.ok) throw new Error(m.provider_refresh_failed())
|
||||
return res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data.totalNewModels === 0 && data.totalNewProviders === 0) {
|
||||
toast.info(m.sync_providers_up_to_date())
|
||||
onSuccess: (data, { provider, trigger }) => {
|
||||
if (data.status === 'unavailable') {
|
||||
toast.info(refreshUnavailableText(data.reason))
|
||||
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
return
|
||||
}
|
||||
setSyncData(data)
|
||||
setIsSyncDialogOpen(true)
|
||||
if (data.models.length === 0) {
|
||||
toast.info(m.provider_refresh_no_new_models({ name: provider.name }))
|
||||
return
|
||||
}
|
||||
setPreview({ provider, models: data.models, trigger })
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message)
|
||||
onError: () => {
|
||||
toast.error(m.provider_refresh_failed())
|
||||
},
|
||||
})
|
||||
|
||||
@@ -143,9 +154,10 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
|
||||
const filteredProviders = useMemo(() => {
|
||||
if (!providers) return []
|
||||
if (!searchQuery.trim()) return providers
|
||||
const query = searchQuery.toLowerCase()
|
||||
return providers.filter((p) => p.name.toLowerCase().includes(query))
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
return providers
|
||||
.filter((p) => p.name.toLowerCase().includes(query))
|
||||
.sort((a, b) => Number(b.configured) - Number(a.configured))
|
||||
}, [providers, searchQuery])
|
||||
|
||||
// Create Mutation
|
||||
@@ -207,120 +219,40 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col space-y-0">
|
||||
<div className="flex-none space-y-4 pb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<Cpu className="w-5 h-5 text-primary" />
|
||||
{m.configured_ai_providers()}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => syncCheckMutation.mutate()}
|
||||
disabled={syncCheckMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{syncCheckMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{m.sync_providers_checking()}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{m.sync_providers()}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setIsCreateDialogOpen(true)}
|
||||
className="bg-primary hover:bg-primary/90 text-primary-foreground gap-2"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{m.add_provider()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative px-0.5">
|
||||
<div className="flex flex-none flex-wrap items-center gap-3 pb-4">
|
||||
<div className="relative min-w-0 flex-[1_1_10rem] px-0.5">
|
||||
<Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={m.search_providers_placeholder()}
|
||||
placeholder={m.search_providers_placeholder()}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10 bg-card border-border focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-0"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={() => setIsCreateDialogOpen(true)} className="gap-2">
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{m.add_provider()}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="flex-1 min-h-0">
|
||||
<div className="pr-4 py-2 grid grid-cols-1 gap-4">
|
||||
{filteredProviders.map((provider) => (
|
||||
<Card
|
||||
<ProviderCard
|
||||
key={provider.id}
|
||||
className="group cursor-pointer hover:border-primary/50 transition-all hover:shadow-md overflow-hidden"
|
||||
onClick={() => setEditingProviderId(provider.id)}
|
||||
>
|
||||
<CardContent className="p-5 flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-4 min-w-0 flex-1">
|
||||
<div className="flex-none p-3 bg-muted rounded-xl group-hover:bg-primary/10 transition-colors">
|
||||
<Globe className="w-6 h-6 text-muted-foreground group-hover:text-primary" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-bold text-foreground truncate">{provider.name}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs text-muted-foreground mt-1">
|
||||
<span className="flex items-center gap-1 flex-none">
|
||||
<Zap className="w-3 h-3" />
|
||||
{provider.config.api}
|
||||
</span>
|
||||
{provider.config.baseUrl && (
|
||||
<span className="flex items-center gap-1 min-w-0">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 flex-none" />
|
||||
<Info className="w-3 h-3 flex-none" />
|
||||
<span className="truncate max-w-[200px] md:max-w-[300px]">
|
||||
{provider.config.baseUrl}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1 flex-none">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 flex-none" />
|
||||
<Maximize2 className="w-3 h-3" />
|
||||
{m.n_models_count({ count: provider.modelsCount })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setProviderToDelete(provider)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
className="text-destructive focus:text-destructive gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" /> {m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ChevronRight className="flex-none w-5 h-5 text-muted-foreground/50 group-hover:text-primary transition-colors" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
provider={provider}
|
||||
isRefreshing={
|
||||
refreshMutation.isPending && refreshMutation.variables?.provider.id === provider.id
|
||||
}
|
||||
refreshInProgress={refreshMutation.isPending}
|
||||
onEdit={() => setEditingProviderId(provider.id)}
|
||||
onRefresh={(trigger) => refreshMutation.mutate({ provider, trigger })}
|
||||
onDelete={() => {
|
||||
setProviderToDelete(provider)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{providers?.length === 0 && (
|
||||
@@ -400,19 +332,125 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<SyncProvidersDialog
|
||||
isOpen={isSyncDialogOpen}
|
||||
onClose={() => setIsSyncDialogOpen(false)}
|
||||
teamId={teamId}
|
||||
syncData={syncData}
|
||||
onSuccess={() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
}}
|
||||
/>
|
||||
{preview && (
|
||||
<RefreshProviderModelsDialog
|
||||
teamId={teamId}
|
||||
providerId={preview.provider.id}
|
||||
providerName={preview.provider.name}
|
||||
models={preview.models}
|
||||
onClose={() => setPreview(null)}
|
||||
onCloseAutoFocus={() => preview.trigger.focus()}
|
||||
onImported={() => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderCard({
|
||||
provider,
|
||||
isRefreshing,
|
||||
refreshInProgress,
|
||||
onEdit,
|
||||
onRefresh,
|
||||
onDelete,
|
||||
}: {
|
||||
provider: Provider
|
||||
isRefreshing: boolean
|
||||
refreshInProgress: boolean
|
||||
onEdit: () => void
|
||||
onRefresh: (button: HTMLButtonElement) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
const unavailable = provider.refreshUnavailableReason
|
||||
const reasonId = `provider-refresh-reason-${provider.id}`
|
||||
const displayUrl = provider.config.baseUrl?.replace(/^https?:\/\//, '')
|
||||
return (
|
||||
<Card className="gap-0 rounded-xl py-0 shadow-none transition-colors hover:border-primary/35">
|
||||
<CardContent className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-2 p-3.5 sm:grid-cols-[auto_minmax(0,1fr)_auto]">
|
||||
<span className="grid size-9 place-items-center rounded-lg bg-muted text-muted-foreground">
|
||||
<Globe aria-hidden="true" className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onEdit}
|
||||
aria-label={m.edit_item({ name: provider.name })}
|
||||
className="max-w-full cursor-pointer rounded-sm text-start font-semibold wrap-anywhere text-foreground hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
|
||||
>
|
||||
{provider.name}
|
||||
</button>
|
||||
{provider.configured && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="border-transparent bg-green-500/10 px-2 text-xs font-medium text-green-800 dark:text-green-300"
|
||||
>
|
||||
{m.provider_configured_badge()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
<span>{API_PROTOCOL_LABELS[provider.config.api] ?? provider.config.api}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{m.n_models_count({ count: provider.modelsCount })}</span>
|
||||
</div>
|
||||
{unavailable ? (
|
||||
<p id={reasonId} className="mt-1 text-xs text-muted-foreground">
|
||||
{refreshUnavailableText(unavailable)}
|
||||
</p>
|
||||
) : displayUrl ? (
|
||||
<p className="mt-1 wrap-anywhere text-xs text-muted-foreground" dir="ltr">
|
||||
{displayUrl}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="col-start-2 flex flex-wrap items-center gap-1 sm:col-start-3">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
disabled={unavailable !== null || refreshInProgress}
|
||||
aria-label={m.provider_refresh_action({ name: provider.name })}
|
||||
aria-describedby={unavailable ? reasonId : undefined}
|
||||
aria-busy={isRefreshing}
|
||||
onClick={(event) => onRefresh(event.currentTarget)}
|
||||
>
|
||||
{isRefreshing ? (
|
||||
<Loader2 aria-hidden="true" className="size-4 motion-safe:animate-spin" />
|
||||
) : (
|
||||
<RefreshCw aria-hidden="true" className="size-4" />
|
||||
)}
|
||||
{isRefreshing ? m.provider_refresh_loading() : m.provider_refresh_models()}
|
||||
</Button>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={m.provider_options({ name: provider.name })}
|
||||
className="size-11 text-muted-foreground hover:text-foreground sm:size-9"
|
||||
>
|
||||
<MoreVertical aria-hidden="true" className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem onSelect={onEdit}>{m.edit()}</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={onDelete} variant="destructive">
|
||||
<Trash2 className="size-4" /> {m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Create Provider Dialog
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { RefreshedProviderModel } from '@shumai/dtos'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RefreshProviderModelsDialog } from './RefreshProviderModelsDialog'
|
||||
|
||||
const { importModels } = vi.hoisted(() => ({ importModels: vi.fn() }))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
providers: { ':providerId': { models: { import: { $post: importModels } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
const models = Array.from({ length: 6 }, (_, index): RefreshedProviderModel => ({
|
||||
modelId: `model-${index + 1}`,
|
||||
name: `Model ${index + 1}`,
|
||||
selectionToken: `model-token-${index + 1}`,
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
}))
|
||||
|
||||
function renderDialog() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const onClose = vi.fn()
|
||||
const onImported = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RefreshProviderModelsDialog
|
||||
teamId="team-1"
|
||||
providerId="provider-1"
|
||||
providerName="OpenAI"
|
||||
models={models}
|
||||
onClose={onClose}
|
||||
onCloseAutoFocus={vi.fn()}
|
||||
onImported={onImported}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return { onClose, onImported }
|
||||
}
|
||||
|
||||
describe('RefreshProviderModelsDialog', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
importModels.mockReset()
|
||||
})
|
||||
|
||||
it('opens a single-provider preview with selectable models and an empty selection', () => {
|
||||
renderDialog()
|
||||
expect(screen.getByRole('heading', { name: 'New models for OpenAI' })).toBeTruthy()
|
||||
expect(screen.getByText('Select the models you want to add.')).toBeTruthy()
|
||||
expect(screen.getAllByRole('checkbox')).toHaveLength(models.length)
|
||||
expect(screen.getByRole('button', { name: 'Add selected' }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('filters models and selects or deselects the visible results', () => {
|
||||
renderDialog()
|
||||
const search = screen.getByRole('textbox')
|
||||
fireEvent.change(search, { target: { value: 'model-2' } })
|
||||
expect(screen.queryByText('Model 1')).toBeNull()
|
||||
expect(screen.getAllByRole('checkbox')).toHaveLength(1)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select visible' }))
|
||||
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('true')
|
||||
expect(screen.getByRole('button', { name: 'Add selected (1)' })).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Deselect visible' }))
|
||||
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('false')
|
||||
expect(screen.getByRole('button', { name: 'Add selected' }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('imports only the selected models into the previewed provider', async () => {
|
||||
importModels.mockResolvedValueOnce(Response.json({ addedModels: 1 }))
|
||||
const { onClose, onImported } = renderDialog()
|
||||
fireEvent.click(screen.getAllByRole('checkbox')[1])
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add selected (1)' }))
|
||||
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
|
||||
expect(onImported).toHaveBeenCalledOnce()
|
||||
expect(importModels).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-1', providerId: 'provider-1' },
|
||||
json: { models: [models[1]] },
|
||||
})
|
||||
})
|
||||
|
||||
it('shows an actionable error when the preview becomes stale', async () => {
|
||||
importModels.mockResolvedValueOnce(new Response(null, { status: 409 }))
|
||||
const { onImported } = renderDialog()
|
||||
fireEvent.click(screen.getAllByRole('checkbox')[0])
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add selected (1)' }))
|
||||
expect((await screen.findByRole('alert')).textContent).toContain('Refresh models again.')
|
||||
expect(onImported).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { RefreshedProviderModel } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface RefreshProviderModelsDialogProps {
|
||||
teamId: string
|
||||
providerId: string
|
||||
providerName: string
|
||||
models: RefreshedProviderModel[]
|
||||
onClose: () => void
|
||||
onCloseAutoFocus: () => void
|
||||
onImported: () => void
|
||||
}
|
||||
|
||||
export function RefreshProviderModelsDialog({
|
||||
teamId,
|
||||
providerId,
|
||||
providerName,
|
||||
models,
|
||||
onClose,
|
||||
onCloseAutoFocus,
|
||||
onImported,
|
||||
}: RefreshProviderModelsDialogProps) {
|
||||
const [selectedIds, setSelectedIds] = useState(() => new Set<string>())
|
||||
const [search, setSearch] = useState('')
|
||||
const query = search.trim().toLowerCase()
|
||||
const filteredModels = models.filter(
|
||||
({ name, modelId }) =>
|
||||
name.toLowerCase().includes(query) || modelId.toLowerCase().includes(query),
|
||||
)
|
||||
const allVisibleSelected =
|
||||
filteredModels.length > 0 && filteredModels.every(({ modelId }) => selectedIds.has(modelId))
|
||||
|
||||
const importMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers[':providerId'].models.import.$post({
|
||||
param: { teamId, providerId },
|
||||
json: { models: models.filter(({ modelId }) => selectedIds.has(modelId)) },
|
||||
})
|
||||
if (res.status === 409) throw new Error(m.provider_refresh_stale())
|
||||
if (!res.ok) throw new Error(m.provider_refresh_import_failed())
|
||||
return res.json()
|
||||
},
|
||||
onSuccess: ({ addedModels }) => {
|
||||
if (addedModels > 0) {
|
||||
toast.success(m.provider_refresh_imported({ count: addedModels, name: providerName }))
|
||||
} else {
|
||||
toast.info(m.provider_refresh_no_new_models({ name: providerName }))
|
||||
}
|
||||
onImported()
|
||||
onClose()
|
||||
},
|
||||
})
|
||||
|
||||
function selectModels(modelIds: string[], selected: boolean) {
|
||||
setSelectedIds((previous) => {
|
||||
const next = new Set(previous)
|
||||
for (const modelId of modelIds) {
|
||||
if (selected) next.add(modelId)
|
||||
else next.delete(modelId)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && !importMutation.isPending && onClose()}>
|
||||
<DialogContent
|
||||
className="sm:max-w-lg"
|
||||
showCloseButton={!importMutation.isPending}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
onCloseAutoFocus()
|
||||
}}
|
||||
>
|
||||
<DialogHeader className="pr-6">
|
||||
<DialogTitle>{m.provider_refresh_dialog_title({ name: providerName })}</DialogTitle>
|
||||
<DialogDescription>{m.provider_refresh_dialog_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{models.length > 5 && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
className="min-w-36 flex-1"
|
||||
aria-label={m.search_models_placeholder()}
|
||||
placeholder={m.search_models_placeholder()}
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={filteredModels.length === 0 || importMutation.isPending}
|
||||
onClick={() =>
|
||||
selectModels(
|
||||
filteredModels.map(({ modelId }) => modelId),
|
||||
!allVisibleSelected,
|
||||
)
|
||||
}
|
||||
>
|
||||
{allVisibleSelected
|
||||
? m.provider_refresh_deselect_visible()
|
||||
: m.provider_refresh_select_visible()}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<ScrollArea className="[&>[data-slot=scroll-area-viewport]]:max-h-[min(24rem,45dvh)]">
|
||||
<ul className="divide-y divide-border pr-3">
|
||||
{filteredModels.map(({ name, modelId, config }) => (
|
||||
<li key={modelId}>
|
||||
<label className="flex min-h-11 cursor-pointer items-center gap-3 rounded-sm px-1 py-2">
|
||||
<Checkbox
|
||||
checked={selectedIds.has(modelId)}
|
||||
disabled={importMutation.isPending}
|
||||
onCheckedChange={(checked) => selectModels([modelId], checked === true)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 wrap-anywhere text-sm font-medium">
|
||||
{name}
|
||||
{name !== modelId && (
|
||||
<span className="block text-xs font-normal text-muted-foreground">
|
||||
{modelId}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{config.reasoning && (
|
||||
<Badge variant="secondary" className="font-normal">
|
||||
{m.reasoning_support()}
|
||||
</Badge>
|
||||
)}
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{filteredModels.length === 0 && (
|
||||
<p className="py-3 text-sm text-muted-foreground">{m.no_matches_found()}</p>
|
||||
)}
|
||||
</ScrollArea>
|
||||
{importMutation.error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{importMutation.error.message}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={importMutation.isPending}
|
||||
onClick={onClose}
|
||||
>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={selectedIds.size === 0 || importMutation.isPending}
|
||||
onClick={() => importMutation.mutate()}
|
||||
>
|
||||
{importMutation.isPending && (
|
||||
<Loader2 aria-hidden="true" className="size-4 motion-safe:animate-spin" />
|
||||
)}
|
||||
{selectedIds.size
|
||||
? m.provider_refresh_add_selection({ count: selectedIds.size })
|
||||
: m.provider_refresh_add_selected()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen, fireEvent } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { SyncProvidersDialog } from './SyncProvidersDialog'
|
||||
import type { SyncCheckResponse } from '@shumai/dtos'
|
||||
|
||||
describe('SyncProvidersDialog', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockSyncData: SyncCheckResponse = {
|
||||
totalNewProviders: 1,
|
||||
totalNewModels: 3,
|
||||
providers: [
|
||||
{
|
||||
name: 'test-new-provider',
|
||||
isNewProvider: true,
|
||||
config: { api: 'openai-responses', apiKey: 'NEW_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'm-new-1',
|
||||
name: 'New Model 1',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
{
|
||||
modelId: 'm-new-2',
|
||||
name: 'New Model 2',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 64000,
|
||||
maxTokens: 2048,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'test-existing-provider',
|
||||
isNewProvider: false,
|
||||
config: { api: 'anthropic-messages', apiKey: 'EXISTING_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'm-existing-add-1',
|
||||
name: 'Existing Provider New Model 1',
|
||||
config: {
|
||||
api: 'anthropic-messages',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 200000,
|
||||
maxTokens: 8192,
|
||||
cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
function renderDialog(props?: Partial<React.ComponentProps<typeof SyncProvidersDialog>>) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SyncProvidersDialog
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
teamId="team-1"
|
||||
syncData={mockSyncData}
|
||||
onSuccess={vi.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders the dialog with description, providers and models pre-selected by default', () => {
|
||||
renderDialog()
|
||||
|
||||
// Title and description
|
||||
expect(screen.getByRole('heading', { name: /sync providers & models/i })).toBeDefined()
|
||||
expect(
|
||||
screen.getAllByText(
|
||||
/existing providers, custom endpoints, api keys, and model configurations will never be deleted or modified/i,
|
||||
).length,
|
||||
).toBeGreaterThan(0)
|
||||
|
||||
// Check provider names
|
||||
expect(screen.getByText('test-new-provider')).toBeDefined()
|
||||
expect(screen.getByText('test-existing-provider')).toBeDefined()
|
||||
|
||||
// Badges
|
||||
expect(screen.getByText(/^new provider$/i)).toBeDefined()
|
||||
expect(screen.getByText(/^existing provider$/i)).toBeDefined()
|
||||
|
||||
// Check that both new and existing providers have checkboxes
|
||||
const newProviderCheckbox = document.getElementById('provider-check-test-new-provider')
|
||||
expect(newProviderCheckbox).toBeDefined()
|
||||
expect(newProviderCheckbox?.getAttribute('data-state')).toBe('checked')
|
||||
|
||||
const existingProviderCheckbox = document.getElementById(
|
||||
'provider-check-test-existing-provider',
|
||||
)
|
||||
expect(existingProviderCheckbox).toBeDefined()
|
||||
expect(existingProviderCheckbox?.getAttribute('data-state')).toBe('checked')
|
||||
|
||||
// Model checkboxes are checked by default
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')
|
||||
expect(mNew1Check).toBeDefined()
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
|
||||
it('toggles all models for an existing provider when its checkbox is clicked', () => {
|
||||
renderDialog()
|
||||
|
||||
const existingProviderCheckbox = document.getElementById(
|
||||
'provider-check-test-existing-provider',
|
||||
)!
|
||||
const existingModelCheck = document.getElementById(
|
||||
'model-check-test-existing-provider-m-existing-add-1',
|
||||
)!
|
||||
|
||||
expect(existingModelCheck.getAttribute('data-state')).toBe('checked')
|
||||
|
||||
// Click to uncheck all
|
||||
fireEvent.click(existingProviderCheckbox)
|
||||
expect(existingModelCheck.getAttribute('data-state')).toBe('unchecked')
|
||||
expect(existingProviderCheckbox.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
// Click to check all
|
||||
fireEvent.click(existingProviderCheckbox)
|
||||
expect(existingModelCheck.getAttribute('data-state')).toBe('checked')
|
||||
expect(existingProviderCheckbox.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
|
||||
it('supports select all and deselect all buttons', () => {
|
||||
renderDialog()
|
||||
|
||||
const deselectAllBtn = screen.getByRole('button', { name: /^deselect all$/i })
|
||||
fireEvent.click(deselectAllBtn)
|
||||
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
const selectAllBtn = screen.getByRole('button', { name: /^select all$/i })
|
||||
fireEvent.click(selectAllBtn)
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
|
||||
it('unchecks new provider when all its models are unchecked', () => {
|
||||
renderDialog()
|
||||
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')!
|
||||
const mNew2Check = document.getElementById('model-check-test-new-provider-m-new-2')!
|
||||
const newProviderCheckbox = document.getElementById('provider-check-test-new-provider')!
|
||||
|
||||
// Uncheck both models
|
||||
fireEvent.click(mNew1Check)
|
||||
expect(newProviderCheckbox.getAttribute('data-state')).toBe('indeterminate')
|
||||
|
||||
fireEvent.click(mNew2Check)
|
||||
expect(newProviderCheckbox.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
// Re-check one model -> provider should automatically check
|
||||
fireEvent.click(mNew1Check)
|
||||
expect(newProviderCheckbox.getAttribute('data-state')).not.toBe('unchecked')
|
||||
})
|
||||
|
||||
it('filters models when user types in search input', () => {
|
||||
renderDialog()
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/filter new providers or models/i)
|
||||
fireEvent.change(searchInput, { target: { value: 'm-existing-add-1' } })
|
||||
|
||||
// Only existing provider model should be visible
|
||||
expect(screen.queryByText('m-new-1')).toBeNull()
|
||||
expect(screen.getByText('Existing Provider New Model 1')).toBeDefined()
|
||||
})
|
||||
|
||||
it('supports expand all and collapse all buttons', () => {
|
||||
renderDialog()
|
||||
|
||||
// Models should be visible initially (all expanded)
|
||||
expect(document.getElementById('model-check-test-new-provider-m-new-1')).toBeDefined()
|
||||
|
||||
// Click Collapse All
|
||||
const collapseAllBtn = screen.getByRole('button', { name: /^collapse all$/i })
|
||||
fireEvent.click(collapseAllBtn)
|
||||
|
||||
// Child models should be collapsed (not in DOM)
|
||||
expect(document.getElementById('model-check-test-new-provider-m-new-1')).toBeNull()
|
||||
|
||||
// Click Expand All
|
||||
const expandAllBtn = screen.getByRole('button', { name: /^expand all$/i })
|
||||
fireEvent.click(expandAllBtn)
|
||||
|
||||
// Child models should be visible again
|
||||
expect(document.getElementById('model-check-test-new-provider-m-new-1')).toBeDefined()
|
||||
})
|
||||
|
||||
it('updates selection and expansion state when syncData prop changes while mounted', () => {
|
||||
const { rerender } = renderDialog()
|
||||
|
||||
// Initially, test-new-provider is present
|
||||
expect(screen.getByText('test-new-provider')).toBeDefined()
|
||||
|
||||
// Deselect all models to change internal state
|
||||
const deselectAllBtn = screen.getByRole('button', { name: /^deselect all$/i })
|
||||
fireEvent.click(deselectAllBtn)
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
// Now supply new syncData prop with different providers and models
|
||||
const updatedSyncData: SyncCheckResponse = {
|
||||
totalNewProviders: 1,
|
||||
totalNewModels: 1,
|
||||
providers: [
|
||||
{
|
||||
name: 'updated-provider',
|
||||
isNewProvider: true,
|
||||
config: { api: 'openai-responses' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'm-updated-1',
|
||||
name: 'Updated Model 1',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 32000,
|
||||
maxTokens: 1024,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SyncProvidersDialog
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
teamId="team-1"
|
||||
syncData={updatedSyncData}
|
||||
onSuccess={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
// New provider should be rendered, expanded by default, and model should be pre-selected
|
||||
expect(screen.getByText('updated-provider')).toBeDefined()
|
||||
const updatedModelCheck = document.getElementById('model-check-updated-provider-m-updated-1')
|
||||
expect(updatedModelCheck).toBeDefined()
|
||||
expect(updatedModelCheck?.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
})
|
||||
@@ -1,474 +0,0 @@
|
||||
import { useState, useMemo, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { ChevronDown, ChevronRight, Cpu, Loader2, Search, Sparkles } from 'lucide-react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { SyncCheckResponse, SyncApplyRequest } from '@shumai/dtos'
|
||||
|
||||
interface SyncProvidersDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
teamId: string
|
||||
syncData: SyncCheckResponse | null
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function SyncProvidersDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
teamId,
|
||||
syncData,
|
||||
onSuccess,
|
||||
}: SyncProvidersDialogProps) {
|
||||
const [filterQuery, setFilterQuery] = useState('')
|
||||
const [expandedProviders, setExpandedProviders] = useState<Set<string>>(() => {
|
||||
return new Set(syncData?.providers.map((p) => p.name) || [])
|
||||
})
|
||||
|
||||
// Pre-selected by default (opt-out)
|
||||
const [selectedModels, setSelectedModels] = useState<Set<string>>(() => {
|
||||
const set = new Set<string>()
|
||||
syncData?.providers.forEach((p) => {
|
||||
p.models.forEach((mItem) => {
|
||||
set.add(`${p.name}:${mItem.modelId}`)
|
||||
})
|
||||
})
|
||||
return set
|
||||
})
|
||||
|
||||
// Sync state if syncData changes
|
||||
useEffect(() => {
|
||||
if (syncData) {
|
||||
setExpandedProviders(new Set(syncData.providers.map((p) => p.name)))
|
||||
const modelSet = new Set<string>()
|
||||
syncData.providers.forEach((p) => {
|
||||
p.models.forEach((mItem) => {
|
||||
modelSet.add(`${p.name}:${mItem.modelId}`)
|
||||
})
|
||||
})
|
||||
setSelectedModels(modelSet)
|
||||
}
|
||||
}, [syncData])
|
||||
|
||||
// Filtered tree data based on filterQuery
|
||||
const filteredTree = useMemo(() => {
|
||||
if (!syncData) return []
|
||||
const q = filterQuery.trim().toLowerCase()
|
||||
if (!q) return syncData.providers
|
||||
|
||||
return syncData.providers
|
||||
.map((p) => {
|
||||
const matchesProvider = p.name.toLowerCase().includes(q)
|
||||
const matchingModels = p.models.filter(
|
||||
(mItem) =>
|
||||
matchesProvider ||
|
||||
mItem.modelId.toLowerCase().includes(q) ||
|
||||
mItem.name.toLowerCase().includes(q),
|
||||
)
|
||||
if (matchingModels.length > 0) {
|
||||
return { ...p, models: matchingModels }
|
||||
}
|
||||
return null
|
||||
})
|
||||
.filter((p): p is NonNullable<typeof p> => p !== null)
|
||||
}, [syncData, filterQuery])
|
||||
|
||||
// Total selected models & providers
|
||||
const totalSelectedModelsCount = selectedModels.size
|
||||
const totalSelectedProvidersCount = useMemo(() => {
|
||||
if (!syncData) return 0
|
||||
let count = 0
|
||||
for (const p of syncData.providers) {
|
||||
const hasSelectedModel = p.models.some((mItem) =>
|
||||
selectedModels.has(`${p.name}:${mItem.modelId}`),
|
||||
)
|
||||
if (hasSelectedModel) count++
|
||||
}
|
||||
return count
|
||||
}, [syncData, selectedModels])
|
||||
|
||||
const toggleExpand = (providerName: string) => {
|
||||
setExpandedProviders((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(providerName)) {
|
||||
next.delete(providerName)
|
||||
} else {
|
||||
next.add(providerName)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleExpandAll = () => {
|
||||
if (!syncData) return
|
||||
setExpandedProviders(new Set(syncData.providers.map((p) => p.name)))
|
||||
}
|
||||
|
||||
const handleCollapseAll = () => {
|
||||
setExpandedProviders(new Set())
|
||||
}
|
||||
|
||||
const toggleModel = (providerName: string, modelId: string) => {
|
||||
const key = `${providerName}:${modelId}`
|
||||
setSelectedModels((prevModels) => {
|
||||
const nextModels = new Set(prevModels)
|
||||
if (nextModels.has(key)) {
|
||||
nextModels.delete(key)
|
||||
} else {
|
||||
nextModels.add(key)
|
||||
}
|
||||
return nextModels
|
||||
})
|
||||
}
|
||||
|
||||
const toggleProvider = (providerName: string) => {
|
||||
const providerData = syncData?.providers.find((p) => p.name === providerName)
|
||||
if (!providerData || providerData.models.length === 0) return
|
||||
|
||||
const allModelsChecked = providerData.models.every((mItem) =>
|
||||
selectedModels.has(`${providerName}:${mItem.modelId}`),
|
||||
)
|
||||
|
||||
setSelectedModels((prev) => {
|
||||
const next = new Set(prev)
|
||||
providerData.models.forEach((mItem) => {
|
||||
const key = `${providerName}:${mItem.modelId}`
|
||||
if (allModelsChecked) {
|
||||
next.delete(key)
|
||||
} else {
|
||||
next.add(key)
|
||||
}
|
||||
})
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleSelectAll = () => {
|
||||
if (!syncData) return
|
||||
const modelSet = new Set<string>()
|
||||
syncData.providers.forEach((p) => {
|
||||
p.models.forEach((mItem) => {
|
||||
modelSet.add(`${p.name}:${mItem.modelId}`)
|
||||
})
|
||||
})
|
||||
setSelectedModels(modelSet)
|
||||
}
|
||||
|
||||
const handleDeselectAll = () => {
|
||||
setSelectedModels(new Set())
|
||||
}
|
||||
|
||||
// Apply mutation
|
||||
const applyMutation = useMutation({
|
||||
mutationFn: async (payload: SyncApplyRequest) => {
|
||||
const res = await client.api.teams[':teamId'].providers['sync-apply'].$post({
|
||||
param: { teamId },
|
||||
json: payload,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: 'Failed to apply sync' }))
|
||||
throw new Error((err as { message?: string }).message || 'Failed to apply sync')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
toast.success(
|
||||
m.sync_providers_success({
|
||||
modelCount: data.addedModels,
|
||||
providerCount: data.addedProviders,
|
||||
}),
|
||||
)
|
||||
onSuccess()
|
||||
onClose()
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!syncData || totalSelectedModelsCount === 0) return
|
||||
|
||||
const providersToSync: SyncApplyRequest['providers'] = []
|
||||
|
||||
for (const p of syncData.providers) {
|
||||
const selectedModelsForProvider = p.models.filter((mItem) =>
|
||||
selectedModels.has(`${p.name}:${mItem.modelId}`),
|
||||
)
|
||||
|
||||
if (selectedModelsForProvider.length > 0) {
|
||||
providersToSync.push({
|
||||
name: p.name,
|
||||
isNewProvider: p.isNewProvider,
|
||||
config: p.config,
|
||||
models: selectedModelsForProvider,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (providersToSync.length === 0) return
|
||||
|
||||
await applyMutation.mutateAsync({
|
||||
providers: providersToSync,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-3xl md:max-w-4xl w-full h-[85vh] max-h-[85vh] flex flex-col p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-6 pb-4 shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2 text-xl font-semibold">
|
||||
<Sparkles className="w-5 h-5 text-primary" />
|
||||
{m.sync_providers_dialog_title()}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-muted-foreground leading-relaxed mt-1.5">
|
||||
{m.sync_providers_dialog_description()}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Controls Toolbar */}
|
||||
<div className="px-6 pb-3 shrink-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
value={filterQuery}
|
||||
onChange={(e) => setFilterQuery(e.target.value)}
|
||||
placeholder={m.sync_providers_search_placeholder()}
|
||||
className="pl-8 h-8 text-xs bg-background"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleExpandAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_expand_all()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCollapseAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_collapse_all()}
|
||||
</Button>
|
||||
<div className="w-px h-4 bg-border mx-1" />
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_select_all()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDeselectAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_deselect_all()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tree List Container */}
|
||||
<div className="flex-1 min-h-0 px-6 overflow-hidden">
|
||||
<ScrollArea className="h-full border border-border/60 rounded-md bg-muted/20">
|
||||
<div className="p-3 space-y-3">
|
||||
{filteredTree.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-muted-foreground">
|
||||
{m.no_matches_found()}
|
||||
</div>
|
||||
) : (
|
||||
filteredTree.map((provider) => {
|
||||
const isExpanded = expandedProviders.has(provider.name)
|
||||
const isNew = provider.isNewProvider
|
||||
|
||||
// Determine provider check state
|
||||
const checkedCount = provider.models.filter((mItem) =>
|
||||
selectedModels.has(`${provider.name}:${mItem.modelId}`),
|
||||
).length
|
||||
const allChecked = checkedCount === provider.models.length
|
||||
const someChecked = checkedCount > 0 && !allChecked
|
||||
|
||||
return (
|
||||
<div
|
||||
key={provider.name}
|
||||
className="border border-border/50 rounded-lg bg-background overflow-hidden"
|
||||
>
|
||||
{/* Provider Header Row */}
|
||||
<div className="flex items-center justify-between px-3 py-2 bg-card hover:bg-muted/40 transition-colors">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpand(provider.name)}
|
||||
className="p-0.5 text-muted-foreground hover:text-foreground rounded transition-colors"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<Checkbox
|
||||
checked={allChecked ? true : someChecked ? 'indeterminate' : false}
|
||||
onCheckedChange={() => toggleProvider(provider.name)}
|
||||
id={`provider-check-${provider.name}`}
|
||||
/>
|
||||
|
||||
<label
|
||||
htmlFor={`provider-check-${provider.name}`}
|
||||
className="font-medium text-sm text-foreground flex items-center gap-2 cursor-pointer select-none"
|
||||
>
|
||||
<Cpu className="w-4 h-4 text-muted-foreground" />
|
||||
<span>{provider.name}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{isNew ? (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-[10px] px-1.5 py-0 bg-primary/10 text-primary border-primary/20"
|
||||
>
|
||||
{m.sync_providers_new_provider()}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 text-muted-foreground"
|
||||
>
|
||||
{m.sync_providers_existing_provider()}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{m.sync_providers_new_models_count({
|
||||
count: provider.models.length,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model Children Rows */}
|
||||
{isExpanded && (
|
||||
<div className="border-t border-border/40 divide-y divide-border/30 bg-muted/10">
|
||||
{provider.models.map((model) => {
|
||||
const isModelChecked = selectedModels.has(
|
||||
`${provider.name}:${model.modelId}`,
|
||||
)
|
||||
return (
|
||||
<div
|
||||
key={model.modelId}
|
||||
className="flex items-center justify-between pl-9 pr-3 py-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<Checkbox
|
||||
checked={isModelChecked}
|
||||
onCheckedChange={() =>
|
||||
toggleModel(provider.name, model.modelId)
|
||||
}
|
||||
id={`model-check-${provider.name}-${model.modelId}`}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`model-check-${provider.name}-${model.modelId}`}
|
||||
className="text-xs font-medium text-foreground cursor-pointer select-none truncate"
|
||||
>
|
||||
{model.name || model.modelId}
|
||||
<span className="ml-1.5 text-[11px] text-muted-foreground font-mono font-normal">
|
||||
{model.modelId}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 shrink-0 ml-2">
|
||||
{model.config.reasoning && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 font-normal border-amber-500/30 text-amber-600 dark:text-amber-400"
|
||||
>
|
||||
{m.sync_providers_reasoning()}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-[11px] text-muted-foreground font-mono">
|
||||
{m.sync_providers_context_window({
|
||||
count: Math.round(model.config.contextWindow / 1000),
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Selected Count & Footer */}
|
||||
<DialogFooter className="p-6 pt-3 shrink-0 border-t border-border flex items-center justify-between sm:justify-between w-full">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{m.sync_providers_selected_count({
|
||||
modelCount: totalSelectedModelsCount,
|
||||
providerCount: totalSelectedProvidersCount,
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
disabled={applyMutation.isPending}
|
||||
>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
disabled={totalSelectedModelsCount === 0 || applyMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{applyMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{m.sync_providers_adding()}
|
||||
</>
|
||||
) : (
|
||||
m.sync_providers_add_selected({
|
||||
count: totalSelectedModelsCount,
|
||||
})
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user