diff --git a/controller/channel.go b/controller/channel.go index a2b5687ab319..1004738c5559 100644 --- a/controller/channel.go +++ b/controller/channel.go @@ -15,7 +15,6 @@ import ( "github.com/QuantumNous/new-api/i18n" "github.com/QuantumNous/new-api/model" relaychannel "github.com/QuantumNous/new-api/relay/channel" - "github.com/QuantumNous/new-api/relay/channel/gemini" "github.com/QuantumNous/new-api/relay/channel/ollama" "github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/service/authz" @@ -1157,13 +1156,9 @@ func equalStringPtr(a, b *string) bool { } func FetchModels(c *gin.Context) { - var req struct { - BaseURL string `json:"base_url"` - Type int `json:"type"` - Key string `json:"key"` - } + var channel model.Channel - if err := c.ShouldBindJSON(&req); err != nil { + if err := c.ShouldBindJSON(&channel); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "success": false, "message": "Invalid request", @@ -1171,108 +1166,26 @@ func FetchModels(c *gin.Context) { return } - baseURL := req.BaseURL - if baseURL == "" { - baseURL = constant.ChannelBaseURLs[req.Type] - } - - // remove line breaks and extra spaces. - key := strings.TrimSpace(req.Key) - key = strings.Split(key, "\n")[0] - - if req.Type == constant.ChannelTypeOllama { - models, err := ollama.FetchOllamaModels(baseURL, key) - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": fmt.Sprintf("获取Ollama模型失败: %s", err.Error()), - }) - return - } - - names := make([]string, 0, len(models)) - for _, modelInfo := range models { - names = append(names, modelInfo.Name) - } - - c.JSON(http.StatusOK, gin.H{ - "success": true, - "data": names, - }) - return - } - - if req.Type == constant.ChannelTypeGemini { - models, err := gemini.FetchGeminiModels(baseURL, key, "") - if err != nil { - c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": fmt.Sprintf("获取Gemini模型失败: %s", err.Error()), - }) - return - } - + if strings.TrimSpace(channel.Key) == "" { c.JSON(http.StatusOK, gin.H{ - "success": true, - "data": models, - }) - return - } - - client := &http.Client{} - url := fmt.Sprintf("%s/v1/models", baseURL) - - request, err := http.NewRequest("GET", url, nil) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ "success": false, - "message": err.Error(), + "message": "Please enter API key first", }) return } - request.Header.Set("Authorization", "Bearer "+key) - - response, err := client.Do(request) + ids, err := fetchChannelUpstreamModelIDs(&channel) if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ - "success": false, - "message": err.Error(), - }) - return - } - //check status code - if response.StatusCode != http.StatusOK { - c.JSON(http.StatusInternalServerError, gin.H{ - "success": false, - "message": "Failed to fetch models", - }) - return - } - defer response.Body.Close() - - var result struct { - Data []struct { - ID string `json:"id"` - } `json:"data"` - } - - if err := json.NewDecoder(response.Body).Decode(&result); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ + c.JSON(http.StatusOK, gin.H{ "success": false, - "message": err.Error(), + "message": fmt.Sprintf("获取模型列表失败: %s", err.Error()), }) return } - var models []string - for _, model := range result.Data { - models = append(models, model.ID) - } - c.JSON(http.StatusOK, gin.H{ "success": true, - "data": models, + "data": ids, }) } diff --git a/web/default/src/components/data-table/core/data-table-colgroup.tsx b/web/default/src/components/data-table/core/data-table-colgroup.tsx index a8724588295c..8cda18cb3c79 100644 --- a/web/default/src/components/data-table/core/data-table-colgroup.tsx +++ b/web/default/src/components/data-table/core/data-table-colgroup.tsx @@ -34,9 +34,12 @@ export function DataTableColgroup({ return ( {columns.map((column) => { - const width = isContentSizedColumn(column.id) - ? undefined - : getColumnWidth(column.getSize(), totalSize) + const width = getColumnWidth( + table, + column.id, + column.getSize(), + totalSize + ) return })} @@ -44,7 +47,20 @@ export function DataTableColgroup({ ) } -function getColumnWidth(columnSize: number, totalSize: number) { +function getColumnWidth( + table: TanstackTable, + columnId: string, + columnSize: number, + totalSize: number +) { + if (isContentSizedColumn(columnId)) { + return undefined + } + + if (table.options.enableColumnResizing === true) { + return `${columnSize}px` + } + if (totalSize <= 0) { return undefined } diff --git a/web/default/src/components/data-table/core/data-table-header.tsx b/web/default/src/components/data-table/core/data-table-header.tsx index 14f25faf0053..9defce909e76 100644 --- a/web/default/src/components/data-table/core/data-table-header.tsx +++ b/web/default/src/components/data-table/core/data-table-header.tsx @@ -21,8 +21,10 @@ import { type Header, type Table as TanstackTable, } from '@tanstack/react-table' +import { useTranslation } from 'react-i18next' import { TableHead, TableHeader, TableRow } from '@/components/ui/table' +import { cn } from '@/lib/utils' import { DataTableColumnHeader } from './column-header' import { isContentSizedColumn } from './content-sized-columns' @@ -43,6 +45,8 @@ export function DataTableHeader({ rowClassName, getColumnClassName, }: DataTableHeaderProps) { + const { t } = useTranslation() + return ( {table.getHeaderGroups().map((headerGroup) => ( @@ -51,10 +55,28 @@ export function DataTableHeader({ {renderHeaderContent(header)} + {shouldRenderColumnResizer(table, header) && ( +
header.column.resetSize()} + onMouseDown={header.getResizeHandler()} + onTouchStart={header.getResizeHandler()} + className={cn( + 'absolute top-0 right-0 h-full w-2 cursor-col-resize touch-none select-none', + 'after:bg-border hover:after:bg-primary after:absolute after:top-2 after:right-0 after:h-[calc(100%-1rem)] after:w-px after:transition-colors', + header.column.getIsResizing() && 'after:bg-primary' + )} + /> + )} ))} @@ -63,6 +85,18 @@ export function DataTableHeader({ ) } +function shouldRenderColumnResizer( + table: TanstackTable, + header: Header +) { + return ( + table.options.enableColumnResizing === true && + !header.isPlaceholder && + header.column.getCanResize() && + !isContentSizedColumn(header.column.id) + ) +} + function getHeaderSizeStyle( header: Header, applyHeaderSize: boolean | undefined diff --git a/web/default/src/components/data-table/hooks/use-data-table.ts b/web/default/src/components/data-table/hooks/use-data-table.ts index 1b8d170be725..5ed06b1ae16f 100644 --- a/web/default/src/components/data-table/hooks/use-data-table.ts +++ b/web/default/src/components/data-table/hooks/use-data-table.ts @@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com import { type ColumnDef, type ColumnFiltersState, + type ColumnSizingState, type ExpandedState, type OnChangeFn, type PaginationState, @@ -48,6 +49,7 @@ type DataTableFeatureOptions = Pick< | 'manualFiltering' | 'manualPagination' | 'manualSorting' + | 'enableColumnResizing' > type DataTableStateOptions = { @@ -58,6 +60,10 @@ type DataTableStateOptions = { columnVisibilityStorageKey?: string | false columnVisibility?: VisibilityState onColumnVisibilityChange?: OnChangeFn + initialColumnSizing?: ColumnSizingState + columnSizingStorageKey?: string | false + columnSizing?: ColumnSizingState + onColumnSizingChange?: OnChangeFn initialRowSelection?: RowSelectionState rowSelection?: RowSelectionState onRowSelectionChange?: OnChangeFn @@ -149,6 +155,32 @@ function readColumnVisibility(storageKey: string | undefined): VisibilityState { } } +function readColumnSizing(storageKey: string | undefined): ColumnSizingState { + if (!storageKey || typeof window === 'undefined') return {} + + try { + const raw = window.localStorage.getItem(storageKey) + if (!raw) return {} + + const parsed = JSON.parse(raw) as unknown + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return {} + } + + return Object.entries(parsed).reduce( + (sizing, [key, value]) => { + if (typeof value === 'number' && Number.isFinite(value) && value > 0) { + sizing[key] = value + } + return sizing + }, + {} + ) + } catch { + return {} + } +} + export function useDataTable(options: UseDataTableOptions) { const { data, @@ -161,6 +193,7 @@ export function useDataTable(options: UseDataTableOptions) { manualSorting, initialSorting = [], initialColumnVisibility = {}, + initialColumnSizing = {}, initialRowSelection = {}, initialExpanded = {}, initialPagination = { pageIndex: 0, pageSize: 20 }, @@ -175,6 +208,10 @@ export function useDataTable(options: UseDataTableOptions) { typeof options.columnVisibilityStorageKey === 'string' ? options.columnVisibilityStorageKey : undefined + const columnSizingStorageKey = + typeof options.columnSizingStorageKey === 'string' + ? options.columnSizingStorageKey + : undefined const resolvedInitialColumnVisibility = React.useMemo( () => ({ ...initialColumnVisibility, @@ -182,6 +219,13 @@ export function useDataTable(options: UseDataTableOptions) { }), [columnVisibilityStorageKey, initialColumnVisibility] ) + const resolvedInitialColumnSizing = React.useMemo( + () => ({ + ...initialColumnSizing, + ...readColumnSizing(columnSizingStorageKey), + }), + [columnSizingStorageKey, initialColumnSizing] + ) const [sorting, onSortingChange] = useControllableTableState( options.sorting, @@ -194,10 +238,17 @@ export function useDataTable(options: UseDataTableOptions) { resolvedInitialColumnVisibility, options.onColumnVisibilityChange ) + const [columnSizing, onColumnSizingChange] = useControllableTableState( + options.columnSizing, + resolvedInitialColumnSizing, + options.onColumnSizingChange + ) const hydratedColumnVisibilityStorageKeyRef = React.useRef( columnVisibilityStorageKey ) + const hydratedColumnSizingStorageKeyRef = React.useRef(columnSizingStorageKey) const skipNextColumnVisibilityPersistRef = React.useRef(false) + const skipNextColumnSizingPersistRef = React.useRef(false) const [rowSelection, onRowSelectionChange] = useControllableTableState( options.rowSelection, initialRowSelection, @@ -228,6 +279,7 @@ export function useDataTable(options: UseDataTableOptions) { state: { sorting, columnVisibility, + columnSizing, rowSelection, expanded, columnFilters: options.columnFilters, @@ -242,8 +294,11 @@ export function useDataTable(options: UseDataTableOptions) { manualFiltering, manualPagination, manualSorting, + enableColumnResizing: options.enableColumnResizing, + columnResizeMode: 'onChange', onSortingChange, onColumnVisibilityChange, + onColumnSizingChange, onRowSelectionChange, onExpandedChange, onColumnFiltersChange: options.onColumnFiltersChange, @@ -290,6 +345,24 @@ export function useDataTable(options: UseDataTableOptions) { resolvedInitialColumnVisibility, ]) + React.useEffect(() => { + if ( + options.columnSizing !== undefined || + columnSizingStorageKey === hydratedColumnSizingStorageKeyRef.current + ) { + return + } + + hydratedColumnSizingStorageKeyRef.current = columnSizingStorageKey + skipNextColumnSizingPersistRef.current = true + onColumnSizingChange(() => resolvedInitialColumnSizing) + }, [ + columnSizingStorageKey, + onColumnSizingChange, + options.columnSizing, + resolvedInitialColumnSizing, + ]) + React.useEffect(() => { if (!columnVisibilityStorageKey || typeof window === 'undefined') return @@ -308,6 +381,24 @@ export function useDataTable(options: UseDataTableOptions) { } }, [columnVisibility, columnVisibilityStorageKey]) + React.useEffect(() => { + if (!columnSizingStorageKey || typeof window === 'undefined') return + + if (skipNextColumnSizingPersistRef.current) { + skipNextColumnSizingPersistRef.current = false + return + } + + try { + window.localStorage.setItem( + columnSizingStorageKey, + JSON.stringify(columnSizing) + ) + } catch { + // Storage can be unavailable in private mode; table controls still work. + } + }, [columnSizing, columnSizingStorageKey]) + return { table, } diff --git a/web/default/src/features/channels/api.ts b/web/default/src/features/channels/api.ts index ba8a67ef2c83..57bad5a80ca0 100644 --- a/web/default/src/features/channels/api.ts +++ b/web/default/src/features/channels/api.ts @@ -529,6 +529,9 @@ export async function fetchModels(data: { base_url: string type: number key: string + setting?: string | null + settings?: string | null + header_override?: string | null }): Promise { const res = await api.post( '/api/channel/fetch_models', diff --git a/web/default/src/features/channels/components/channels-columns.tsx b/web/default/src/features/channels/components/channels-columns.tsx index 807e35c61bbe..f55ca7ca7862 100644 --- a/web/default/src/features/channels/components/channels-columns.tsx +++ b/web/default/src/features/channels/components/channels-columns.tsx @@ -559,6 +559,7 @@ export function useChannelsColumns( }, enableSorting: false, enableHiding: false, + enableResizing: false, size: 40, } satisfies ColumnDef, ] @@ -623,13 +624,13 @@ export function useChannelsColumns( const hasParamOverride = Boolean(channel.param_override?.trim()) return ( -
-
-
+
+
+
{isPassThrough && ( @@ -683,6 +684,7 @@ export function useChannelsColumns(
) }, + size: 260, minSize: 200, }, diff --git a/web/default/src/features/channels/components/channels-table.tsx b/web/default/src/features/channels/components/channels-table.tsx index 81a59a339fec..b278a492698b 100644 --- a/web/default/src/features/channels/components/channels-table.tsx +++ b/web/default/src/features/channels/components/channels-table.tsx @@ -67,6 +67,7 @@ import { DataTableBulkActions } from './data-table-bulk-actions' const route = getRouteApi('/_authenticated/channels/') const CHANNELS_COLUMN_VISIBILITY_STORAGE_KEY = 'channels:column-visibility' +const CHANNELS_COLUMN_SIZING_STORAGE_KEY = 'channels:column-sizing' const CHANNELS_VIEW_MODE_STORAGE_KEY = 'channels:view-mode' const CHANNELS_STATUS_FILTER_STORAGE_KEY = 'channel-status-filter' @@ -316,6 +317,7 @@ export function ChannelsTable() { tag: false, }, columnVisibilityStorageKey: CHANNELS_COLUMN_VISIBILITY_STORAGE_KEY, + columnSizingStorageKey: CHANNELS_COLUMN_SIZING_STORAGE_KEY, columnFilters, pagination, globalFilter, @@ -331,6 +333,7 @@ export function ChannelsTable() { manualSorting: true, manualFiltering: true, withExpandedRowModel: true, + enableColumnResizing: true, ensurePageInRange, }) diff --git a/web/default/src/features/channels/components/drawers/channel-mutate-drawer.tsx b/web/default/src/features/channels/components/drawers/channel-mutate-drawer.tsx index f21228c34626..fa048d0065c2 100644 --- a/web/default/src/features/channels/components/drawers/channel-mutate-drawer.tsx +++ b/web/default/src/features/channels/components/drawers/channel-mutate-drawer.tsx @@ -159,6 +159,7 @@ import { findMissingModelsInMapping, validateModelMappingJson, hasAdvancedSettingsErrors, + transformFormDataToFetchModelsPayload, } from '../../lib' import { collectInvalidStatusCodeEntries, @@ -1352,15 +1353,13 @@ export function ChannelMutateDrawer({ setFetchModelsDialogOpen(true) }, [isEditing, canEditSensitive, form, t]) - const createModeFetcher = useCallback(async (): Promise => { + const formModeFetcher = useCallback(async (): Promise => { if (!canEditSensitive) { throw new Error(t("You don't have necessary permission")) } - const response = await fetchModels({ - type: form.getValues('type'), - key: form.getValues('key'), - base_url: form.getValues('base_url') || '', - }) + const response = await fetchModels( + transformFormDataToFetchModelsPayload(form.getValues()) + ) if (response.success && response.data) { return response.data } @@ -4552,7 +4551,9 @@ export function ChannelMutateDrawer({ }} redirectModels={redirectModelList} redirectSourceModels={redirectModelKeyList} - customFetcher={!isEditing ? createModeFetcher : undefined} + customFetcher={ + !isEditing || currentKey?.trim() ? formModeFetcher : undefined + } channelName={!isEditing ? currentName?.trim() : undefined} existingModelsOverride={ !isEditing diff --git a/web/default/src/features/channels/lib/channel-form.ts b/web/default/src/features/channels/lib/channel-form.ts index 33a5fb707a92..ff98395d4241 100644 --- a/web/default/src/features/channels/lib/channel-form.ts +++ b/web/default/src/features/channels/lib/channel-form.ts @@ -564,12 +564,15 @@ function buildSettingsJSON(formData: ChannelFormValues): string { settingsObj.allow_inference_geo = formData.allow_inference_geo === true } else { if ('disable_store' in settingsObj) delete settingsObj.disable_store - if ('allow_safety_identifier' in settingsObj) + if ('allow_safety_identifier' in settingsObj) { delete settingsObj.allow_safety_identifier - if ('allow_include_obfuscation' in settingsObj) + } + if ('allow_include_obfuscation' in settingsObj) { delete settingsObj.allow_include_obfuscation - if (formData.type !== 14 && 'allow_inference_geo' in settingsObj) + } + if (formData.type !== 14 && 'allow_inference_geo' in settingsObj) { delete settingsObj.allow_inference_geo + } } // Anthropic (type 14): claude_beta_query, allow_inference_geo, allow_speed @@ -592,14 +595,14 @@ function buildSettingsJSON(formData: ChannelFormValues): string { settingsObj.upstream_model_update_auto_sync_enabled = settingsObj.upstream_model_update_check_enabled === true && formData.upstream_model_update_auto_sync_enabled === true - settingsObj.upstream_model_update_ignored_models = Array.from( - new Set( + settingsObj.upstream_model_update_ignored_models = [ + ...new Set( String(formData.upstream_model_update_ignored_models || '') .split(',') .map((model) => model.trim()) .filter(Boolean) - ) - ) + ), + ] if ( !Array.isArray(settingsObj.upstream_model_update_last_detected_models) || settingsObj.upstream_model_update_check_enabled !== true @@ -739,6 +742,26 @@ export function transformFormDataToUpdatePayload( return payload } +export function transformFormDataToFetchModelsPayload( + formData: ChannelFormValues +): { + base_url: string + type: number + key: string + setting: string + settings: string + header_override: string +} { + return { + base_url: normalizeBaseUrl(formData.base_url) || '', + type: formData.type, + key: formData.key, + setting: buildSettingJSON(formData), + settings: buildSettingsJSON(formData), + header_override: formData.header_override || '', + } +} + // ============================================================================ // Validation Helpers // ============================================================================