diff --git a/apps/web/e2e/tests/team/quotas-settings.spec.ts b/apps/web/e2e/tests/team/quotas-settings.spec.ts index ee8c7221..650e5d56 100644 --- a/apps/web/e2e/tests/team/quotas-settings.spec.ts +++ b/apps/web/e2e/tests/team/quotas-settings.spec.ts @@ -12,6 +12,11 @@ test('owner manages resource quotas in settings and resets usage from the dashbo // 2. Click the Quotas sidebar tab await page.getByRole('button', { name: /Quotas|配额/i }).click() + // Verify URL contains #quotas and remains after reload + expect(page.url()).toContain('#quotas') + await page.reload() + expect(page.url()).toContain('#quotas') + // 3. Verify Quotas settings card is displayed with empty state await expect(page.getByRole('heading', { name: /^(Resource Quotas|资源配额)$/i })).toBeVisible() await expect(page.getByText(/No resource quotas configured|暂未配置资源配额/i)).toBeVisible() diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index 49b6d752..fe45eb71 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -1257,3 +1257,31 @@ describe('createAgentSession enabled skill filtering', () => { } }) }) + +describe('getModelFromDb', () => { + it('should prioritize provider active api protocol over model config api', () => { + const providers: DbProviderInfo[] = [ + { + name: 'custom-provider', + config: { api: 'anthropic-messages', apiKey: 'KEY' }, + models: [ + { + modelId: 'my-model', + name: 'My Model', + config: { + api: 'openai-responses', // stale model config + reasoning: false, + input: ['text'], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, + maxTokens: 4096, + }, + }, + ], + }, + ] + + const model = getModelFromDb(providers, 'custom-provider', 'my-model') + expect(model.api).toBe('anthropic-messages') + }) +}) diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 0593ecdc..24da829b 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -70,10 +70,10 @@ export function getModelFromDb(providers: DbProviderInfo[], providerName: string if (dbProvider.config.baseUrl) { m.baseUrl = dbProvider.config.baseUrl } + Object.assign(m, dbModel.config) if (dbProvider.config.api) { m.api = dbProvider.config.api } - Object.assign(m, dbModel.config) if (dbModel.name) { m.name = dbModel.name } diff --git a/packages/api/src/provider.test.ts b/packages/api/src/provider.test.ts index 8e89b09a..6f59b3f9 100644 --- a/packages/api/src/provider.test.ts +++ b/packages/api/src/provider.test.ts @@ -163,13 +163,13 @@ describe('provider api', () => { const res = await app.request('/providers/p1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ config, models }), + body: JSON.stringify({ name: 'new-name', config, models }), }) expect(res.status).toBe(200) const data = await res.json() expect(data.config.baseUrl).toBe('https://new-url.com') - expect(providerService.update).toHaveBeenCalledWith('t1', 'p1', config, models) + expect(providerService.update).toHaveBeenCalledWith('t1', 'p1', config, models, 'new-name') expect(authzService.hasPermission).toHaveBeenCalledWith({ user: expect.anything(), permission: Permission.Admin, @@ -184,6 +184,111 @@ describe('provider api', () => { }) }) + it('POST /providers/:id/models creates a model', async () => { + vi.mocked(providerService.getById).mockResolvedValue({ + id: 'p1', + teamId: 't1', + } as unknown as Awaited>) + const modelData = { + modelId: 'm1', + name: 'Model 1', + config: { + reasoning: true, + input: ['text' as const], + contextWindow: 128000, + maxTokens: 4096, + cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 }, + }, + } + vi.mocked(providerService.createModel).mockResolvedValue({ + id: 'm-db-1', + providerId: 'p1', + modelId: 'm1', + name: 'Model 1', + config: modelData.config, + createdAt: new Date(), + updatedAt: new Date(), + }) + + const res = await app.request('/providers/p1/models', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(modelData), + }) + + expect(res.status).toBe(201) + const data = await res.json() + expect(data.id).toBe('m-db-1') + expect(providerService.createModel).toHaveBeenCalledWith('t1', 'p1', modelData) + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: expect.anything(), + permission: Permission.Admin, + type: ResourceType.Provider, + id: 'p1', + }) + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: 'provider_update', + teamId: 't1', + userId: 'user1', + itemId: 'p1', + }) + }) + + it('PUT /providers/:id/models/:modelDbId updates a model', async () => { + vi.mocked(providerService.getById).mockResolvedValue({ + id: 'p1', + teamId: 't1', + } as unknown as Awaited>) + const updateData = { + name: 'Updated Model', + } + vi.mocked(providerService.updateModel).mockResolvedValue({ + id: 'm-db-1', + providerId: 'p1', + modelId: 'm1', + name: 'Updated Model', + config: { + reasoning: false, + input: ['text'], + contextWindow: 128000, + maxTokens: 4096, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + createdAt: new Date(), + updatedAt: new Date(), + }) + + const res = await app.request('/providers/p1/models/m-db-1', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(updateData), + }) + + expect(res.status).toBe(200) + const data = await res.json() + expect(data.name).toBe('Updated Model') + expect(providerService.updateModel).toHaveBeenCalledWith('t1', 'p1', 'm-db-1', updateData) + }) + + it('DELETE /providers/:id/models/:modelDbId deletes a model', async () => { + vi.mocked(providerService.getById).mockResolvedValue({ + id: 'p1', + teamId: 't1', + } as unknown as Awaited>) + vi.mocked(providerService.deleteModel).mockResolvedValue({ + id: 'm-db-1', + } as unknown as Awaited>) + + const res = await app.request('/providers/p1/models/m-db-1', { + method: 'DELETE', + }) + + expect(res.status).toBe(200) + const data = await res.json() + expect(data.success).toBe(true) + expect(providerService.deleteModel).toHaveBeenCalledWith('t1', 'p1', 'm-db-1') + }) + it('DELETE /providers/:id deletes provider', async () => { vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', diff --git a/packages/api/src/provider.ts b/packages/api/src/provider.ts index fc18d9fd..5b396d2c 100644 --- a/packages/api/src/provider.ts +++ b/packages/api/src/provider.ts @@ -2,7 +2,13 @@ import { zValidator } from '@hono/zod-validator' import { Hono } from 'hono' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { providerService } from '@shumai/core/src/provider/provider' -import { createProviderRequestSchema, updateProviderRequestSchema, AuditAction } from '@shumai/dtos' +import { + createModelRequestSchema, + createProviderRequestSchema, + updateModelRequestSchema, + updateProviderRequestSchema, + AuditAction, +} from '@shumai/dtos' import type { Prisma } from '@shumai/db' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' @@ -67,7 +73,7 @@ const route = new Hono<{ Variables: { user: User } }>() .put('/providers/:id', zValidator('json', updateProviderRequestSchema), async (c) => { const id = c.req.param('id') const user = c.get('user') - const { config, models } = c.req.valid('json') + const { name, config, models } = c.req.valid('json') await authzService.hasPermission({ user, @@ -79,7 +85,7 @@ const route = new Hono<{ Variables: { user: User } }>() const providerBefore = await providerService.getById(id) if (!providerBefore) throw new Error('Provider not found') - const provider = await providerService.update(providerBefore.teamId, id, config, models) + const provider = await providerService.update(providerBefore.teamId, id, config, models, name) await auditLogService.logAction({ action: AuditAction.provider_update, teamId: providerBefore.teamId, @@ -89,6 +95,86 @@ const route = new Hono<{ Variables: { user: User } }>() return c.json(provider) }) + .post('/providers/:id/models', zValidator('json', createModelRequestSchema), async (c) => { + const id = c.req.param('id') + const user = c.get('user') + const data = c.req.valid('json') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Provider, + id, + }) + + const provider = await providerService.getById(id) + if (!provider) throw new Error('Provider not found') + + const model = await providerService.createModel(provider.teamId, id, data) + await auditLogService.logAction({ + action: AuditAction.provider_update, + teamId: provider.teamId, + userId: user?.id, + itemId: id, + }) + return c.json(model, 201) + }) + + .put( + '/providers/:id/models/:modelDbId', + zValidator('json', updateModelRequestSchema), + async (c) => { + const id = c.req.param('id') + const modelDbId = c.req.param('modelDbId') + const user = c.get('user') + const data = c.req.valid('json') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Provider, + id, + }) + + const provider = await providerService.getById(id) + if (!provider) throw new Error('Provider not found') + + const model = await providerService.updateModel(provider.teamId, id, modelDbId, data) + await auditLogService.logAction({ + action: AuditAction.provider_update, + teamId: provider.teamId, + userId: user?.id, + itemId: id, + }) + return c.json(model) + }, + ) + + .delete('/providers/:id/models/:modelDbId', async (c) => { + const id = c.req.param('id') + const modelDbId = c.req.param('modelDbId') + const user = c.get('user') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Provider, + id, + }) + + const providerBefore = await providerService.getById(id) + if (!providerBefore) throw new Error('Provider not found') + + await providerService.deleteModel(providerBefore.teamId, id, modelDbId) + await auditLogService.logAction({ + action: AuditAction.provider_update, + teamId: providerBefore.teamId, + userId: user?.id, + itemId: id, + }) + return c.json({ success: true }) + }) + .delete('/providers/:id', async (c) => { const id = c.req.param('id') const user = c.get('user') diff --git a/packages/core/src/provider/provider.test.ts b/packages/core/src/provider/provider.test.ts index e7a29a35..a4c388ec 100644 --- a/packages/core/src/provider/provider.test.ts +++ b/packages/core/src/provider/provider.test.ts @@ -191,4 +191,159 @@ describe('ProviderService', () => { const updatedAgent = updatedAgents.find((a) => a.id === agent!.id) expect(updatedAgent?.modelId).toBe(initialModelId) }) + + it('should support granular model CRUD operations and order by id desc', async () => { + const team = await teamService.ensureDefaultTeam() + const provider = await providerService.create( + team.id, + 'test-granular-provider', + { api: 'openai-completions', apiKey: 'key1' }, + [], + ) + + // 1. createModel + const createdModel1 = await providerService.createModel(team.id, provider.id, { + modelId: 'custom-model-1', + name: 'Custom Model 1', + config: { + reasoning: true, + input: ['text', 'image'], + contextWindow: 200000, + maxTokens: 8192, + cost: { input: 1.5, output: 5, cacheRead: 0.1, cacheWrite: 0.5 }, + }, + }) + expect(createdModel1.modelId).toBe('custom-model-1') + expect(createdModel1.name).toBe('Custom Model 1') + expect((createdModel1.config as { reasoning: boolean }).reasoning).toBe(true) + + // Check duplicate modelId error + await expect( + providerService.createModel(team.id, provider.id, { + modelId: 'custom-model-1', + name: 'Duplicate', + config: { + reasoning: false, + input: ['text'], + contextWindow: 100000, + maxTokens: 4000, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + }), + ).rejects.toThrow('already exists') + + // 2. createModel 2 + const createdModel2 = await providerService.createModel(team.id, provider.id, { + modelId: 'custom-model-2', + name: 'Custom Model 2', + config: { + reasoning: false, + input: ['text'], + contextWindow: 100000, + maxTokens: 4000, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + }) + + // 3. listModelsByProvider should return newest first (id desc) + const models = await providerService.listModelsByProvider(team.id, provider.id) + expect(models).toHaveLength(2) + expect(models[0].id).toBe(createdModel2.id) + expect(models[1].id).toBe(createdModel1.id) + + // 4. updateModel + const updatedModel = await providerService.updateModel(team.id, provider.id, createdModel1.id, { + name: 'Updated Model 1', + config: { + reasoning: false, + input: ['text'], + contextWindow: 64000, + maxTokens: 2048, + cost: { input: 2, output: 8, cacheRead: 0.2, cacheWrite: 0.8 }, + }, + }) + expect(updatedModel.name).toBe('Updated Model 1') + expect((updatedModel.config as { reasoning: boolean }).reasoning).toBe(false) + expect((updatedModel.config as { cost: { input: number } }).cost.input).toBe(2) + + // 5. update provider config and name without touching models + const updatedProvider = await providerService.update( + team.id, + provider.id, + { api: 'openai-completions', apiKey: 'new-key' }, + undefined, + 'renamed-provider', + ) + expect(updatedProvider.name).toBe('renamed-provider') + expect(updatedProvider.config.apiKey).toBe('new-key') + const modelsAfterProviderUpdate = await providerService.listModelsByProvider( + team.id, + provider.id, + ) + expect(modelsAfterProviderUpdate).toHaveLength(2) + + // 6. deleteModel + await providerService.deleteModel(team.id, provider.id, createdModel2.id) + const modelsAfterDelete = await providerService.listModelsByProvider(team.id, provider.id) + expect(modelsAfterDelete).toHaveLength(1) + expect(modelsAfterDelete[0].id).toBe(createdModel1.id) + }) + + it('should propagate provider API protocol change to existing models', async () => { + const team = await teamService.ensureDefaultTeam() + + // 1. Create provider with openai-responses + const provider = await providerService.create( + team.id, + 'test-protocol-provider', + { api: 'openai-responses', apiKey: 'key-1' }, + [ + { + modelId: 'm1', + name: 'Model 1', + config: { + api: 'openai-responses', + reasoning: false, + input: ['text'], + contextWindow: 128000, + maxTokens: 4096, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + }, + { + modelId: 'm2', + name: 'Model 2', + config: { + api: 'openai-responses', + reasoning: true, + input: ['text'], + contextWindow: 64000, + maxTokens: 2048, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + }, + ], + ) + + const initialModels = await providerService.listModelsByProvider(team.id, provider.id) + expect(initialModels).toHaveLength(2) + expect((initialModels[0].config as { api: string }).api).toBe('openai-responses') + expect((initialModels[1].config as { api: string }).api).toBe('openai-responses') + + // 2. Update provider global API protocol to anthropic-messages without passing models + const updatedProvider = await providerService.update( + team.id, + provider.id, + { api: 'anthropic-messages', apiKey: 'key-2' }, + undefined, + 'test-protocol-provider', + ) + expect(updatedProvider.config.api).toBe('anthropic-messages') + + // 3. Verify that all existing models under this provider were updated + const modelsAfterUpdate = await providerService.listModelsByProvider(team.id, provider.id) + expect(modelsAfterUpdate).toHaveLength(2) + expect((modelsAfterUpdate[0].config as { api: string }).api).toBe('anthropic-messages') + expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages') + }) }) diff --git a/packages/core/src/provider/provider.ts b/packages/core/src/provider/provider.ts index 5d197f19..80321ce3 100644 --- a/packages/core/src/provider/provider.ts +++ b/packages/core/src/provider/provider.ts @@ -1,5 +1,10 @@ import { prisma } from '@shumai/db' -import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos' +import { + CreateModelRequest, + ProviderConfigSerializable, + providerModelSchema, + UpdateModelRequest, +} from '@shumai/dtos' import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin' import { z } from 'zod' @@ -74,7 +79,7 @@ export class ProviderService { providerId, provider: { teamId }, }, - orderBy: { id: 'asc' }, + orderBy: { id: 'desc' }, }) } @@ -82,7 +87,7 @@ export class ProviderService { teamId: string, name: string, config: ProviderConfigSerializable, - models: ProviderModel[], + models: ProviderModel[] = [], ) { return this.prismaClient.provider.create({ data: { @@ -105,60 +110,177 @@ export class ProviderService { teamId: string, id: string, config: ProviderConfigSerializable, - models: ProviderModel[], + models?: ProviderModel[], + name?: string, ) { return this.prismaClient.$transaction(async (tx) => { - const existingModels = await tx.model.findMany({ - where: { providerId: id }, - }) - - const existingByModelId = new Map(existingModels.map((m) => [m.modelId, m])) - const incomingModelIds = new Set(models.map((m) => m.modelId)) - - // Delete models that are no longer in the incoming list - const modelsToDelete = existingModels.filter((m) => !incomingModelIds.has(m.modelId)) - if (modelsToDelete.length > 0) { - await tx.model.deleteMany({ - where: { - id: { in: modelsToDelete.map((m) => m.id) }, - }, + if (models !== undefined) { + const existingModels = await tx.model.findMany({ + where: { providerId: id }, }) - } - // Update existing models or create new ones - for (const m of models) { - const existing = existingByModelId.get(m.modelId) - if (existing) { - await tx.model.update({ - where: { id: existing.id }, - data: { - name: m.name, - config: m.config, - }, - }) - } else { - await tx.model.create({ - data: { - providerId: id, - modelId: m.modelId, - name: m.name, - config: m.config, + const existingByModelId = new Map(existingModels.map((m) => [m.modelId, m])) + const incomingModelIds = new Set(models.map((m) => m.modelId)) + + // Delete models that are no longer in the incoming list + const modelsToDelete = existingModels.filter((m) => !incomingModelIds.has(m.modelId)) + if (modelsToDelete.length > 0) { + await tx.model.deleteMany({ + where: { + id: { in: modelsToDelete.map((m) => m.id) }, }, }) } + + // Update existing models or create new ones + for (const m of models) { + const existing = existingByModelId.get(m.modelId) + const modelConfig = { + ...m.config, + api: m.config?.api || config.api, + } + if (existing) { + await tx.model.update({ + where: { id: existing.id }, + data: { + name: m.name, + config: modelConfig, + }, + }) + } else { + await tx.model.create({ + data: { + providerId: id, + modelId: m.modelId, + name: m.name, + config: modelConfig, + }, + }) + } + } + } else if (config.api) { + // Propagate provider API protocol change to all existing models + const existingModels = await tx.model.findMany({ + where: { providerId: id }, + }) + for (const m of existingModels) { + const currentConfig = m.config + if (currentConfig.api !== config.api) { + await tx.model.update({ + where: { id: m.id }, + data: { + config: { + ...currentConfig, + api: config.api, + }, + }, + }) + } + } } - // Update provider config + // Update provider config and optional name return tx.provider.update({ where: { id, teamId }, data: { config, + ...(name ? { name } : {}), }, include: { models: true }, }) }) } + async createModel(teamId: string, providerId: string, data: CreateModelRequest) { + const provider = await this.prismaClient.provider.findUnique({ + where: { id: providerId, teamId }, + }) + if (!provider) { + throw new Error('Provider not found') + } + + const existing = await this.prismaClient.model.findFirst({ + where: { + providerId, + modelId: data.modelId, + }, + }) + if (existing) { + throw new Error(`Model with id "${data.modelId}" already exists for this provider`) + } + + return this.prismaClient.model.create({ + data: { + providerId, + modelId: data.modelId, + name: data.name ?? '', + config: data.config, + }, + }) + } + + async updateModel( + teamId: string, + providerId: string, + modelDbId: string, + data: UpdateModelRequest, + ) { + const provider = await this.prismaClient.provider.findUnique({ + where: { id: providerId, teamId }, + }) + if (!provider) { + throw new Error('Provider not found') + } + + const model = await this.prismaClient.model.findFirst({ + where: { id: modelDbId, providerId }, + }) + if (!model) { + throw new Error('Model not found') + } + + if (data.modelId && data.modelId !== model.modelId) { + const existingWithNewId = await this.prismaClient.model.findFirst({ + where: { + providerId, + modelId: data.modelId, + }, + }) + if (existingWithNewId) { + throw new Error(`Model with id "${data.modelId}" already exists for this provider`) + } + } + + return this.prismaClient.model.update({ + where: { id: modelDbId }, + data: { + ...(data.modelId ? { modelId: data.modelId } : {}), + ...(data.name !== undefined ? { name: data.name } : {}), + ...(data.config ? { config: data.config } : {}), + }, + }) + } + + async deleteModel(teamId: string, providerId: string, modelDbId: string) { + const provider = await this.prismaClient.provider.findUnique({ + where: { id: providerId, teamId }, + }) + if (!provider) { + throw new Error('Provider not found') + } + + const model = await this.prismaClient.model.findFirst({ + where: { id: modelDbId, providerId }, + }) + if (!model) { + throw new Error('Model not found') + } + + return this.prismaClient.model.delete({ + where: { id: modelDbId }, + }) + } + async delete(teamId: string, id: string) { const provider = await this.prismaClient.provider.findUnique({ where: { id, teamId }, diff --git a/packages/dtos/src/provider.ts b/packages/dtos/src/provider.ts index 5469f3c7..9b3e2d78 100644 --- a/packages/dtos/src/provider.ts +++ b/packages/dtos/src/provider.ts @@ -49,14 +49,35 @@ export type ProviderConfigSerializable = z.infer export const createProviderRequestSchema = z.object({ name: z.string().min(1, 'Provider name is required'), config: providerConfigSchema, - models: z.array(providerModelSchema).min(1, 'At least one model is required'), + models: z.array(providerModelSchema).default([]), }) +export type CreateProviderRequest = z.infer + export const updateProviderRequestSchema = z.object({ + name: z.string().min(1, 'Provider name is required').optional(), config: providerConfigSchema, - models: z.array(providerModelSchema).min(1, 'At least one model is required'), + models: z.array(providerModelSchema).optional(), }) +export type UpdateProviderRequest = z.infer + +export const createModelRequestSchema = z.object({ + modelId: z.string().min(1, 'Model ID is required'), + name: z.string().min(0).default(''), + config: providerModelConfigSchema, +}) + +export type CreateModelRequest = z.infer + +export const updateModelRequestSchema = z.object({ + modelId: z.string().min(1, 'Model ID is required').optional(), + name: z.string().min(0).optional(), + config: providerModelConfigSchema.optional(), +}) + +export type UpdateModelRequest = z.infer + export const providerResponseSchema = z.object({ id: z.string(), name: z.string(), diff --git a/packages/webui/components/settings/AgentFormDialog.tsx b/packages/webui/components/settings/AgentFormDialog.tsx index 3e7f3623..3a459c3f 100644 --- a/packages/webui/components/settings/AgentFormDialog.tsx +++ b/packages/webui/components/settings/AgentFormDialog.tsx @@ -12,6 +12,7 @@ import { DialogTitle, } from '@/ui/components/ui/dialog' import { Field, FieldLabel, FieldError } from '@/ui/components/ui/field' +import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover' import { Select, SelectContent, @@ -22,8 +23,8 @@ import { import { Switch } from '@/ui/components/ui/switch' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useForm, useStore } from '@tanstack/react-form' -import { Loader2, Puzzle, Server, Terminal } from 'lucide-react' -import { useEffect, useMemo } from 'react' +import { Check, ChevronDown, Loader2, Puzzle, Search, Server, Terminal, Zap } from 'lucide-react' +import { useEffect, useMemo, useState } from 'react' import { m } from '@/ui/paraglide/messages.js' import { toast } from 'sonner' import { AgentInfo, AgentType, ThinkingLevel, thinkingLevelSchema } from '@shumai/dtos' @@ -218,6 +219,44 @@ export function AgentFormDialog({ enabled: !!selectedProviderId && isOpen, }) + const [providerSearchQuery, setProviderSearchQuery] = useState('') + const [isProviderSelectOpen, setIsProviderSelectOpen] = useState(false) + + // Sort providers alphabetically by name + const sortedProviders = useMemo(() => { + if (!providers) return [] + return [...providers].sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())) + }, [providers]) + + // Filter providers based on search query + const filteredProviders = useMemo(() => { + if (!providerSearchQuery.trim()) return sortedProviders + const q = providerSearchQuery.toLowerCase() + return sortedProviders.filter((p) => p.name.toLowerCase().includes(q)) + }, [sortedProviders, providerSearchQuery]) + + const [modelSearchQuery, setModelSearchQuery] = useState('') + const [isModelSelectOpen, setIsModelSelectOpen] = useState(false) + + // Sort models alphabetically by display name / modelId + const sortedModels = useMemo(() => { + if (!models) return [] + return [...models].sort((a, b) => { + const nameA = (a.name || a.modelId).toLowerCase() + const nameB = (b.name || b.modelId).toLowerCase() + return nameA.localeCompare(nameB) + }) + }, [models]) + + // Filter models based on search query + const filteredModels = useMemo(() => { + if (!modelSearchQuery.trim()) return sortedModels + const q = modelSearchQuery.toLowerCase() + return sortedModels.filter( + (m) => m.modelId.toLowerCase().includes(q) || (m.name && m.name.toLowerCase().includes(q)), + ) + }, [sortedModels, modelSearchQuery]) + const createMutation = useMutation({ mutationFn: async (values: AgentFormValues) => { const res = await client.api.teams[':teamId'].agents.$post({ @@ -259,6 +298,10 @@ export function AgentFormDialog({ useEffect(() => { if (isOpen) { form.reset() + setProviderSearchQuery('') + setIsProviderSelectOpen(false) + setModelSearchQuery('') + setIsModelSelectOpen(false) } }, [isOpen, initialValues, type]) @@ -421,27 +464,109 @@ export function AgentFormDialog({ children={(field) => { const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched + const selectedProvider = providers?.find((p) => p.id === field.state.value) + return ( {m.provider()} - + + + + e.stopPropagation()} + > +
+ + setProviderSearchQuery(e.target.value)} + className="pl-8 h-8 text-xs bg-muted/40" + autoFocus + /> +
+ e.stopPropagation()} + > + {filteredProviders.length === 0 ? ( +
+ {m.no_providers_found()} +
+ ) : ( +
+ {filteredProviders.map((p) => { + const isSelected = field.state.value === p.id + return ( +
{ + field.handleChange(p.id) + form.setFieldValue('modelId', '') + setModelSearchQuery('') + setIsProviderSelectOpen(false) + setProviderSearchQuery('') + }} + className={cn( + 'flex items-center justify-between px-2.5 py-2 rounded-md text-xs cursor-pointer transition-colors', + isSelected + ? 'bg-accent text-accent-foreground font-medium' + : 'hover:bg-muted/60 text-foreground', + )} + > + {p.name} + {isSelected && ( + + )} +
+ ) + })} +
+ )} +
+
+ {isInvalid && ( )} @@ -455,28 +580,141 @@ export function AgentFormDialog({ children={(field) => { const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched + const selectedModel = models?.find((m) => m.id === field.state.value) + return ( {m.model()} {isModelsLoading && } - + + + + e.stopPropagation()} + > +
+ + setModelSearchQuery(e.target.value)} + className="pl-8 h-8 text-xs bg-muted/40" + autoFocus + /> +
+ e.stopPropagation()} + > + {filteredModels.length === 0 ? ( +
+ {m.no_models_found()} +
+ ) : ( +
+ {filteredModels.map((m) => { + const isSelected = field.state.value === m.id + return ( +
{ + field.handleChange(m.id) + setIsModelSelectOpen(false) + setModelSearchQuery('') + }} + className={cn( + 'flex items-center justify-between px-2.5 py-2 rounded-md text-xs cursor-pointer transition-colors', + isSelected + ? 'bg-accent text-accent-foreground font-medium' + : 'hover:bg-muted/60 text-foreground', + )} + > +
+
+ + {m.name || m.modelId} + + {m.name && m.name !== m.modelId && ( + + ({m.modelId}) + + )} + {m.config?.reasoning && ( + + + + )} +
+
+ {isSelected && ( + + )} +
+ ) + })} +
+ )} +
+
+ {isInvalid && ( )} diff --git a/packages/webui/components/settings/ModelFormDialog.test.tsx b/packages/webui/components/settings/ModelFormDialog.test.tsx new file mode 100644 index 00000000..c83f4991 --- /dev/null +++ b/packages/webui/components/settings/ModelFormDialog.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen } from '@testing-library/react' +import React from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { ModelFormDialog } from './ModelFormDialog' +import type { ModelFormValues } from './ModelFormDialog' + +describe('ModelFormDialog', () => { + afterEach(() => { + cleanup() + }) + + const model1: ModelFormValues = { + modelId: 'gpt-4o', + name: 'GPT-4o Production', + config: { + api: 'openai-responses', + reasoning: true, + input: ['text', 'image'], + contextWindow: 128000, + maxTokens: 4096, + cost: { input: 2.5, output: 10, cacheRead: 1.25, cacheWrite: 2.5 }, + }, + } + + const model2: ModelFormValues = { + modelId: 'claude-3-5-sonnet', + name: 'Claude 3.5 Sonnet', + config: { + api: 'anthropic-messages', + reasoning: false, + input: ['text'], + contextWindow: 200000, + maxTokens: 8192, + cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, + }, + } + + it('populates fields with initialValues when opened for editing', () => { + render( + , + ) + + const modelIdInput = screen.getByLabelText(/model id/i) as HTMLInputElement + const nameInput = screen.getByLabelText(/display name/i) as HTMLInputElement + + expect(modelIdInput.value).toBe('gpt-4o') + expect(nameInput.value).toBe('GPT-4o Production') + }) + + it('updates fields when switching between different models', () => { + const { rerender } = render( + , + ) + + let modelIdInput = screen.getByLabelText(/model id/i) as HTMLInputElement + expect(modelIdInput.value).toBe('gpt-4o') + + rerender( + , + ) + + modelIdInput = screen.getByLabelText(/model id/i) as HTMLInputElement + const nameInput = screen.getByLabelText(/display name/i) as HTMLInputElement + + expect(modelIdInput.value).toBe('claude-3-5-sonnet') + expect(nameInput.value).toBe('Claude 3.5 Sonnet') + }) +}) diff --git a/packages/webui/components/settings/ModelFormDialog.tsx b/packages/webui/components/settings/ModelFormDialog.tsx new file mode 100644 index 00000000..04f522e0 --- /dev/null +++ b/packages/webui/components/settings/ModelFormDialog.tsx @@ -0,0 +1,398 @@ +import { ScrollArea } from '@/ui/components/ui/scroll-area' +import { Button } from '@/ui/components/ui/button' +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/ui/components/ui/dialog' +import { Field, FieldError, FieldLabel } from '@/ui/components/ui/field' +import { Input } from '@/ui/components/ui/input' +import { Switch } from '@/ui/components/ui/switch' +import { createModelRequestSchema } from '@shumai/dtos' +import { useForm } from '@tanstack/react-form' +import { DollarSign, Loader2 } from 'lucide-react' +import { useEffect, useMemo } from 'react' +import { z } from 'zod' +import { m } from '@/ui/paraglide/messages.js' + +export type ModelFormValues = z.infer + +export interface ModelFormDialogProps { + isOpen: boolean + onClose: () => void + onSubmit: (values: ModelFormValues) => void + initialValues?: ModelFormValues | null + title: string + isLoading?: boolean + defaultApi?: string + existingModelIds?: string[] +} + +export function ModelFormDialog({ + isOpen, + onClose, + onSubmit, + initialValues, + title, + isLoading = false, + defaultApi, + existingModelIds = [], +}: ModelFormDialogProps) { + const schema = useMemo(() => { + return createModelRequestSchema.extend({ + modelId: z + .string() + .min(1, m.model_id()) + .refine( + (id) => { + if (initialValues?.modelId === id) return true + return !existingModelIds.includes(id) + }, + { message: m.model_id_already_exists() }, + ), + }) + }, [existingModelIds, initialValues]) + + const getDefaultValues = () => + (initialValues || { + modelId: '', + name: '', + config: { + api: defaultApi, + reasoning: false, + input: ['text'], + contextWindow: 128000, + maxTokens: 4096, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + }, + }, + }) as z.input + + const form = useForm({ + defaultValues: getDefaultValues(), + validators: { + onSubmit: schema, + }, + onSubmit: async ({ value }) => { + onSubmit(value as ModelFormValues) + }, + }) + + useEffect(() => { + if (isOpen) { + form.reset(getDefaultValues()) + } + }, [isOpen, initialValues, defaultApi, form]) + + const mapErrors = (errors: unknown[]) => { + return errors.map((e) => { + if (typeof e === 'string') return { message: e } + if (e && typeof e === 'object' && 'message' in e) { + return { message: String(e.message) } + } + return { message: String(e || '') } + }) + } + + return ( + + + + {title} + + +
{ + e.preventDefault() + e.stopPropagation() + form.handleSubmit() + }} + className="flex-1 flex flex-col min-h-0 overflow-hidden" + > +
+ +
+ {/* Basic Model Info */} +
+ { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + {m.model_id()} + field.handleChange(e.target.value)} + placeholder={m.model_id_placeholder()} + aria-invalid={isInvalid} + /> + {isInvalid && } + + ) + }} + /> + + { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + {m.display_name_optional()} + field.handleChange(e.target.value)} + placeholder={m.model_name_placeholder()} + aria-invalid={isInvalid} + /> + {isInvalid && } + + ) + }} + /> +
+ + {/* Parameters & Reasoning */} +
+

