mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +00:00
feat(provider): add provider and model sync feature with vendored generator (#378)
* feat(provider): vendor and adapt pi model generator - Vendor generate-models.ts, model-data.ts, and models-dev-reasoning-options.ts from @earendil-works/pi tag v0.82.1 - Adapt imports to use @earendil-works/pi-ai and expose generateModels programmatic function - Add compare.test.ts to verify vendored generator against original built-in catalog - Add packages/core/src/provider/generator to eslint ignores * feat(provider): add provider and model sync api and ui * feat(webui): add checkbox for existing providers and clean dialog description * feat(webui): add expand all and collapse all to sync providers dialog * refactor(provider): remove compare.test.ts and cli overhead from generate-models * fix(provider): add 30s timeout and strict error handling to sync catalog fetching * fix(e2e): eliminate drag-and-drop race condition on webkit Allow requestAnimationFrame collision updates to settle in dragCard helper before releasing pointer, and scope fileCard locator via data-testid to avoid matching sidebar tree items.
This commit is contained in:
@@ -235,6 +235,7 @@ export function FileCard({
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
data-testid="file-card"
|
||||
className={cn(
|
||||
'group relative flex cursor-pointer select-none flex-col overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary h-full m-1 outline-none focus:outline-none focus-visible:outline-none',
|
||||
(isSelected || isChecked) && 'outline-1 outline-primary border-primary',
|
||||
|
||||
@@ -189,6 +189,7 @@ export function FileListItem({
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
data-testid="file-card"
|
||||
className="group cursor-pointer select-none transition-colors whitespace-nowrap flex w-full outline-none focus:outline-none focus-visible:outline-none"
|
||||
>
|
||||
<div
|
||||
|
||||
@@ -276,6 +276,7 @@ export function FolderCard({
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
data-testid="file-card"
|
||||
className={cn(
|
||||
'group relative w-full md:max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full outline-none focus:outline-none focus-visible:outline-none',
|
||||
)}
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { providerConfigSchema, KNOWN_APIS } from '@shumai/dtos'
|
||||
import { providerConfigSchema, KNOWN_APIS, type SyncCheckResponse } from '@shumai/dtos'
|
||||
import { useForm } from '@tanstack/react-form'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { InferResponseType } from 'hono/client'
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
Maximize2,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
Zap,
|
||||
@@ -60,6 +61,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'
|
||||
|
||||
const API_PROTOCOL_LABELS: Record<(typeof KNOWN_APIS)[number], string> = {
|
||||
'openai-completions': 'OpenAI Completions',
|
||||
@@ -92,6 +94,33 @@ 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)
|
||||
|
||||
// Check updates mutation
|
||||
const syncCheckMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers['sync-check'].$post({
|
||||
param: { teamId },
|
||||
})
|
||||
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()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data.totalNewModels === 0 && data.totalNewProviders === 0) {
|
||||
toast.info(m.sync_providers_up_to_date())
|
||||
return
|
||||
}
|
||||
setSyncData(data)
|
||||
setIsSyncDialogOpen(true)
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
// Fetch Providers
|
||||
const { data: providers, isLoading } = useQuery({
|
||||
@@ -184,13 +213,33 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
<Cpu className="w-5 h-5 text-primary" />
|
||||
{m.configured_ai_providers()}
|
||||
</h3>
|
||||
<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 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">
|
||||
@@ -350,6 +399,16 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<SyncProvidersDialog
|
||||
isOpen={isSyncDialogOpen}
|
||||
onClose={() => setIsSyncDialogOpen(false)}
|
||||
teamId={teamId}
|
||||
syncData={syncData}
|
||||
onSuccess={() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
// @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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,474 @@
|
||||
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