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
53 changes: 53 additions & 0 deletions controller/model_meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,59 @@ func CreateModelMeta(c *gin.Context) {
// UpdateModelMeta 更新模型
func UpdateModelMeta(c *gin.Context) {
statusOnly := c.Query("status_only") == "true"
orderOnly := c.Query("order_only") == "true"

if orderOnly {
var req struct {
Id int `json:"id"`
DisplayOrder *int `json:"display_order"`
Pinned *int `json:"pinned"`
}
if err := c.ShouldBindJSON(&req); err != nil {
common.ApiError(c, err)
return
}
if req.Id == 0 {
common.ApiErrorMsg(c, "缺少模型 ID")
return
}
updates := map[string]interface{}{
"updated_time": common.GetTimestamp(),
}
if req.DisplayOrder != nil {
displayOrder := *req.DisplayOrder
if displayOrder < 0 {
displayOrder = 0
}
updates["display_order"] = displayOrder
}
if req.Pinned != nil {
pinned := 0
if *req.Pinned != 0 {
pinned = 1
}
updates["pinned"] = pinned
}
if len(updates) == 1 {
common.ApiErrorMsg(c, "缺少排序字段")
return
}
res := model.DB.Model(&model.Model{}).Where("id = ?", req.Id).Updates(updates)
if res.Error != nil {
common.ApiError(c, res.Error)
return
}
if res.RowsAffected == 0 {
var count int64
if err := model.DB.Model(&model.Model{}).Where("id = ?", req.Id).Count(&count).Error; err != nil || count == 0 {
common.ApiErrorMsg(c, "模型不存在")
return
Comment on lines +155 to +157

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not map DB count errors to “模型不存在”.

Line 155 currently treats query errors and true not-found as the same result. That can hide real DB failures and return a false 404-style message.

Suggested fix
-			if err := model.DB.Model(&model.Model{}).Where("id = ?", req.Id).Count(&count).Error; err != nil || count == 0 {
-				common.ApiErrorMsg(c, "模型不存在")
-				return
-			}
+			if err := model.DB.Model(&model.Model{}).Where("id = ?", req.Id).Count(&count).Error; err != nil {
+				common.ApiError(c, err)
+				return
+			}
+			if count == 0 {
+				common.ApiErrorMsg(c, "模型不存在")
+				return
+			}
🤖 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/model_meta.go` around lines 155 - 157, The code currently
conflates DB query errors with a not-found result when calling
model.DB.Model(&model.Model{}).Where("id = ?", req.Id).Count(&count).Error and
then returns common.ApiErrorMsg(c, "模型不存在"); change this to first check if err
!= nil and handle it as a DB/internal error (e.g., call common.ApiErrorMsg with
an internal error message or the err details) and only if err == nil and count
== 0 return the not-found message "模型不存在"; update the error-handling branches
around Count(&count).Error, keeping the same req.Id/Model references and using
common.ApiErrorMsg for each distinct case.

}
}
model.RefreshPricing()
common.ApiSuccess(c, gin.H{"id": req.Id})
return
}

var m model.Model
if err := c.ShouldBindJSON(&m); err != nil {
Expand Down
29 changes: 28 additions & 1 deletion controller/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -543,10 +543,37 @@ func GetUserModels(c *gin.Context) {
}
}
}
// Sort by pinned and display_order from the models metadata table.
// Keep models that only exist in abilities as a fallback, so legacy/custom
// configurations are not hidden if their metadata row is missing.
var orderedModels []string
if len(models) > 0 {
var metaList []model.Model
if err := model.DB.Where("model_name IN ?", models).Order("pinned DESC, display_order ASC, id DESC").Find(&metaList).Error; err == nil {
orderedSet := make(map[string]bool, len(models))
for _, m := range metaList {
if _, ok := orderedSet[m.ModelName]; !ok {
orderedModels = append(orderedModels, m.ModelName)
orderedSet[m.ModelName] = true
}
}
// Append any models that were not found in metadata (shouldn't happen, but safe)
for _, nm := range models {
if !orderedSet[nm] {
orderedModels = append(orderedModels, nm)
orderedSet[nm] = true
}
}
} else {
orderedModels = models
}
} else {
orderedModels = models
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": models,
"data": orderedModels,
})
return
}
Expand Down
22 changes: 19 additions & 3 deletions model/model_meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ type Model struct {
EnableGroups []string `json:"enable_groups,omitempty" gorm:"-"`
QuotaTypes []int `json:"quota_types,omitempty" gorm:"-"`
NameRule int `json:"name_rule" gorm:"default:0"`
DisplayOrder int `json:"display_order" gorm:"default:0;index:idx_models_order,priority:2"`
Pinned int `json:"pinned" gorm:"default:0;index:idx_models_order,priority:1"`

MatchedModels []string `json:"matched_models,omitempty" gorm:"-"`
MatchedCount int `json:"matched_count,omitempty" gorm:"-"`
Expand All @@ -48,6 +50,7 @@ func (mi *Model) Insert() error {
now := common.GetTimestamp()
mi.CreatedTime = now
mi.UpdatedTime = now
mi.NormalizeOrdering()

// 保存原始值(因为 Create 后可能被 GORM 的 default 标签覆盖为 1)
originalStatus := mi.Status
Expand All @@ -62,6 +65,8 @@ func (mi *Model) Insert() error {
return DB.Model(&Model{}).Where("id = ?", mi.Id).Updates(map[string]interface{}{
"status": originalStatus,
"sync_official": originalSyncOfficial,
"display_order": mi.DisplayOrder,
"pinned": mi.Pinned,
}).Error
}

Expand All @@ -76,12 +81,22 @@ func IsModelNameDuplicated(id int, name string) (bool, error) {

func (mi *Model) Update() error {
mi.UpdatedTime = common.GetTimestamp()
mi.NormalizeOrdering()
// 使用 Select 强制更新所有字段,包括零值
return DB.Model(&Model{}).Where("id = ?", mi.Id).
Select("model_name", "description", "icon", "tags", "vendor_id", "endpoints", "status", "sync_official", "name_rule", "updated_time").
Select("model_name", "description", "icon", "tags", "vendor_id", "endpoints", "status", "sync_official", "name_rule", "display_order", "pinned", "updated_time").
Updates(mi).Error
}

func (mi *Model) NormalizeOrdering() {
if mi.DisplayOrder < 0 {
mi.DisplayOrder = 0
}
if mi.Pinned != 0 {
mi.Pinned = 1
}
}

func (mi *Model) Delete() error {
return DB.Delete(mi).Error
}
Expand All @@ -106,7 +121,8 @@ func GetVendorModelCounts() (map[int64]int64, error) {

func GetAllModels(offset int, limit int) ([]*Model, error) {
var models []*Model
err := DB.Order("id DESC").Offset(offset).Limit(limit).Find(&models).Error
// No JOIN here, so unqualified column names are safe across supported DBs.
err := DB.Order("pinned DESC, display_order ASC, id DESC").Offset(offset).Limit(limit).Find(&models).Error
return models, err
}

Expand Down Expand Up @@ -210,7 +226,7 @@ func SearchModels(keyword string, vendor string, offset int, limit int) ([]*Mode
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
if err := db.Order("models.id DESC").Offset(offset).Limit(limit).Find(&models).Error; err != nil {
if err := db.Order("models.pinned DESC, models.display_order ASC, models.id DESC").Offset(offset).Limit(limit).Find(&models).Error; err != nil {
return nil, 0, err
}
return models, total, nil
Expand Down
18 changes: 18 additions & 0 deletions model/pricing.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package model
import (
"encoding/json"
"fmt"
"sort"
"strings"

"sync"
Expand All @@ -16,11 +17,14 @@ import (
)

type Pricing struct {
Id int `json:"id"`
ModelName string `json:"model_name"`
Description string `json:"description,omitempty"`
Icon string `json:"icon,omitempty"`
Tags string `json:"tags,omitempty"`
VendorID int `json:"vendor_id,omitempty"`
DisplayOrder int `json:"display_order"`
Pinned int `json:"pinned"`
QuotaType int `json:"quota_type"`
ModelRatio float64 `json:"model_ratio"`
ModelPrice float64 `json:"model_price"`
Expand Down Expand Up @@ -299,10 +303,13 @@ func updatePricing() {
if meta.Status != 1 {
continue
}
pricing.Id = meta.Id
pricing.Description = meta.Description
pricing.Icon = meta.Icon
pricing.Tags = meta.Tags
pricing.VendorID = meta.VendorID
pricing.DisplayOrder = meta.DisplayOrder
pricing.Pinned = meta.Pinned
}
modelPrice, findPrice := ratio_setting.GetModelPrice(model, false)
if findPrice {
Expand Down Expand Up @@ -340,6 +347,17 @@ func updatePricing() {
pricingMap = append(pricingMap, pricing)
}

// 按 pinned DESC, display_order ASC, id DESC 排序,确保输出顺序稳定一致
sort.SliceStable(pricingMap, func(i, j int) bool {
if pricingMap[i].Pinned != pricingMap[j].Pinned {
return pricingMap[i].Pinned > pricingMap[j].Pinned
}
if pricingMap[i].DisplayOrder != pricingMap[j].DisplayOrder {
return pricingMap[i].DisplayOrder < pricingMap[j].DisplayOrder
}
return pricingMap[i].Id > pricingMap[j].Id
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// 防止大更新后数据不通用
if len(pricingMap) > 0 {
pricingMap[0].PricingVersion = "5a90f2b86c08bd983a9a2e6d66c255f4eaef9c4bc934386d2b6ae84ef0ff1f1f"
Expand Down
72 changes: 72 additions & 0 deletions web/classic/src/components/table/models/ModelsColumnDefs.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,17 @@ import {
Tag,
Typography,
Modal,
InputNumber,
Switch,
Tooltip,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
getLobeHubIcon,
stringToColor,
API,
showError,
showSuccess,
} from '../../../helpers';
import {
renderLimitedItems,
Expand All @@ -38,6 +43,24 @@ import {

const { Text } = Typography;

const updateModelOrdering = async (record, changes, refresh, t) => {
try {
const res = await API.put('/api/models/?order_only=true', {
id: record.id,
...changes,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功完成!'));
await refresh();
} else {
showError(t(message));
}
} catch (error) {
showError(error.response?.data?.message || t('操作失败'));
}
};

// Render timestamp
function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
Expand Down Expand Up @@ -298,6 +321,55 @@ export const getModelsColumns = ({
</Text>
),
},
{
title: t('置顶'),
dataIndex: 'pinned',
align: 'center',
width: 90,
render: (value, record) => (
<div onClick={(e) => e.stopPropagation()}>
<Switch
size='small'
checked={Boolean(value)}
onChange={(checked) =>
updateModelOrdering(
record,
{ pinned: checked ? 1 : 0 },
refresh,
t,
)
}
/>
</div>
),
},
{
title: t('展示顺序'),
dataIndex: 'display_order',
width: 130,
render: (value, record) => (
<div onClick={(e) => e.stopPropagation()}>
<InputNumber
key={`${record.id}-${value ?? 0}`}
size='small'
defaultValue={value ?? 0}
step={1}
Comment on lines +352 to +356

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

InputNumber should be controlled to avoid stale table values.

defaultValue is only applied on first mount; after refresh or external updates, the cell can display outdated order. Bind value to current row data instead.

Suggested patch
-          <InputNumber
+          <InputNumber
             size='small'
-            defaultValue={value ?? 0}
+            value={value ?? 0}
             step={1}
🤖 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/classic/src/components/table/models/ModelsColumnDefs.jsx` around lines
354 - 357, The InputNumber is using defaultValue, which makes it uncontrolled
and stale; change it to a controlled input by replacing defaultValue with value
(bind it to the current row field, e.g. value={row.someOrderField ?? 0}) and
wire its onChange to the table/row update handler (call the existing cell update
function or dispatch setRowData/updateRecord from ModelsColumnDefs) so edits
update the underlying data model; remove defaultValue and ensure the value prop
reflects the latest row data.

min={0}
onBlur={(event) => {
const nextValue = Number(event.target.value || 0);
if (nextValue === (record.display_order ?? 0)) return;
updateModelOrdering(
record,
{ display_order: nextValue },
refresh,
t,
);
}}
style={{ width: 96 }}
/>
</div>
),
},
{
title: t('匹配类型'),
dataIndex: 'name_rule',
Expand Down
24 changes: 24 additions & 0 deletions web/classic/src/components/table/models/modals/EditModelModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ const EditModelModal = (props) => {
name_rule: props.editingModel?.model_name ? 0 : undefined, // 通过未配置模型过来的固定为精确匹配
status: true,
sync_official: true,
pinned: false,
display_order: 0,
});

const handleCancel = () => {
Expand Down Expand Up @@ -151,6 +153,8 @@ const EditModelModal = (props) => {
// 处理status/sync_official,将数字转为布尔值
data.status = data.status === 1;
data.sync_official = (data.sync_official ?? 1) === 1;
data.pinned = Boolean(data.pinned);
data.display_order = data.display_order ?? 0;
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...data });
}
Expand Down Expand Up @@ -198,6 +202,8 @@ const EditModelModal = (props) => {
endpoints: values.endpoints || '',
status: values.status ? 1 : 0,
sync_official: values.sync_official ? 1 : 0,
pinned: values.pinned ? 1 : 0,
display_order: values.display_order ?? 0,
};

if (isEdit) {
Expand Down Expand Up @@ -524,6 +530,24 @@ const EditModelModal = (props) => {
}
/>
</Col>
<Col span={24}>
<Form.Switch
field='pinned'
label={t('置顶')}
extraText={t('置顶模型会优先展示在模型广场和用户模型列表中')}
size='large'
/>
</Col>
<Col span={24}>
<Form.InputNumber
field='display_order'
label={t('展示顺序')}
step={1}
min={0}
extraText={t('默认排序时数值越小越靠前')}
style={{ width: '100%' }}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/>
</Col>
<Col span={24}>
<Form.Switch
field='sync_official'
Expand Down
6 changes: 5 additions & 1 deletion web/classic/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -3825,6 +3825,10 @@
"并确认自行承担部署": "confirm that I bear legal responsibility arising from deployment",
"运营和收费行为产生的法律责任": "operation and charging behavior",
",": ", ",
"、": ", "
"、": ", ",
"置顶": "Pinned",
"展示顺序": "Display Order",
"置顶模型会优先展示在模型广场和用户模型列表中": "Pinned models appear first in the marketplace and user model list",
"默认排序时数值越小越靠前": "Lower values appear first when default sort is used"
}
}
6 changes: 5 additions & 1 deletion web/classic/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -3679,6 +3679,10 @@
"并确认自行承担部署": "confirm that I bear legal responsibility arising from deployment",
"运营和收费行为产生的法律责任": "operation and charging behavior",
",": ", ",
"、": ", "
"、": ", ",
"置顶": "Épinglé",
"展示顺序": "Ordre d'affichage",
"置顶模型会优先展示在模型广场和用户模型列表中": "Les modèles épinglés apparaissent en premier dans la marketplace et la liste des modèles utilisateur",
"默认排序时数值越小越靠前": "Les valeurs les plus faibles apparaissent en premier avec le tri par défaut"
}
}
Loading