Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(frontend): 修复复制模型时模型名称被改写的问题 (#3830)

LL_Ricky9842e51d40a5
diff --git a/frontend/src/api/model/index.ts b/frontend/src/api/model/index.ts
index 24cb59303..97c4687b5 100644
--- a/frontend/src/api/model/index.ts
+++ b/frontend/src/api/model/index.ts
@@ -99,6 +99,24 @@ export interface ModelConfig {
deleted_at?: string | null;
}
+// 复制模型。只提交展示名;name 与凭证由服务端从源模型复制。
+export function copyModelConfig(id: string, displayName: string): Promise<ModelConfig> {
+ return new Promise((resolve, reject) => {
+ post(`/api/v1/models/${id}/copy`, { display_name: displayName })
+ .then((response: any) => {
+ if (response.success && response.data) {
+ resolve(response.data);
+ } else {
+ reject(new Error(response.message || ''));
+ }
+ })
+ .catch((error: any) => {
+ console.error('Failed to copy model:', error);
+ reject(error);
+ });
+ });
+}
+
// 创建模型
export function createModel(data: ModelConfig): Promise<ModelConfig> {
return new Promise((resolve, reject) => {
diff --git a/frontend/src/utils/modelCopyName.test.ts b/frontend/src/utils/modelCopyName.test.ts
new file mode 100644
index 000000000..52337ac87
--- /dev/null
+++ b/frontend/src/utils/modelCopyName.test.ts
@@ -0,0 +1,42 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ MODEL_DISPLAY_NAME_MAX_LEN,
+ generateCopyDisplayName,
+ modelCopyLabel,
+} from './modelCopyName.ts'
+
+test('modelCopyLabel prefers a trimmed display name and otherwise uses name', () => {
+ assert.equal(modelCopyLabel({ display_name: ' 生产 GPT ', name: 'gpt-4o' }), '生产 GPT')
+ assert.equal(modelCopyLabel({ display_name: ' ', name: 'gpt-4o' }), 'gpt-4o')
+ assert.equal(modelCopyLabel({ name: 'qwen3:8b' }), 'qwen3:8b')
+})
+
+test('generateCopyDisplayName suffixes the display label and keeps later copies numbered', () => {
+ assert.equal(generateCopyDisplayName('生产 GPT', ['生产 GPT'], ' 副本'), '生产 GPT 副本')
+ assert.equal(
+ generateCopyDisplayName('生产 GPT', ['生产 GPT', '生产 GPT 副本'], ' 副本'),
+ '生产 GPT 副本 2',
+ )
+})
+
+test('generateCopyDisplayName treats a name-only row as occupying that label', () => {
+ assert.equal(
+ generateCopyDisplayName('gpt-4o', ['gpt-4o', 'gpt-4o 副本'], ' 副本'),
+ 'gpt-4o 副本 2',
+ )
+})
+
+test('generateCopyDisplayName fits the label into the display_name column', () => {
+ const suffix = ' 副本'
+ const base = '名'.repeat(300)
+ const first = generateCopyDisplayName(base, [], suffix)
+ assert.equal(Array.from(first).length, MODEL_DISPLAY_NAME_MAX_LEN)
+ assert.equal(first.endsWith(suffix), true)
+
+ const second = generateCopyDisplayName(base, [first], suffix)
+ assert.equal(Array.from(second).length, MODEL_DISPLAY_NAME_MAX_LEN)
+ assert.equal(second.endsWith(`${suffix} 2`), true)
+ assert.notEqual(first, second)
+})
diff --git a/frontend/src/utils/modelCopyName.ts b/frontend/src/utils/modelCopyName.ts
new file mode 100644
index 000000000..234db0297
--- /dev/null
+++ b/frontend/src/utils/modelCopyName.ts
@@ -0,0 +1,47 @@
+// models.display_name is VARCHAR(255). Keep this aligned with
+// types.ModelDisplayNameMaxLen.
+export const MODEL_DISPLAY_NAME_MAX_LEN = 255
+
+const MAX_COPY_ATTEMPTS = 10000
+
+export function modelCopyLabel(model: { display_name?: string | null; name?: string | null }): string {
+ const displayName = model.display_name?.trim()
+ return displayName || model.name || ''
+}
+
+// generateCopyDisplayName builds a display label that is not already used
+// and fits in the display_name column. The model name is not part of the
+// result; callers keep the source name unchanged.
+export function generateCopyDisplayName(
+ originalDisplayName: string,
+ existingLabels: Iterable<string>,
+ suffix: string,
+): string {
+ const base = originalDisplayName.trim()
+ const taken = new Set(existingLabels)
+ let counter: number | undefined
+ let candidate = fitCopyDisplayName(base, suffix, counter).trim()
+ for (let attempt = 0; attempt < MAX_COPY_ATTEMPTS; attempt++) {
+ if (candidate && !taken.has(candidate)) {
+ return candidate
+ }
+ counter = counter == null ? 2 : counter + 1
+ const next = fitCopyDisplayName(base, suffix, counter).trim()
+ if (next === candidate) {
+ break
+ }
+ candidate = next
+ }
+ throw new Error('unique copy display name exceeds the length limit')
+}
+
+function fitCopyDisplayName(base: string, suffix: string, counter?: number): string {
+ const tail = counter == null ? suffix : `${suffix} ${counter}`
+ const tailChars = Array.from(tail)
+ const baseChars = Array.from(base)
+ if (tailChars.length >= MODEL_DISPLAY_NAME_MAX_LEN) {
+ return tailChars.slice(tailChars.length - MODEL_DISPLAY_NAME_MAX_LEN).join('')
+ }
+ const room = MODEL_DISPLAY_NAME_MAX_LEN - tailChars.length
+ return baseChars.slice(0, room).join('') + tail
+}
diff --git a/frontend/src/views/settings/ModelSettings.vue b/frontend/src/views/settings/ModelSettings.vue
index 7219e7dc7..9efa20824 100644
--- a/frontend/src/views/settings/ModelSettings.vue
+++ b/frontend/src/views/settings/ModelSettings.vue
@@ -294,6 +294,7 @@ import ModelDebugDrawer from '@/components/ModelDebugDrawer.vue'
import {
listModels,
createModel,
+ copyModelConfig,
updateModel as updateModelAPI,
deleteModel as deleteModelAPI,
ModelInUseError,
@@ -307,6 +308,7 @@ import {
type ModelUsageResourceKind,
} from '@/api/model'
import { useAuthStore } from '@/stores/auth'
+import { generateCopyDisplayName, modelCopyLabel } from '@/utils/modelCopyName'
import { useUIStore } from '@/stores/ui'
import { focusKbEditorSection } from '@/config/contextualGuides'
import { useChatResourcesStore } from '@/stores/chatResources'
@@ -358,6 +360,7 @@ watch(
// 模型列表数据
const allModels = ref<ModelConfig[]>([])
+const copyingModelId = ref<string | null>(null)
// 后端 type → 前端分组 type 的映射
const backendTypeToModelType: Record<string, ModelType> = {
@@ -805,7 +808,7 @@ const getModelOptions = (type: ModelType, model: any) => {
// Models are tenant-wide infrastructure (LLM credentials); the
// backend gates every mutation behind Admin+ (see RegisterModelRoutes).
// Non-Admins get an empty action menu — viewing is fine, but editing,
- // copying (also goes through createModel), and deleting are not.
+ // copying (POST /models/:id/copy), and deleting are not.
if (!authStore.hasRole('admin')) {
return options
}
@@ -834,23 +837,10 @@ const handleMenuAction = (data: { value: string }, type: ModelType, model: any)
}
}
-// 生成不重复的复制名称
-const generateCopyName = (originalName: string): string => {
- const suffix = t('modelSettings.copySuffix')
- const existingNames = new Set(allModels.value.map(m => m.name))
- let candidate = `${originalName}${suffix}`
- let counter = 2
- while (existingNames.has(candidate)) {
- candidate = `${originalName}${suffix} ${counter}`
- counter += 1
- }
- return candidate
-}
-
-// 复制模型
+// 复制模型。name 与凭证由服务端从源记录复制;这里只生成不重复的展示名。
const copyModel = async (_type: ModelType, modelId: string) => {
const source = allModels.value.find(m => m.id === modelId)
- if (!source) {
+ if (!source?.id || copyingModelId.value) {
return
}
if (source.is_builtin) {
@@ -858,22 +848,21 @@ const copyModel = async (_type: ModelType, modelId: string) => {
return
}
+ copyingModelId.value = modelId
try {
- const newModel: ModelConfig = {
- name: generateCopyName(source.name),
- display_name: source.display_name || '',
- type: source.type,
- source: source.source,
- description: source.description || '',
- parameters: JSON.parse(JSON.stringify(source.parameters || {}))
- }
-
- await createModel(newModel)
+ const displayName = generateCopyDisplayName(
+ modelCopyLabel(source),
+ allModels.value.map(model => modelCopyLabel(model)),
+ t('modelSettings.copySuffix'),
+ )
+ await copyModelConfig(source.id, displayName)
MessagePlugin.success(t('modelSettings.toasts.copied'))
await loadModels()
} catch (error: any) {
console.error('复制模型失败:', error)
MessagePlugin.error(error.message || t('modelSettings.toasts.copyFailed'))
+ } finally {
+ copyingModelId.value = null
}
}
diff --git a/internal/application/service/model.go b/internal/application/service/model.go
index 8d842c664..302f49ee9 100644
--- a/internal/application/service/model.go
+++ b/internal/application/service/model.go
@@ -2,9 +2,11 @@ package service
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"strings"
+ "unicode/utf8"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
@@ -132,7 +134,87 @@ func (s *modelService) CreateModel(ctx context.Context, model *types.Model) erro
return err
}
- // Start asynchronous model download
+ s.downloadModelAsync(ctx, model)
+
+ logger.Infof(ctx, "Model creation initiated successfully: %s", model.ID)
+ return nil
+}
+
+// CopyModel clones a tenant-owned model. The stored name stays the upstream
+// model identifier. displayName is the label chosen by the caller. Credentials
+// are copied from the source row because list responses never include them.
+// An active local model is already present, so the copy does not download it
+// again. A local model that is still downloading or failed starts a pull.
+func (s *modelService) CopyModel(ctx context.Context, sourceID, displayName string) (*types.Model, error) {
+ sourceID = strings.TrimSpace(sourceID)
+ if sourceID == "" {
+ return nil, apperrors.NewBadRequestError("model ID cannot be empty")
+ }
+ displayName = strings.TrimSpace(utils.SanitizeForLog(displayName))
+ if displayName == "" {
+ return nil, apperrors.NewBadRequestError("display name is required")
+ }
+ if utf8.RuneCountInString(displayName) > types.ModelDisplayNameMaxLen {
+ return nil, apperrors.NewBadRequestError("display name is too long")
+ }
+
+ tenantID := types.MustTenantIDFromContext(ctx)
+ source, err := s.repo.GetByID(ctx, tenantID, sourceID)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "model_id": sourceID,
+ })
+ return nil, err
+ }
+ if source == nil {
+ return nil, ErrModelNotFound
+ }
+ if source.IsBuiltin {
+ return nil, apperrors.NewBadRequestError("builtin models cannot be copied")
+ }
+
+ params, err := cloneModelParameters(source.Parameters)
+ if err != nil {
+ return nil, err
+ }
+ model := &types.Model{
+ TenantID: tenantID,
+ Name: source.Name,
+ DisplayName: displayName,
+ Type: source.Type,
+ Source: source.Source,
+ Description: source.Description,
+ Parameters: params,
+ }
+ logger.Infof(ctx, "Copying model %s as %q", source.ID, displayName)
+
+ // Remote rows, and local rows that already finished downloading, are
+ // configuration copies. Only a local row that is not active needs a pull.
+ if model.Source != types.ModelSourceLocal || source.Status == types.ModelStatusActive {
+ model.Status = types.ModelStatusActive
+ if err := s.repo.Create(ctx, model); err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "model_id": source.ID,
+ "model_name": model.Name,
+ })
+ return nil, err
+ }
+ return model, nil
+ }
+
+ model.Status = types.ModelStatusDownloading
+ if err := s.repo.Create(ctx, model); err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "model_id": source.ID,
+ "model_name": model.Name,
+ })
+ return nil, err
+ }
+ s.downloadModelAsync(ctx, model)
+ return model, nil
+}
+
+func (s *modelService) downloadModelAsync(ctx context.Context, model *types.Model) {
logger.Infof(ctx, "Starting background download for model: %s", model.Name)
newCtx := logger.CloneContext(ctx)
go func() {
@@ -150,9 +232,18 @@ func (s *modelService) CreateModel(ctx context.Context, model *types.Model) erro
logger.Infof(newCtx, "Updating model status to: %s", model.Status)
s.repo.Update(newCtx, model)
}()
+}
- logger.Infof(ctx, "Model creation initiated successfully: %s", model.ID)
- return nil
+func cloneModelParameters(params types.ModelParameters) (types.ModelParameters, error) {
+ raw, err := json.Marshal(params)
+ if err != nil {
+ return types.ModelParameters{}, err
+ }
+ var cloned types.ModelParameters
+ if err := json.Unmarshal(raw, &cloned); err != nil {
+ return types.ModelParameters{}, err
+ }
+ return cloned, nil
}
// GetModelByID retrieves a model by its ID
diff --git a/internal/application/service/model_copy_test.go b/internal/application/service/model_copy_test.go
new file mode 100644
index 000000000..c61e3dab5
--- /dev/null
+++ b/internal/application/service/model_copy_test.go
@@ -0,0 +1,155 @@
+package service
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubCopyModelRepo struct {
+ source *types.Model
+ created *types.Model
+ updates int
+}
+
+func (s *stubCopyModelRepo) Create(_ context.Context, model *types.Model) error {
+ copied := *model
+ s.created = &copied
+ return nil
+}
+
+func (s *stubCopyModelRepo) GetByID(_ context.Context, _ uint64, id string) (*types.Model, error) {
+ if s.source != nil && s.source.ID == id {
+ return s.source, nil
+ }
+ return nil, nil
+}
+
+func (s *stubCopyModelRepo) List(context.Context, uint64, types.ModelType, types.ModelSource) ([]*types.Model, error) {
+ return nil, nil
+}
+
+func (s *stubCopyModelRepo) Update(context.Context, *types.Model) error {
+ s.updates++
+ return nil
+}
+
+func (s *stubCopyModelRepo) Delete(context.Context, uint64, string) error { return nil }
+
+func (s *stubCopyModelRepo) ClearDefaultByType(context.Context, uint, types.ModelType, string) error {
+ return nil
+}
+
+func TestCopyModel_CopiesCredentialsAndKeepsName(t *testing.T) {
+ source := &types.Model{
+ ID: "src",
+ TenantID: 7,
+ Name: "gpt-4o",
+ DisplayName: "生产 GPT",
+ Type: types.ModelTypeKnowledgeQA,
+ Source: types.ModelSourceRemote,
+ Description: "primary",
+ IsDefault: true,
+ Status: types.ModelStatusActive,
+ Parameters: types.ModelParameters{
+ BaseURL: "https://api.example.com/v1",
+ APIKey: "sk-live",
+ AppSecret: "app-secret",
+ Provider: "openai",
+ ExtraConfig: map[string]string{
+ "region": "us",
+ "secret_key": "stored-secret",
+ },
+ Spec: &types.ModelSpecOverride{
+ API: "openai-completions",
+ Compat: map[string]any{"temperature": "0.2"},
+ },
+ },
+ }
+ repo := &stubCopyModelRepo{source: source}
+ svc := NewModelService(repo, &stubKBRepoForModelDelete{}, &stubAgentRepoForModelDelete{}, nil, nil, nil)
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+
+ copied, err := svc.CopyModel(ctx, "src", " 生产 GPT 副本\n")
+ require.NoError(t, err)
+ require.NotNil(t, repo.created)
+ assert.Equal(t, copied, repo.created)
+ assert.Empty(t, copied.ID)
+ assert.Equal(t, uint64(7), copied.TenantID)
+ assert.Equal(t, "gpt-4o", copied.Name)
+ assert.Equal(t, "生产 GPT 副本", copied.DisplayName)
+ assert.Equal(t, "primary", copied.Description)
+ assert.Equal(t, types.ModelStatusActive, copied.Status)
+ assert.False(t, copied.IsDefault)
+ assert.False(t, copied.IsBuiltin)
+ assert.Equal(t, "sk-live", copied.Parameters.APIKey)
+ assert.Equal(t, "app-secret", copied.Parameters.AppSecret)
+ assert.Equal(t, "stored-secret", copied.Parameters.ExtraConfig["secret_key"])
+ assert.Equal(t, "https://api.example.com/v1", copied.Parameters.BaseURL)
+ assert.Zero(t, repo.updates)
+
+ copied.Parameters.ExtraConfig["region"] = "changed"
+ copied.Parameters.APIKey = "changed"
+ copied.Parameters.Spec.Compat["extra"] = "1"
+ assert.Equal(t, "us", source.Parameters.ExtraConfig["region"])
+ assert.Equal(t, "sk-live", source.Parameters.APIKey)
+ _, carried := source.Parameters.Spec.Compat["extra"]
+ assert.False(t, carried)
+}
+
+func TestCopyModel_ActiveLocalModelSkipsDownload(t *testing.T) {
+ repo := &stubCopyModelRepo{source: &types.Model{
+ ID: "local-src",
+ Name: "qwen3:8b",
+ Type: types.ModelTypeKnowledgeQA,
+ Source: types.ModelSourceLocal,
+ Status: types.ModelStatusActive,
+ }}
+ svc := NewModelService(repo, &stubKBRepoForModelDelete{}, &stubAgentRepoForModelDelete{}, nil, nil, nil)
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+
+ copied, err := svc.CopyModel(ctx, "local-src", "qwen3:8b 副本")
+ require.NoError(t, err)
+ assert.Equal(t, "qwen3:8b", copied.Name)
+ assert.Equal(t, types.ModelStatusActive, copied.Status)
+ assert.Equal(t, types.ModelSourceLocal, copied.Source)
+ assert.Zero(t, repo.updates)
+}
+
+func TestCopyModel_RejectsBuiltinMissingAndOverlongDisplayName(t *testing.T) {
+ repo := &stubCopyModelRepo{source: &types.Model{
+ ID: "builtin",
+ Name: "gpt-4o",
+ IsBuiltin: true,
+ Source: types.ModelSourceRemote,
+ Status: types.ModelStatusActive,
+ }}
+ svc := NewModelService(repo, &stubKBRepoForModelDelete{}, &stubAgentRepoForModelDelete{}, nil, nil, nil)
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+
+ _, err := svc.CopyModel(ctx, "builtin", "副本")
+ require.Error(t, err)
+ appErr, ok := apperrors.IsAppError(err)
+ require.True(t, ok)
+ assert.Equal(t, apperrors.ErrBadRequest, appErr.Code)
+ assert.Nil(t, repo.created)
+
+ _, err = svc.CopyModel(ctx, "missing", "副本")
+ assert.ErrorIs(t, err, ErrModelNotFound)
+
+ _, err = svc.CopyModel(ctx, "builtin", " ")
+ appErr, ok = apperrors.IsAppError(err)
+ require.True(t, ok)
+ assert.Equal(t, apperrors.ErrBadRequest, appErr.Code)
+
+ _, err = svc.CopyModel(ctx, "builtin", strings.Repeat("名", types.ModelDisplayNameMaxLen+1))
+ appErr, ok = apperrors.IsAppError(err)
+ require.True(t, ok)
+ assert.Equal(t, apperrors.ErrBadRequest, appErr.Code)
+ assert.Contains(t, appErr.Message, "too long")
+}
diff --git a/internal/application/service/session_knowledge_qa_test.go b/internal/application/service/session_knowledge_qa_test.go
index 4519d3e02..682350711 100644
--- a/internal/application/service/session_knowledge_qa_test.go
+++ b/internal/application/service/session_knowledge_qa_test.go
@@ -85,6 +85,10 @@ func (s *stubModelService) CreateModel(context.Context, *types.Model) error {
return nil
}
+func (s *stubModelService) CopyModel(context.Context, string, string) (*types.Model, error) {
+ return nil, nil
+}
+
func (s *stubModelService) GetModelByID(_ context.Context, id string) (*types.Model, error) {
return s.modelsByID[id], nil
}
diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go
index 879bd7411..abb563099 100644
--- a/internal/application/service/tenant_skill_install_test.go
+++ b/internal/application/service/tenant_skill_install_test.go
@@ -3324,6 +3324,10 @@ type installModelService struct {
}
func (s *installModelService) CreateModel(context.Context, *types.Model) error { return nil }
+func (s *installModelService) CopyModel(context.Context, string, string) (*types.Model, error) {
+ return nil, nil
+}
+
func (s *installModelService) GetModelByID(context.Context, string) (*types.Model, error) {
return nil, nil
}
diff --git a/internal/handler/model.go b/internal/handler/model.go
index 778546f5c..94319b2cd 100644
--- a/internal/handler/model.go
+++ b/internal/handler/model.go
@@ -128,6 +128,76 @@ func (h *ModelHandler) CreateModel(c *gin.Context) {
})
}
+// CopyModelRequest is the body of POST /models/:id/copy. Only the display
+// name is client-supplied. The model name and credentials come from the
+// stored source row.
+type CopyModelRequest struct {
+ DisplayName string `json:"display_name" binding:"required"`
+}
+
+// CopyModel godoc
+// @Summary 复制模型
+// @Description 复制模型配置。name 与源模型一致,凭证从已存记录复制,不接受客户端重传。
+// @Tags 模型管理
+// @Accept json
+// @Produce json
+// @Param id path string true "源模型ID"
+// @Param request body CopyModelRequest true "副本展示名"
+// @Success 201 {object} map[string]interface{} "复制的模型"
+// @Failure 400 {object} errors.AppError "请求参数错误"
+// @Failure 404 {object} errors.AppError "模型不存在"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /models/{id}/copy [post]
+func (h *ModelHandler) CopyModel(c *gin.Context) {
+ ctx := c.Request.Context()
+
+ id := secutils.SanitizeForLog(c.Param("id"))
+ if id == "" {
+ logger.Error(ctx, "Model ID is empty")
+ _ = c.Error(errors.NewBadRequestError("Model ID cannot be empty"))
+ return
+ }
+
+ var req CopyModelRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ logger.Error(ctx, "Failed to parse request parameters", err)
+ _ = c.Error(errors.NewBadRequestError(err.Error()))
+ return
+ }
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ if tenantID == 0 {
+ logger.Error(ctx, "Tenant ID is empty")
+ _ = c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
+ return
+ }
+
+ model, err := h.service.CopyModel(ctx, id, req.DisplayName)
+ if err != nil {
+ if err == service.ErrModelNotFound {
+ logger.Warnf(ctx, "Model not found, ID: %s", id)
+ _ = c.Error(errors.NewNotFoundError("Model not found"))
+ return
+ }
+ if appErr, ok := errors.IsAppError(err); ok {
+ _ = c.Error(appErr)
+ return
+ }
+ logger.ErrorWithFields(ctx, err, nil)
+ _ = c.Error(errors.NewInternalServerError(err.Error()))
+ return
+ }
+
+ logger.Infof(ctx, "Model copied successfully, ID: %s, Name: %s",
+ secutils.SanitizeForLog(model.ID),
+ secutils.SanitizeForLog(model.Name),
+ )
+ c.JSON(http.StatusCreated, gin.H{
+ "success": true,
+ "data": dto.NewModelResponse(ctx, model),
+ })
+}
+
// GetModel godoc
// @Summary 获取模型详情
// @Description 根据ID获取模型详情
diff --git a/internal/handler/model_copy_test.go b/internal/handler/model_copy_test.go
new file mode 100644
index 000000000..81eadb4e8
--- /dev/null
+++ b/internal/handler/model_copy_test.go
@@ -0,0 +1,69 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type stubCopyModelService struct {
+ interfaces.ModelService
+ sourceID string
+ displayName string
+ model *types.Model
+}
+
+func (s *stubCopyModelService) CopyModel(_ context.Context, sourceID, displayName string) (*types.Model, error) {
+ s.sourceID = sourceID
+ s.displayName = displayName
+ return s.model, nil
+}
+
+func TestCopyModelResponseOmitsCredentials(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ stub := &stubCopyModelService{
+ model: &types.Model{
+ ID: "copy-1",
+ Name: "gpt-4o",
+ DisplayName: "生产 GPT 副本",
+ Type: types.ModelTypeKnowledgeQA,
+ Source: types.ModelSourceRemote,
+ Status: types.ModelStatusActive,
+ Parameters: types.ModelParameters{
+ BaseURL: "https://api.example.com/v1",
+ APIKey: "sk-live",
+ AppSecret: "app-secret",
+ },
+ },
+ }
+ h := NewModelHandler(stub)
+ router := gin.New()
+ router.POST("/models/:id/copy", func(c *gin.Context) {
+ c.Set(types.TenantIDContextKey.String(), uint64(7))
+ h.CopyModel(c)
+ })
+
+ payload := bytes.NewBufferString(`{"display_name":"生产 GPT 副本"}`)
+ req := httptest.NewRequest(http.MethodPost, "/models/src/copy", payload)
+ req.Header.Set("Content-Type", "application/json")
+ req = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(7)))
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusCreated, rec.Code)
+ body := rec.Body.String()
+ require.NotContains(t, body, "sk-live")
+ require.NotContains(t, body, "app-secret")
+ require.Contains(t, body, `"name":"gpt-4o"`)
+ require.Contains(t, body, `"display_name":"生产 GPT 副本"`)
+ require.Contains(t, body, `"api_key":{"configured":true}`)
+ require.Equal(t, "src", stub.sourceID)
+ require.Equal(t, "生产 GPT 副本", stub.displayName)
+}
diff --git a/internal/models/api/endpoint_test.go b/internal/models/api/endpoint_test.go
index 284380b6b..b59a63ca8 100644
--- a/internal/models/api/endpoint_test.go
+++ b/internal/models/api/endpoint_test.go
@@ -12,7 +12,7 @@ import (
)
func TestDoKeepsHeadersOnHTTPError(t *testing.T) {
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Retry-After", "12")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":"rate limited"}`))
diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go
index 9c77eb5d7..73dd49b0d 100644
--- a/internal/router/router_api_key_capabilities_test.go
+++ b/internal/router/router_api_key_capabilities_test.go
@@ -363,6 +363,7 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
{http.MethodGet, "/api/v1/tenants", types.APIKeyCapabilityManageTenantSettings},
{http.MethodGet, "/api/v1/models", types.APIKeyCapabilityManageModels},
{http.MethodDelete, "/api/v1/models/:id", types.APIKeyCapabilityManageModels},
+ {http.MethodPost, "/api/v1/models/:id/copy", types.APIKeyCapabilityManageModels},
{http.MethodPost, "/api/v1/evaluation", types.APIKeyCapabilityRunEvaluations},
{http.MethodGet, "/api/v1/system/info", types.APIKeyCapabilityManageVectorStores},
{http.MethodGet, "/api/v1/mcp-services", types.APIKeyCapabilityManageMCPServices},
diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.go
index 4156bf507..36fd2a11f 100644
--- a/internal/router/routes_infra.go
+++ b/internal/router/routes_infra.go
@@ -31,6 +31,8 @@ func RegisterModelRoutes(
models.GET("", g.Viewer(), handler.ListModels)
// 调试已保存模型会发起真实上游调用并产生费用 — Admin+
models.POST("/:id/debug", g.Admin(), handler.DebugModel)
+ // 复制模型配置(含已存凭证)— Admin+
+ models.POST("/:id/copy", g.Admin(), handler.CopyModel)
// 获取单个模型 — Viewer+
models.GET("/:id", g.Viewer(), handler.GetModel)
// 更新模型 — Admin+;内置模型仍由服务层额外限定为 SystemAdmin。
diff --git a/internal/types/interfaces/model.go b/internal/types/interfaces/model.go
index b29f27563..959084196 100644
--- a/internal/types/interfaces/model.go
+++ b/internal/types/interfaces/model.go
@@ -15,6 +15,10 @@ import (
type ModelService interface {
// CreateModel creates a model
CreateModel(ctx context.Context, model *types.Model) error
+ // CopyModel clones a tenant model. The model name stays the source
+ // identifier; displayName is the caller-chosen label. Stored credentials
+ // are copied with the row. An active local model is not downloaded again.
+ CopyModel(ctx context.Context, sourceID, displayName string) (*types.Model, error)
// GetModelByID gets a model by ID
GetModelByID(ctx context.Context, id string) (*types.Model, error)
// ListModels lists all models
diff --git a/internal/types/model.go b/internal/types/model.go
index 69fb38b86..633cbf285 100644
--- a/internal/types/model.go
+++ b/internal/types/model.go
@@ -200,6 +200,9 @@ func (o *ModelSpecOverride) CompatJSON() json.RawMessage {
// "value too long for type" failure at INSERT time.
const ModelIDMaxLen = 64
+// ModelDisplayNameMaxLen matches models.display_name VARCHAR(255).
+const ModelDisplayNameMaxLen = 255
+
// DefaultBuiltinModelTenantID is the tenant id that built-in models are
// assigned to when YAML does not specify one. Kept in sync with the seed
// value of tenants_id_seq in migrations/versioned/000000_init.up.sql