Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 8 additions & 95 deletions controller/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -1157,122 +1156,36 @@ 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",
})
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,
Comment on lines +1159 to +1188

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate GetNextEnabledKey and inspect its dependency on Status/ChannelInfo
ast-grep run --pattern 'func (channel *Channel) GetNextEnabledKey($$$) $$$' --lang go model
rg -n -A 40 'func \(channel \*Channel\) GetNextEnabledKey' model

Repository: QuantumNous/new-api

Length of output: 7220


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect Channel shape, the fetch-models controller path, and any normalization before GetNextEnabledKey.
ast-grep outline model/channel.go --view expanded
printf '\n--- controller path ---\n'
ast-grep outline controller/channel_upstream_update.go --view expanded
printf '\n--- fetch payload source ---\n'
rg -n -A 40 -B 20 'transformFormDataToFetchModelsPayload|fetchChannelUpstreamModelIDs|GetNextEnabledKey\(' controller model

Repository: QuantumNous/new-api

Length of output: 35307


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the Channel struct, JSON tags, and the fetch-models request transformation.
sed -n '1,260p' model/channel.go | cat -n
printf '\n--- fetch-models transformation ---\n'
rg -n -A 80 -B 30 'transformFormDataToFetchModelsPayload|FetchModels|fetchChannelUpstreamModelIDs' controller

Repository: QuantumNous/new-api

Length of output: 39500


Populate ChannelInfo for this form-based fetch path. GetNextEnabledKey() ignores Status, but it does require ChannelInfo.IsMultiKey; with the current raw ShouldBindJSON payload, pasted multi-line API keys stay unsplit and are treated as one key.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/channel.go` around lines 1159 - 1188, Populate ChannelInfo before
calling fetchChannelUpstreamModelIDs in the form-based handler so
GetNextEnabledKey can detect multi-key input correctly. After ShouldBindJSON on
model.Channel, construct or fill channel.ChannelInfo with IsMultiKey set from
the request context/params as needed, and ensure the existing key-splitting
logic is used for pasted multi-line API keys instead of treating channel.Key as
a single value.

})
}

Expand Down
24 changes: 20 additions & 4 deletions web/default/src/components/data-table/core/data-table-colgroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,33 @@ export function DataTableColgroup<TData>({
return (
<colgroup>
{columns.map((column) => {
const width = isContentSizedColumn(column.id)
? undefined
: getColumnWidth(column.getSize(), totalSize)
const width = getColumnWidth(
table,
column.id,
column.getSize(),
totalSize
)

return <col key={column.id} style={{ width }} />
})}
</colgroup>
)
}

function getColumnWidth(columnSize: number, totalSize: number) {
function getColumnWidth<TData>(
table: TanstackTable<TData>,
columnId: string,
columnSize: number,
totalSize: number
) {
if (isContentSizedColumn(columnId)) {
return undefined
}

if (table.options.enableColumnResizing === true) {
return `${columnSize}px`
}

if (totalSize <= 0) {
return undefined
}
Expand Down
36 changes: 35 additions & 1 deletion web/default/src/components/data-table/core/data-table-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -43,6 +45,8 @@ export function DataTableHeader<TData>({
rowClassName,
getColumnClassName,
}: DataTableHeaderProps<TData>) {
const { t } = useTranslation()

return (
<TableHeader className={className}>
{table.getHeaderGroups().map((headerGroup) => (
Expand All @@ -51,10 +55,28 @@ export function DataTableHeader<TData>({
<TableHead
key={header.id}
colSpan={header.colSpan}
className={getColumnClassName?.(header.column.id, 'header')}
className={cn(
'relative',
getColumnClassName?.(header.column.id, 'header')
)}
style={getHeaderSizeStyle(header, applyHeaderSize)}
>
{renderHeaderContent(header)}
{shouldRenderColumnResizer(table, header) && (
<div
role='separator'
aria-orientation='vertical'
aria-label={t('Resize column')}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -e json . web/default/src/i18n/locales --exec rg -l '"Resize column"' {}

Repository: QuantumNous/new-api

Length of output: 157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== locale files ==\n'
fd -a -t f '.*\.json$' web/default/src/i18n/locales

printf '\n== search for Resize column (case-sensitive) ==\n'
rg -n '"Resize column"|Resize column' web/default/src/i18n/locales || true

printf '\n== inspect i18n config ==\n'
fd -a -t f 'i18n' web/default/src | sed -n '1,20p'
rg -n "fallbackLng|lng|keySeparator|nsSeparator|returnNull|returnEmptyString|fallbackNS" web/default/src/i18n web/default/src --glob '!**/*.map' || true

Repository: QuantumNous/new-api

Length of output: 1000


Add Resize column to the locale files. The new aria-label key is missing from web/default/src/i18n/locales/*.json, so it will fall back to the English key in every locale.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/components/data-table/core/data-table-header.tsx` at line 69,
The new aria-label in DataTableHeader uses the literal “Resize column” without a
localized entry, so add this key to the locale JSON files under
web/default/src/i18n/locales and wire it into the existing translation set.
Update the relevant i18n resources used by data-table-header.tsx so the
t('Resize column') lookup resolves in every locale instead of falling back to
English.

Source: Coding guidelines

onDoubleClick={() => 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'
)}
/>
)}
Comment on lines +58 to +79

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Resize handle is mouse/touch-only; no keyboard support.

The resizer div (Lines 65-79) uses role='separator' with onMouseDown/onTouchStart only — there's no tabIndex, no onKeyDown, and no aria-valuenow/aria-valuemin/aria-valuemax. Keyboard-only users cannot resize columns at all with this implementation, which is a common headless-table pitfall since TanStack Table intentionally leaves all accessibility to the consumer.

As per coding guidelines, web/default/**/*.{ts,tsx} components must "ensure keyboard operability and sensible focus order, add ARIA attributes when needed."

Consider adding tabIndex={0} plus an onKeyDown handler that nudges header.column.getSize() via arrow keys (calling the table's setColumnSizing or equivalent), and exposing current/min/max via ARIA attributes.

Also applies to: 88-99

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/components/data-table/core/data-table-header.tsx` around
lines 58 - 79, The column resizer in data-table-header is mouse/touch-only and
lacks keyboard accessibility. Update the resizer element in DataTableHeader to
be focusable and operable via keyboard by adding a tab stop and an onKeyDown
handler that adjusts the column size using the table/header sizing APIs. Also
expose the current sizing state with appropriate ARIA attributes on the
separator element so keyboard-only users can resize columns.

Source: Coding guidelines

</TableHead>
))}
</TableRow>
Expand All @@ -63,6 +85,18 @@ export function DataTableHeader<TData>({
)
}

function shouldRenderColumnResizer<TData>(
table: TanstackTable<TData>,
header: Header<TData, unknown>
) {
return (
table.options.enableColumnResizing === true &&
!header.isPlaceholder &&
header.column.getCanResize() &&
!isContentSizedColumn(header.column.id)
)
}

function getHeaderSizeStyle<TData>(
header: Header<TData, unknown>,
applyHeaderSize: boolean | undefined
Expand Down
Loading