♻️ refactor(channels): rebuild channel create/edit drawer with modular sections and improved form UX

Restructure the default-theme channel create/edit experience to align with
classic frontend behavior, modern form UX patterns, and the project's Base UI
design system.

Channel editor architecture:
- Split the monolithic channel mutate drawer into focused section components
  (basic, API access, auth, models, advanced) with shared drawer layout
  primitives
- Extract submission, toast handling, and react-query cache invalidation into
  `useChannelMutateForm`
- Add a dedicated loading skeleton for channel detail fetch during edit mode
- Remove the top-level configuration summary block per UX feedback

Form validation and data handling:
- Strengthen `channel-form` Zod schema with JSON, model mapping, status code
  mapping, Codex credential, and Vertex AI key refinements
- Move type-specific conditional validation into `superRefine`
- Normalize base URL formatting and tighten model mapping value validation

Model mapping editor:
- Add Visual/JSON tabbed editing with inline JSON and duplicate-key feedback
- Improve accessibility for icon-only actions and add model suggestion datalists

MultiSelect component:
- Replace the custom cmdk-based implementation with Base UI Combobox chips
- Align focus, border, ring, disabled, and invalid states with standard Input
  styling via `ComboboxChips`
- Preserve existing API (`options`, `selected`, `onChange`, `allowCreate`,
  `createLabel`) for all current callers
- Support inline custom value creation, comma/newline batch input, searchable
  options, portal-based dropdown positioning, and chip removal

Models & groups UX:
- Integrate manual custom model entry directly into the model MultiSelect
- Remove the separate manual model input/button block
- Keep selected-model count and existing model-mapping guardrail behavior

i18n:
- Add and sync translation keys for new editor sections, validation messages,
  model mapping UI, and MultiSelect empty/create labels across en, zh, fr, ja,
  ru, and vi
- Remove obsolete keys tied to the deprecated summary and manual model entry UI