{m.parameters()}

+ ( + + + {m.reasoning_support()} + + + + )} + /> + +
+ { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.context_window_tokens()} + + field.handleChange(parseInt(e.target.value) || 0)} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> + + { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.max_output_tokens()} + + field.handleChange(parseInt(e.target.value) || 0)} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> +
+
+ + {/* Pricing Section */} +
+

+ + {m.pricing()} +

+
+ { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.input_cost_1m()} + + field.handleChange(parseFloat(e.target.value) || 0)} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> + + { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.output_cost_1m()} + + field.handleChange(parseFloat(e.target.value) || 0)} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> + + { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.cache_read_cost_1m()} + + field.handleChange(parseFloat(e.target.value) || 0)} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> + + { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.cache_write_cost_1m()} + + field.handleChange(parseFloat(e.target.value) || 0)} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> +
+
+
+
+
+ + + + [state.canSubmit, state.isSubmitting]} + children={([canSubmit, isSubmitting]) => ( + + )} + /> + +
+
+
+ ) +} diff --git a/packages/webui/components/settings/ProvidersSettings.tsx b/packages/webui/components/settings/ProvidersSettings.tsx index befafc29..a0f47857 100644 --- a/packages/webui/components/settings/ProvidersSettings.tsx +++ b/packages/webui/components/settings/ProvidersSettings.tsx @@ -37,15 +37,14 @@ import { SelectTrigger, SelectValue, } from '@/ui/components/ui/select' -import { Switch } from '@/ui/components/ui/switch' -import { providerConfigSchema, providerModelSchema, KNOWN_APIS } from '@shumai/dtos' +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs' +import { providerConfigSchema, KNOWN_APIS } 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, - DollarSign, Globe, Info, Loader2, @@ -60,6 +59,7 @@ import { useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { z } from 'zod' import { m } from '@/ui/paraglide/messages.js' +import { ModelFormDialog, ModelFormValues } from './ModelFormDialog' const API_PROTOCOL_LABELS: Record<(typeof KNOWN_APIS)[number], string> = { 'openai-completions': 'OpenAI Completions', @@ -73,19 +73,14 @@ const API_PROTOCOL_LABELS: Record<(typeof KNOWN_APIS)[number], string> = { 'google-vertex': 'Google Vertex', } -const providerFormSchemaBase = z.object({ - name: z.string().min(1, m.provider_name_is_required()), - config: providerConfigSchema, - models: z.array(providerModelSchema).min(1, m.at_least_one_model_required()), -}) - -type ProviderFormValues = z.infer - type ProvidersResponse = InferResponseType< (typeof client.api.teams)[':teamId']['providers']['$get'] > type Provider = ProvidersResponse[number] +type ModelsResponse = InferResponseType<(typeof client.api.providers)[':id']['models']['$get']> +type ProviderModelItem = ModelsResponse[number] + interface ProvidersSettingsProps { teamId: string } @@ -115,19 +110,6 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) { [providers, editingProviderId], ) - // Fetch models for editing - const { data: editingModels, isLoading: isModelsLoading } = useQuery({ - queryKey: ['teams', teamId, 'providers', editingProviderId, 'models'], - queryFn: async () => { - const res = await client.api.providers[':id'].models.$get({ - param: { id: editingProviderId! }, - }) - if (!res.ok) throw new Error('Failed to fetch models') - return await res.json() - }, - enabled: !!editingProviderId, - }) - const existingProviderNames = useMemo(() => providers?.map((p) => p.name) || [], [providers]) const filteredProviders = useMemo(() => { @@ -139,7 +121,11 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) { // Create Mutation const createMutation = useMutation({ - mutationFn: async (values: ProviderFormValues) => { + mutationFn: async (values: { + name: string + config: z.infer + models: ModelFormValues[] + }) => { const res = await client.api.teams[':teamId'].providers.$post({ param: { teamId }, json: { @@ -161,29 +147,6 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) { }, }) - // Update Mutation - const updateMutation = useMutation({ - mutationFn: async ({ id, values }: { id: string; values: ProviderFormValues }) => { - const res = await client.api.providers[':id'].$put({ - param: { id }, - json: { - config: values.config, - models: values.models, - }, - }) - if (!res.ok) throw new Error('Failed to update provider') - return await res.json() - }, - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] }) - setEditingProviderId(null) - toast.success(m.provider_updated_successfully()) - }, - onError: (error) => { - toast.error(m.error_message({ message: error.message })) - }, - }) - // Delete Mutation const deleteMutation = useMutation({ mutationFn: async (id: string) => { @@ -257,14 +220,6 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
{provider.name} - {provider.isBuiltin && ( - - {m.built_in()} - - )}
@@ -284,16 +239,13 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) { {m.n_models_count({ count: provider.modelsCount })} - {editingProviderId === provider.id && isModelsLoading && ( - - )}
- + e.stopPropagation()}> -
+ {/* Initial Models Section */} +
+
+
+ +

