mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 12:24:39 +00:00
feat(provider): refresh models per AI provider
This commit is contained in:
@@ -6,9 +6,9 @@
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"@earendil-works/chord": "1.5.0",
|
||||
"@earendil-works/pi-ai": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
"@earendil-works/chord": "1.7.0",
|
||||
"@earendil-works/pi-ai": "1.7.0",
|
||||
"@earendil-works/pi-durable": "1.7.0",
|
||||
"@google/genai": "2.28.0",
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"types": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"@better-auth/mcp": "1.7.12",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.7.0",
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@shumai/core": "workspace:*",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import providerRoute from './provider'
|
||||
import { providerService } from '@shumai/core/src/provider/provider'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
@@ -34,6 +35,7 @@ describe('provider api', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
@@ -320,78 +322,65 @@ describe('provider api', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/providers/sync-check checks for updates', async () => {
|
||||
vi.mocked(providerService.checkUpdates).mockResolvedValue({
|
||||
providers: [
|
||||
{
|
||||
name: 'deepseek',
|
||||
isNewProvider: true,
|
||||
config: { api: 'openai-responses', apiKey: 'DEEPSEEK_API_KEY' },
|
||||
models: [],
|
||||
const modelsPath = '/teams/t1/providers/p1/models'
|
||||
const selection = {
|
||||
models: [
|
||||
{
|
||||
modelId: 'test-model',
|
||||
name: 'Test Model',
|
||||
selectionToken: 'selected-model-token',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
],
|
||||
totalNewProviders: 1,
|
||||
totalNewModels: 0,
|
||||
})
|
||||
},
|
||||
],
|
||||
}
|
||||
const importRequest = {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(selection),
|
||||
}
|
||||
|
||||
const res = await app.request('/teams/t1/providers/sync-check', {
|
||||
method: 'POST',
|
||||
})
|
||||
it('previews refresh results for the requested provider as a team admin', async () => {
|
||||
vi.mocked(providerService.refreshModels).mockResolvedValue({ status: 'ready', models: [] })
|
||||
|
||||
const res = await app.request(modelsPath + '/refresh', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.totalNewProviders).toBe(1)
|
||||
expect(data.providers).toHaveLength(1)
|
||||
expect(providerService.checkUpdates).toHaveBeenCalledWith('t1')
|
||||
expect(res.headers.get('Cache-Control')).toBe('no-store')
|
||||
expect(await res.json()).toEqual({ status: 'ready', models: [] })
|
||||
expect(providerService.refreshModels).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(auditLogService.logAction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/providers/sync-apply applies sync selection', async () => {
|
||||
vi.mocked(providerService.applySync).mockResolvedValue({
|
||||
addedProviders: 1,
|
||||
addedModels: 3,
|
||||
})
|
||||
|
||||
const payload = {
|
||||
providers: [
|
||||
{
|
||||
name: 'deepseek',
|
||||
isNewProvider: true,
|
||||
config: { api: 'openai-responses', apiKey: 'KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'deepseek-v4-flash',
|
||||
name: 'DeepSeek V4 Flash',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const res = await app.request('/teams/t1/providers/sync-apply', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
it('returns the server reason for an unavailable refresh', async () => {
|
||||
vi.mocked(providerService.refreshModels).mockResolvedValue({
|
||||
status: 'unavailable',
|
||||
reason: 'missing_credentials',
|
||||
})
|
||||
|
||||
const res = await app.request(modelsPath + '/refresh', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.addedProviders).toBe(1)
|
||||
expect(data.addedModels).toBe(3)
|
||||
expect(providerService.applySync).toHaveBeenCalledWith('t1', payload)
|
||||
expect(await res.json()).toEqual({ status: 'unavailable', reason: 'missing_credentials' })
|
||||
})
|
||||
|
||||
it('imports the selection into the scoped provider and records its audit entry', async () => {
|
||||
vi.mocked(providerService.importModels).mockResolvedValue({ addedModels: 1 })
|
||||
|
||||
const res = await app.request(modelsPath + '/import', importRequest)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ addedModels: 1 })
|
||||
expect(providerService.importModels).toHaveBeenCalledWith('t1', 'p1', selection)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
@@ -402,6 +391,36 @@ describe('provider api', () => {
|
||||
action: 'provider_update',
|
||||
teamId: 't1',
|
||||
userId: 'user1',
|
||||
itemId: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('skips the audit entry when the selected models already exist', async () => {
|
||||
vi.mocked(providerService.importModels).mockResolvedValue({ addedModels: 0 })
|
||||
const res = await app.request(modelsPath + '/import', importRequest)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ addedModels: 0 })
|
||||
expect(auditLogService.logAction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects requests without team-admin permission before looking up the provider', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(new HTTPException(403))
|
||||
const refresh = await app.request(modelsPath + '/refresh', { method: 'POST' })
|
||||
const apply = await app.request(modelsPath + '/import', importRequest)
|
||||
expect(refresh.status).toBe(403)
|
||||
expect(apply.status).toBe(403)
|
||||
expect(providerService.refreshModels).not.toHaveBeenCalled()
|
||||
expect(providerService.importModels).not.toHaveBeenCalled()
|
||||
expect(auditLogService.logAction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an empty import selection before performing a write', async () => {
|
||||
const res = await app.request(modelsPath + '/import', {
|
||||
...importRequest,
|
||||
body: JSON.stringify({ models: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(providerService.importModels).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,7 +5,7 @@ import { providerService } from '@shumai/core/src/provider/provider'
|
||||
import {
|
||||
createModelRequestSchema,
|
||||
createProviderRequestSchema,
|
||||
syncApplyRequestSchema,
|
||||
importProviderModelsRequestSchema,
|
||||
updateModelRequestSchema,
|
||||
updateProviderRequestSchema,
|
||||
AuditAction,
|
||||
@@ -31,8 +31,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(providers)
|
||||
})
|
||||
|
||||
.post('/teams/:teamId/providers/sync-check', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
.post('/teams/:teamId/providers/:providerId/models/refresh', async (c) => {
|
||||
const { teamId, providerId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
@@ -42,15 +42,16 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await providerService.checkUpdates(teamId)
|
||||
const result = await providerService.refreshModels(teamId, providerId)
|
||||
c.header('Cache-Control', 'no-store')
|
||||
return c.json(result)
|
||||
})
|
||||
|
||||
.post(
|
||||
'/teams/:teamId/providers/sync-apply',
|
||||
zValidator('json', syncApplyRequestSchema),
|
||||
'/teams/:teamId/providers/:providerId/models/import',
|
||||
zValidator('json', importProviderModelsRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const { teamId, providerId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
const body = c.req.valid('json')
|
||||
|
||||
@@ -61,12 +62,15 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await providerService.applySync(teamId, body)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.provider_update,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
})
|
||||
const result = await providerService.importModels(teamId, providerId, body)
|
||||
if (result.addedModels > 0) {
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.provider_update,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: providerId,
|
||||
})
|
||||
}
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -28,9 +28,10 @@
|
||||
"@aws-sdk/s3-request-presigner": "3.1121.0",
|
||||
"@better-auth/mcp": "1.7.12",
|
||||
"@better-auth/oauth-provider": "1.7.12",
|
||||
"@earendil-works/chord": "1.5.0",
|
||||
"@earendil-works/pi-ai": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
"@earendil-works/chord": "1.7.0",
|
||||
"@earendil-works/pi-ai": "1.7.0",
|
||||
"@earendil-works/pi-coding-agent": "1.7.0",
|
||||
"@earendil-works/pi-durable": "1.7.0",
|
||||
"@google/genai": "2.28.0",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
|
||||
@@ -92,8 +92,10 @@ export async function openSessionCache(sessionId: string) {
|
||||
throw new Error('Session commit sequence mismatch')
|
||||
seq = receipt.seq
|
||||
}
|
||||
if (result.stored !== commits.length)
|
||||
if (result.kind === 'refused') {
|
||||
throw result.refused ?? new Error('Session restoration refused')
|
||||
}
|
||||
if (result.stored !== commits.length) throw new Error('Session restoration was incomplete')
|
||||
}
|
||||
await save(true)
|
||||
} catch (error) {
|
||||
|
||||
@@ -19,7 +19,7 @@ export const ENV_MAP: Record<string, string> = {
|
||||
openai: 'OPENAI_API_KEY',
|
||||
anthropic: 'ANTHROPIC_API_KEY',
|
||||
'github-copilot': 'COPILOT_GITHUB_TOKEN',
|
||||
'azure-openai-responses': 'AZURE_OPENAI_API_KEY',
|
||||
azure: 'AZURE_OPENAI_API_KEY',
|
||||
deepseek: 'DEEPSEEK_API_KEY',
|
||||
google: 'GEMINI_API_KEY',
|
||||
'google-vertex': 'GOOGLE_CLOUD_API_KEY',
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
{
|
||||
"anthropic": {
|
||||
"models": {
|
||||
"claude-3-5-sonnet-20241022": {
|
||||
"id": "claude-3-5-sonnet-20241022",
|
||||
"name": "Claude 3.5 Sonnet",
|
||||
"tool_call": true,
|
||||
"reasoning": false,
|
||||
"limit": {
|
||||
"context": 200000,
|
||||
"output": 8192
|
||||
},
|
||||
"cost": {
|
||||
"input": 3,
|
||||
"output": 15,
|
||||
"cache_read": 0.3,
|
||||
"cache_write": 3.75
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"openai": {
|
||||
"models": {
|
||||
"gpt-4o": {
|
||||
"id": "gpt-4o",
|
||||
"name": "GPT-4o",
|
||||
"tool_call": true,
|
||||
"reasoning": false,
|
||||
"limit": {
|
||||
"context": 128000,
|
||||
"output": 4096
|
||||
},
|
||||
"cost": {
|
||||
"input": 2.5,
|
||||
"output": 10
|
||||
}
|
||||
},
|
||||
"gpt-4o-extra-new": {
|
||||
"id": "gpt-4o-extra-new",
|
||||
"name": "GPT-4o Extra New",
|
||||
"tool_call": true,
|
||||
"reasoning": false,
|
||||
"limit": {
|
||||
"context": 128000,
|
||||
"output": 4096
|
||||
},
|
||||
"cost": {
|
||||
"input": 2.5,
|
||||
"output": 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "meta/llama-3.1-70b-instruct"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "meta-llama/llama-3.1-8b-instruct",
|
||||
"name": "Meta: Llama 3.1 8B Instruct",
|
||||
"context_length": 131072,
|
||||
"pricing": {
|
||||
"prompt": "0.00000005",
|
||||
"completion": "0.00000008"
|
||||
},
|
||||
"top_provider": {
|
||||
"max_completion_tokens": 8192
|
||||
},
|
||||
"supported_parameters": ["tools"]
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,42 +0,0 @@
|
||||
import type { ThinkingLevel, ThinkingLevelMap } from '@earendil-works/pi-ai'
|
||||
|
||||
export type ModelsDevReasoningOption =
|
||||
| { type: 'toggle' }
|
||||
| {
|
||||
type: 'effort'
|
||||
values: Array<
|
||||
'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'default' | null
|
||||
>
|
||||
}
|
||||
| { type: 'budget_tokens'; min?: number; max?: number }
|
||||
|
||||
const THINKING_LEVELS: readonly ThinkingLevel[] = [
|
||||
'minimal',
|
||||
'low',
|
||||
'medium',
|
||||
'high',
|
||||
'xhigh',
|
||||
'max',
|
||||
]
|
||||
|
||||
/**
|
||||
* Converts models.dev verified effort values into Pi's selectable thinking levels.
|
||||
* Values without a Pi equivalent (`default` and JSON `null`) are intentionally
|
||||
* omitted.
|
||||
*/
|
||||
export function getEffortThinkingLevelMap(
|
||||
options: readonly ModelsDevReasoningOption[],
|
||||
): ThinkingLevelMap | undefined {
|
||||
const effortValues = options.flatMap((option) => (option.type === 'effort' ? option.values : []))
|
||||
if (effortValues.length === 0) return undefined
|
||||
|
||||
const supported = new Set(effortValues)
|
||||
if (!THINKING_LEVELS.some((level) => supported.has(level)) && !supported.has('none'))
|
||||
return undefined
|
||||
|
||||
const map: ThinkingLevelMap = { off: supported.has('none') ? 'none' : null }
|
||||
for (const level of THINKING_LEVELS) {
|
||||
map[level] = supported.has(level) ? level : null
|
||||
}
|
||||
return map
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
||||
import { InMemoryCredentialStore } from '@earendil-works/pi-ai'
|
||||
import { getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all'
|
||||
import {
|
||||
providerConfigSchema,
|
||||
providerModelConfigSchema,
|
||||
type ProviderConfigSerializable,
|
||||
type ProviderRefreshUnavailableReason,
|
||||
type RefreshedProviderModel,
|
||||
} from '@shumai/dtos'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
type RefreshConnection =
|
||||
| { configured: boolean; unavailableReason: ProviderRefreshUnavailableReason }
|
||||
| { configured: true; unavailableReason: null; piProviderId: string; apiKey: string }
|
||||
|
||||
type SelectionProvider = {
|
||||
id: string
|
||||
teamId: string
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
type ModelCandidate = Omit<RefreshedProviderModel, 'selectionToken'>
|
||||
|
||||
const PREVIEW_LIFETIME_MS = 15 * 60 * 1000
|
||||
const REFRESH_TIMEOUT_MS = 30_000
|
||||
const localSigningKey = randomBytes(32)
|
||||
const builtinConnections = new Map<string, Set<string>>(
|
||||
getBuiltinProviders().map((id) => [
|
||||
id,
|
||||
new Set(getBuiltinModels(id).map((model) => connectionKey(model.api, model.baseUrl))),
|
||||
]),
|
||||
)
|
||||
|
||||
function connectionKey(api: string, baseUrl: string | undefined): string {
|
||||
return JSON.stringify([api, (baseUrl ?? '').replace(/\/+$/, '')])
|
||||
}
|
||||
|
||||
function resolveSavedKey(value: string | undefined): string | undefined {
|
||||
const key = value?.trim()
|
||||
if (!key) return undefined
|
||||
const envValue = process.env[key]?.trim()
|
||||
if (envValue) return envValue
|
||||
if (/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(key) || Object.hasOwn(process.env, key)) {
|
||||
return undefined
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
export function getRefreshConnection(
|
||||
name: string,
|
||||
config: ProviderConfigSerializable,
|
||||
): RefreshConnection {
|
||||
const apiKey = resolveSavedKey(config.apiKey)
|
||||
if (!apiKey) return { configured: false, unavailableReason: 'missing_credentials' }
|
||||
if (!providerConfigSchema.shape.api.safeParse(config.api).success) {
|
||||
return { configured: true, unavailableReason: 'unsupported_connection' }
|
||||
}
|
||||
|
||||
const key = connectionKey(config.api, config.baseUrl)
|
||||
const providerName = name === 'azure-openai-responses' ? 'azure' : name
|
||||
const namedConnections = builtinConnections.get(providerName)
|
||||
if (namedConnections?.has(key)) {
|
||||
return { configured: true, unavailableReason: null, piProviderId: providerName, apiKey }
|
||||
}
|
||||
// A renamed provider can still be recognized when its saved connection uniquely identifies it.
|
||||
if (!namedConnections && config.baseUrl) {
|
||||
const matches = [...builtinConnections].filter(([, connections]) => connections.has(key))
|
||||
if (matches.length === 1) {
|
||||
return { configured: true, unavailableReason: null, piProviderId: matches[0][0], apiKey }
|
||||
}
|
||||
}
|
||||
return { configured: true, unavailableReason: 'unsupported_connection' }
|
||||
}
|
||||
|
||||
export async function discoverProviderModels(
|
||||
connection: Extract<RefreshConnection, { unavailableReason: null }>,
|
||||
config: ProviderConfigSerializable,
|
||||
): Promise<ModelCandidate[]> {
|
||||
const { piProviderId, apiKey } = connection
|
||||
const { ModelRuntime } = await import('@earendil-works/pi-coding-agent')
|
||||
const credentials = new InMemoryCredentialStore()
|
||||
await credentials.modify(piProviderId, async () => ({ type: 'api_key', key: apiKey }))
|
||||
const runtime = await ModelRuntime.create({
|
||||
credentials,
|
||||
modelsPath: null,
|
||||
refreshOnCreate: false,
|
||||
})
|
||||
const result = await runtime.refresh({
|
||||
providers: [piProviderId],
|
||||
allowNetwork: true,
|
||||
force: true,
|
||||
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
|
||||
})
|
||||
if (result.aborted || result.errors.has(piProviderId)) {
|
||||
throw new HTTPException(502, { message: 'Could not refresh provider models' })
|
||||
}
|
||||
|
||||
const key = connectionKey(config.api, config.baseUrl)
|
||||
return runtime.getModels(piProviderId).flatMap((model) => {
|
||||
if (
|
||||
typeof model.id !== 'string' ||
|
||||
!model.id ||
|
||||
typeof model.baseUrl !== 'string' ||
|
||||
connectionKey(model.api, model.baseUrl) !== key
|
||||
) {
|
||||
return []
|
||||
}
|
||||
const modelConfig = providerModelConfigSchema.safeParse({
|
||||
api: model.api,
|
||||
reasoning: model.reasoning,
|
||||
input: model.input,
|
||||
contextWindow: model.contextWindow,
|
||||
maxTokens: model.maxTokens,
|
||||
cost: model.cost,
|
||||
})
|
||||
if (!modelConfig.success) return []
|
||||
const name = typeof model.name === 'string' && model.name ? model.name : model.id
|
||||
return [{ modelId: model.id, name, config: modelConfig.data }]
|
||||
})
|
||||
}
|
||||
|
||||
function signSelection(
|
||||
provider: SelectionProvider,
|
||||
apiKey: string,
|
||||
model: ModelCandidate,
|
||||
expiresAt: number,
|
||||
): Buffer {
|
||||
const key = process.env.BETTER_AUTH_SECRET || localSigningKey
|
||||
return createHmac('sha256', key)
|
||||
.update(
|
||||
JSON.stringify([
|
||||
'shumai-provider-model-refresh:v1',
|
||||
provider.teamId,
|
||||
provider.id,
|
||||
provider.updatedAt,
|
||||
apiKey,
|
||||
expiresAt,
|
||||
model.modelId,
|
||||
model.name,
|
||||
providerModelConfigSchema.parse(model.config),
|
||||
]),
|
||||
)
|
||||
.digest()
|
||||
}
|
||||
|
||||
export function signModelPreview(
|
||||
provider: SelectionProvider,
|
||||
apiKey: string,
|
||||
models: ModelCandidate[],
|
||||
): RefreshedProviderModel[] {
|
||||
const expiresAt = Date.now() + PREVIEW_LIFETIME_MS
|
||||
return models.map((model) => ({
|
||||
...model,
|
||||
selectionToken: `${expiresAt}.${signSelection(provider, apiKey, model, expiresAt).toString('base64url')}`,
|
||||
}))
|
||||
}
|
||||
|
||||
export function isCurrentModelSelection(
|
||||
provider: SelectionProvider,
|
||||
apiKey: string,
|
||||
model: RefreshedProviderModel,
|
||||
): boolean {
|
||||
const match = /^(\d{13})\.([\w-]{43})$/.exec(model.selectionToken)
|
||||
if (!match) return false
|
||||
const expiresAt = Number(match[1])
|
||||
if (expiresAt <= Date.now()) return false
|
||||
const signature = Buffer.from(match[2], 'base64url')
|
||||
return timingSafeEqual(signature, signSelection(provider, apiKey, model, expiresAt))
|
||||
}
|
||||
@@ -3,46 +3,49 @@ import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { providerService } from './provider'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import * as generateModelsModule from './generator/generate-models'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
|
||||
import { z } from 'zod'
|
||||
import modelsDevFixture from './fixtures/models-dev.json'
|
||||
import openRouterFixture from './fixtures/openrouter.json'
|
||||
import nvidiaFixture from './fixtures/nvidia.json'
|
||||
import type { RefreshedProviderModel } from '@shumai/dtos'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
const openaiConfig = {
|
||||
api: 'openai-responses',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
apiKey: 'saved-test-key',
|
||||
} satisfies ProviderConfigSerializable
|
||||
|
||||
function setupCatalogFetchMock() {
|
||||
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
|
||||
if (url.includes('models.dev')) {
|
||||
return new Response(JSON.stringify(modelsDevFixture), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
const candidateConfig = {
|
||||
api: openaiConfig.api,
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 256000,
|
||||
maxTokens: 16000,
|
||||
cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 },
|
||||
} satisfies ProviderModel['config']
|
||||
|
||||
function catalogModel(id: string, options?: { api?: string; baseUrl?: string }) {
|
||||
return { ...candidateConfig, baseUrl: openaiConfig.baseUrl, id, name: id, ...options }
|
||||
}
|
||||
|
||||
function mockCatalog(models: ReturnType<typeof catalogModel>[]) {
|
||||
const requests: Request[] = []
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push(request)
|
||||
if (new URL(request.url).origin !== 'https://pi.dev') {
|
||||
throw new Error('Unexpected catalog host')
|
||||
}
|
||||
if (url.includes('openrouter.ai')) {
|
||||
return new Response(JSON.stringify(openRouterFixture), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
if (url.includes('nvidia')) {
|
||||
return new Response(JSON.stringify(nvidiaFixture), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
if (url.includes('ai-gateway')) {
|
||||
return new Response(JSON.stringify({ data: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
return originalFetch(input)
|
||||
return Response.json(models, {
|
||||
headers: { 'Last-Modified': 'Wed, 01 Jan 2031 00:00:00 GMT' },
|
||||
})
|
||||
})
|
||||
return requests
|
||||
}
|
||||
|
||||
function readyModels(result: Awaited<ReturnType<typeof providerService.refreshModels>>) {
|
||||
if (result.status !== 'ready') throw new Error('Expected refreshed models')
|
||||
return result.models
|
||||
}
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
@@ -385,182 +388,218 @@ describe('ProviderService', () => {
|
||||
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
|
||||
})
|
||||
|
||||
it('should check for updates and correctly segregate new vs existing providers', async () => {
|
||||
const fetchSpy = setupCatalogFetchMock()
|
||||
try {
|
||||
// 1. Check updates with empty team: all discovered providers are new
|
||||
const emptyTeam = await prisma.team.create({
|
||||
data: { name: 'Empty Provider Team' },
|
||||
describe('model refresh', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('reports resolved credentials and eligibility separately and preserves legacy Kimi', async () => {
|
||||
vi.stubEnv('CUSTOM_OPENAI_KEY', 'a-resolved-test-key')
|
||||
vi.stubEnv('UNSET_ANTHROPIC_KEY', undefined)
|
||||
const team = await prisma.team.create({ data: { name: 'Providers' } })
|
||||
const configured = await providerService.create(team.id, 'OpenAI production', {
|
||||
...openaiConfig,
|
||||
apiKey: 'CUSTOM_OPENAI_KEY',
|
||||
})
|
||||
const initialCheck = await providerService.checkUpdates(emptyTeam.id)
|
||||
expect(initialCheck.totalNewProviders).toBeGreaterThan(0)
|
||||
expect(initialCheck.totalNewModels).toBeGreaterThan(0)
|
||||
expect(initialCheck.providers.every((p) => p.isNewProvider)).toBe(true)
|
||||
const unconfigured = await providerService.create(team.id, 'anthropic', {
|
||||
api: 'anthropic-messages',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
apiKey: 'UNSET_ANTHROPIC_KEY',
|
||||
})
|
||||
const legacyConfig = {
|
||||
api: 'anthropic-messages',
|
||||
baseUrl: 'https://api.kimi.com/coding',
|
||||
apiKey: 'literal-kimi-key',
|
||||
} satisfies ProviderConfigSerializable
|
||||
const legacy = await providerService.create(team.id, 'kimi-coding', legacyConfig)
|
||||
const providers = await providerService.listByTeam(team.id)
|
||||
expect(providers).toHaveLength(3)
|
||||
expect(providers).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: configured.id,
|
||||
configured: true,
|
||||
refreshUnavailableReason: null,
|
||||
config: { ...openaiConfig, apiKey: 'CUSTOM_OPENAI_KEY' },
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: unconfigured.id,
|
||||
configured: false,
|
||||
refreshUnavailableReason: 'missing_credentials',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: legacy.id,
|
||||
configured: true,
|
||||
refreshUnavailableReason: 'unsupported_connection',
|
||||
}),
|
||||
]),
|
||||
)
|
||||
|
||||
// 2. With default team (which has builtin providers initialized)
|
||||
const teamWithBuiltins = await teamService.ensureDefaultTeam()
|
||||
const requests = mockCatalog([])
|
||||
await expect(providerService.refreshModels(team.id, unconfigured.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'missing_credentials',
|
||||
})
|
||||
await expect(providerService.refreshModels(team.id, legacy.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'unsupported_connection',
|
||||
})
|
||||
expect(requests).toHaveLength(0)
|
||||
expect(await providerService.getById(legacy.id)).toMatchObject({ config: legacyConfig })
|
||||
})
|
||||
|
||||
// 3. Check updates after init: existing providers should have isNewProvider: false
|
||||
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
|
||||
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
|
||||
expect(existing).toBeDefined()
|
||||
if (existing) {
|
||||
expect(existing.isNewProvider).toBe(false)
|
||||
const dbModels = await providerService.listModelsByProvider(
|
||||
teamWithBuiltins.id,
|
||||
(await providerService.listByTeam(teamWithBuiltins.id)).find(
|
||||
(p) => p.name === existing.name,
|
||||
)!.id,
|
||||
)
|
||||
const dbModelIds = new Set(dbModels.map((m) => m.modelId))
|
||||
for (const m of existing.models) {
|
||||
expect(dbModelIds.has(m.modelId)).toBe(false)
|
||||
it('refreshes only the requested provider and filters existing and incompatible models', async () => {
|
||||
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const providers = await providerService.listByTeam(team.id)
|
||||
const openai = providers.find(({ name }) => name === 'openai')!
|
||||
const existingModels = await providerService.listModelsByProvider(team.id, openai.id)
|
||||
const requests = mockCatalog([
|
||||
catalogModel(existingModels[0].modelId),
|
||||
catalogModel('new-model'),
|
||||
catalogModel('wrong-api', { api: 'openai-completions' }),
|
||||
catalogModel('wrong-url', { baseUrl: 'https://other.example/v1' }),
|
||||
])
|
||||
|
||||
const result = await providerService.refreshModels(team.id, openai.id)
|
||||
expect(result).toMatchObject({
|
||||
status: 'ready',
|
||||
models: [{ modelId: 'new-model', name: 'new-model', config: candidateConfig }],
|
||||
})
|
||||
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
|
||||
'/api/models/providers/openai',
|
||||
])
|
||||
expect(requests[0].headers.has('Authorization')).toBe(false)
|
||||
expect(JSON.stringify(result)).not.toContain(openaiConfig.apiKey)
|
||||
expect(await providerService.listModelsByProvider(team.id, openai.id)).toEqual(existingModels)
|
||||
expect(await providerService.listByTeam(team.id)).toEqual(providers)
|
||||
})
|
||||
|
||||
it('passes the saved key to OpenRouter and confines the refresh to its trusted endpoint', async () => {
|
||||
const openRouterKey = 'saved-openrouter-test-key'
|
||||
vi.stubEnv('SHUMAI_TEST_OPENROUTER_KEY', openRouterKey)
|
||||
const team = await prisma.team.create({ data: { name: 'OpenRouter' } })
|
||||
const baseUrl = 'https://openrouter.ai/api/v1'
|
||||
const api = 'openai-completions' as const
|
||||
const provider = await providerService.create(team.id, 'openrouter', {
|
||||
api,
|
||||
baseUrl: baseUrl + '/',
|
||||
apiKey: 'SHUMAI_TEST_OPENROUTER_KEY',
|
||||
})
|
||||
const modelId = 'org/new-openrouter-model'
|
||||
const requestedUrls: string[] = []
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
const url = new URL(request.url)
|
||||
requestedUrls.push(url.origin + url.pathname)
|
||||
if (url.hostname === 'pi.dev') {
|
||||
expect(request.headers.has('Authorization')).toBe(false)
|
||||
return Response.json([catalogModel(modelId, { api, baseUrl })], {
|
||||
headers: { 'Last-Modified': 'Wed, 01 Jan 2031 00:00:00 GMT' },
|
||||
})
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
expect(url.href).toBe(baseUrl + '/models/user')
|
||||
expect(request.headers.get('Authorization')).toBe('Bearer ' + openRouterKey)
|
||||
return Response.json({ data: [{ id: modelId }] })
|
||||
})
|
||||
|
||||
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const spy = vi
|
||||
.spyOn(generateModelsModule, 'generateModels')
|
||||
.mockRejectedValueOnce(new Error('Failed to load models.dev catalog: 502 Bad Gateway'))
|
||||
const models = readyModels(await providerService.refreshModels(team.id, provider.id))
|
||||
expect(models.map(({ modelId }) => modelId)).toEqual([modelId])
|
||||
expect(requestedUrls).toEqual([
|
||||
'https://pi.dev/api/models/providers/openrouter',
|
||||
baseUrl + '/models/user',
|
||||
])
|
||||
|
||||
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
|
||||
'Failed to load models.dev catalog: 502 Bad Gateway',
|
||||
)
|
||||
spy.mockRestore()
|
||||
})
|
||||
|
||||
it('should throw an error when upstream catalog is empty in checkUpdates', async () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const spy = vi.spyOn(generateModelsModule, 'generateModels').mockResolvedValueOnce({
|
||||
providers: {},
|
||||
groupedProviders: {},
|
||||
sortedProviderIds: [],
|
||||
const customProvider = await providerService.update(team.id, provider.id, {
|
||||
...provider.config,
|
||||
baseUrl: 'https://openrouter-proxy.example/api/v1',
|
||||
})
|
||||
await expect(providerService.refreshModels(team.id, customProvider.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'unsupported_connection',
|
||||
})
|
||||
expect(requestedUrls).toHaveLength(2)
|
||||
})
|
||||
|
||||
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
|
||||
'Failed to retrieve model catalog from upstream services',
|
||||
)
|
||||
spy.mockRestore()
|
||||
})
|
||||
it('distinguishes a successful empty preview from an upstream error', async () => {
|
||||
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const provider = (await providerService.listByTeam(team.id)).find(
|
||||
({ name }) => name === 'openai',
|
||||
)!
|
||||
mockCatalog([])
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toEqual({
|
||||
status: 'ready',
|
||||
models: [],
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(
|
||||
async () => new Response(null, { status: 400 }),
|
||||
)
|
||||
|
||||
it('should apply sync by adding selected providers and models without modifying existing ones', async () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
|
||||
// Create an existing provider with 1 model and a custom apiKey
|
||||
const existingProvider = await providerService.create(
|
||||
team.id,
|
||||
'test-existing-provider',
|
||||
{ api: 'openai-responses', apiKey: 'custom-api-key', baseUrl: 'https://example.com' },
|
||||
[
|
||||
{
|
||||
modelId: 'existing-m1',
|
||||
name: 'Existing Model 1',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
// Apply sync with 1 new provider and 1 new model on the existing provider
|
||||
const syncResult = await providerService.applySync(team.id, {
|
||||
providers: [
|
||||
{
|
||||
name: 'test-new-synced-provider',
|
||||
isNewProvider: true,
|
||||
config: {
|
||||
api: 'anthropic-messages',
|
||||
apiKey: 'ENV_SYNC_KEY',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
},
|
||||
models: [
|
||||
{
|
||||
modelId: 'new-p-m1',
|
||||
name: 'New Provider 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 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'test-existing-provider',
|
||||
isNewProvider: false,
|
||||
config: { api: 'openai-responses', apiKey: 'should-not-override' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'existing-m2',
|
||||
name: 'Newly Added Model 2',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
// Duplicate model that already exists: should be ignored
|
||||
{
|
||||
modelId: 'existing-m1',
|
||||
name: 'Existing Model 1 Overwrite Attempt',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 999999,
|
||||
maxTokens: 999999,
|
||||
cost: { input: 9, output: 9, cacheRead: 9, cacheWrite: 9 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).rejects.toMatchObject({
|
||||
status: 502,
|
||||
})
|
||||
})
|
||||
|
||||
expect(syncResult.addedProviders).toBe(1)
|
||||
expect(syncResult.addedModels).toBe(2)
|
||||
it('imports only the selected models once and preserves existing models and settings', async () => {
|
||||
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const provider = (await providerService.listByTeam(team.id)).find(
|
||||
({ name }) => name === 'openai',
|
||||
)!
|
||||
const original = await providerService.getById(provider.id)
|
||||
const existing = await providerService.listModelsByProvider(team.id, provider.id)
|
||||
mockCatalog([catalogModel('new-model'), catalogModel('unselected-model')])
|
||||
const preview = readyModels(await providerService.refreshModels(team.id, provider.id))
|
||||
const selection = { models: preview.filter(({ modelId }) => modelId === 'new-model') }
|
||||
|
||||
// Verify existing provider config was NOT modified
|
||||
const reloadedExisting = await providerService.getById(existingProvider.id)
|
||||
expect((reloadedExisting?.config as { apiKey: string }).apiKey).toBe('custom-api-key')
|
||||
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
|
||||
addedModels: 1,
|
||||
})
|
||||
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
|
||||
addedModels: 0,
|
||||
})
|
||||
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([
|
||||
expect.objectContaining({ modelId: 'new-model', config: candidateConfig }),
|
||||
...existing,
|
||||
])
|
||||
expect(await providerService.getById(provider.id)).toEqual(original)
|
||||
})
|
||||
|
||||
// Verify existing model was NOT modified
|
||||
const existingModels = await providerService.listModelsByProvider(team.id, existingProvider.id)
|
||||
expect(existingModels).toHaveLength(2)
|
||||
const m1 = existingModels.find((m) => m.modelId === 'existing-m1')
|
||||
expect(m1?.name).toBe('Existing Model 1')
|
||||
expect((m1?.config as { contextWindow: number }).contextWindow).toBe(128000)
|
||||
it('rejects out-of-team, tampered, and stale selections without adding models', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Refresh Team' } })
|
||||
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
|
||||
const provider = await providerService.create(team.id, 'openai', openaiConfig)
|
||||
const requests = mockCatalog([catalogModel('new-model')])
|
||||
await expect(providerService.refreshModels(otherTeam.id, provider.id)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
})
|
||||
expect(requests).toHaveLength(0)
|
||||
|
||||
// Verify newly added model on existing provider
|
||||
const m2 = existingModels.find((m) => m.modelId === 'existing-m2')
|
||||
expect(m2).toBeDefined()
|
||||
expect(m2?.name).toBe('Newly Added Model 2')
|
||||
const preview = readyModels(await providerService.refreshModels(team.id, provider.id))
|
||||
const candidate = preview.find(({ modelId }) => modelId === 'new-model')!
|
||||
const expectRejected = (models: RefreshedProviderModel[]) =>
|
||||
expect(
|
||||
providerService.importModels(team.id, provider.id, { models }),
|
||||
).rejects.toMatchObject({
|
||||
status: 409,
|
||||
})
|
||||
await expect(
|
||||
providerService.importModels(otherTeam.id, provider.id, { models: [candidate] }),
|
||||
).rejects.toMatchObject({ status: 404 })
|
||||
await expectRejected([{ ...candidate, name: 'Changed metadata' }])
|
||||
|
||||
// Verify newly added provider
|
||||
const providers = await providerService.listByTeam(team.id)
|
||||
const newProvider = providers.find((p) => p.name === 'test-new-synced-provider')
|
||||
expect(newProvider).toBeDefined()
|
||||
expect(newProvider?.isBuiltin).toBe(true)
|
||||
expect((newProvider?.config as { apiKey: string }).apiKey).toBe('ENV_SYNC_KEY')
|
||||
const secondProvider = await providerService.create(team.id, 'Other OpenAI', openaiConfig)
|
||||
await expect(
|
||||
providerService.importModels(team.id, secondProvider.id, { models: [candidate] }),
|
||||
).rejects.toMatchObject({ status: 409 })
|
||||
|
||||
const newProviderModels = await providerService.listModelsByProvider(team.id, newProvider!.id)
|
||||
expect(newProviderModels).toHaveLength(1)
|
||||
expect(newProviderModels[0].modelId).toBe('new-p-m1')
|
||||
await providerService.update(team.id, provider.id, { ...openaiConfig, apiKey: 'changed-key' })
|
||||
await expectRejected([candidate])
|
||||
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([])
|
||||
expect(await providerService.listModelsByProvider(team.id, secondProvider.id)).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import {
|
||||
CreateModelRequest,
|
||||
ImportProviderModelsRequest,
|
||||
ProviderConfigSerializable,
|
||||
ProviderModelRefreshResponse,
|
||||
providerModelSchema,
|
||||
SyncApplyRequest,
|
||||
SyncApplyResponse,
|
||||
SyncCheckResponse,
|
||||
SyncModelItem,
|
||||
SyncProviderItem,
|
||||
UpdateModelRequest,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
ENV_MAP,
|
||||
getBuiltinProvidersMap,
|
||||
PRIORITY_PROVIDERS,
|
||||
} from '@shumai/core/src/provider/builtin'
|
||||
import { generateModels } from '@shumai/core/src/provider/generator/generate-models'
|
||||
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
discoverProviderModels,
|
||||
getRefreshConnection,
|
||||
isCurrentModelSelection,
|
||||
signModelPreview,
|
||||
} from './model-refresh'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
|
||||
@@ -70,11 +69,23 @@ export class ProviderService {
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
|
||||
return providers.map((p) => ({
|
||||
...p,
|
||||
modelsCount: p._count.models,
|
||||
_count: undefined,
|
||||
}))
|
||||
return providers.map(
|
||||
({ _count, id, teamId, name, config, isBuiltin, createdAt, updatedAt }) => {
|
||||
const connection = getRefreshConnection(name, config)
|
||||
return {
|
||||
id,
|
||||
teamId,
|
||||
name,
|
||||
config,
|
||||
isBuiltin,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
modelsCount: _count.models,
|
||||
configured: connection.configured,
|
||||
refreshUnavailableReason: connection.unavailableReason,
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
@@ -124,6 +135,11 @@ export class ProviderService {
|
||||
name?: string,
|
||||
) {
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
const provider = await tx.provider.update({
|
||||
where: { id, teamId },
|
||||
data: { config, ...(name ? { name } : {}) },
|
||||
})
|
||||
|
||||
if (models !== undefined) {
|
||||
const existingModels = await tx.model.findMany({
|
||||
where: { providerId: id },
|
||||
@@ -189,15 +205,7 @@ export class ProviderService {
|
||||
}
|
||||
}
|
||||
|
||||
// Update provider config and optional name
|
||||
return tx.provider.update({
|
||||
where: { id, teamId },
|
||||
data: {
|
||||
config,
|
||||
...(name ? { name } : {}),
|
||||
},
|
||||
include: { models: true },
|
||||
})
|
||||
return { ...provider, models: await tx.model.findMany({ where: { providerId: id } }) }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -305,179 +313,52 @@ export class ProviderService {
|
||||
})
|
||||
}
|
||||
|
||||
async checkUpdates(teamId: string): Promise<SyncCheckResponse> {
|
||||
const catalog = await generateModels({ strict: true, timeoutMs: 30000 })
|
||||
|
||||
if (!catalog || catalog.sortedProviderIds.length === 0) {
|
||||
throw new Error('Failed to retrieve model catalog from upstream services')
|
||||
}
|
||||
|
||||
const existingProviders = await this.prismaClient.provider.findMany({
|
||||
where: { teamId },
|
||||
include: { models: true },
|
||||
async refreshModels(teamId: string, providerId: string): Promise<ProviderModelRefreshResponse> {
|
||||
const provider = await this.prismaClient.provider.findUnique({
|
||||
where: { id: providerId, teamId },
|
||||
include: { models: { select: { modelId: true } } },
|
||||
})
|
||||
if (!provider) throw new HTTPException(404, { message: 'Provider not found' })
|
||||
|
||||
const existingProviderMap = new Map<string, (typeof existingProviders)[number]>()
|
||||
for (const p of existingProviders) {
|
||||
existingProviderMap.set(p.name, p)
|
||||
const connection = getRefreshConnection(provider.name, provider.config)
|
||||
if (connection.unavailableReason) {
|
||||
return { status: 'unavailable', reason: connection.unavailableReason }
|
||||
}
|
||||
|
||||
const items: SyncProviderItem[] = []
|
||||
let totalNewProviders = 0
|
||||
let totalNewModels = 0
|
||||
|
||||
for (const providerId of catalog.sortedProviderIds) {
|
||||
const modelsMap = catalog.providers[providerId]
|
||||
if (!modelsMap) continue
|
||||
const modelList = Object.values(modelsMap)
|
||||
if (modelList.length === 0) continue
|
||||
|
||||
const existingProvider = existingProviderMap.get(providerId)
|
||||
|
||||
if (!existingProvider) {
|
||||
const firstModel = modelList[0]
|
||||
const newModels: SyncModelItem[] = modelList.map((m) => ({
|
||||
modelId: m.id,
|
||||
name: m.name || m.id,
|
||||
config: {
|
||||
api: m.api as ProviderConfigSerializable['api'],
|
||||
reasoning: m.reasoning ?? false,
|
||||
input: (m.input ?? ['text']) as ('text' | 'image')[],
|
||||
contextWindow: m.contextWindow,
|
||||
maxTokens: m.maxTokens,
|
||||
cost: {
|
||||
input: m.cost?.input ?? 0,
|
||||
output: m.cost?.output ?? 0,
|
||||
cacheRead: m.cost?.cacheRead ?? 0,
|
||||
cacheWrite: m.cost?.cacheWrite ?? 0,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
items.push({
|
||||
name: providerId,
|
||||
isNewProvider: true,
|
||||
config: {
|
||||
api: firstModel.api as ProviderConfigSerializable['api'],
|
||||
baseUrl: firstModel.baseUrl,
|
||||
apiKey: ENV_MAP[providerId] || '',
|
||||
},
|
||||
models: newModels,
|
||||
})
|
||||
|
||||
totalNewProviders++
|
||||
totalNewModels += newModels.length
|
||||
} else {
|
||||
const existingModelIds = new Set(existingProvider.models.map((m) => m.modelId))
|
||||
const newModels: SyncModelItem[] = []
|
||||
|
||||
for (const m of modelList) {
|
||||
if (!existingModelIds.has(m.id)) {
|
||||
newModels.push({
|
||||
modelId: m.id,
|
||||
name: m.name || m.id,
|
||||
config: {
|
||||
api: m.api as ProviderConfigSerializable['api'],
|
||||
reasoning: m.reasoning ?? false,
|
||||
input: (m.input ?? ['text']) as ('text' | 'image')[],
|
||||
contextWindow: m.contextWindow,
|
||||
maxTokens: m.maxTokens,
|
||||
cost: {
|
||||
input: m.cost?.input ?? 0,
|
||||
output: m.cost?.output ?? 0,
|
||||
cacheRead: m.cost?.cacheRead ?? 0,
|
||||
cacheWrite: m.cost?.cacheWrite ?? 0,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (newModels.length > 0) {
|
||||
items.push({
|
||||
name: providerId,
|
||||
isNewProvider: false,
|
||||
config: existingProvider.config as ProviderConfigSerializable,
|
||||
models: newModels,
|
||||
})
|
||||
totalNewModels += newModels.length
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items.sort((a, b) => {
|
||||
const indexA = PRIORITY_PROVIDERS.indexOf(a.name)
|
||||
const indexB = PRIORITY_PROVIDERS.indexOf(b.name)
|
||||
if (indexA !== -1 && indexB !== -1) return indexA - indexB
|
||||
if (indexA !== -1) return -1
|
||||
if (indexB !== -1) return 1
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
|
||||
const models = await discoverProviderModels(connection, provider.config)
|
||||
const existingIds = new Set(provider.models.map(({ modelId }) => modelId))
|
||||
return {
|
||||
providers: items,
|
||||
totalNewProviders,
|
||||
totalNewModels,
|
||||
status: 'ready',
|
||||
models: signModelPreview(
|
||||
provider,
|
||||
connection.apiKey,
|
||||
models.filter(({ modelId }) => !existingIds.has(modelId)),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
async applySync(teamId: string, payload: SyncApplyRequest): Promise<SyncApplyResponse> {
|
||||
let addedProviders = 0
|
||||
let addedModels = 0
|
||||
async importModels(teamId: string, providerId: string, { models }: ImportProviderModelsRequest) {
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
// Keep the connection stable until the validated selection has been inserted.
|
||||
const [locked] = await tx.$queryRaw<{ id: string }[]>`
|
||||
SELECT id FROM providers WHERE id = ${providerId} AND team_id = ${teamId} FOR NO KEY UPDATE
|
||||
`
|
||||
if (!locked) throw new HTTPException(404, { message: 'Provider not found' })
|
||||
const provider = await tx.provider.findUniqueOrThrow({ where: { id: providerId } })
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
for (const providerItem of payload.providers) {
|
||||
let providerId: string
|
||||
|
||||
if (providerItem.isNewProvider) {
|
||||
const existing = await tx.provider.findFirst({
|
||||
where: { teamId, name: providerItem.name },
|
||||
})
|
||||
if (!existing) {
|
||||
const created = await tx.provider.create({
|
||||
data: {
|
||||
teamId,
|
||||
name: providerItem.name,
|
||||
isBuiltin: true,
|
||||
config: providerItem.config,
|
||||
},
|
||||
})
|
||||
providerId = created.id
|
||||
addedProviders++
|
||||
} else {
|
||||
providerId = existing.id
|
||||
}
|
||||
} else {
|
||||
const existing = await tx.provider.findFirst({
|
||||
where: { teamId, name: providerItem.name },
|
||||
})
|
||||
if (!existing) continue
|
||||
providerId = existing.id
|
||||
}
|
||||
|
||||
for (const modelItem of providerItem.models) {
|
||||
const existingModel = await tx.model.findFirst({
|
||||
where: {
|
||||
providerId,
|
||||
modelId: modelItem.modelId,
|
||||
},
|
||||
})
|
||||
if (!existingModel) {
|
||||
await tx.model.create({
|
||||
data: {
|
||||
providerId,
|
||||
modelId: modelItem.modelId,
|
||||
name: modelItem.name || modelItem.modelId,
|
||||
config: modelItem.config,
|
||||
},
|
||||
})
|
||||
addedModels++
|
||||
}
|
||||
}
|
||||
const connection = getRefreshConnection(provider.name, provider.config)
|
||||
if (
|
||||
connection.unavailableReason ||
|
||||
!models.every((model) => isCurrentModelSelection(provider, connection.apiKey, model))
|
||||
) {
|
||||
throw new HTTPException(409, { message: 'Refresh the model list before importing' })
|
||||
}
|
||||
})
|
||||
|
||||
return { addedProviders, addedModels }
|
||||
const { count } = await tx.model.createMany({
|
||||
data: models.map(({ modelId, name, config }) => ({ providerId, modelId, name, config })),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
return { addedModels: count }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"@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",
|
||||
"zod": "4.5.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,60 +78,52 @@ export const updateModelRequestSchema = z.object({
|
||||
|
||||
export type UpdateModelRequest = z.infer<typeof updateModelRequestSchema>
|
||||
|
||||
export const providerRefreshUnavailableReasonSchema = z.enum([
|
||||
'missing_credentials',
|
||||
'unsupported_connection',
|
||||
])
|
||||
|
||||
export type ProviderRefreshUnavailableReason = z.infer<
|
||||
typeof providerRefreshUnavailableReasonSchema
|
||||
>
|
||||
|
||||
export const providerResponseSchema = z.object({
|
||||
id: z.string(),
|
||||
teamId: z.string(),
|
||||
name: z.string(),
|
||||
isBuiltin: z.boolean(),
|
||||
config: providerConfigSchema,
|
||||
models: z.array(providerModelSchema).optional(),
|
||||
modelsCount: z.number().optional(),
|
||||
configured: z.boolean(),
|
||||
refreshUnavailableReason: providerRefreshUnavailableReasonSchema.nullable(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
})
|
||||
|
||||
export type ProviderResponse = z.infer<typeof providerResponseSchema>
|
||||
|
||||
export const syncModelItemSchema = z.object({
|
||||
export const refreshedProviderModelSchema = z.object({
|
||||
modelId: z.string().min(1),
|
||||
name: z.string().default(''),
|
||||
config: providerModelConfigSchema,
|
||||
selectionToken: z.string().min(1).max(100),
|
||||
})
|
||||
|
||||
export type SyncModelItem = z.infer<typeof syncModelItemSchema>
|
||||
export type RefreshedProviderModel = z.infer<typeof refreshedProviderModelSchema>
|
||||
|
||||
export const syncProviderItemSchema = z.object({
|
||||
name: z.string(),
|
||||
isNewProvider: z.boolean(),
|
||||
config: providerConfigSchema,
|
||||
models: z.array(syncModelItemSchema),
|
||||
export const providerModelRefreshResponseSchema = z.discriminatedUnion('status', [
|
||||
z.object({ status: z.literal('ready'), models: z.array(refreshedProviderModelSchema) }),
|
||||
z.object({
|
||||
status: z.literal('unavailable'),
|
||||
reason: providerRefreshUnavailableReasonSchema,
|
||||
}),
|
||||
])
|
||||
|
||||
export type ProviderModelRefreshResponse = z.infer<typeof providerModelRefreshResponseSchema>
|
||||
|
||||
export const importProviderModelsRequestSchema = z.object({
|
||||
models: z.array(refreshedProviderModelSchema).min(1),
|
||||
})
|
||||
|
||||
export type SyncProviderItem = z.infer<typeof syncProviderItemSchema>
|
||||
|
||||
export const syncCheckResponseSchema = z.object({
|
||||
providers: z.array(syncProviderItemSchema),
|
||||
totalNewProviders: z.number(),
|
||||
totalNewModels: z.number(),
|
||||
})
|
||||
|
||||
export type SyncCheckResponse = z.infer<typeof syncCheckResponseSchema>
|
||||
|
||||
export const syncApplyRequestSchema = z.object({
|
||||
providers: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
isNewProvider: z.boolean(),
|
||||
config: providerConfigSchema,
|
||||
models: z.array(syncModelItemSchema),
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
export type SyncApplyRequest = z.infer<typeof syncApplyRequestSchema>
|
||||
|
||||
export const syncApplyResponseSchema = z.object({
|
||||
addedProviders: z.number(),
|
||||
addedModels: z.number(),
|
||||
})
|
||||
|
||||
export type SyncApplyResponse = z.infer<typeof syncApplyResponseSchema>
|
||||
export type ImportProviderModelsRequest = z.infer<typeof importProviderModelsRequestSchema>
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@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",
|
||||
"@google/genai": "2.28.0",
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/core": "workspace:*",
|
||||
|
||||
@@ -38,17 +38,19 @@ import {
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { providerConfigSchema, KNOWN_APIS, type SyncCheckResponse } from '@shumai/dtos'
|
||||
import {
|
||||
providerConfigSchema,
|
||||
KNOWN_APIS,
|
||||
type ProviderRefreshUnavailableReason,
|
||||
type RefreshedProviderModel,
|
||||
} from '@shumai/dtos'
|
||||
import { useForm } from '@tanstack/react-form'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { InferResponseType } from 'hono/client'
|
||||
import {
|
||||
ChevronRight,
|
||||
Cpu,
|
||||
Globe,
|
||||
Info,
|
||||
Loader2,
|
||||
Maximize2,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
@@ -61,7 +63,7 @@ import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { ModelFormDialog, ModelFormValues } from './ModelFormDialog'
|
||||
import { SyncProvidersDialog } from './SyncProvidersDialog'
|
||||
import { RefreshProviderModelsDialog } from './RefreshProviderModelsDialog'
|
||||
|
||||
const API_PROTOCOL_LABELS: Record<(typeof KNOWN_APIS)[number], string> = {
|
||||
'openai-completions': 'OpenAI Completions',
|
||||
@@ -87,6 +89,12 @@ interface ProvidersSettingsProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
function refreshUnavailableText(reason: ProviderRefreshUnavailableReason) {
|
||||
return reason === 'missing_credentials'
|
||||
? m.provider_refresh_missing_credentials()
|
||||
: m.provider_refresh_unsupported_connection()
|
||||
}
|
||||
|
||||
export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
|
||||
@@ -94,31 +102,34 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [providerToDelete, setProviderToDelete] = useState<Provider | null>(null)
|
||||
const [isSyncDialogOpen, setIsSyncDialogOpen] = useState(false)
|
||||
const [syncData, setSyncData] = useState<SyncCheckResponse | null>(null)
|
||||
const [preview, setPreview] = useState<{
|
||||
provider: Provider
|
||||
models: RefreshedProviderModel[]
|
||||
trigger: HTMLButtonElement
|
||||
} | null>(null)
|
||||
|
||||
// Check updates mutation
|
||||
const syncCheckMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers['sync-check'].$post({
|
||||
param: { teamId },
|
||||
const refreshMutation = useMutation({
|
||||
mutationFn: async ({ provider }: { provider: Provider; trigger: HTMLButtonElement }) => {
|
||||
const res = await client.api.teams[':teamId'].providers[':providerId'].models.refresh.$post({
|
||||
param: { teamId, providerId: provider.id },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: 'Failed to check updates' }))
|
||||
throw new Error((err as { message?: string }).message || 'Failed to check updates')
|
||||
}
|
||||
return await res.json()
|
||||
if (!res.ok) throw new Error(m.provider_refresh_failed())
|
||||
return res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data.totalNewModels === 0 && data.totalNewProviders === 0) {
|
||||
toast.info(m.sync_providers_up_to_date())
|
||||
onSuccess: (data, { provider, trigger }) => {
|
||||
if (data.status === 'unavailable') {
|
||||
toast.info(refreshUnavailableText(data.reason))
|
||||
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
return
|
||||
}
|
||||
setSyncData(data)
|
||||
setIsSyncDialogOpen(true)
|
||||
if (data.models.length === 0) {
|
||||
toast.info(m.provider_refresh_no_new_models({ name: provider.name }))
|
||||
return
|
||||
}
|
||||
setPreview({ provider, models: data.models, trigger })
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message)
|
||||
onError: () => {
|
||||
toast.error(m.provider_refresh_failed())
|
||||
},
|
||||
})
|
||||
|
||||
@@ -143,9 +154,10 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
|
||||
const filteredProviders = useMemo(() => {
|
||||
if (!providers) return []
|
||||
if (!searchQuery.trim()) return providers
|
||||
const query = searchQuery.toLowerCase()
|
||||
return providers.filter((p) => p.name.toLowerCase().includes(query))
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
return providers
|
||||
.filter((p) => p.name.toLowerCase().includes(query))
|
||||
.sort((a, b) => Number(b.configured) - Number(a.configured))
|
||||
}, [providers, searchQuery])
|
||||
|
||||
// Create Mutation
|
||||
@@ -207,120 +219,40 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col space-y-0">
|
||||
<div className="flex-none space-y-4 pb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<Cpu className="w-5 h-5 text-primary" />
|
||||
{m.configured_ai_providers()}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => syncCheckMutation.mutate()}
|
||||
disabled={syncCheckMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{syncCheckMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{m.sync_providers_checking()}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{m.sync_providers()}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setIsCreateDialogOpen(true)}
|
||||
className="bg-primary hover:bg-primary/90 text-primary-foreground gap-2"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{m.add_provider()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative px-0.5">
|
||||
<div className="flex flex-none flex-wrap items-center gap-3 pb-4">
|
||||
<div className="relative min-w-0 flex-[1_1_10rem] px-0.5">
|
||||
<Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={m.search_providers_placeholder()}
|
||||
placeholder={m.search_providers_placeholder()}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10 bg-card border-border focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-0"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={() => setIsCreateDialogOpen(true)} className="gap-2">
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{m.add_provider()}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="flex-1 min-h-0">
|
||||
<div className="pr-4 py-2 grid grid-cols-1 gap-4">
|
||||
{filteredProviders.map((provider) => (
|
||||
<Card
|
||||
<ProviderCard
|
||||
key={provider.id}
|
||||
className="group cursor-pointer hover:border-primary/50 transition-all hover:shadow-md overflow-hidden"
|
||||
onClick={() => setEditingProviderId(provider.id)}
|
||||
>
|
||||
<CardContent className="p-5 flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-4 min-w-0 flex-1">
|
||||
<div className="flex-none p-3 bg-muted rounded-xl group-hover:bg-primary/10 transition-colors">
|
||||
<Globe className="w-6 h-6 text-muted-foreground group-hover:text-primary" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-bold text-foreground truncate">{provider.name}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs text-muted-foreground mt-1">
|
||||
<span className="flex items-center gap-1 flex-none">
|
||||
<Zap className="w-3 h-3" />
|
||||
{provider.config.api}
|
||||
</span>
|
||||
{provider.config.baseUrl && (
|
||||
<span className="flex items-center gap-1 min-w-0">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 flex-none" />
|
||||
<Info className="w-3 h-3 flex-none" />
|
||||
<span className="truncate max-w-[200px] md:max-w-[300px]">
|
||||
{provider.config.baseUrl}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1 flex-none">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 flex-none" />
|
||||
<Maximize2 className="w-3 h-3" />
|
||||
{m.n_models_count({ count: provider.modelsCount })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setProviderToDelete(provider)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
className="text-destructive focus:text-destructive gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" /> {m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ChevronRight className="flex-none w-5 h-5 text-muted-foreground/50 group-hover:text-primary transition-colors" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
provider={provider}
|
||||
isRefreshing={
|
||||
refreshMutation.isPending && refreshMutation.variables?.provider.id === provider.id
|
||||
}
|
||||
refreshInProgress={refreshMutation.isPending}
|
||||
onEdit={() => setEditingProviderId(provider.id)}
|
||||
onRefresh={(trigger) => refreshMutation.mutate({ provider, trigger })}
|
||||
onDelete={() => {
|
||||
setProviderToDelete(provider)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{providers?.length === 0 && (
|
||||
@@ -400,19 +332,125 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<SyncProvidersDialog
|
||||
isOpen={isSyncDialogOpen}
|
||||
onClose={() => setIsSyncDialogOpen(false)}
|
||||
teamId={teamId}
|
||||
syncData={syncData}
|
||||
onSuccess={() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
}}
|
||||
/>
|
||||
{preview && (
|
||||
<RefreshProviderModelsDialog
|
||||
teamId={teamId}
|
||||
providerId={preview.provider.id}
|
||||
providerName={preview.provider.name}
|
||||
models={preview.models}
|
||||
onClose={() => setPreview(null)}
|
||||
onCloseAutoFocus={() => preview.trigger.focus()}
|
||||
onImported={() => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderCard({
|
||||
provider,
|
||||
isRefreshing,
|
||||
refreshInProgress,
|
||||
onEdit,
|
||||
onRefresh,
|
||||
onDelete,
|
||||
}: {
|
||||
provider: Provider
|
||||
isRefreshing: boolean
|
||||
refreshInProgress: boolean
|
||||
onEdit: () => void
|
||||
onRefresh: (button: HTMLButtonElement) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
const unavailable = provider.refreshUnavailableReason
|
||||
const reasonId = `provider-refresh-reason-${provider.id}`
|
||||
const displayUrl = provider.config.baseUrl?.replace(/^https?:\/\//, '')
|
||||
return (
|
||||
<Card className="gap-0 rounded-xl py-0 shadow-none transition-colors hover:border-primary/35">
|
||||
<CardContent className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-2 p-3.5 sm:grid-cols-[auto_minmax(0,1fr)_auto]">
|
||||
<span className="grid size-9 place-items-center rounded-lg bg-muted text-muted-foreground">
|
||||
<Globe aria-hidden="true" className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onEdit}
|
||||
aria-label={m.edit_item({ name: provider.name })}
|
||||
className="max-w-full cursor-pointer rounded-sm text-start font-semibold wrap-anywhere text-foreground hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
|
||||
>
|
||||
{provider.name}
|
||||
</button>
|
||||
{provider.configured && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="border-transparent bg-green-500/10 px-2 text-xs font-medium text-green-800 dark:text-green-300"
|
||||
>
|
||||
{m.provider_configured_badge()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
<span>{API_PROTOCOL_LABELS[provider.config.api] ?? provider.config.api}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{m.n_models_count({ count: provider.modelsCount })}</span>
|
||||
</div>
|
||||
{unavailable ? (
|
||||
<p id={reasonId} className="mt-1 text-xs text-muted-foreground">
|
||||
{refreshUnavailableText(unavailable)}
|
||||
</p>
|
||||
) : displayUrl ? (
|
||||
<p className="mt-1 wrap-anywhere text-xs text-muted-foreground" dir="ltr">
|
||||
{displayUrl}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="col-start-2 flex flex-wrap items-center gap-1 sm:col-start-3">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
disabled={unavailable !== null || refreshInProgress}
|
||||
aria-label={m.provider_refresh_action({ name: provider.name })}
|
||||
aria-describedby={unavailable ? reasonId : undefined}
|
||||
aria-busy={isRefreshing}
|
||||
onClick={(event) => onRefresh(event.currentTarget)}
|
||||
>
|
||||
{isRefreshing ? (
|
||||
<Loader2 aria-hidden="true" className="size-4 motion-safe:animate-spin" />
|
||||
) : (
|
||||
<RefreshCw aria-hidden="true" className="size-4" />
|
||||
)}
|
||||
{isRefreshing ? m.provider_refresh_loading() : m.provider_refresh_models()}
|
||||
</Button>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={m.provider_options({ name: provider.name })}
|
||||
className="size-11 text-muted-foreground hover:text-foreground sm:size-9"
|
||||
>
|
||||
<MoreVertical aria-hidden="true" className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem onSelect={onEdit}>{m.edit()}</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={onDelete} variant="destructive">
|
||||
<Trash2 className="size-4" /> {m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Create Provider Dialog
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { RefreshedProviderModel } from '@shumai/dtos'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RefreshProviderModelsDialog } from './RefreshProviderModelsDialog'
|
||||
|
||||
const { importModels } = vi.hoisted(() => ({ importModels: vi.fn() }))
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
providers: { ':providerId': { models: { import: { $post: importModels } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
const models = Array.from({ length: 6 }, (_, index): RefreshedProviderModel => ({
|
||||
modelId: `model-${index + 1}`,
|
||||
name: `Model ${index + 1}`,
|
||||
selectionToken: `model-token-${index + 1}`,
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
}))
|
||||
|
||||
function renderDialog() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const onClose = vi.fn()
|
||||
const onImported = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RefreshProviderModelsDialog
|
||||
teamId="team-1"
|
||||
providerId="provider-1"
|
||||
providerName="OpenAI"
|
||||
models={models}
|
||||
onClose={onClose}
|
||||
onCloseAutoFocus={vi.fn()}
|
||||
onImported={onImported}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return { onClose, onImported }
|
||||
}
|
||||
|
||||
describe('RefreshProviderModelsDialog', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
importModels.mockReset()
|
||||
})
|
||||
|
||||
it('opens a single-provider preview with selectable models and an empty selection', () => {
|
||||
renderDialog()
|
||||
expect(screen.getByRole('heading', { name: 'New models for OpenAI' })).toBeTruthy()
|
||||
expect(screen.getByText('Select the models you want to add.')).toBeTruthy()
|
||||
expect(screen.getAllByRole('checkbox')).toHaveLength(models.length)
|
||||
expect(screen.getByRole('button', { name: 'Add selected' }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('filters models and selects or deselects the visible results', () => {
|
||||
renderDialog()
|
||||
const search = screen.getByRole('textbox')
|
||||
fireEvent.change(search, { target: { value: 'model-2' } })
|
||||
expect(screen.queryByText('Model 1')).toBeNull()
|
||||
expect(screen.getAllByRole('checkbox')).toHaveLength(1)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select visible' }))
|
||||
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('true')
|
||||
expect(screen.getByRole('button', { name: 'Add selected (1)' })).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Deselect visible' }))
|
||||
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('false')
|
||||
expect(screen.getByRole('button', { name: 'Add selected' }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('imports only the selected models into the previewed provider', async () => {
|
||||
importModels.mockResolvedValueOnce(Response.json({ addedModels: 1 }))
|
||||
const { onClose, onImported } = renderDialog()
|
||||
fireEvent.click(screen.getAllByRole('checkbox')[1])
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add selected (1)' }))
|
||||
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
|
||||
expect(onImported).toHaveBeenCalledOnce()
|
||||
expect(importModels).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-1', providerId: 'provider-1' },
|
||||
json: { models: [models[1]] },
|
||||
})
|
||||
})
|
||||
|
||||
it('shows an actionable error when the preview becomes stale', async () => {
|
||||
importModels.mockResolvedValueOnce(new Response(null, { status: 409 }))
|
||||
const { onImported } = renderDialog()
|
||||
fireEvent.click(screen.getAllByRole('checkbox')[0])
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add selected (1)' }))
|
||||
expect((await screen.findByRole('alert')).textContent).toContain('Refresh models again.')
|
||||
expect(onImported).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { RefreshedProviderModel } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface RefreshProviderModelsDialogProps {
|
||||
teamId: string
|
||||
providerId: string
|
||||
providerName: string
|
||||
models: RefreshedProviderModel[]
|
||||
onClose: () => void
|
||||
onCloseAutoFocus: () => void
|
||||
onImported: () => void
|
||||
}
|
||||
|
||||
export function RefreshProviderModelsDialog({
|
||||
teamId,
|
||||
providerId,
|
||||
providerName,
|
||||
models,
|
||||
onClose,
|
||||
onCloseAutoFocus,
|
||||
onImported,
|
||||
}: RefreshProviderModelsDialogProps) {
|
||||
const [selectedIds, setSelectedIds] = useState(() => new Set<string>())
|
||||
const [search, setSearch] = useState('')
|
||||
const query = search.trim().toLowerCase()
|
||||
const filteredModels = models.filter(
|
||||
({ name, modelId }) =>
|
||||
name.toLowerCase().includes(query) || modelId.toLowerCase().includes(query),
|
||||
)
|
||||
const allVisibleSelected =
|
||||
filteredModels.length > 0 && filteredModels.every(({ modelId }) => selectedIds.has(modelId))
|
||||
|
||||
const importMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers[':providerId'].models.import.$post({
|
||||
param: { teamId, providerId },
|
||||
json: { models: models.filter(({ modelId }) => selectedIds.has(modelId)) },
|
||||
})
|
||||
if (res.status === 409) throw new Error(m.provider_refresh_stale())
|
||||
if (!res.ok) throw new Error(m.provider_refresh_import_failed())
|
||||
return res.json()
|
||||
},
|
||||
onSuccess: ({ addedModels }) => {
|
||||
if (addedModels > 0) {
|
||||
toast.success(m.provider_refresh_imported({ count: addedModels, name: providerName }))
|
||||
} else {
|
||||
toast.info(m.provider_refresh_no_new_models({ name: providerName }))
|
||||
}
|
||||
onImported()
|
||||
onClose()
|
||||
},
|
||||
})
|
||||
|
||||
function selectModels(modelIds: string[], selected: boolean) {
|
||||
setSelectedIds((previous) => {
|
||||
const next = new Set(previous)
|
||||
for (const modelId of modelIds) {
|
||||
if (selected) next.add(modelId)
|
||||
else next.delete(modelId)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && !importMutation.isPending && onClose()}>
|
||||
<DialogContent
|
||||
className="sm:max-w-lg"
|
||||
showCloseButton={!importMutation.isPending}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
onCloseAutoFocus()
|
||||
}}
|
||||
>
|
||||
<DialogHeader className="pr-6">
|
||||
<DialogTitle>{m.provider_refresh_dialog_title({ name: providerName })}</DialogTitle>
|
||||
<DialogDescription>{m.provider_refresh_dialog_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{models.length > 5 && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
className="min-w-36 flex-1"
|
||||
aria-label={m.search_models_placeholder()}
|
||||
placeholder={m.search_models_placeholder()}
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={filteredModels.length === 0 || importMutation.isPending}
|
||||
onClick={() =>
|
||||
selectModels(
|
||||
filteredModels.map(({ modelId }) => modelId),
|
||||
!allVisibleSelected,
|
||||
)
|
||||
}
|
||||
>
|
||||
{allVisibleSelected
|
||||
? m.provider_refresh_deselect_visible()
|
||||
: m.provider_refresh_select_visible()}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<ScrollArea className="[&>[data-slot=scroll-area-viewport]]:max-h-[min(24rem,45dvh)]">
|
||||
<ul className="divide-y divide-border pr-3">
|
||||
{filteredModels.map(({ name, modelId, config }) => (
|
||||
<li key={modelId}>
|
||||
<label className="flex min-h-11 cursor-pointer items-center gap-3 rounded-sm px-1 py-2">
|
||||
<Checkbox
|
||||
checked={selectedIds.has(modelId)}
|
||||
disabled={importMutation.isPending}
|
||||
onCheckedChange={(checked) => selectModels([modelId], checked === true)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 wrap-anywhere text-sm font-medium">
|
||||
{name}
|
||||
{name !== modelId && (
|
||||
<span className="block text-xs font-normal text-muted-foreground">
|
||||
{modelId}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{config.reasoning && (
|
||||
<Badge variant="secondary" className="font-normal">
|
||||
{m.reasoning_support()}
|
||||
</Badge>
|
||||
)}
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{filteredModels.length === 0 && (
|
||||
<p className="py-3 text-sm text-muted-foreground">{m.no_matches_found()}</p>
|
||||
)}
|
||||
</ScrollArea>
|
||||
{importMutation.error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{importMutation.error.message}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={importMutation.isPending}
|
||||
onClick={onClose}
|
||||
>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={selectedIds.size === 0 || importMutation.isPending}
|
||||
onClick={() => importMutation.mutate()}
|
||||
>
|
||||
{importMutation.isPending && (
|
||||
<Loader2 aria-hidden="true" className="size-4 motion-safe:animate-spin" />
|
||||
)}
|
||||
{selectedIds.size
|
||||
? m.provider_refresh_add_selection({ count: selectedIds.size })
|
||||
: m.provider_refresh_add_selected()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen, fireEvent } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { SyncProvidersDialog } from './SyncProvidersDialog'
|
||||
import type { SyncCheckResponse } from '@shumai/dtos'
|
||||
|
||||
describe('SyncProvidersDialog', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const mockSyncData: SyncCheckResponse = {
|
||||
totalNewProviders: 1,
|
||||
totalNewModels: 3,
|
||||
providers: [
|
||||
{
|
||||
name: 'test-new-provider',
|
||||
isNewProvider: true,
|
||||
config: { api: 'openai-responses', apiKey: 'NEW_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'm-new-1',
|
||||
name: 'New Model 1',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
{
|
||||
modelId: 'm-new-2',
|
||||
name: 'New Model 2',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 64000,
|
||||
maxTokens: 2048,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'test-existing-provider',
|
||||
isNewProvider: false,
|
||||
config: { api: 'anthropic-messages', apiKey: 'EXISTING_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'm-existing-add-1',
|
||||
name: 'Existing Provider New Model 1',
|
||||
config: {
|
||||
api: 'anthropic-messages',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 200000,
|
||||
maxTokens: 8192,
|
||||
cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
function renderDialog(props?: Partial<React.ComponentProps<typeof SyncProvidersDialog>>) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SyncProvidersDialog
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
teamId="team-1"
|
||||
syncData={mockSyncData}
|
||||
onSuccess={vi.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
it('renders the dialog with description, providers and models pre-selected by default', () => {
|
||||
renderDialog()
|
||||
|
||||
// Title and description
|
||||
expect(screen.getByRole('heading', { name: /sync providers & models/i })).toBeDefined()
|
||||
expect(
|
||||
screen.getAllByText(
|
||||
/existing providers, custom endpoints, api keys, and model configurations will never be deleted or modified/i,
|
||||
).length,
|
||||
).toBeGreaterThan(0)
|
||||
|
||||
// Check provider names
|
||||
expect(screen.getByText('test-new-provider')).toBeDefined()
|
||||
expect(screen.getByText('test-existing-provider')).toBeDefined()
|
||||
|
||||
// Badges
|
||||
expect(screen.getByText(/^new provider$/i)).toBeDefined()
|
||||
expect(screen.getByText(/^existing provider$/i)).toBeDefined()
|
||||
|
||||
// Check that both new and existing providers have checkboxes
|
||||
const newProviderCheckbox = document.getElementById('provider-check-test-new-provider')
|
||||
expect(newProviderCheckbox).toBeDefined()
|
||||
expect(newProviderCheckbox?.getAttribute('data-state')).toBe('checked')
|
||||
|
||||
const existingProviderCheckbox = document.getElementById(
|
||||
'provider-check-test-existing-provider',
|
||||
)
|
||||
expect(existingProviderCheckbox).toBeDefined()
|
||||
expect(existingProviderCheckbox?.getAttribute('data-state')).toBe('checked')
|
||||
|
||||
// Model checkboxes are checked by default
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')
|
||||
expect(mNew1Check).toBeDefined()
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
|
||||
it('toggles all models for an existing provider when its checkbox is clicked', () => {
|
||||
renderDialog()
|
||||
|
||||
const existingProviderCheckbox = document.getElementById(
|
||||
'provider-check-test-existing-provider',
|
||||
)!
|
||||
const existingModelCheck = document.getElementById(
|
||||
'model-check-test-existing-provider-m-existing-add-1',
|
||||
)!
|
||||
|
||||
expect(existingModelCheck.getAttribute('data-state')).toBe('checked')
|
||||
|
||||
// Click to uncheck all
|
||||
fireEvent.click(existingProviderCheckbox)
|
||||
expect(existingModelCheck.getAttribute('data-state')).toBe('unchecked')
|
||||
expect(existingProviderCheckbox.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
// Click to check all
|
||||
fireEvent.click(existingProviderCheckbox)
|
||||
expect(existingModelCheck.getAttribute('data-state')).toBe('checked')
|
||||
expect(existingProviderCheckbox.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
|
||||
it('supports select all and deselect all buttons', () => {
|
||||
renderDialog()
|
||||
|
||||
const deselectAllBtn = screen.getByRole('button', { name: /^deselect all$/i })
|
||||
fireEvent.click(deselectAllBtn)
|
||||
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
const selectAllBtn = screen.getByRole('button', { name: /^select all$/i })
|
||||
fireEvent.click(selectAllBtn)
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
|
||||
it('unchecks new provider when all its models are unchecked', () => {
|
||||
renderDialog()
|
||||
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')!
|
||||
const mNew2Check = document.getElementById('model-check-test-new-provider-m-new-2')!
|
||||
const newProviderCheckbox = document.getElementById('provider-check-test-new-provider')!
|
||||
|
||||
// Uncheck both models
|
||||
fireEvent.click(mNew1Check)
|
||||
expect(newProviderCheckbox.getAttribute('data-state')).toBe('indeterminate')
|
||||
|
||||
fireEvent.click(mNew2Check)
|
||||
expect(newProviderCheckbox.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
// Re-check one model -> provider should automatically check
|
||||
fireEvent.click(mNew1Check)
|
||||
expect(newProviderCheckbox.getAttribute('data-state')).not.toBe('unchecked')
|
||||
})
|
||||
|
||||
it('filters models when user types in search input', () => {
|
||||
renderDialog()
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(/filter new providers or models/i)
|
||||
fireEvent.change(searchInput, { target: { value: 'm-existing-add-1' } })
|
||||
|
||||
// Only existing provider model should be visible
|
||||
expect(screen.queryByText('m-new-1')).toBeNull()
|
||||
expect(screen.getByText('Existing Provider New Model 1')).toBeDefined()
|
||||
})
|
||||
|
||||
it('supports expand all and collapse all buttons', () => {
|
||||
renderDialog()
|
||||
|
||||
// Models should be visible initially (all expanded)
|
||||
expect(document.getElementById('model-check-test-new-provider-m-new-1')).toBeDefined()
|
||||
|
||||
// Click Collapse All
|
||||
const collapseAllBtn = screen.getByRole('button', { name: /^collapse all$/i })
|
||||
fireEvent.click(collapseAllBtn)
|
||||
|
||||
// Child models should be collapsed (not in DOM)
|
||||
expect(document.getElementById('model-check-test-new-provider-m-new-1')).toBeNull()
|
||||
|
||||
// Click Expand All
|
||||
const expandAllBtn = screen.getByRole('button', { name: /^expand all$/i })
|
||||
fireEvent.click(expandAllBtn)
|
||||
|
||||
// Child models should be visible again
|
||||
expect(document.getElementById('model-check-test-new-provider-m-new-1')).toBeDefined()
|
||||
})
|
||||
|
||||
it('updates selection and expansion state when syncData prop changes while mounted', () => {
|
||||
const { rerender } = renderDialog()
|
||||
|
||||
// Initially, test-new-provider is present
|
||||
expect(screen.getByText('test-new-provider')).toBeDefined()
|
||||
|
||||
// Deselect all models to change internal state
|
||||
const deselectAllBtn = screen.getByRole('button', { name: /^deselect all$/i })
|
||||
fireEvent.click(deselectAllBtn)
|
||||
const mNew1Check = document.getElementById('model-check-test-new-provider-m-new-1')
|
||||
expect(mNew1Check?.getAttribute('data-state')).toBe('unchecked')
|
||||
|
||||
// Now supply new syncData prop with different providers and models
|
||||
const updatedSyncData: SyncCheckResponse = {
|
||||
totalNewProviders: 1,
|
||||
totalNewModels: 1,
|
||||
providers: [
|
||||
{
|
||||
name: 'updated-provider',
|
||||
isNewProvider: true,
|
||||
config: { api: 'openai-responses' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'm-updated-1',
|
||||
name: 'Updated Model 1',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 32000,
|
||||
maxTokens: 1024,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SyncProvidersDialog
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
teamId="team-1"
|
||||
syncData={updatedSyncData}
|
||||
onSuccess={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
// New provider should be rendered, expanded by default, and model should be pre-selected
|
||||
expect(screen.getByText('updated-provider')).toBeDefined()
|
||||
const updatedModelCheck = document.getElementById('model-check-updated-provider-m-updated-1')
|
||||
expect(updatedModelCheck).toBeDefined()
|
||||
expect(updatedModelCheck?.getAttribute('data-state')).toBe('checked')
|
||||
})
|
||||
})
|
||||
@@ -1,474 +0,0 @@
|
||||
import { useState, useMemo, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { ChevronDown, ChevronRight, Cpu, Loader2, Search, Sparkles } from 'lucide-react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { SyncCheckResponse, SyncApplyRequest } from '@shumai/dtos'
|
||||
|
||||
interface SyncProvidersDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
teamId: string
|
||||
syncData: SyncCheckResponse | null
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function SyncProvidersDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
teamId,
|
||||
syncData,
|
||||
onSuccess,
|
||||
}: SyncProvidersDialogProps) {
|
||||
const [filterQuery, setFilterQuery] = useState('')
|
||||
const [expandedProviders, setExpandedProviders] = useState<Set<string>>(() => {
|
||||
return new Set(syncData?.providers.map((p) => p.name) || [])
|
||||
})
|
||||
|
||||
// Pre-selected by default (opt-out)
|
||||
const [selectedModels, setSelectedModels] = useState<Set<string>>(() => {
|
||||
const set = new Set<string>()
|
||||
syncData?.providers.forEach((p) => {
|
||||
p.models.forEach((mItem) => {
|
||||
set.add(`${p.name}:${mItem.modelId}`)
|
||||
})
|
||||
})
|
||||
return set
|
||||
})
|
||||
|
||||
// Sync state if syncData changes
|
||||
useEffect(() => {
|
||||
if (syncData) {
|
||||
setExpandedProviders(new Set(syncData.providers.map((p) => p.name)))
|
||||
const modelSet = new Set<string>()
|
||||
syncData.providers.forEach((p) => {
|
||||
p.models.forEach((mItem) => {
|
||||
modelSet.add(`${p.name}:${mItem.modelId}`)
|
||||
})
|
||||
})
|
||||
setSelectedModels(modelSet)
|
||||
}
|
||||
}, [syncData])
|
||||
|
||||
// Filtered tree data based on filterQuery
|
||||
const filteredTree = useMemo(() => {
|
||||
if (!syncData) return []
|
||||
const q = filterQuery.trim().toLowerCase()
|
||||
if (!q) return syncData.providers
|
||||
|
||||
return syncData.providers
|
||||
.map((p) => {
|
||||
const matchesProvider = p.name.toLowerCase().includes(q)
|
||||
const matchingModels = p.models.filter(
|
||||
(mItem) =>
|
||||
matchesProvider ||
|
||||
mItem.modelId.toLowerCase().includes(q) ||
|
||||
mItem.name.toLowerCase().includes(q),
|
||||
)
|
||||
if (matchingModels.length > 0) {
|
||||
return { ...p, models: matchingModels }
|
||||
}
|
||||
return null
|
||||
})
|
||||
.filter((p): p is NonNullable<typeof p> => p !== null)
|
||||
}, [syncData, filterQuery])
|
||||
|
||||
// Total selected models & providers
|
||||
const totalSelectedModelsCount = selectedModels.size
|
||||
const totalSelectedProvidersCount = useMemo(() => {
|
||||
if (!syncData) return 0
|
||||
let count = 0
|
||||
for (const p of syncData.providers) {
|
||||
const hasSelectedModel = p.models.some((mItem) =>
|
||||
selectedModels.has(`${p.name}:${mItem.modelId}`),
|
||||
)
|
||||
if (hasSelectedModel) count++
|
||||
}
|
||||
return count
|
||||
}, [syncData, selectedModels])
|
||||
|
||||
const toggleExpand = (providerName: string) => {
|
||||
setExpandedProviders((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(providerName)) {
|
||||
next.delete(providerName)
|
||||
} else {
|
||||
next.add(providerName)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleExpandAll = () => {
|
||||
if (!syncData) return
|
||||
setExpandedProviders(new Set(syncData.providers.map((p) => p.name)))
|
||||
}
|
||||
|
||||
const handleCollapseAll = () => {
|
||||
setExpandedProviders(new Set())
|
||||
}
|
||||
|
||||
const toggleModel = (providerName: string, modelId: string) => {
|
||||
const key = `${providerName}:${modelId}`
|
||||
setSelectedModels((prevModels) => {
|
||||
const nextModels = new Set(prevModels)
|
||||
if (nextModels.has(key)) {
|
||||
nextModels.delete(key)
|
||||
} else {
|
||||
nextModels.add(key)
|
||||
}
|
||||
return nextModels
|
||||
})
|
||||
}
|
||||
|
||||
const toggleProvider = (providerName: string) => {
|
||||
const providerData = syncData?.providers.find((p) => p.name === providerName)
|
||||
if (!providerData || providerData.models.length === 0) return
|
||||
|
||||
const allModelsChecked = providerData.models.every((mItem) =>
|
||||
selectedModels.has(`${providerName}:${mItem.modelId}`),
|
||||
)
|
||||
|
||||
setSelectedModels((prev) => {
|
||||
const next = new Set(prev)
|
||||
providerData.models.forEach((mItem) => {
|
||||
const key = `${providerName}:${mItem.modelId}`
|
||||
if (allModelsChecked) {
|
||||
next.delete(key)
|
||||
} else {
|
||||
next.add(key)
|
||||
}
|
||||
})
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleSelectAll = () => {
|
||||
if (!syncData) return
|
||||
const modelSet = new Set<string>()
|
||||
syncData.providers.forEach((p) => {
|
||||
p.models.forEach((mItem) => {
|
||||
modelSet.add(`${p.name}:${mItem.modelId}`)
|
||||
})
|
||||
})
|
||||
setSelectedModels(modelSet)
|
||||
}
|
||||
|
||||
const handleDeselectAll = () => {
|
||||
setSelectedModels(new Set())
|
||||
}
|
||||
|
||||
// Apply mutation
|
||||
const applyMutation = useMutation({
|
||||
mutationFn: async (payload: SyncApplyRequest) => {
|
||||
const res = await client.api.teams[':teamId'].providers['sync-apply'].$post({
|
||||
param: { teamId },
|
||||
json: payload,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: 'Failed to apply sync' }))
|
||||
throw new Error((err as { message?: string }).message || 'Failed to apply sync')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
toast.success(
|
||||
m.sync_providers_success({
|
||||
modelCount: data.addedModels,
|
||||
providerCount: data.addedProviders,
|
||||
}),
|
||||
)
|
||||
onSuccess()
|
||||
onClose()
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!syncData || totalSelectedModelsCount === 0) return
|
||||
|
||||
const providersToSync: SyncApplyRequest['providers'] = []
|
||||
|
||||
for (const p of syncData.providers) {
|
||||
const selectedModelsForProvider = p.models.filter((mItem) =>
|
||||
selectedModels.has(`${p.name}:${mItem.modelId}`),
|
||||
)
|
||||
|
||||
if (selectedModelsForProvider.length > 0) {
|
||||
providersToSync.push({
|
||||
name: p.name,
|
||||
isNewProvider: p.isNewProvider,
|
||||
config: p.config,
|
||||
models: selectedModelsForProvider,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (providersToSync.length === 0) return
|
||||
|
||||
await applyMutation.mutateAsync({
|
||||
providers: providersToSync,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-3xl md:max-w-4xl w-full h-[85vh] max-h-[85vh] flex flex-col p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-6 pb-4 shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2 text-xl font-semibold">
|
||||
<Sparkles className="w-5 h-5 text-primary" />
|
||||
{m.sync_providers_dialog_title()}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-muted-foreground leading-relaxed mt-1.5">
|
||||
{m.sync_providers_dialog_description()}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Controls Toolbar */}
|
||||
<div className="px-6 pb-3 shrink-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
value={filterQuery}
|
||||
onChange={(e) => setFilterQuery(e.target.value)}
|
||||
placeholder={m.sync_providers_search_placeholder()}
|
||||
className="pl-8 h-8 text-xs bg-background"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleExpandAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_expand_all()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCollapseAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_collapse_all()}
|
||||
</Button>
|
||||
<div className="w-px h-4 bg-border mx-1" />
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_select_all()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDeselectAll}
|
||||
className="h-8 text-xs px-2.5"
|
||||
>
|
||||
{m.sync_providers_deselect_all()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tree List Container */}
|
||||
<div className="flex-1 min-h-0 px-6 overflow-hidden">
|
||||
<ScrollArea className="h-full border border-border/60 rounded-md bg-muted/20">
|
||||
<div className="p-3 space-y-3">
|
||||
{filteredTree.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-muted-foreground">
|
||||
{m.no_matches_found()}
|
||||
</div>
|
||||
) : (
|
||||
filteredTree.map((provider) => {
|
||||
const isExpanded = expandedProviders.has(provider.name)
|
||||
const isNew = provider.isNewProvider
|
||||
|
||||
// Determine provider check state
|
||||
const checkedCount = provider.models.filter((mItem) =>
|
||||
selectedModels.has(`${provider.name}:${mItem.modelId}`),
|
||||
).length
|
||||
const allChecked = checkedCount === provider.models.length
|
||||
const someChecked = checkedCount > 0 && !allChecked
|
||||
|
||||
return (
|
||||
<div
|
||||
key={provider.name}
|
||||
className="border border-border/50 rounded-lg bg-background overflow-hidden"
|
||||
>
|
||||
{/* Provider Header Row */}
|
||||
<div className="flex items-center justify-between px-3 py-2 bg-card hover:bg-muted/40 transition-colors">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpand(provider.name)}
|
||||
className="p-0.5 text-muted-foreground hover:text-foreground rounded transition-colors"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<Checkbox
|
||||
checked={allChecked ? true : someChecked ? 'indeterminate' : false}
|
||||
onCheckedChange={() => toggleProvider(provider.name)}
|
||||
id={`provider-check-${provider.name}`}
|
||||
/>
|
||||
|
||||
<label
|
||||
htmlFor={`provider-check-${provider.name}`}
|
||||
className="font-medium text-sm text-foreground flex items-center gap-2 cursor-pointer select-none"
|
||||
>
|
||||
<Cpu className="w-4 h-4 text-muted-foreground" />
|
||||
<span>{provider.name}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{isNew ? (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-[10px] px-1.5 py-0 bg-primary/10 text-primary border-primary/20"
|
||||
>
|
||||
{m.sync_providers_new_provider()}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 text-muted-foreground"
|
||||
>
|
||||
{m.sync_providers_existing_provider()}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{m.sync_providers_new_models_count({
|
||||
count: provider.models.length,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model Children Rows */}
|
||||
{isExpanded && (
|
||||
<div className="border-t border-border/40 divide-y divide-border/30 bg-muted/10">
|
||||
{provider.models.map((model) => {
|
||||
const isModelChecked = selectedModels.has(
|
||||
`${provider.name}:${model.modelId}`,
|
||||
)
|
||||
return (
|
||||
<div
|
||||
key={model.modelId}
|
||||
className="flex items-center justify-between pl-9 pr-3 py-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<Checkbox
|
||||
checked={isModelChecked}
|
||||
onCheckedChange={() =>
|
||||
toggleModel(provider.name, model.modelId)
|
||||
}
|
||||
id={`model-check-${provider.name}-${model.modelId}`}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`model-check-${provider.name}-${model.modelId}`}
|
||||
className="text-xs font-medium text-foreground cursor-pointer select-none truncate"
|
||||
>
|
||||
{model.name || model.modelId}
|
||||
<span className="ml-1.5 text-[11px] text-muted-foreground font-mono font-normal">
|
||||
{model.modelId}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 shrink-0 ml-2">
|
||||
{model.config.reasoning && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 font-normal border-amber-500/30 text-amber-600 dark:text-amber-400"
|
||||
>
|
||||
{m.sync_providers_reasoning()}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-[11px] text-muted-foreground font-mono">
|
||||
{m.sync_providers_context_window({
|
||||
count: Math.round(model.config.contextWindow / 1000),
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Selected Count & Footer */}
|
||||
<DialogFooter className="p-6 pt-3 shrink-0 border-t border-border flex items-center justify-between sm:justify-between w-full">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{m.sync_providers_selected_count({
|
||||
modelCount: totalSelectedModelsCount,
|
||||
providerCount: totalSelectedProvidersCount,
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
disabled={applyMutation.isPending}
|
||||
>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
disabled={totalSelectedModelsCount === 0 || applyMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{applyMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{m.sync_providers_adding()}
|
||||
</>
|
||||
) : (
|
||||
m.sync_providers_add_selected({
|
||||
count: totalSelectedModelsCount,
|
||||
})
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -459,27 +459,25 @@
|
||||
"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_missing_credentials": "Set an API key to refresh models.",
|
||||
"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",
|
||||
|
||||
@@ -444,27 +444,25 @@
|
||||
"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_missing_credentials": "모델을 새로 고치려면 API 키를 설정하세요.",
|
||||
"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": "기본 제공",
|
||||
|
||||
@@ -459,27 +459,25 @@
|
||||
"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_missing_credentials": "设置 API 密钥后即可刷新模型。",
|
||||
"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": "内置",
|
||||
|
||||
@@ -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">
|
||||
|
||||
Reference in New Issue
Block a user