feat(provider): refresh models from the public Pi catalog

This commit is contained in:
yiling
2026-11-29 18:49:27 +08:00
parent d315253450
commit 0899a7e59d
34 changed files with 1560 additions and 4404 deletions
@@ -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,19 @@ interface ProvidersSettingsProps {
teamId: string
}
function refreshUnavailableText(reason: ProviderRefreshUnavailableReason) {
switch (reason) {
case 'legacy_kimi_connection':
return m.provider_refresh_legacy_kimi_connection()
case 'azure_deployment_required':
return m.provider_refresh_azure_deployment_required()
case 'catalog_unavailable':
return m.provider_refresh_catalog_unavailable()
case 'unsupported_connection':
return m.provider_refresh_unsupported_connection()
}
}
export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
const queryClient = useQueryClient()
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
@@ -94,31 +109,40 @@ 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
providerUpdatedAt: string
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,
providerUpdatedAt: data.providerUpdatedAt,
models: data.models,
trigger,
})
},
onError: (error: Error) => {
toast.error(error.message)
onError: () => {
toast.error(m.provider_refresh_failed())
},
})
@@ -143,9 +167,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 +232,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 +345,123 @@ 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}
providerUpdatedAt={preview.providerUpdatedAt}
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="px-2 text-xs font-medium">
{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}`,
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"
providerUpdatedAt="2026-11-29T09:15:00.000Z"
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: { providerUpdatedAt: '2026-11-29T09:15:00.000Z', modelIds: ['model-2'] },
})
})
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,187 @@
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
providerUpdatedAt: string
providerName: string
models: RefreshedProviderModel[]
onClose: () => void
onCloseAutoFocus: () => void
onImported: () => void
}
export function RefreshProviderModelsDialog({
teamId,
providerId,
providerUpdatedAt,
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: { providerUpdatedAt, modelIds: [...selectedIds] },
})
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>
)
}
+20 -20
View File
@@ -459,27 +459,27 @@
"ai": "AI",
"providers": "Providers",
"providers_description": "Configure AI providers and their models for this team.",
"configured_ai_providers": "Configured AI Providers",
"provider_configured_badge": "Configured",
"provider_options": "Options for {name}",
"provider_refresh_models": "Refresh models",
"provider_refresh_action": "Refresh models for {name}",
"provider_refresh_loading": "Refreshing…",
"provider_refresh_legacy_kimi_connection": "The public Kimi catalog uses Chat Completions. You can still add models manually to this Anthropic Messages connection.",
"provider_refresh_azure_deployment_required": "Set an Azure endpoint and map deployed model IDs to refresh models.",
"provider_refresh_catalog_unavailable": "Pi does not publish a model catalog for this provider.",
"provider_refresh_unsupported_connection": "Refresh is unavailable for this endpoint or API.",
"provider_refresh_failed": "Could not refresh models. Try again.",
"provider_refresh_no_new_models": "No new models for {name}.",
"provider_refresh_dialog_title": "New models for {name}",
"provider_refresh_dialog_description": "Select the models you want to add.",
"provider_refresh_select_visible": "Select visible",
"provider_refresh_deselect_visible": "Deselect visible",
"provider_refresh_add_selected": "Add selected",
"provider_refresh_add_selection": "Add selected ({count})",
"provider_refresh_imported": "Added {count} models to {name}.",
"provider_refresh_import_failed": "Could not add the selected models. Try again.",
"provider_refresh_stale": "This preview has expired or the connection changed. Refresh models again.",
"add_provider": "Add Provider",
"sync_providers": "Sync Providers",
"sync_providers_checking": "Checking for updates...",
"sync_providers_dialog_title": "Sync Providers & Models",
"sync_providers_dialog_description": "Select the new providers and models you want to add. Existing providers, custom endpoints, API keys, and model configurations will never be deleted or modified.",
"sync_providers_up_to_date": "All providers and models are already up to date.",
"sync_providers_select_all": "Select All",
"sync_providers_deselect_all": "Deselect All",
"sync_providers_expand_all": "Expand All",
"sync_providers_collapse_all": "Collapse All",
"sync_providers_search_placeholder": "Filter new providers or models...",
"sync_providers_new_provider": "New Provider",
"sync_providers_existing_provider": "Existing Provider",
"sync_providers_new_models_count": "{count} new models",
"sync_providers_selected_count": "{modelCount} models selected across {providerCount} providers",
"sync_providers_reasoning": "reasoning",
"sync_providers_context_window": "{count}k ctx",
"sync_providers_add_selected": "Add Selected ({count})",
"sync_providers_adding": "Adding...",
"sync_providers_success": "Successfully added {modelCount} models across {providerCount} providers.",
"search_providers_placeholder": "Search providers...",
"no_providers_found": "No providers found",
"built_in": "Built-in",
+20 -20
View File
@@ -444,27 +444,27 @@
"ai": "AI",
"providers": "프로바이더",
"providers_description": "이 팀의 AI 프로바이더와 모델을 설정합니다.",
"configured_ai_providers": "설정된 AI 프로바이더",
"provider_configured_badge": "설정됨",
"provider_options": "{name} 옵션",
"provider_refresh_models": "모델 새로 고침",
"provider_refresh_action": "{name}의 모델 새로 고침",
"provider_refresh_loading": "새로 고치는 중…",
"provider_refresh_legacy_kimi_connection": "Kimi 공개 카탈로그는 Chat Completions를 사용합니다. 이 Anthropic Messages 연결에 모델을 직접 추가할 수 있습니다.",
"provider_refresh_azure_deployment_required": "모델을 새로 고치려면 Azure 엔드포인트를 설정하고 배포된 모델 ID를 매핑하세요.",
"provider_refresh_catalog_unavailable": "Pi에서 이 제공업체의 모델 카탈로그를 제공하지 않습니다.",
"provider_refresh_unsupported_connection": "이 엔드포인트 또는 API에서는 모델을 새로 고칠 수 없습니다.",
"provider_refresh_failed": "모델을 새로 고침할 수 없습니다. 다시 시도하세요.",
"provider_refresh_no_new_models": "{name}에 새 모델이 없습니다.",
"provider_refresh_dialog_title": "{name}의 새 모델",
"provider_refresh_dialog_description": "추가할 모델을 선택하세요.",
"provider_refresh_select_visible": "표시된 모델 선택",
"provider_refresh_deselect_visible": "표시된 모델 선택 해제",
"provider_refresh_add_selected": "선택한 모델 추가",
"provider_refresh_add_selection": "선택한 모델 추가({count}개)",
"provider_refresh_imported": "{name}에 모델 {count}개를 추가했습니다.",
"provider_refresh_import_failed": "선택한 모델을 추가할 수 없습니다. 다시 시도하세요.",
"provider_refresh_stale": "미리 보기가 만료되었거나 연결이 변경되었습니다. 모델을 다시 새로 고치세요.",
"add_provider": "프로바이더 추가",
"sync_providers": "프로바이더 동기화",
"sync_providers_checking": "업데이트 확인 중...",
"sync_providers_dialog_title": "프로바이더 및 모델 동기화",
"sync_providers_dialog_description": "추가할 새 프로바이더와 모델을 선택하세요. 기존 프로바이더, 사용자 지정 엔드포인트, API 키, 모델 설정은 삭제되거나 변경되지 않습니다.",
"sync_providers_up_to_date": "모든 프로바이더와 모델이 최신 상태입니다.",
"sync_providers_select_all": "모두 선택",
"sync_providers_deselect_all": "모두 선택 해제",
"sync_providers_expand_all": "모두 펼치기",
"sync_providers_collapse_all": "모두 접기",
"sync_providers_search_placeholder": "새 프로바이더 또는 모델 필터...",
"sync_providers_new_provider": "새 프로바이더",
"sync_providers_existing_provider": "기존 프로바이더",
"sync_providers_new_models_count": "새 모델 {count}개",
"sync_providers_selected_count": "프로바이더 {providerCount}개에서 모델 {modelCount}개 선택됨",
"sync_providers_reasoning": "추론",
"sync_providers_context_window": "컨텍스트 {count}k",
"sync_providers_add_selected": "선택 항목 추가({count})",
"sync_providers_adding": "추가 중...",
"sync_providers_success": "프로바이더 {providerCount}개에 모델 {modelCount}개를 추가했습니다.",
"search_providers_placeholder": "프로바이더 검색...",
"no_providers_found": "프로바이더를 찾을 수 없습니다",
"built_in": "기본 제공",
+20 -20
View File
@@ -459,27 +459,27 @@
"ai": "AI",
"providers": "提供商",
"providers_description": "为此团队配置 AI 提供商及其模型。",
"configured_ai_providers": "已配置的 AI 提供商",
"provider_configured_badge": "已配置",
"provider_options": "{name} 的选项",
"provider_refresh_models": "刷新模型",
"provider_refresh_action": "刷新 {name} 的模型",
"provider_refresh_loading": "正在刷新…",
"provider_refresh_legacy_kimi_connection": "Kimi 的公开目录使用 Chat Completions。你仍然可以为此 Anthropic Messages 连接手动添加模型。",
"provider_refresh_azure_deployment_required": "设置 Azure 端点和已部署模型的 ID 映射后,即可刷新模型。",
"provider_refresh_catalog_unavailable": "Pi 未发布此提供商的模型目录。",
"provider_refresh_unsupported_connection": "此端点或 API 不支持刷新模型。",
"provider_refresh_failed": "无法刷新模型,请重试。",
"provider_refresh_no_new_models": "{name} 暂无新模型。",
"provider_refresh_dialog_title": "{name} 的新模型",
"provider_refresh_dialog_description": "请选择要添加的模型。",
"provider_refresh_select_visible": "选中当前结果",
"provider_refresh_deselect_visible": "取消选中当前结果",
"provider_refresh_add_selected": "添加所选模型",
"provider_refresh_add_selection": "添加所选模型({count} 个)",
"provider_refresh_imported": "已向 {name} 添加 {count} 个模型。",
"provider_refresh_import_failed": "无法添加所选模型,请重试。",
"provider_refresh_stale": "预览已过期或连接已更改,请重新刷新模型。",
"add_provider": "添加提供商",
"sync_providers": "同步提供商",
"sync_providers_checking": "正在检查更新...",
"sync_providers_dialog_title": "同步提供商与模型",
"sync_providers_dialog_description": "选择您希望添加的新提供商和模型。现有的提供商、自定义端点、API 密钥和模型配置绝不会被删除或修改。",
"sync_providers_up_to_date": "所有提供商和模型均已是最新状态。",
"sync_providers_select_all": "全选",
"sync_providers_deselect_all": "取消全选",
"sync_providers_expand_all": "全部展开",
"sync_providers_collapse_all": "全部折叠",
"sync_providers_search_placeholder": "筛选新提供商或模型...",
"sync_providers_new_provider": "新提供商",
"sync_providers_existing_provider": "现有提供商",
"sync_providers_new_models_count": "{count} 个新模型",
"sync_providers_selected_count": "已选 {modelCount} 个模型,分布在 {providerCount} 个提供商中",
"sync_providers_reasoning": "深度思考",
"sync_providers_context_window": "{count}k 上下文",
"sync_providers_add_selected": "添加所选 ({count})",
"sync_providers_adding": "正在添加...",
"sync_providers_success": "已成功添加 {providerCount} 个提供商中的 {modelCount} 个模型。",
"search_providers_placeholder": "搜索提供商...",
"no_providers_found": "未找到提供商",
"built_in": "内置",
+2 -2
View File
@@ -10,8 +10,8 @@
"@dnd-kit/abstract": "0.5.0",
"@dnd-kit/dom": "0.5.0",
"@dnd-kit/react": "0.5.0",
"@earendil-works/pi-ai": "1.5.0",
"@earendil-works/pi-durable": "1.5.0",
"@earendil-works/pi-ai": "1.7.0",
"@earendil-works/pi-durable": "1.7.0",
"@ferrucc-io/emoji-picker": "0.1.2",
"@hookform/resolvers": "5.9.1",
"@lexical/code": "0.49.0",
@@ -533,7 +533,12 @@ export function TeamSettingsPage() {
<div className="h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300">
<div className="flex flex-col md:flex-row h-full">
{/* Sidebar */}
<div className="w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300">
<div
className={cn(
'w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300',
activeTab === 'providers' && 'max-h-[28dvh] shrink-0 md:max-h-none',
)}
>
<nav className="p-4 space-y-1 mt-4">
{/* Personal Settings */}
<div className="mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider">
@@ -801,8 +806,13 @@ export function TeamSettingsPage() {
</div>
{/* Main Content Area */}
<main className="flex-1 bg-background/50 h-full flex flex-col transition-colors duration-300 overflow-y-hidden">
<div className="flex-1 flex flex-col max-w-4xl w-full mx-auto p-6 md:p-10 overflow-hidden">
<main className="flex-1 min-h-0 min-w-0 bg-background/50 h-full flex flex-col transition-colors duration-300 overflow-y-hidden">
<div
className={cn(
'flex-1 flex flex-col max-w-4xl w-full mx-auto p-6 md:p-10 overflow-hidden',
activeTab === 'providers' && 'p-4 md:p-10',
)}
>
<div className="flex-none flex items-center justify-between mb-6">
<div>
<h2 className="text-2xl font-bold text-foreground">