Affected areas:
- `web/default/src/features/channels/components/drawers/`
- `web/default/src/features/channels/hooks/use-channel-mutate-form.ts`
- `web/default/src/features/channels/lib/channel-form.ts`
- `web/default/src/features/channels/lib/model-mapping-validation.ts`
- `web/default/src/features/channels/components/model-mapping-editor.tsx`
- `web/default/src/components/multi-select.tsx`
- `web/default/src/i18n/locales/*.json`
This commit is contained in:
t0ng7u
2026-05-26 01:22:49 +08:00
parent 583da45296
commit 3d850d38b6
19 changed files with 3465 additions and 2478 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,78 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import { ChevronDown, Settings } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
type ChannelAdvancedSectionProps = {
children: ReactNode
open: boolean
onOpenChange: (open: boolean) => void
}
export function ChannelAdvancedSection(props: ChannelAdvancedSectionProps) {
const { t } = useTranslation()
return (
<Collapsible open={props.open} onOpenChange={props.onOpenChange}>
<CollapsibleTrigger
render={
<button
type='button'
className='hover:bg-muted/40 border-border/60 flex w-full items-center justify-between rounded-lg border px-3 py-3 text-left transition-colors'
aria-expanded={props.open}
/>
}
>
<div className='flex items-start gap-3'>
<span className='bg-muted text-muted-foreground flex size-8 shrink-0 items-center justify-center rounded-md'>
<Settings className='h-4 w-4' aria-hidden='true' />
</span>
<div className='flex flex-col gap-0.5'>
<div className='text-[13px] font-semibold'>
{t('Advanced Settings')}
</div>
<div className='text-muted-foreground text-xs'>
{t(
'Request overrides, routing behavior, and upstream model automation'
)}
</div>
</div>
</div>
<ChevronDown
className={cn(
'text-muted-foreground h-4 w-4 shrink-0 transition-transform',
props.open && 'rotate-180'
)}
aria-hidden='true'
/>
</CollapsibleTrigger>
<CollapsibleContent className='mt-5 flex flex-col gap-5'>
{props.children}
</CollapsibleContent>
</Collapsible>
)
}
@@ -0,0 +1,46 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import { Link2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import {
SideDrawerSection,
SideDrawerSectionHeader,
} from '@/components/drawer-layout'
type ChannelApiAccessSectionProps = {
children: ReactNode
}
export function ChannelApiAccessSection(props: ChannelApiAccessSectionProps) {
const { t } = useTranslation()
return (
<SideDrawerSection>
<SideDrawerSectionHeader
title={t('API Access')}
description={t(
'Endpoint, provider-specific settings, and credentials.'
)}
icon={<Link2 className='h-4 w-4' aria-hidden='true' />}
/>
{props.children}
</SideDrawerSection>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import { KeyRound } from 'lucide-react'
import { useTranslation } from 'react-i18next'
type ChannelAuthSectionProps = {
children: ReactNode
}
export function ChannelAuthSection(props: ChannelAuthSectionProps) {
const { t } = useTranslation()
return (
<div className='border-border/60 flex flex-col gap-4 border-t pt-4'>
<div className='flex items-center gap-2'>
<KeyRound
className='text-muted-foreground h-3.5 w-3.5'
aria-hidden='true'
/>
<h4 className='text-muted-foreground text-xs font-medium tracking-wide uppercase'>
{t('Authentication')}
</h4>
</div>
{props.children}
</div>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import { Server } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import {
SideDrawerSection,
SideDrawerSectionHeader,
} from '@/components/drawer-layout'
type ChannelBasicSectionProps = {
children: ReactNode
}
export function ChannelBasicSection(props: ChannelBasicSectionProps) {
const { t } = useTranslation()
return (
<SideDrawerSection>
<SideDrawerSectionHeader
title={t('Basic Information')}
description={t('Name, provider type, and availability.')}
icon={<Server className='h-4 w-4' aria-hidden='true' />}
/>
{props.children}
</SideDrawerSection>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useTranslation } from 'react-i18next'
import { Skeleton } from '@/components/ui/skeleton'
export function ChannelEditorLoadingState() {
const { t } = useTranslation()
return (
<div
className='border-border/60 flex flex-col gap-4 rounded-lg border p-4'
aria-live='polite'
>
<div>
<p className='text-sm font-medium'>{t('Loading channel details')}</p>
<p className='text-muted-foreground mt-1 text-xs'>
{t('Please wait before editing to avoid overwriting saved values.')}
</p>
</div>
<div className='grid gap-4 sm:grid-cols-2'>
<Skeleton className='h-10 w-full' />
<Skeleton className='h-10 w-full' />
</div>
<Skeleton className='h-24 w-full' />
<Skeleton className='h-32 w-full' />
</div>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import { Boxes } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import {
SideDrawerSection,
SideDrawerSectionHeader,
} from '@/components/drawer-layout'
type ChannelModelsSectionProps = {
children: ReactNode
}
export function ChannelModelsSection(props: ChannelModelsSectionProps) {
const { t } = useTranslation()
return (
<SideDrawerSection>
<SideDrawerSectionHeader
title={t('Models & Groups')}
description={t('Published models, groups, and model remapping rules.')}
icon={<Boxes className='h-4 w-4' aria-hidden='true' />}
/>
{props.children}
</SideDrawerSection>
)
}
@@ -0,0 +1,24 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export * from './channel-advanced-section'
export * from './channel-api-access-section'
export * from './channel-auth-section'
export * from './channel-basic-section'
export * from './channel-editor-loading-state'
export * from './channel-models-section'
@@ -16,18 +16,22 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useRef } from 'react'
import { Code, Table, Plus, Trash2 } from 'lucide-react'
import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { Code, Plus, Table, Trash2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
type ModelMappingEditorProps = {
value: string
onChange: (value: string) => void
disabled?: boolean
sourceModelOptions?: string[]
targetModelOptions?: string[]
}
type MappingRow = {
@@ -36,30 +40,59 @@ type MappingRow = {
to: string
}
export function ModelMappingEditor({
value,
onChange,
disabled = false,
}: ModelMappingEditorProps) {
const DUPLICATE_MAPPING_SENTINEL = '{ "duplicate_source_models": '
function getDuplicateSources(rows: MappingRow[]): string[] {
const seen = new Set<string>()
const duplicates = new Set<string>()
for (const row of rows) {
const source = row.from.trim()
if (!source) continue
if (seen.has(source)) {
duplicates.add(source)
} else {
seen.add(source)
}
}
return Array.from(duplicates)
}
export function ModelMappingEditor(props: ModelMappingEditorProps) {
const { t } = useTranslation()
const sourceListId = useId()
const targetListId = useId()
const [mode, setMode] = useState<'visual' | 'json'>('visual')
const [rows, setRows] = useState<MappingRow[]>([])
const [jsonValue, setJsonValue] = useState(value)
const [jsonValue, setJsonValue] = useState(props.value)
const [jsonError, setJsonError] = useState<string | null>(null)
const nextRowIdRef = useRef(0)
const duplicateSources = useMemo(() => getDuplicateSources(rows), [rows])
const createRowId = () => {
nextRowIdRef.current += 1
return `mapping-${nextRowIdRef.current}`
}
const parseJsonToRows = (json: string) => {
const parseJsonToRows = (json: string): boolean => {
try {
if (!json.trim()) {
setRows([])
return
setJsonError(null)
return true
}
const parsed = JSON.parse(json)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
setJsonError(t('Model mapping must be a valid JSON object'))
return false
}
const entries = Object.entries(parsed)
const invalidValue = entries.find(([, to]) => typeof to !== 'string')
if (invalidValue) {
setJsonError(t('Model mapping values must be strings'))
return false
}
setRows((previousRows) => {
const remainingRows = [...previousRows]
return entries.map(([from, to], index) => {
@@ -85,17 +118,20 @@ export function ModelMappingEditor({
}
})
})
setJsonError(null)
return true
} catch (_error) {
// Invalid JSON, keep current rows
setJsonError(t('Model mapping must be valid JSON format'))
return false
}
}
// Parse JSON to rows when value changes externally
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
setJsonValue(value)
parseJsonToRows(value)
}, [value])
setJsonValue(props.value)
parseJsonToRows(props.value)
}, [props.value])
const convertRowsToJson = (updatedRows: MappingRow[]): string => {
if (updatedRows.length === 0) {
@@ -110,22 +146,33 @@ export function ModelMappingEditor({
return JSON.stringify(obj, null, 2)
}
const syncRows = (updatedRows: MappingRow[]) => {
setRows(updatedRows)
const duplicates = getDuplicateSources(updatedRows)
if (duplicates.length > 0) {
setJsonError(t('Duplicate source model mappings are not allowed'))
setJsonValue(DUPLICATE_MAPPING_SENTINEL)
props.onChange(DUPLICATE_MAPPING_SENTINEL)
return
}
const json = convertRowsToJson(updatedRows)
setJsonError(null)
setJsonValue(json)
props.onChange(json)
}
const handleAddRow = () => {
const newRow: MappingRow = {
id: createRowId(),
from: '',
to: '',
}
const updatedRows = [...rows, newRow]
setRows(updatedRows)
syncRows([...rows, newRow])
}
const handleDeleteRow = (id: string) => {
const updatedRows = rows.filter((row) => row.id !== id)
setRows(updatedRows)
const json = convertRowsToJson(updatedRows)
setJsonValue(json)
onChange(json)
syncRows(rows.filter((row) => row.id !== id))
}
const handleRowChange = (
@@ -136,15 +183,12 @@ export function ModelMappingEditor({
const updatedRows = rows.map((row) =>
row.id === id ? { ...row, [field]: newValue } : row
)
setRows(updatedRows)
const json = convertRowsToJson(updatedRows)
setJsonValue(json)
onChange(json)
syncRows(updatedRows)
}
const handleJsonChange = (newJson: string) => {
setJsonValue(newJson)
onChange(newJson)
props.onChange(newJson)
parseJsonToRows(newJson)
}
@@ -155,62 +199,69 @@ export function ModelMappingEditor({
2
)
setJsonValue(template)
onChange(template)
props.onChange(template)
parseJsonToRows(template)
}
const toggleMode = () => {
if (mode === 'visual') {
// Switching to JSON mode: sync rows to JSON
const json = convertRowsToJson(rows)
setJsonValue(json)
onChange(json)
const handleModeChange = (nextMode: string) => {
if (nextMode !== 'visual' && nextMode !== 'json') return
if (nextMode === 'json') {
const duplicates = getDuplicateSources(rows)
if (duplicates.length === 0) {
const json = convertRowsToJson(rows)
setJsonValue(json)
props.onChange(json)
}
setMode('json')
} else {
// Switching to visual mode: sync JSON to rows
parseJsonToRows(jsonValue)
setMode('visual')
return
}
parseJsonToRows(jsonValue)
setMode('visual')
}
return (
<div className='space-y-2'>
<div className='flex items-center justify-between'>
<div className='flex gap-2'>
<Button
type='button'
variant='outline'
size='sm'
onClick={toggleMode}
disabled={disabled}
>
{mode === 'visual' ? (
<>
<Code className='mr-2 h-4 w-4' />
{t('JSON Mode')}
</>
) : (
<>
<Table className='mr-2 h-4 w-4' />
{t('Visual Mode')}
</>
)}
</Button>
<Tabs value={mode} onValueChange={handleModeChange} className='space-y-2'>
<div className='flex items-center justify-between gap-3'>
<TabsList>
<TabsTrigger value='visual'>
<Table className='h-4 w-4' aria-hidden='true' />
{t('Visual')}
</TabsTrigger>
<TabsTrigger value='json'>
<Code className='h-4 w-4' aria-hidden='true' />
{t('JSON')}
</TabsTrigger>
</TabsList>
<Button
type='button'
variant='link'
size='sm'
className='h-auto p-0'
onClick={handleFillTemplate}
disabled={disabled}
disabled={props.disabled}
>
{t('Fill Template')}
</Button>
</div>
</div>
{mode === 'visual' ? (
<div className='space-y-2'>
{jsonError && (
<Alert variant='destructive'>
<AlertDescription>{jsonError}</AlertDescription>
</Alert>
)}
{duplicateSources.length > 0 && (
<Alert>
<AlertDescription>
{t('Duplicate source model(s): {{models}}', {
models: duplicateSources.join(', '),
})}
</AlertDescription>
</Alert>
)}
<TabsContent value='visual' className='space-y-2'>
{rows.length > 0 ? (
<div className='space-y-2'>
<div className='grid grid-cols-[1fr_1fr_auto] gap-2 text-sm font-medium'>
@@ -229,7 +280,8 @@ export function ModelMappingEditor({
handleRowChange(row.id, 'from', e.target.value)
}
placeholder='gpt-3.5-turbo'
disabled={disabled}
disabled={props.disabled}
list={sourceListId}
/>
<Input
value={row.to}
@@ -237,17 +289,19 @@ export function ModelMappingEditor({
handleRowChange(row.id, 'to', e.target.value)
}
placeholder='gpt-3.5-turbo-0125'
disabled={disabled}
disabled={props.disabled}
list={targetListId}
/>
<Button
type='button'
variant='ghost'
size='icon'
onClick={() => handleDeleteRow(row.id)}
disabled={disabled}
disabled={props.disabled}
className='h-10 w-10'
aria-label={t('Delete mapping')}
>
<Trash2 className='h-4 w-4' />
<Trash2 className='h-4 w-4' aria-hidden='true' />
</Button>
</div>
))}
@@ -264,22 +318,42 @@ export function ModelMappingEditor({
variant='outline'
size='sm'
onClick={handleAddRow}
disabled={disabled}
disabled={props.disabled}
className='w-full'
>
<Plus className='mr-2 h-4 w-4' />
{t('Add Mapping')}
</Button>
</div>
) : (
<Textarea
value={jsonValue}
onChange={(e) => handleJsonChange(e.target.value)}
placeholder={t('{"original-model": "replacement-model"}')}
disabled={disabled}
rows={8}
className={cn('font-mono text-sm')}
/>
</TabsContent>
<TabsContent value='json'>
<Textarea
value={jsonValue}
onChange={(e) => handleJsonChange(e.target.value)}
placeholder={t('{"original-model": "replacement-model"}')}
disabled={props.disabled}
rows={8}
className={cn(
'font-mono text-sm',
jsonError && 'border-destructive'
)}
aria-invalid={Boolean(jsonError)}
/>
</TabsContent>
</Tabs>
{props.sourceModelOptions && props.sourceModelOptions.length > 0 && (
<datalist id={sourceListId}>
{props.sourceModelOptions.map((model) => (
<option key={model} value={model} />
))}
</datalist>
)}
{props.targetModelOptions && props.targetModelOptions.length > 0 && (
<datalist id={targetListId}>
{props.targetModelOptions.map((model) => (
<option key={model} value={model} />
))}
</datalist>
)}
</div>
)
@@ -0,0 +1,106 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { createChannel, updateChannel } from '../api'
import { ERROR_MESSAGES, SUCCESS_MESSAGES } from '../constants'
import {
transformFormDataToCreatePayload,
transformFormDataToUpdatePayload,
type ChannelFormValues,
} from '../lib'
import type { Channel } from '../types'
type UseChannelMutateFormParams = {
currentRow?: Channel | null
isEditing: boolean
isMultiKeyChannel: boolean
onSuccess: () => void
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
function getErrorMessage(error: unknown): string | undefined {
if (error instanceof Error && typeof error.message === 'string') {
return error.message
}
if (!isRecord(error)) return undefined
const response = error.response
if (isRecord(response)) {
const data = response.data
if (isRecord(data)) {
const message = data.message
if (typeof message === 'string') return message
}
}
const message = error.message
if (typeof message === 'string') return message
return undefined
}
export function useChannelMutateForm(props: UseChannelMutateFormParams) {
const { t } = useTranslation()
return useMutation({
mutationFn: async (data: ChannelFormValues): Promise<string> => {
if (props.isEditing && props.currentRow) {
const payload = transformFormDataToUpdatePayload(
data,
props.currentRow.id
)
const payloadWithKeyMode =
props.isMultiKeyChannel && data.key_mode
? {
...payload,
key_mode: data.key_mode,
}
: payload
const response = await updateChannel(
props.currentRow.id,
payloadWithKeyMode
)
if (!response.success) {
throw new Error(response.message || t(ERROR_MESSAGES.UPDATE_FAILED))
}
return SUCCESS_MESSAGES.UPDATED
}
const payload = transformFormDataToCreatePayload(data)
const response = await createChannel(payload)
if (!response.success) {
throw new Error(response.message || t(ERROR_MESSAGES.CREATE_FAILED))
}
return SUCCESS_MESSAGES.CREATED
},
onSuccess: (messageKey) => {
toast.success(t(messageKey))
props.onSuccess()
},
onError: (error: unknown) => {
toast.error(getErrorMessage(error) || t(ERROR_MESSAGES.CREATE_FAILED))
},
})
}
+246 -59
View File
@@ -17,68 +17,249 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { z } from 'zod'
import { CHANNEL_STATUS, MODEL_FETCHABLE_TYPES } from '../constants'
import {
CHANNEL_STATUS,
ERROR_MESSAGES,
MODEL_FETCHABLE_TYPES,
} from '../constants'
import type { Channel } from '../types'
// ============================================================================
// Form Validation Schema
// ============================================================================
export const channelFormSchema = z.object({
name: z.string().min(1, 'Channel name is required'),
type: z.number().min(0, 'Channel type is required'),
base_url: z.string().optional(),
key: z.string(),
openai_organization: z.string().optional(),
models: z.string().min(1, 'At least one model is required'),
group: z.array(z.string()).min(1, 'At least one group is required'),
model_mapping: z.string().optional(),
priority: z.number().optional(),
weight: z.number().optional(),
test_model: z.string().optional(),
auto_ban: z.number().optional(),
status: z.number(),
status_code_mapping: z.string().optional(),
tag: z.string().optional(),
remark: z
.string()
.max(255, 'Remark must be less than 255 characters')
.optional(),
setting: z.string().optional(),
param_override: z.string().optional(),
header_override: z.string().optional(),
settings: z.string().optional(),
other: z.string().optional(),
// Multi-key options (not sent to backend directly)
multi_key_mode: z.enum(['single', 'batch', 'multi_to_single']).optional(),
multi_key_type: z.enum(['random', 'polling']).optional(),
batch_add_set_key_prefix_2_name: z.boolean().optional(),
key_mode: z.enum(['append', 'replace']).optional(), // For editing multi-key channels
// Channel extra settings (stored in setting JSON, not sent directly)
force_format: z.boolean().optional(),
thinking_to_content: z.boolean().optional(),
proxy: z.string().optional(),
pass_through_body_enabled: z.boolean().optional(),
system_prompt: z.string().optional(),
system_prompt_override: z.boolean().optional(),
// Type-specific settings (stored in settings JSON)
is_enterprise_account: z.boolean().optional(), // OpenRouter specific
vertex_key_type: z.enum(['json', 'api_key']).optional(), // Vertex AI specific
aws_key_type: z.enum(['ak_sk', 'api_key']).optional(), // AWS specific
azure_responses_version: z.string().optional(), // Azure specific
// Field passthrough controls (stored in settings JSON)
allow_service_tier: z.boolean().optional(), // OpenAI/Anthropic
disable_store: z.boolean().optional(), // OpenAI only
allow_safety_identifier: z.boolean().optional(), // OpenAI only
allow_include_obfuscation: z.boolean().optional(), // OpenAI: include usage obfuscation
allow_inference_geo: z.boolean().optional(), // OpenAI/Anthropic: inference geography
allow_speed: z.boolean().optional(), // Anthropic: speed mode control
claude_beta_query: z.boolean().optional(), // Anthropic: beta query passthrough
// Upstream model update settings (stored in settings JSON)
upstream_model_update_check_enabled: z.boolean().optional(),
upstream_model_update_auto_sync_enabled: z.boolean().optional(),
upstream_model_update_ignored_models: z.string().optional(),
})
function parseOptionalJson(value: string | undefined): unknown {
if (!value?.trim()) return undefined
return JSON.parse(value)
}
function isJsonObjectValue(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isOptionalJsonObject(value: string | undefined): boolean {
try {
const parsed = parseOptionalJson(value)
return parsed === undefined || isJsonObjectValue(parsed)
} catch {
return false
}
}
function isOptionalModelMapping(value: string | undefined): boolean {
try {
const parsed = parseOptionalJson(value)
if (parsed === undefined) return true
if (!isJsonObjectValue(parsed)) return false
return Object.values(parsed).every((item) => typeof item === 'string')
} catch {
return false
}
}
function isOptionalStatusCodeMapping(value: string | undefined): boolean {
try {
const parsed = parseOptionalJson(value)
if (parsed === undefined) return true
if (!isJsonObjectValue(parsed)) return false
return Object.entries(parsed).every(([from, to]) => {
const fromCode = Number(from)
const toCode = Number(to)
return (
Number.isInteger(fromCode) &&
Number.isInteger(toCode) &&
fromCode >= 100 &&
fromCode <= 599 &&
toCode >= 100 &&
toCode <= 599
)
})
} catch {
return false
}
}
function isCodexCredential(value: string | undefined): boolean {
try {
const parsed = parseOptionalJson(value)
if (parsed === undefined) return true
return (
isJsonObjectValue(parsed) &&
typeof parsed.access_token === 'string' &&
parsed.access_token.trim().length > 0 &&
typeof parsed.account_id === 'string' &&
parsed.account_id.trim().length > 0
)
} catch {
return false
}
}
function isVertexJsonKey(value: string | undefined): boolean {
try {
const parsed = parseOptionalJson(value)
if (parsed === undefined) return true
if (Array.isArray(parsed)) {
return parsed.every((item) => isJsonObjectValue(item))
}
return isJsonObjectValue(parsed)
} catch {
return false
}
}
function addRequiredIssue(
ctx: z.RefinementCtx,
path: string,
message: string
): void {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [path],
message,
})
}
export const channelFormSchema = z
.object({
name: z.string().min(1, ERROR_MESSAGES.REQUIRED_NAME),
type: z.number().min(0, ERROR_MESSAGES.REQUIRED_TYPE),
base_url: z.string().optional(),
key: z.string(),
openai_organization: z.string().optional(),
models: z.string().min(1, ERROR_MESSAGES.REQUIRED_MODELS),
group: z.array(z.string()).min(1, ERROR_MESSAGES.REQUIRED_GROUP),
model_mapping: z
.string()
.optional()
.refine(
isOptionalModelMapping,
'Model mapping must be a JSON object with string values'
),
priority: z.number().optional(),
weight: z.number().optional(),
test_model: z.string().optional(),
auto_ban: z.number().optional(),
status: z.number(),
status_code_mapping: z
.string()
.optional()
.refine(
isOptionalStatusCodeMapping,
'Status code mapping must use valid HTTP status codes'
),
tag: z.string().optional(),
remark: z
.string()
.max(255, 'Remark must be less than 255 characters')
.optional(),
setting: z
.string()
.optional()
.refine(isOptionalJsonObject, ERROR_MESSAGES.INVALID_JSON),
param_override: z
.string()
.optional()
.refine(isOptionalJsonObject, ERROR_MESSAGES.INVALID_JSON),
header_override: z
.string()
.optional()
.refine(isOptionalJsonObject, ERROR_MESSAGES.INVALID_JSON),
settings: z
.string()
.optional()
.refine(isOptionalJsonObject, ERROR_MESSAGES.INVALID_JSON),
other: z.string().optional(),
// Multi-key options (not sent to backend directly)
multi_key_mode: z.enum(['single', 'batch', 'multi_to_single']).optional(),
multi_key_type: z.enum(['random', 'polling']).optional(),
batch_add_set_key_prefix_2_name: z.boolean().optional(),
key_mode: z.enum(['append', 'replace']).optional(), // For editing multi-key channels
// Channel extra settings (stored in setting JSON, not sent directly)
force_format: z.boolean().optional(),
thinking_to_content: z.boolean().optional(),
proxy: z.string().optional(),
pass_through_body_enabled: z.boolean().optional(),
system_prompt: z.string().optional(),
system_prompt_override: z.boolean().optional(),
// Type-specific settings (stored in settings JSON)
is_enterprise_account: z.boolean().optional(), // OpenRouter specific
vertex_key_type: z.enum(['json', 'api_key']).optional(), // Vertex AI specific
aws_key_type: z.enum(['ak_sk', 'api_key']).optional(), // AWS specific
azure_responses_version: z.string().optional(), // Azure specific
// Field passthrough controls (stored in settings JSON)
allow_service_tier: z.boolean().optional(), // OpenAI/Anthropic
disable_store: z.boolean().optional(), // OpenAI only
allow_safety_identifier: z.boolean().optional(), // OpenAI only
allow_include_obfuscation: z.boolean().optional(), // OpenAI: include usage obfuscation
allow_inference_geo: z.boolean().optional(), // OpenAI/Anthropic: inference geography
allow_speed: z.boolean().optional(), // Anthropic: speed mode control
claude_beta_query: z.boolean().optional(), // Anthropic: beta query passthrough
// Upstream model update settings (stored in settings JSON)
upstream_model_update_check_enabled: z.boolean().optional(),
upstream_model_update_auto_sync_enabled: z.boolean().optional(),
upstream_model_update_ignored_models: z.string().optional(),
})
.superRefine((data, ctx) => {
if ([3, 8, 36, 45].includes(data.type) && !data.base_url?.trim()) {
addRequiredIssue(
ctx,
'base_url',
'Base URL is required for this channel type'
)
}
if ([3, 18, 21, 39, 41, 49].includes(data.type) && !data.other?.trim()) {
addRequiredIssue(
ctx,
'other',
'This channel type requires additional configuration'
)
}
if (data.type === 57) {
if (data.multi_key_mode && data.multi_key_mode !== 'single') {
addRequiredIssue(
ctx,
'multi_key_mode',
'Codex channels do not support batch creation'
)
}
if (data.key?.trim() && !isCodexCredential(data.key)) {
addRequiredIssue(
ctx,
'key',
'Codex credential must be a JSON object with access_token and account_id'
)
}
}
if (
data.type === 41 &&
data.vertex_key_type === 'json' &&
data.key?.trim() &&
!isVertexJsonKey(data.key)
) {
addRequiredIssue(
ctx,
'key',
'Vertex AI service account key must be valid JSON'
)
}
if (
data.type === 41 &&
data.vertex_key_type === 'api_key' &&
data.multi_key_mode &&
data.multi_key_mode !== 'single'
) {
addRequiredIssue(
ctx,
'multi_key_mode',
'Vertex AI API Key mode does not support batch creation'
)
}
})
export type ChannelFormValues = z.infer<typeof channelFormSchema>
@@ -389,6 +570,12 @@ function buildSettingsJSON(formData: ChannelFormValues): string {
return JSON.stringify(settingsObj)
}
function normalizeBaseUrl(value: string | undefined): string {
return String(value || '')
.trim()
.replace(/\/+$/, '')
}
/**
* Transform form data to API payload for creating channel
*/
@@ -403,7 +590,7 @@ export function transformFormDataToCreatePayload(formData: ChannelFormValues): {
const channel: Partial<Channel> = {
name: formData.name,
type: formData.type,
base_url: formData.base_url || null,
base_url: normalizeBaseUrl(formData.base_url) || null,
key: formData.key,
openai_organization: formData.openai_organization || null,
models: formData.models,
@@ -452,7 +639,7 @@ export function transformFormDataToUpdatePayload(
id: channelId,
name: formData.name,
type: formData.type,
base_url: formData.base_url || null,
base_url: normalizeBaseUrl(formData.base_url) || null,
openai_organization: formData.openai_organization || null,
models: formData.models,
group: formatGroups(formData.group),
@@ -485,7 +672,7 @@ export function transformFormDataToUpdatePayload(
})
// Send explicit empty strings for nullable fields so GORM updates can clear them.
payload.base_url = formData.base_url || ''
payload.base_url = normalizeBaseUrl(formData.base_url) || ''
payload.openai_organization = formData.openai_organization || ''
payload.test_model = formData.test_model || ''
payload.tag = formData.tag || ''
@@ -179,6 +179,12 @@ export function validateModelMappingJson(modelMapping: string): {
error: 'Model mapping must be a valid JSON object',
}
}
if (Object.values(parsed).some((value) => typeof value !== 'string')) {
return {
valid: false,
error: 'Model mapping values must be strings',
}
}
return { valid: true }
} catch {
return {