+ {m.models_configuration()} +

+
+ +
-
- {modelsField.state.value.map((_, index) => ( -
- {/* Row 1: ID and Name */} -
- { - const isInvalid = - !!field.state.meta.errors.length && field.state.meta.isTouched - return ( - - {m.model_id()} - field.handleChange(e.target.value)} - placeholder="gpt-4o" - aria-invalid={isInvalid} - /> - {isInvalid && ( - - )} - - ) - }} - /> - { - const isInvalid = - !!field.state.meta.errors.length && field.state.meta.isTouched - return ( - - - {m.display_name_optional()} - - field.handleChange(e.target.value)} - placeholder="e.g., GPT-4o" - aria-invalid={isInvalid} - disabled={isBuiltin} - /> - {isInvalid && ( - - )} - - ) - }} - /> -
- - {/* Row 2: Reasoning and Context Window */} -
- ( - - - {m.reasoning_support()} - - - - )} - /> - { - const isInvalid = - !!field.state.meta.errors.length && field.state.meta.isTouched - return ( - - - {m.context_window_tokens()} - - - field.handleChange(parseInt(e.target.value) || 0) - } - aria-invalid={isInvalid} - disabled={isBuiltin} - /> - {isInvalid && ( - - )} - - ) - }} - /> -
- - {/* Row 3: Constraints and Cost */} -
- { - const isInvalid = - !!field.state.meta.errors.length && field.state.meta.isTouched - return ( - - - {m.max_output_tokens()} - - - field.handleChange(parseInt(e.target.value) || 0) - } - aria-invalid={isInvalid} - disabled={isBuiltin} - /> - {isInvalid && ( - - )} - - ) - }} - /> - { - const isInvalid = - !!field.state.meta.errors.length && field.state.meta.isTouched - return ( - - - {m.input_cost_1m()} - - - field.handleChange(parseFloat(e.target.value) || 0) - } - aria-invalid={isInvalid} - disabled={isBuiltin} - /> - {isInvalid && ( - - )} - - ) - }} - /> - { - const isInvalid = - !!field.state.meta.errors.length && field.state.meta.isTouched - return ( - - - {m.output_cost_1m()} - - - field.handleChange(parseFloat(e.target.value) || 0) - } - aria-invalid={isInvalid} - disabled={isBuiltin} - /> - {isInvalid && ( - - )} - - ) - }} - /> -
- - + {initialModels.length === 0 ? ( +
+ {m.no_models_found()} +
+ ) : ( +
+ {initialModels.map((model, idx) => ( +
setEditingModelIndex(idx)} + > +
+
+ + {model.name || model.modelId} + + + {model.modelId} + + {model.config.reasoning && ( + + {m.reasoning_support()} + + )}
- ))} +
+ + {model.config.contextWindow?.toLocaleString()} {m.tokens()} + + · + + {m.cost_per_million({ + input: model.config.cost?.input ?? 0, + output: model.config.cost?.output ?? 0, + })} + +
+
+
+ +
-
- )} - /> + ))} +
+ )}
@@ -920,39 +678,589 @@ function ProviderFormDialog({ {isSubmitting || isLoading ? ( ) : ( - m.save_configuration() + m.add_provider() )} )} /> - - - - - {m.are_you_absolutely_sure()} - - {m.delete_provider_confirmation({ name: initialValues?.name ?? '' })} - - - - setIsDeleteDialogOpen(false)}> - {m.cancel()} - - { - onDelete?.() - setIsDeleteDialogOpen(false) + {/* Sub-dialog for adding/editing a model */} + {(isAddModelOpen || editingModelIndex !== null) && ( + { + setIsAddModelOpen(false) + setEditingModelIndex(null) + }} + onSubmit={handleSaveModel} + title={editingModelIndex !== null ? m.edit_model() : m.add_model()} + initialValues={editingModelIndex !== null ? initialModels[editingModelIndex] : null} + defaultApi={form.getFieldValue('config.api') as string} + existingModelIds={initialModels + .filter((_, i) => i !== editingModelIndex) + .map((m) => m.modelId)} + /> + )} + + + ) +} + +// --------------------------------------------------------------------------- +// Edit Provider Dialog (Tabs: General Settings & Models) +// --------------------------------------------------------------------------- + +interface EditProviderDialogProps { + isOpen: boolean + onClose: () => void + provider: Provider + teamId: string + existingProviderNames: string[] +} + +function EditProviderDialog({ + isOpen, + onClose, + provider, + teamId, + existingProviderNames, +}: EditProviderDialogProps) { + const queryClient = useQueryClient() + const [activeTab, setActiveTab] = useState<'general' | 'models'>('general') + const [modelsSearchQuery, setModelsSearchQuery] = useState('') + + // Sub-dialogs state + const [isAddModelOpen, setIsAddModelOpen] = useState(false) + const [editingModel, setEditingModel] = useState(null) + const [modelToDelete, setModelToDelete] = useState(null) + + // Fetch models for this provider + const { data: models = [], isLoading: isModelsLoading } = useQuery({ + queryKey: ['teams', teamId, 'providers', provider.id, 'models'], + queryFn: async () => { + const res = await client.api.providers[':id'].models.$get({ + param: { id: provider.id }, + }) + if (!res.ok) throw new Error('Failed to fetch models') + return await res.json() + }, + enabled: isOpen, + }) + + // Mutations + const updateProviderMutation = useMutation({ + mutationFn: async (values: { name: string; config: z.infer }) => { + const res = await client.api.providers[':id'].$put({ + param: { id: provider.id }, + json: { + name: values.name, + config: values.config, + }, + }) + if (!res.ok) throw new Error('Failed to update provider') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] }) + toast.success(m.provider_updated_successfully()) + }, + onError: (error) => { + toast.error(m.error_message({ message: error.message })) + }, + }) + + const createModelMutation = useMutation({ + mutationFn: async (values: ModelFormValues) => { + const res = await client.api.providers[':id'].models.$post({ + param: { id: provider.id }, + json: values, + }) + if (!res.ok) throw new Error('Failed to create model') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: ['teams', teamId, 'providers', provider.id, 'models'], + }) + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] }) + setIsAddModelOpen(false) + toast.success(m.model_created_successfully()) + }, + onError: (error) => { + toast.error(m.error_message({ message: error.message })) + }, + }) + + const updateModelMutation = useMutation({ + mutationFn: async ({ modelDbId, values }: { modelDbId: string; values: ModelFormValues }) => { + const res = await client.api.providers[':id'].models[':modelDbId'].$put({ + param: { id: provider.id, modelDbId }, + json: values, + }) + if (!res.ok) throw new Error('Failed to update model') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: ['teams', teamId, 'providers', provider.id, 'models'], + }) + setEditingModel(null) + toast.success(m.model_updated_successfully()) + }, + onError: (error) => { + toast.error(m.error_message({ message: error.message })) + }, + }) + + const deleteModelMutation = useMutation({ + mutationFn: async (modelDbId: string) => { + const res = await client.api.providers[':id'].models[':modelDbId'].$delete({ + param: { id: provider.id, modelDbId }, + }) + if (!res.ok) throw new Error('Failed to delete model') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: ['teams', teamId, 'providers', provider.id, 'models'], + }) + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] }) + setModelToDelete(null) + toast.success(m.model_deleted_successfully()) + }, + onError: (error) => { + toast.error(m.error_message({ message: error.message })) + }, + }) + + // General Settings Form + const generalSchema = useMemo(() => { + return z.object({ + name: z + .string() + .min(1, m.provider_name_is_required()) + .refine( + (name) => { + if (provider.name === name) return true + return !existingProviderNames.includes(name) + }, + { message: m.provider_name_must_be_unique() }, + ), + config: providerConfigSchema, + }) + }, [existingProviderNames, provider.name]) + + const form = useForm({ + defaultValues: { + name: provider.name, + config: provider.config, + } as z.input, + validators: { + onSubmit: generalSchema, + }, + onSubmit: async ({ value }) => { + updateProviderMutation.mutate({ + name: value.name, + config: value.config as z.infer, + }) + }, + }) + + useEffect(() => { + if (isOpen) { + form.reset() + setActiveTab('general') + setModelsSearchQuery('') + } + }, [isOpen, form]) + + const mapErrors = (errors: unknown[]) => { + return errors.map((e) => { + if (typeof e === 'string') return { message: e } + if (e && typeof e === 'object' && 'message' in e) { + return { message: String(e.message) } + } + return { message: String(e || '') } + }) + } + + // Filtered models + const filteredModels = useMemo(() => { + if (!modelsSearchQuery.trim()) return models + const query = modelsSearchQuery.toLowerCase() + return models.filter( + (m) => m.modelId.toLowerCase().includes(query) || m.name?.toLowerCase().includes(query), + ) + }, [models, modelsSearchQuery]) + + return ( + + + + {m.edit_item({ name: provider.name })} + {m.configure_provider_description()} + + + setActiveTab(val as 'general' | 'models')} + className="flex-1 flex flex-col min-h-0" + > +
+ + {m.general_settings()} + + {m.models()} + + {models.length} + + + +
+ + {/* Tab 1: General Settings */} + +
{ + e.preventDefault() + e.stopPropagation() + form.handleSubmit() }} + className="flex-1 flex flex-col min-h-0" > - {m.delete()} - - - - +
+ +
+
+ { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + {m.provider_name()} + field.handleChange(e.target.value)} + placeholder={m.provider_name_placeholder()} + aria-invalid={isInvalid} + /> + {isInvalid && ( + + )} + + ) + }} + /> + + { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.global_api_protocol()} + + + {isInvalid && ( + + )} + + ) + }} + /> + +
+ { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + + {m.base_url_optional()} + + field.handleChange(e.target.value)} + placeholder="https://api.openai.com/v1" + aria-invalid={isInvalid} + /> + {m.override_default_endpoint()} + {isInvalid && ( + + )} + + ) + }} + /> +
+ +
+ { + const isInvalid = + !!field.state.meta.errors.length && field.state.meta.isTouched + return ( + + {m.api_key()} + field.handleChange(e.target.value)} + placeholder={m.api_key_placeholder()} + aria-invalid={isInvalid} + /> + + {m.api_key_description()} + + {isInvalid && ( + + )} + + ) + }} + /> +
+
+
+
+
+ + + + [state.canSubmit, state.isSubmitting]} + children={([canSubmit, isSubmitting]) => ( + + )} + /> + +
+
+ + {/* Tab 2: Models Management */} + + {/* Search and Add Header */} +
+
+ + setModelsSearchQuery(e.target.value)} + className="pl-9 h-9" + /> +
+ + +
+ + {/* Models List */} +
+ + {isModelsLoading ? ( +
+ +
+ ) : filteredModels.length === 0 ? ( +
+ {m.no_models_found()} +
+ ) : ( +
+ {filteredModels.map((model) => ( +
setEditingModel(model)} + > +
+
+ + {model.name || model.modelId} + + + {model.modelId} + + {model.config?.reasoning && ( + + {m.reasoning_support()} + + )} +
+
+ + {model.config?.contextWindow?.toLocaleString()} {m.tokens()} + + · + + {m.max_tokens_label({ + count: model.config?.maxTokens?.toLocaleString() ?? '0', + })} + + · + + {m.cost_per_million({ + input: model.config?.cost?.input ?? 0, + output: model.config?.cost?.output ?? 0, + })} + +
+
+ +
+ +
+
+ ))} +
+ )} +
+
+
+
+ + {/* Sub-dialog for adding a new model */} + {isAddModelOpen && ( + setIsAddModelOpen(false)} + onSubmit={(values) => createModelMutation.mutate(values)} + title={m.add_model()} + isLoading={createModelMutation.isPending} + defaultApi={provider.config.api} + existingModelIds={models.map((m) => m.modelId)} + /> + )} + + {/* Sub-dialog for editing an existing model */} + {editingModel && ( + setEditingModel(null)} + onSubmit={(values) => + updateModelMutation.mutate({ modelDbId: editingModel.id, values }) + } + title={m.edit_model()} + isLoading={updateModelMutation.isPending} + initialValues={{ + modelId: editingModel.modelId, + name: editingModel.name, + config: editingModel.config, + }} + defaultApi={provider.config.api} + existingModelIds={models.filter((m) => m.id !== editingModel.id).map((m) => m.modelId)} + /> + )} + + {/* Alert Dialog for confirming model deletion */} + !open && setModelToDelete(null)} + > + + + {m.are_you_absolutely_sure()} + + {m.delete_model_confirmation({ + name: modelToDelete?.name || modelToDelete?.modelId || '', + })} + + + + setModelToDelete(null)}> + {m.cancel()} + + { + if (modelToDelete) { + deleteModelMutation.mutate(modelToDelete.id) + } + }} + > + {deleteModelMutation.isPending ? ( + + ) : ( + + )} + {m.delete()} + + + + +
) } diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 555a59f3..5d085ced 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -312,6 +312,7 @@ "configured_ai_providers": "Configured AI Providers", "add_provider": "Add Provider", "search_providers_placeholder": "Search providers...", + "no_providers_found": "No providers found", "built_in": "Built-in", "models_count": "Models", "n_models_count": "{count} Models", @@ -340,6 +341,20 @@ "api_key_description": "You can provide a literal value (e.g. sk-...) or an Environment variable name (e.g. MY_API_KEY).", "models_configuration": "Models Configuration", "add_model": "Add Model", + "edit_model": "Edit Model", + "delete_model": "Delete Model", + "delete_model_confirmation": "This action cannot be undone. This will permanently delete the model \"{name}\".", + "model_created_successfully": "Model created successfully", + "model_updated_successfully": "Model updated successfully", + "model_deleted_successfully": "Model deleted successfully", + "models": "Models", + "search_models_placeholder": "Search models by ID or name...", + "no_models_found": "No models found", + "page_info": "Page {current} of {total}", + "previous": "Previous", + "next": "Next", + "pricing": "Pricing ($ per 1M tokens)", + "parameters": "Parameters", "model_id": "Model ID", "display_name_optional": "Display Name (Optional)", "reasoning_support": "Reasoning Support", @@ -347,8 +362,16 @@ "max_output_tokens": "Max Output Tokens", "input_cost_1m": "Input Cost (1M)", "output_cost_1m": "Output Cost (1M)", + "tokens": "tokens", + "cache_read_cost_1m": "Cache Read Cost (1M)", + "cache_write_cost_1m": "Cache Write Cost (1M)", "save_configuration": "Save Configuration", "at_least_one_model_required": "At least one model is required", + "model_id_already_exists": "Model ID already exists for this provider", + "model_id_placeholder": "e.g., gpt-4o, claude-3-5-sonnet-20241022", + "model_name_placeholder": "e.g., GPT-4o", + "cost_per_million": "${input}/1M in · ${output}/1M out", + "max_tokens_label": "max {count}", "provider": "Provider", "model": "Model", "select_provider": "Select Provider", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index fbfd10e1..10d507d6 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -312,6 +312,7 @@ "configured_ai_providers": "已配置的 AI 提供商", "add_provider": "添加提供商", "search_providers_placeholder": "搜索提供商...", + "no_providers_found": "未找到提供商", "built_in": "内置", "models_count": "模型", "n_models_count": "{count} 个模型", @@ -340,6 +341,20 @@ "api_key_description": "您可以提供一个字面值(例如 sk-...)或环境变量名称(例如 MY_API_KEY)。", "models_configuration": "模型配置", "add_model": "添加模型", + "edit_model": "编辑模型", + "delete_model": "删除模型", + "delete_model_confirmation": "此操作无法撤销。这将永久删除模型 \"{name}\"。", + "model_created_successfully": "模型创建成功", + "model_updated_successfully": "模型更新成功", + "model_deleted_successfully": "模型删除成功", + "models": "模型列表", + "search_models_placeholder": "按 ID 或名称搜索模型...", + "no_models_found": "未找到模型", + "page_info": "第 {current} 页,共 {total} 页", + "previous": "上一页", + "next": "下一页", + "pricing": "计费(每百万令牌美元)", + "parameters": "参数", "model_id": "模型 ID", "display_name_optional": "显示名称(可选)", "reasoning_support": "推理支持", @@ -347,8 +362,16 @@ "max_output_tokens": "最大输出令牌数", "input_cost_1m": "输入成本(每百万)", "output_cost_1m": "输出成本(每百万)", + "tokens": "令牌", + "cache_read_cost_1m": "缓存读取成本(每百万)", + "cache_write_cost_1m": "缓存写入成本(每百万)", "save_configuration": "保存配置", "at_least_one_model_required": "至少需要一个模型", + "model_id_already_exists": "此提供商已存在该模型 ID", + "model_id_placeholder": "例如:gpt-4o, claude-3-5-sonnet-20241022", + "model_name_placeholder": "例如:GPT-4o", + "cost_per_million": "${input}/1M 输入 · ${output}/1M 输出", + "max_tokens_label": "最大 {count}", "provider": "提供商", "model": "模型", "select_provider": "选择提供商", diff --git a/packages/webui/paraglide/messages/_index.d.ts b/packages/webui/paraglide/messages/_index.d.ts index fc07b45e..edbfd57d 100644 --- a/packages/webui/paraglide/messages/_index.d.ts +++ b/packages/webui/paraglide/messages/_index.d.ts @@ -296,6 +296,7 @@ export * from "./providers_description.js"; export * from "./configured_ai_providers.js"; export * from "./add_provider.js"; export * from "./search_providers_placeholder.js"; +export * from "./no_providers_found.js"; export * from "./built_in.js"; export * from "./models_count.js"; export * from "./n_models_count.js"; @@ -324,6 +325,20 @@ export * from "./api_key_placeholder.js"; export * from "./api_key_description.js"; export * from "./models_configuration.js"; export * from "./add_model.js"; +export * from "./edit_model.js"; +export * from "./delete_model.js"; +export * from "./delete_model_confirmation.js"; +export * from "./model_created_successfully.js"; +export * from "./model_updated_successfully.js"; +export * from "./model_deleted_successfully.js"; +export * from "./models.js"; +export * from "./search_models_placeholder.js"; +export * from "./no_models_found.js"; +export * from "./page_info.js"; +export * from "./previous.js"; +export * from "./next.js"; +export * from "./pricing.js"; +export * from "./parameters.js"; export * from "./model_id.js"; export * from "./display_name_optional.js"; export * from "./reasoning_support.js"; @@ -331,8 +346,16 @@ export * from "./context_window_tokens.js"; export * from "./max_output_tokens.js"; export * from "./input_cost_1m.js"; export * from "./output_cost_1m.js"; +export * from "./tokens.js"; +export * from "./cache_read_cost_1m.js"; +export * from "./cache_write_cost_1m.js"; export * from "./save_configuration.js"; export * from "./at_least_one_model_required.js"; +export * from "./model_id_already_exists.js"; +export * from "./model_id_placeholder.js"; +export * from "./model_name_placeholder.js"; +export * from "./cost_per_million.js"; +export * from "./max_tokens_label.js"; export * from "./provider.js"; export * from "./model.js"; export * from "./select_provider.js"; diff --git a/packages/webui/paraglide/messages/_index.js b/packages/webui/paraglide/messages/_index.js index a70afb54..c6f1a0e5 100644 --- a/packages/webui/paraglide/messages/_index.js +++ b/packages/webui/paraglide/messages/_index.js @@ -298,6 +298,7 @@ export * from './providers_description.js' export * from './configured_ai_providers.js' export * from './add_provider.js' export * from './search_providers_placeholder.js' +export * from './no_providers_found.js' export * from './built_in.js' export * from './models_count.js' export * from './n_models_count.js' @@ -326,6 +327,20 @@ export * from './api_key_placeholder.js' export * from './api_key_description.js' export * from './models_configuration.js' export * from './add_model.js' +export * from './edit_model.js' +export * from './delete_model.js' +export * from './delete_model_confirmation.js' +export * from './model_created_successfully.js' +export * from './model_updated_successfully.js' +export * from './model_deleted_successfully.js' +export * from './models.js' +export * from './search_models_placeholder.js' +export * from './no_models_found.js' +export * from './page_info.js' +export * from './previous.js' +export * from './next.js' +export * from './pricing.js' +export * from './parameters.js' export * from './model_id.js' export * from './display_name_optional.js' export * from './reasoning_support.js' @@ -333,8 +348,16 @@ export * from './context_window_tokens.js' export * from './max_output_tokens.js' export * from './input_cost_1m.js' export * from './output_cost_1m.js' +export * from './tokens.js' +export * from './cache_read_cost_1m.js' +export * from './cache_write_cost_1m.js' export * from './save_configuration.js' export * from './at_least_one_model_required.js' +export * from './model_id_already_exists.js' +export * from './model_id_placeholder.js' +export * from './model_name_placeholder.js' +export * from './cost_per_million.js' +export * from './max_tokens_label.js' export * from './provider.js' export * from './model.js' export * from './select_provider.js' diff --git a/packages/webui/paraglide/messages/cache_read_cost_1m.d.ts b/packages/webui/paraglide/messages/cache_read_cost_1m.d.ts new file mode 100644 index 00000000..dd07b858 --- /dev/null +++ b/packages/webui/paraglide/messages/cache_read_cost_1m.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Cache Read Cost (1M)" | +* +* @param {Cache_Read_Cost_1mInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const cache_read_cost_1m: ((inputs?: Cache_Read_Cost_1mInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Cache_Read_Cost_1mInputs = {}; diff --git a/packages/webui/paraglide/messages/cache_read_cost_1m.js b/packages/webui/paraglide/messages/cache_read_cost_1m.js new file mode 100644 index 00000000..dbcbdf25 --- /dev/null +++ b/packages/webui/paraglide/messages/cache_read_cost_1m.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Cache_Read_Cost_1mInputs */ + +const en_cache_read_cost_1m = /** @type {(inputs: Cache_Read_Cost_1mInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Cache Read Cost (1M)`) +}; + +const zh_cache_read_cost_1m = /** @type {(inputs: Cache_Read_Cost_1mInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`缓存读取成本(每百万)`) +}; + +/** +* | output | +* | --- | +* | "Cache Read Cost (1M)" | +* +* @param {Cache_Read_Cost_1mInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const cache_read_cost_1m = /** @type {((inputs?: Cache_Read_Cost_1mInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_cache_read_cost_1m(inputs) + return zh_cache_read_cost_1m(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/cache_write_cost_1m.d.ts b/packages/webui/paraglide/messages/cache_write_cost_1m.d.ts new file mode 100644 index 00000000..6efd0eb2 --- /dev/null +++ b/packages/webui/paraglide/messages/cache_write_cost_1m.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Cache Write Cost (1M)" | +* +* @param {Cache_Write_Cost_1mInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const cache_write_cost_1m: ((inputs?: Cache_Write_Cost_1mInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Cache_Write_Cost_1mInputs = {}; diff --git a/packages/webui/paraglide/messages/cache_write_cost_1m.js b/packages/webui/paraglide/messages/cache_write_cost_1m.js new file mode 100644 index 00000000..00afdfa4 --- /dev/null +++ b/packages/webui/paraglide/messages/cache_write_cost_1m.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Cache_Write_Cost_1mInputs */ + +const en_cache_write_cost_1m = /** @type {(inputs: Cache_Write_Cost_1mInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Cache Write Cost (1M)`) +}; + +const zh_cache_write_cost_1m = /** @type {(inputs: Cache_Write_Cost_1mInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`缓存写入成本(每百万)`) +}; + +/** +* | output | +* | --- | +* | "Cache Write Cost (1M)" | +* +* @param {Cache_Write_Cost_1mInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const cache_write_cost_1m = /** @type {((inputs?: Cache_Write_Cost_1mInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_cache_write_cost_1m(inputs) + return zh_cache_write_cost_1m(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/cost_per_million.d.ts b/packages/webui/paraglide/messages/cost_per_million.d.ts new file mode 100644 index 00000000..14cb7193 --- /dev/null +++ b/packages/webui/paraglide/messages/cost_per_million.d.ts @@ -0,0 +1,19 @@ +/** +* | output | +* | --- | +* | "${input}/1M in · ${output}/1M out" | +* +* @param {Cost_Per_MillionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const cost_per_million: ((inputs: Cost_Per_MillionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Cost_Per_MillionInputs = { + input: NonNullable; + output: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/cost_per_million.js b/packages/webui/paraglide/messages/cost_per_million.js new file mode 100644 index 00000000..103d328d --- /dev/null +++ b/packages/webui/paraglide/messages/cost_per_million.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ input: NonNullable, output: NonNullable }} Cost_Per_MillionInputs */ + +const en_cost_per_million = /** @type {(inputs: Cost_Per_MillionInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`$${i?.input}/1M in · $${i?.output}/1M out`) +}; + +const zh_cost_per_million = /** @type {(inputs: Cost_Per_MillionInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`$${i?.input}/1M 输入 · $${i?.output}/1M 输出`) +}; + +/** +* | output | +* | --- | +* | "${input}/1M in · ${output}/1M out" | +* +* @param {Cost_Per_MillionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const cost_per_million = /** @type {((inputs: Cost_Per_MillionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_cost_per_million(inputs) + return zh_cost_per_million(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/delete_model.d.ts b/packages/webui/paraglide/messages/delete_model.d.ts new file mode 100644 index 00000000..ef11e1d3 --- /dev/null +++ b/packages/webui/paraglide/messages/delete_model.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Delete Model" | +* +* @param {Delete_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const delete_model: ((inputs?: Delete_ModelInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Delete_ModelInputs = {}; diff --git a/packages/webui/paraglide/messages/delete_model.js b/packages/webui/paraglide/messages/delete_model.js new file mode 100644 index 00000000..db9e7ede --- /dev/null +++ b/packages/webui/paraglide/messages/delete_model.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Delete_ModelInputs */ + +const en_delete_model = /** @type {(inputs: Delete_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Delete Model`) +}; + +const zh_delete_model = /** @type {(inputs: Delete_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`删除模型`) +}; + +/** +* | output | +* | --- | +* | "Delete Model" | +* +* @param {Delete_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const delete_model = /** @type {((inputs?: Delete_ModelInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_delete_model(inputs) + return zh_delete_model(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/delete_model_confirmation.d.ts b/packages/webui/paraglide/messages/delete_model_confirmation.d.ts new file mode 100644 index 00000000..b834658b --- /dev/null +++ b/packages/webui/paraglide/messages/delete_model_confirmation.d.ts @@ -0,0 +1,18 @@ +/** +* | output | +* | --- | +* | "This action cannot be undone. This will permanently delete the model \"{name}\"." | +* +* @param {Delete_Model_ConfirmationInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const delete_model_confirmation: ((inputs: Delete_Model_ConfirmationInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Delete_Model_ConfirmationInputs = { + name: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/delete_model_confirmation.js b/packages/webui/paraglide/messages/delete_model_confirmation.js new file mode 100644 index 00000000..75bb1738 --- /dev/null +++ b/packages/webui/paraglide/messages/delete_model_confirmation.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ name: NonNullable }} Delete_Model_ConfirmationInputs */ + +const en_delete_model_confirmation = /** @type {(inputs: Delete_Model_ConfirmationInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`This action cannot be undone. This will permanently delete the model "${i?.name}".`) +}; + +const zh_delete_model_confirmation = /** @type {(inputs: Delete_Model_ConfirmationInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`此操作无法撤销。这将永久删除模型 "${i?.name}"。`) +}; + +/** +* | output | +* | --- | +* | "This action cannot be undone. This will permanently delete the model \"{name}\"." | +* +* @param {Delete_Model_ConfirmationInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const delete_model_confirmation = /** @type {((inputs: Delete_Model_ConfirmationInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_delete_model_confirmation(inputs) + return zh_delete_model_confirmation(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/edit_model.d.ts b/packages/webui/paraglide/messages/edit_model.d.ts new file mode 100644 index 00000000..3a3c2753 --- /dev/null +++ b/packages/webui/paraglide/messages/edit_model.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Edit Model" | +* +* @param {Edit_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const edit_model: ((inputs?: Edit_ModelInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Edit_ModelInputs = {}; diff --git a/packages/webui/paraglide/messages/edit_model.js b/packages/webui/paraglide/messages/edit_model.js new file mode 100644 index 00000000..e51cd0f5 --- /dev/null +++ b/packages/webui/paraglide/messages/edit_model.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Edit_ModelInputs */ + +const en_edit_model = /** @type {(inputs: Edit_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Edit Model`) +}; + +const zh_edit_model = /** @type {(inputs: Edit_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`编辑模型`) +}; + +/** +* | output | +* | --- | +* | "Edit Model" | +* +* @param {Edit_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const edit_model = /** @type {((inputs?: Edit_ModelInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_edit_model(inputs) + return zh_edit_model(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/max_tokens_label.d.ts b/packages/webui/paraglide/messages/max_tokens_label.d.ts new file mode 100644 index 00000000..eade12d0 --- /dev/null +++ b/packages/webui/paraglide/messages/max_tokens_label.d.ts @@ -0,0 +1,18 @@ +/** +* | output | +* | --- | +* | "max {count}" | +* +* @param {Max_Tokens_LabelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const max_tokens_label: ((inputs: Max_Tokens_LabelInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Max_Tokens_LabelInputs = { + count: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/max_tokens_label.js b/packages/webui/paraglide/messages/max_tokens_label.js new file mode 100644 index 00000000..5da9e2dd --- /dev/null +++ b/packages/webui/paraglide/messages/max_tokens_label.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ count: NonNullable }} Max_Tokens_LabelInputs */ + +const en_max_tokens_label = /** @type {(inputs: Max_Tokens_LabelInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`max ${i?.count}`) +}; + +const zh_max_tokens_label = /** @type {(inputs: Max_Tokens_LabelInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`最大 ${i?.count}`) +}; + +/** +* | output | +* | --- | +* | "max {count}" | +* +* @param {Max_Tokens_LabelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const max_tokens_label = /** @type {((inputs: Max_Tokens_LabelInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_max_tokens_label(inputs) + return zh_max_tokens_label(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_created_successfully.d.ts b/packages/webui/paraglide/messages/model_created_successfully.d.ts new file mode 100644 index 00000000..9ac9a049 --- /dev/null +++ b/packages/webui/paraglide/messages/model_created_successfully.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model created successfully" | +* +* @param {Model_Created_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_created_successfully: ((inputs?: Model_Created_SuccessfullyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Created_SuccessfullyInputs = {}; diff --git a/packages/webui/paraglide/messages/model_created_successfully.js b/packages/webui/paraglide/messages/model_created_successfully.js new file mode 100644 index 00000000..fa1eee58 --- /dev/null +++ b/packages/webui/paraglide/messages/model_created_successfully.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Created_SuccessfullyInputs */ + +const en_model_created_successfully = /** @type {(inputs: Model_Created_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model created successfully`) +}; + +const zh_model_created_successfully = /** @type {(inputs: Model_Created_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型创建成功`) +}; + +/** +* | output | +* | --- | +* | "Model created successfully" | +* +* @param {Model_Created_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_created_successfully = /** @type {((inputs?: Model_Created_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_created_successfully(inputs) + return zh_model_created_successfully(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_deleted_successfully.d.ts b/packages/webui/paraglide/messages/model_deleted_successfully.d.ts new file mode 100644 index 00000000..1c197084 --- /dev/null +++ b/packages/webui/paraglide/messages/model_deleted_successfully.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model deleted successfully" | +* +* @param {Model_Deleted_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_deleted_successfully: ((inputs?: Model_Deleted_SuccessfullyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Deleted_SuccessfullyInputs = {}; diff --git a/packages/webui/paraglide/messages/model_deleted_successfully.js b/packages/webui/paraglide/messages/model_deleted_successfully.js new file mode 100644 index 00000000..9a555d45 --- /dev/null +++ b/packages/webui/paraglide/messages/model_deleted_successfully.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Deleted_SuccessfullyInputs */ + +const en_model_deleted_successfully = /** @type {(inputs: Model_Deleted_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model deleted successfully`) +}; + +const zh_model_deleted_successfully = /** @type {(inputs: Model_Deleted_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型删除成功`) +}; + +/** +* | output | +* | --- | +* | "Model deleted successfully" | +* +* @param {Model_Deleted_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_deleted_successfully = /** @type {((inputs?: Model_Deleted_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_deleted_successfully(inputs) + return zh_model_deleted_successfully(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_id_already_exists.d.ts b/packages/webui/paraglide/messages/model_id_already_exists.d.ts new file mode 100644 index 00000000..5010cde6 --- /dev/null +++ b/packages/webui/paraglide/messages/model_id_already_exists.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model ID already exists for this provider" | +* +* @param {Model_Id_Already_ExistsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_id_already_exists: ((inputs?: Model_Id_Already_ExistsInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Id_Already_ExistsInputs = {}; diff --git a/packages/webui/paraglide/messages/model_id_already_exists.js b/packages/webui/paraglide/messages/model_id_already_exists.js new file mode 100644 index 00000000..622b9939 --- /dev/null +++ b/packages/webui/paraglide/messages/model_id_already_exists.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Id_Already_ExistsInputs */ + +const en_model_id_already_exists = /** @type {(inputs: Model_Id_Already_ExistsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model ID already exists for this provider`) +}; + +const zh_model_id_already_exists = /** @type {(inputs: Model_Id_Already_ExistsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`此提供商已存在该模型 ID`) +}; + +/** +* | output | +* | --- | +* | "Model ID already exists for this provider" | +* +* @param {Model_Id_Already_ExistsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_id_already_exists = /** @type {((inputs?: Model_Id_Already_ExistsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_id_already_exists(inputs) + return zh_model_id_already_exists(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_id_placeholder.d.ts b/packages/webui/paraglide/messages/model_id_placeholder.d.ts new file mode 100644 index 00000000..3b85d72e --- /dev/null +++ b/packages/webui/paraglide/messages/model_id_placeholder.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "e.g., gpt-4o, claude-3-5-sonnet-20241022" | +* +* @param {Model_Id_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_id_placeholder: ((inputs?: Model_Id_PlaceholderInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Id_PlaceholderInputs = {}; diff --git a/packages/webui/paraglide/messages/model_id_placeholder.js b/packages/webui/paraglide/messages/model_id_placeholder.js new file mode 100644 index 00000000..8a6a171a --- /dev/null +++ b/packages/webui/paraglide/messages/model_id_placeholder.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Id_PlaceholderInputs */ + +const en_model_id_placeholder = /** @type {(inputs: Model_Id_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`e.g., gpt-4o, claude-3-5-sonnet-20241022`) +}; + +const zh_model_id_placeholder = /** @type {(inputs: Model_Id_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`例如:gpt-4o, claude-3-5-sonnet-20241022`) +}; + +/** +* | output | +* | --- | +* | "e.g., gpt-4o, claude-3-5-sonnet-20241022" | +* +* @param {Model_Id_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_id_placeholder = /** @type {((inputs?: Model_Id_PlaceholderInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_id_placeholder(inputs) + return zh_model_id_placeholder(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_name_placeholder.d.ts b/packages/webui/paraglide/messages/model_name_placeholder.d.ts new file mode 100644 index 00000000..f895fd82 --- /dev/null +++ b/packages/webui/paraglide/messages/model_name_placeholder.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "e.g., GPT-4o" | +* +* @param {Model_Name_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_name_placeholder: ((inputs?: Model_Name_PlaceholderInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Name_PlaceholderInputs = {}; diff --git a/packages/webui/paraglide/messages/model_name_placeholder.js b/packages/webui/paraglide/messages/model_name_placeholder.js new file mode 100644 index 00000000..f1959363 --- /dev/null +++ b/packages/webui/paraglide/messages/model_name_placeholder.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Name_PlaceholderInputs */ + +const en_model_name_placeholder = /** @type {(inputs: Model_Name_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`e.g., GPT-4o`) +}; + +const zh_model_name_placeholder = /** @type {(inputs: Model_Name_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`例如:GPT-4o`) +}; + +/** +* | output | +* | --- | +* | "e.g., GPT-4o" | +* +* @param {Model_Name_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_name_placeholder = /** @type {((inputs?: Model_Name_PlaceholderInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_name_placeholder(inputs) + return zh_model_name_placeholder(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_updated_successfully.d.ts b/packages/webui/paraglide/messages/model_updated_successfully.d.ts new file mode 100644 index 00000000..31d25128 --- /dev/null +++ b/packages/webui/paraglide/messages/model_updated_successfully.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model updated successfully" | +* +* @param {Model_Updated_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_updated_successfully: ((inputs?: Model_Updated_SuccessfullyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Updated_SuccessfullyInputs = {}; diff --git a/packages/webui/paraglide/messages/model_updated_successfully.js b/packages/webui/paraglide/messages/model_updated_successfully.js new file mode 100644 index 00000000..428cef4e --- /dev/null +++ b/packages/webui/paraglide/messages/model_updated_successfully.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Updated_SuccessfullyInputs */ + +const en_model_updated_successfully = /** @type {(inputs: Model_Updated_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model updated successfully`) +}; + +const zh_model_updated_successfully = /** @type {(inputs: Model_Updated_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型更新成功`) +}; + +/** +* | output | +* | --- | +* | "Model updated successfully" | +* +* @param {Model_Updated_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_updated_successfully = /** @type {((inputs?: Model_Updated_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_updated_successfully(inputs) + return zh_model_updated_successfully(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/models.d.ts b/packages/webui/paraglide/messages/models.d.ts new file mode 100644 index 00000000..936a716f --- /dev/null +++ b/packages/webui/paraglide/messages/models.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Models" | +* +* @param {ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const models: ((inputs?: ModelsInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type ModelsInputs = {}; diff --git a/packages/webui/paraglide/messages/models.js b/packages/webui/paraglide/messages/models.js new file mode 100644 index 00000000..15f4a61d --- /dev/null +++ b/packages/webui/paraglide/messages/models.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} ModelsInputs */ + +const en_models = /** @type {(inputs: ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Models`) +}; + +const zh_models = /** @type {(inputs: ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型列表`) +}; + +/** +* | output | +* | --- | +* | "Models" | +* +* @param {ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const models = /** @type {((inputs?: ModelsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_models(inputs) + return zh_models(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/next.d.ts b/packages/webui/paraglide/messages/next.d.ts new file mode 100644 index 00000000..3ab2872d --- /dev/null +++ b/packages/webui/paraglide/messages/next.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Next" | +* +* @param {NextInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const next: ((inputs?: NextInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type NextInputs = {}; diff --git a/packages/webui/paraglide/messages/next.js b/packages/webui/paraglide/messages/next.js new file mode 100644 index 00000000..241059ee --- /dev/null +++ b/packages/webui/paraglide/messages/next.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} NextInputs */ + +const en_next = /** @type {(inputs: NextInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Next`) +}; + +const zh_next = /** @type {(inputs: NextInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`下一页`) +}; + +/** +* | output | +* | --- | +* | "Next" | +* +* @param {NextInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const next = /** @type {((inputs?: NextInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_next(inputs) + return zh_next(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/no_models_found.d.ts b/packages/webui/paraglide/messages/no_models_found.d.ts new file mode 100644 index 00000000..d18957a0 --- /dev/null +++ b/packages/webui/paraglide/messages/no_models_found.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "No models found" | +* +* @param {No_Models_FoundInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const no_models_found: ((inputs?: No_Models_FoundInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type No_Models_FoundInputs = {}; diff --git a/packages/webui/paraglide/messages/no_models_found.js b/packages/webui/paraglide/messages/no_models_found.js new file mode 100644 index 00000000..900bb965 --- /dev/null +++ b/packages/webui/paraglide/messages/no_models_found.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} No_Models_FoundInputs */ + +const en_no_models_found = /** @type {(inputs: No_Models_FoundInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`No models found`) +}; + +const zh_no_models_found = /** @type {(inputs: No_Models_FoundInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`未找到模型`) +}; + +/** +* | output | +* | --- | +* | "No models found" | +* +* @param {No_Models_FoundInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const no_models_found = /** @type {((inputs?: No_Models_FoundInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_no_models_found(inputs) + return zh_no_models_found(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/no_providers_found.d.ts b/packages/webui/paraglide/messages/no_providers_found.d.ts new file mode 100644 index 00000000..88e8addc --- /dev/null +++ b/packages/webui/paraglide/messages/no_providers_found.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "No providers found" | +* +* @param {No_Providers_FoundInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const no_providers_found: ((inputs?: No_Providers_FoundInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type No_Providers_FoundInputs = {}; diff --git a/packages/webui/paraglide/messages/no_providers_found.js b/packages/webui/paraglide/messages/no_providers_found.js new file mode 100644 index 00000000..a8b5a137 --- /dev/null +++ b/packages/webui/paraglide/messages/no_providers_found.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} No_Providers_FoundInputs */ + +const en_no_providers_found = /** @type {(inputs: No_Providers_FoundInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`No providers found`) +}; + +const zh_no_providers_found = /** @type {(inputs: No_Providers_FoundInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`未找到提供商`) +}; + +/** +* | output | +* | --- | +* | "No providers found" | +* +* @param {No_Providers_FoundInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const no_providers_found = /** @type {((inputs?: No_Providers_FoundInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_no_providers_found(inputs) + return zh_no_providers_found(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/page_info.d.ts b/packages/webui/paraglide/messages/page_info.d.ts new file mode 100644 index 00000000..d0fdfd8d --- /dev/null +++ b/packages/webui/paraglide/messages/page_info.d.ts @@ -0,0 +1,19 @@ +/** +* | output | +* | --- | +* | "Page {current} of {total}" | +* +* @param {Page_InfoInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const page_info: ((inputs: Page_InfoInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Page_InfoInputs = { + current: NonNullable; + total: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/page_info.js b/packages/webui/paraglide/messages/page_info.js new file mode 100644 index 00000000..192062be --- /dev/null +++ b/packages/webui/paraglide/messages/page_info.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ current: NonNullable, total: NonNullable }} Page_InfoInputs */ + +const en_page_info = /** @type {(inputs: Page_InfoInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`Page ${i?.current} of ${i?.total}`) +}; + +const zh_page_info = /** @type {(inputs: Page_InfoInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`第 ${i?.current} 页,共 ${i?.total} 页`) +}; + +/** +* | output | +* | --- | +* | "Page {current} of {total}" | +* +* @param {Page_InfoInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const page_info = /** @type {((inputs: Page_InfoInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_page_info(inputs) + return zh_page_info(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/parameters.d.ts b/packages/webui/paraglide/messages/parameters.d.ts new file mode 100644 index 00000000..15ef6ebe --- /dev/null +++ b/packages/webui/paraglide/messages/parameters.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Parameters" | +* +* @param {ParametersInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const parameters: ((inputs?: ParametersInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type ParametersInputs = {}; diff --git a/packages/webui/paraglide/messages/parameters.js b/packages/webui/paraglide/messages/parameters.js new file mode 100644 index 00000000..a27edcbf --- /dev/null +++ b/packages/webui/paraglide/messages/parameters.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} ParametersInputs */ + +const en_parameters = /** @type {(inputs: ParametersInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Parameters`) +}; + +const zh_parameters = /** @type {(inputs: ParametersInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`参数`) +}; + +/** +* | output | +* | --- | +* | "Parameters" | +* +* @param {ParametersInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const parameters = /** @type {((inputs?: ParametersInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_parameters(inputs) + return zh_parameters(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/previous.d.ts b/packages/webui/paraglide/messages/previous.d.ts new file mode 100644 index 00000000..e2b8f229 --- /dev/null +++ b/packages/webui/paraglide/messages/previous.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Previous" | +* +* @param {PreviousInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const previous: ((inputs?: PreviousInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type PreviousInputs = {}; diff --git a/packages/webui/paraglide/messages/previous.js b/packages/webui/paraglide/messages/previous.js new file mode 100644 index 00000000..c992871f --- /dev/null +++ b/packages/webui/paraglide/messages/previous.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} PreviousInputs */ + +const en_previous = /** @type {(inputs: PreviousInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Previous`) +}; + +const zh_previous = /** @type {(inputs: PreviousInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`上一页`) +}; + +/** +* | output | +* | --- | +* | "Previous" | +* +* @param {PreviousInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const previous = /** @type {((inputs?: PreviousInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_previous(inputs) + return zh_previous(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/pricing.d.ts b/packages/webui/paraglide/messages/pricing.d.ts new file mode 100644 index 00000000..50c34509 --- /dev/null +++ b/packages/webui/paraglide/messages/pricing.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Pricing ($ per 1M tokens)" | +* +* @param {PricingInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const pricing: ((inputs?: PricingInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type PricingInputs = {}; diff --git a/packages/webui/paraglide/messages/pricing.js b/packages/webui/paraglide/messages/pricing.js new file mode 100644 index 00000000..b13a134b --- /dev/null +++ b/packages/webui/paraglide/messages/pricing.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} PricingInputs */ + +const en_pricing = /** @type {(inputs: PricingInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Pricing ($ per 1M tokens)`) +}; + +const zh_pricing = /** @type {(inputs: PricingInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`计费(每百万令牌美元)`) +}; + +/** +* | output | +* | --- | +* | "Pricing ($ per 1M tokens)" | +* +* @param {PricingInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const pricing = /** @type {((inputs?: PricingInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_pricing(inputs) + return zh_pricing(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/search_models_placeholder.d.ts b/packages/webui/paraglide/messages/search_models_placeholder.d.ts new file mode 100644 index 00000000..0813d479 --- /dev/null +++ b/packages/webui/paraglide/messages/search_models_placeholder.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Search models by ID or name..." | +* +* @param {Search_Models_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const search_models_placeholder: ((inputs?: Search_Models_PlaceholderInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Search_Models_PlaceholderInputs = {}; diff --git a/packages/webui/paraglide/messages/search_models_placeholder.js b/packages/webui/paraglide/messages/search_models_placeholder.js new file mode 100644 index 00000000..f4d8b7c5 --- /dev/null +++ b/packages/webui/paraglide/messages/search_models_placeholder.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Search_Models_PlaceholderInputs */ + +const en_search_models_placeholder = /** @type {(inputs: Search_Models_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Search models by ID or name...`) +}; + +const zh_search_models_placeholder = /** @type {(inputs: Search_Models_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`按 ID 或名称搜索模型...`) +}; + +/** +* | output | +* | --- | +* | "Search models by ID or name..." | +* +* @param {Search_Models_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const search_models_placeholder = /** @type {((inputs?: Search_Models_PlaceholderInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_search_models_placeholder(inputs) + return zh_search_models_placeholder(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/tokens.d.ts b/packages/webui/paraglide/messages/tokens.d.ts new file mode 100644 index 00000000..5762ff08 --- /dev/null +++ b/packages/webui/paraglide/messages/tokens.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "tokens" | +* +* @param {TokensInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const tokens: ((inputs?: TokensInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type TokensInputs = {}; diff --git a/packages/webui/paraglide/messages/tokens.js b/packages/webui/paraglide/messages/tokens.js new file mode 100644 index 00000000..6bacf63b --- /dev/null +++ b/packages/webui/paraglide/messages/tokens.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} TokensInputs */ + +const en_tokens = /** @type {(inputs: TokensInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`tokens`) +}; + +const zh_tokens = /** @type {(inputs: TokensInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`令牌`) +}; + +/** +* | output | +* | --- | +* | "tokens" | +* +* @param {TokensInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const tokens = /** @type {((inputs?: TokensInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_tokens(inputs) + return zh_tokens(inputs) +}); \ No newline at end of file diff --git a/packages/webui/routes/teams/$teamId/settings.lazy.tsx b/packages/webui/routes/teams/$teamId/settings.lazy.tsx index e0bbe212..3faf8728 100644 --- a/packages/webui/routes/teams/$teamId/settings.lazy.tsx +++ b/packages/webui/routes/teams/$teamId/settings.lazy.tsx @@ -58,10 +58,51 @@ type SettingsTab = | 'notifications' | 'developer' +const VALID_SETTINGS_TABS: readonly SettingsTab[] = [ + 'general', + 'transcode', + 'quotas', + 'skills', + 'mcp', + 'providers', + 'agents', + 'sandbox', + 'notifications', + 'developer', +] + +function getTabFromHash(): SettingsTab { + if (typeof window === 'undefined') return 'general' + const hash = window.location.hash.replace(/^#/, '') + return (VALID_SETTINGS_TABS as readonly string[]).includes(hash) + ? (hash as SettingsTab) + : 'general' +} + function TeamSettingsPage() { const { teamId } = Route.useParams() const queryClient = useQueryClient() - const [activeTab, setActiveTab] = useState('general') + const [activeTab, setActiveTabState] = useState(getTabFromHash) + + const handleTabChange = (tab: SettingsTab) => { + setActiveTabState(tab) + const newHash = tab === 'general' ? '' : `#${tab}` + if (window.location.hash !== newHash) { + window.history.replaceState( + null, + '', + window.location.pathname + window.location.search + newHash, + ) + } + } + + useEffect(() => { + const onHashChange = () => { + setActiveTabState(getTabFromHash()) + } + window.addEventListener('hashchange', onHashChange) + return () => window.removeEventListener('hashchange', onHashChange) + }, []) const [profileName, setProfileName] = useState('') const [isCropOpen, setIsCropOpen] = useState(false) const [cropImageSrc, setCropImageSrc] = useState(null) @@ -128,7 +169,7 @@ function TeamSettingsPage() { 'sandbox', ] if (me && me.role !== 'owner' && ownerOnlyTabs.includes(activeTab)) { - setActiveTab('general') + handleTabChange('general') } }, [me, activeTab]) @@ -295,7 +336,7 @@ function TeamSettingsPage() {