mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 12:54:55 +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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user