Skip to content

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

Simplify KB duplicate API and improve naming/docs coverage.

wizardchen6ac1703198cb
diff --git a/client/knowledgebase.go b/client/knowledgebase.go
index b79a11d15..0561e1b34 100644
--- a/client/knowledgebase.go
+++ b/client/knowledgebase.go
@@ -241,10 +241,6 @@ type CopyKnowledgeBaseResponse struct {
Message string `json:"message"`
}
-type DuplicateKnowledgeBaseRequest struct {
- TargetID string `json:"target_id,omitempty"`
-}
-
type DuplicateKnowledgeBaseResponse struct {
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
@@ -477,11 +473,10 @@ func (c *Client) CopyKnowledgeBase(ctx context.Context, request *CopyKnowledgeBa
func (c *Client) DuplicateKnowledgeBase(
ctx context.Context,
knowledgeBaseID string,
- request *DuplicateKnowledgeBaseRequest,
) (*DuplicateKnowledgeBaseResponse, error) {
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/duplicate", knowledgeBaseID)
- resp, err := c.doRequest(ctx, http.MethodPost, path, request, nil)
+ resp, err := c.doRequest(ctx, http.MethodPost, path, nil, nil)
if err != nil {
return nil, err
}
diff --git a/client/knowledgebase_duplicate_test.go b/client/knowledgebase_duplicate_test.go
new file mode 100644
index 000000000..e3c7fca10
--- /dev/null
+++ b/client/knowledgebase_duplicate_test.go
@@ -0,0 +1,57 @@
+package client
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestDuplicateKnowledgeBase(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ t.Fatalf("method = %s, want POST", r.Method)
+ }
+ if r.URL.Path != "/api/v1/knowledge-bases/kb-1/duplicate" {
+ t.Fatalf("path = %s, want /api/v1/knowledge-bases/kb-1/duplicate", r.URL.Path)
+ }
+ if r.ContentLength > 0 {
+ t.Fatalf("expected empty request body, got content-length=%d", r.ContentLength)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "success": true,
+ "data": map[string]interface{}{
+ "source_id": "kb-1",
+ "target_id": "kb-2",
+ "message": "Knowledge base duplicate created",
+ "knowledge_base": map[string]interface{}{
+ "id": "kb-2",
+ "name": "Source Copy",
+ "type": "document",
+ },
+ },
+ })
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, WithAPIKey("sk-test"))
+ resp, err := c.DuplicateKnowledgeBase(context.Background(), "kb-1")
+ if err != nil {
+ t.Fatalf("DuplicateKnowledgeBase() error = %v", err)
+ }
+ if resp.SourceID != "kb-1" {
+ t.Fatalf("SourceID = %q, want kb-1", resp.SourceID)
+ }
+ if resp.TargetID != "kb-2" {
+ t.Fatalf("TargetID = %q, want kb-2", resp.TargetID)
+ }
+ if resp.KnowledgeBase.ID != "kb-2" {
+ t.Fatalf("KnowledgeBase.ID = %q, want kb-2", resp.KnowledgeBase.ID)
+ }
+ if resp.KnowledgeBase.Name != "Source Copy" {
+ t.Fatalf("KnowledgeBase.Name = %q, want Source Copy", resp.KnowledgeBase.Name)
+ }
+}
diff --git a/docs/api/knowledge-base.md b/docs/api/knowledge-base.md
index 86b1c976f..fc79e088d 100644
--- a/docs/api/knowledge-base.md
+++ b/docs/api/knowledge-base.md
@@ -22,6 +22,7 @@
| GET | `/knowledge-bases/:id/hybrid-search` | 混合搜索(兼容旧客户端,需 JSON 请求体) |
| POST | `/knowledge-bases/copy` | 拷贝知识库(异步任务) |
| GET | `/knowledge-bases/copy/progress/:task_id` | 获取拷贝进度 |
+| POST | `/knowledge-bases/:id/duplicate` | 创建知识库副本(仅设置) |
| GET | `/knowledge-bases/:id/move-targets` | 获取可迁移目标知识库列表 |
## POST `/knowledge-bases` - 创建知识库
@@ -529,6 +530,77 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/copy/progress/kb_c
}
```
+## POST `/knowledge-bases/:id/duplicate` - 创建知识库副本
+
+同步创建一个**仅包含设置**的新知识库副本。会复制分块、模型、索引策略、Wiki/FAQ 配置等设置字段,但**不会**复制知识条目、分块内容、FAQ 条目、Wiki 页面、向量/关键词索引、数据源绑定、分享关系或置顶状态。
+
+与 `POST /knowledge-bases/copy` 的区别:
+
+| 能力 | `/duplicate` | `/copy` |
+| ---- | ------------ | ------- |
+| 执行方式 | 同步,立即返回新 KB | 异步任务,需轮询 progress |
+| 复制内容 | 仅设置 | 设置 + 全部知识内容 |
+| 新 KB ID | 服务端自动生成 UUID | 可指定已有目标库或新建 |
+
+**权限**:需要 `Contributor+`,且对源知识库至少有 `Viewer` 读权限(路由层 `KBAccessRead`)。源知识库必须属于调用者所在租户,否则返回 `403 Forbidden`。
+
+**命名规则**:新 KB 名称在源名称后追加本地化后缀(依据 `Accept-Language` 或 `WEKNORA_LANGUAGE`),例如中文 `原名 副本`、英文 `Original Name Copy`;若同名已存在则递增为 `原名 副本 2`、`Original Name Copy 2` 等。
+
+**路径参数**:
+
+| 字段 | 类型 | 说明 |
+| ---- | ------ | ----------- |
+| id | string | 源知识库 ID |
+
+**请求**:
+
+```curl
+curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/duplicate' \
+--header 'Authorization: Bearer <token>' \
+--header 'Accept-Language: zh-CN' \
+--request POST
+```
+
+**响应**(HTTP 201):
+
+```json
+{
+ "success": true,
+ "data": {
+ "source_id": "kb-00000001",
+ "target_id": "kb-00000002",
+ "message": "Knowledge base duplicate created",
+ "knowledge_base": {
+ "id": "kb-00000002",
+ "name": "产品文档 副本",
+ "type": "document",
+ "description": "…",
+ "embedding_model_id": "embed-1",
+ "chunking_config": {},
+ "knowledge_count": 0,
+ "chunk_count": 0
+ }
+ }
+}
+```
+
+**响应字段(`data`)**:
+
+| 字段 | 类型 | 说明 |
+| --------------- | ------ | ---------------------------- |
+| source_id | string | 源知识库 ID |
+| target_id | string | 新创建的知识库 ID |
+| message | string | 操作结果描述 |
+| knowledge_base | object | 新副本的完整知识库对象 |
+
+**常见错误**:
+
+| 场景 | HTTP | 说明 |
+| -------------------- | ---- | ---- |
+| 源知识库不存在 | 404 | `Source knowledge base not found` |
+| 源库属于其他租户 | 403 | `No permission to duplicate this knowledge base` |
+| 向量存储绑定无效 | 400 | 源库绑定的 vector store 不可用 |
+
## GET `/knowledge-bases/:id/move-targets` - 获取可迁移目标知识库列表
返回当前知识库的内容**可以迁移到**的目标知识库列表。筛选规则:
diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts
index 815070de7..44e5f55a8 100644
--- a/frontend/src/api/knowledge-base/index.ts
+++ b/frontend/src/api/knowledge-base/index.ts
@@ -135,8 +135,8 @@ export function copyKnowledgeBase(data: { source_id: string; target_id?: string
return post(`/api/v1/knowledge-bases/copy`, data);
}
-export function duplicateKnowledgeBase(id: string, data: { target_id?: string } = {}) {
- return post(`/api/v1/knowledge-bases/${id}/duplicate`, data);
+export function duplicateKnowledgeBase(id: string) {
+ return post(`/api/v1/knowledge-bases/${id}/duplicate`);
}
// 获取可移动目标知识库列表(同类型、同Embedding模型)
diff --git a/internal/agent/tools/query_knowledge_graph_test.go b/internal/agent/tools/query_knowledge_graph_test.go
index 681927514..d2cc20897 100644
--- a/internal/agent/tools/query_knowledge_graph_test.go
+++ b/internal/agent/tools/query_knowledge_graph_test.go
@@ -86,7 +86,6 @@ func (s *stubKnowledgeBaseService) CopyKnowledgeBase(
func (s *stubKnowledgeBaseService) DuplicateKnowledgeBase(
context.Context,
string,
- string,
) (*types.KnowledgeBase, error) {
return nil, nil
}
diff --git a/internal/application/service/datasource_service_test.go b/internal/application/service/datasource_service_test.go
index 635f4bc55..e2f39749e 100644
--- a/internal/application/service/datasource_service_test.go
+++ b/internal/application/service/datasource_service_test.go
@@ -103,7 +103,7 @@ func (s *processSyncKBService) ResolveEmbeddingModelKeys(context.Context, []*typ
func (s *processSyncKBService) CopyKnowledgeBase(context.Context, string, string) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
return nil, nil, nil
}
-func (s *processSyncKBService) DuplicateKnowledgeBase(context.Context, string, string) (*types.KnowledgeBase, error) {
+func (s *processSyncKBService) DuplicateKnowledgeBase(context.Context, string) (*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) GetRepository() interfaces.KnowledgeBaseRepository { return nil }
diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go
index 95cad82d4..e056f37be 100644
--- a/internal/application/service/knowledgebase.go
+++ b/internal/application/service/knowledgebase.go
@@ -1035,10 +1035,8 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
func (s *knowledgeBaseService) DuplicateKnowledgeBase(
ctx context.Context,
srcKB string,
- targetID string,
) (*types.KnowledgeBase, error) {
srcKB = strings.TrimSpace(srcKB)
- targetID = strings.TrimSpace(targetID)
if srcKB == "" {
return nil, apperrors.NewBadRequestError("source knowledge base ID cannot be empty")
}
@@ -1055,11 +1053,7 @@ func (s *knowledgeBaseService) DuplicateKnowledgeBase(
if err != nil {
return nil, err
}
- if targetID != "" {
- targetKB.ID = targetID
- } else {
- targetKB.ID = uuid.New().String()
- }
+ targetKB.ID = uuid.New().String()
targetKB.TenantID = tenantID
targetKB.Name = s.buildDuplicateKnowledgeBaseName(ctx, tenantID, sourceKB.Name)
targetKB.CreatorID = ""
@@ -1095,20 +1089,54 @@ func (s *knowledgeBaseService) DuplicateKnowledgeBase(
return targetKB, nil
}
+func duplicateKBCopySuffix(locale string) string {
+ locale = strings.ToLower(locale)
+ switch {
+ case strings.HasPrefix(locale, "zh"):
+ return " 副本"
+ case strings.HasPrefix(locale, "ko"):
+ return " 사본"
+ case strings.HasPrefix(locale, "ru"):
+ return " копия"
+ default:
+ return " Copy"
+ }
+}
+
+func duplicateKBDefaultName(locale string) string {
+ locale = strings.ToLower(locale)
+ switch {
+ case strings.HasPrefix(locale, "zh"):
+ return "知识库"
+ case strings.HasPrefix(locale, "ko"):
+ return "지식베이스"
+ case strings.HasPrefix(locale, "ru"):
+ return "База знаний"
+ default:
+ return "Knowledge Base"
+ }
+}
+
func (s *knowledgeBaseService) buildDuplicateKnowledgeBaseName(
ctx context.Context,
tenantID uint64,
sourceName string,
) string {
+ locale, ok := types.LanguageFromContext(ctx)
+ if !ok {
+ locale = types.DefaultLanguage()
+ }
+ suffix := duplicateKBCopySuffix(locale)
+
baseName := strings.TrimSpace(sourceName)
if baseName == "" {
- baseName = "知识库"
+ baseName = duplicateKBDefaultName(locale)
}
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
logger.Warnf(ctx, "List tenant knowledge bases failed while building duplicate name: %v", err)
- return baseName + " 副本"
+ return baseName + suffix
}
existing := make(map[string]struct{}, len(kbs))
@@ -1119,12 +1147,12 @@ func (s *knowledgeBaseService) buildDuplicateKnowledgeBaseName(
existing[kb.Name] = struct{}{}
}
- candidate := baseName + " 副本"
+ candidate := baseName + suffix
if _, ok := existing[candidate]; !ok {
return candidate
}
for i := 2; ; i++ {
- candidate = fmt.Sprintf("%s 副本 %d", baseName, i)
+ candidate = fmt.Sprintf("%s%s %d", baseName, suffix, i)
if _, ok := existing[candidate]; !ok {
return candidate
}
diff --git a/internal/application/service/knowledgebase_pr3_test.go b/internal/application/service/knowledgebase_pr3_test.go
index 2c0e0569c..f080ccdb4 100644
--- a/internal/application/service/knowledgebase_pr3_test.go
+++ b/internal/application/service/knowledgebase_pr3_test.go
@@ -423,10 +423,10 @@ func TestDuplicateKnowledgeBase_CreatesSettingsOnlyDuplicate(t *testing.T) {
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
ctx := context.WithValue(ctxWithTenant(1), types.UserIDContextKey, "copy-user")
- target, err := svc.DuplicateKnowledgeBase(ctx, "src", "copy-id")
+ target, err := svc.DuplicateKnowledgeBase(ctx, "src")
require.NoError(t, err)
- require.Equal(t, "copy-id", target.ID)
+ require.NotEmpty(t, target.ID)
assert.Equal(t, uint64(1), target.TenantID)
assert.Equal(t, "copy-user", target.CreatorID)
assert.Equal(t, "Source KB 副本", target.Name)
@@ -456,7 +456,7 @@ func TestDuplicateKnowledgeBase_CreatesSettingsOnlyDuplicate(t *testing.T) {
assert.Zero(t, target.ProcessingCount)
assert.Zero(t, target.ShareCount)
assert.Empty(t, target.CreatorName)
- require.Same(t, target, repo.rows["copy-id"])
+ require.Same(t, target, repo.rows[target.ID])
}
func TestDuplicateKnowledgeBase_UsesDistinctNameWhenDuplicateExists(t *testing.T) {
@@ -475,8 +475,25 @@ func TestDuplicateKnowledgeBase_UsesDistinctNameWhenDuplicateExists(t *testing.T
}
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
- target, err := svc.DuplicateKnowledgeBase(ctxWithTenant(1), "src", "copy-id")
+ target, err := svc.DuplicateKnowledgeBase(ctxWithTenant(1), "src")
require.NoError(t, err)
assert.Equal(t, "Source KB 副本 2", target.Name)
}
+
+func TestDuplicateKnowledgeBase_UsesLocalizedEnglishSuffix(t *testing.T) {
+ repo := newFakeKBRepo()
+ repo.rows["src"] = &types.KnowledgeBase{
+ ID: "src",
+ Name: "Source KB",
+ Type: types.KnowledgeBaseTypeDocument,
+ TenantID: 1,
+ }
+ svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
+ ctx := context.WithValue(ctxWithTenant(1), types.LanguageContextKey, "en-US")
+
+ target, err := svc.DuplicateKnowledgeBase(ctx, "src")
+ require.NoError(t, err)
+
+ assert.Equal(t, "Source KB Copy", target.Name)
+}
diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go
index 4beff0dbe..ca6e078b5 100644
--- a/internal/handler/knowledgebase.go
+++ b/internal/handler/knowledgebase.go
@@ -936,10 +936,6 @@ type CopyKnowledgeBaseResponse struct {
Message string `json:"message"`
}
-type DuplicateKnowledgeBaseRequest struct {
- TargetID string `json:"target_id"`
-}
-
type DuplicateKnowledgeBaseResponse struct {
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
@@ -1131,9 +1127,8 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
// @Tags 知识库
// @Accept json
// @Produce json
-// @Param id path string true "源知识库 ID"
-// @Param request body DuplicateKnowledgeBaseRequest false "创建副本请求"
-// @Success 201 {object} map[string]interface{} "创建后的知识库副本"
+// @Param id path string true "源知识库 ID"
+// @Success 201 {object} map[string]interface{} "创建后的知识库副本"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Router /knowledge-bases/{id}/duplicate [post]
@@ -1144,13 +1139,6 @@ func (h *KnowledgeBaseHandler) DuplicateKnowledgeBase(c *gin.Context) {
c.Error(apperrors.NewBadRequestError("Knowledge base ID cannot be empty"))
return
}
- var req DuplicateKnowledgeBaseRequest
- if c.Request.Body != nil && c.Request.ContentLength != 0 {
- if err := c.ShouldBindJSON(&req); err != nil {
- c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
- return
- }
- }
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
sourceKB, err := h.service.GetKnowledgeBaseByID(ctx, sourceID)
@@ -1171,7 +1159,7 @@ func (h *KnowledgeBaseHandler) DuplicateKnowledgeBase(c *gin.Context) {
return
}
- targetKB, err := h.service.DuplicateKnowledgeBase(ctx, sourceID, req.TargetID)
+ targetKB, err := h.service.DuplicateKnowledgeBase(ctx, sourceID)
if err != nil {
if appErr, ok := apperrors.IsAppError(err); ok {
c.Error(appErr)
diff --git a/internal/handler/knowledgebase_copy_preflight_test.go b/internal/handler/knowledgebase_copy_preflight_test.go
index ce8ae100e..c164bcad2 100644
--- a/internal/handler/knowledgebase_copy_preflight_test.go
+++ b/internal/handler/knowledgebase_copy_preflight_test.go
@@ -2,6 +2,7 @@ package handler
import (
"context"
+ "errors"
"net/http"
"net/http/httptest"
"strings"
@@ -9,6 +10,8 @@ import (
"github.com/gin-gonic/gin"
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -19,7 +22,7 @@ import (
type stubKBCopyService struct {
interfaces.KnowledgeBaseService
byID func(ctx context.Context, id string) (*types.KnowledgeBase, error)
- duplicate func(ctx context.Context, sourceID, targetID string) (*types.KnowledgeBase, error)
+ duplicate func(ctx context.Context, sourceID string) (*types.KnowledgeBase, error)
}
func (s *stubKBCopyService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
@@ -29,9 +32,8 @@ func (s *stubKBCopyService) GetKnowledgeBaseByID(ctx context.Context, id string)
func (s *stubKBCopyService) DuplicateKnowledgeBase(
ctx context.Context,
sourceID string,
- targetID string,
) (*types.KnowledgeBase, error) {
- return s.duplicate(ctx, sourceID, targetID)
+ return s.duplicate(ctx, sourceID)
}
func newDuplicateRouter(svc interfaces.KnowledgeBaseService) *gin.Engine {
@@ -49,7 +51,7 @@ func newDuplicateRouter(svc interfaces.KnowledgeBaseService) *gin.Engine {
}
func TestDuplicateHandler_ReturnsCreatedKnowledgeBase(t *testing.T) {
- var gotSourceID, gotTargetID string
+ var gotSourceID string
svc := &stubKBCopyService{
byID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
if id != "src" {
@@ -57,12 +59,12 @@ func TestDuplicateHandler_ReturnsCreatedKnowledgeBase(t *testing.T) {
}
return &types.KnowledgeBase{ID: "src", TenantID: 1, Name: "Source"}, nil
},
- duplicate: func(_ context.Context, sourceID, targetID string) (*types.KnowledgeBase, error) {
- gotSourceID, gotTargetID = sourceID, targetID
+ duplicate: func(_ context.Context, sourceID string) (*types.KnowledgeBase, error) {
+ gotSourceID = sourceID
return &types.KnowledgeBase{
ID: "copy-id",
TenantID: 1,
- Name: "Source",
+ Name: "Source Copy",
CreatorID: "u-test",
}, nil
},
@@ -70,16 +72,14 @@ func TestDuplicateHandler_ReturnsCreatedKnowledgeBase(t *testing.T) {
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate",
- strings.NewReader(`{"target_id":"copy-id"}`))
- req.Header.Set("Content-Type", "application/json")
+ req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("expected 201 for duplicate, got %d body=%s", w.Code, w.Body.String())
}
- if gotSourceID != "src" || gotTargetID != "copy-id" {
- t.Fatalf("duplicate service called with source=%q target=%q", gotSourceID, gotTargetID)
+ if gotSourceID != "src" {
+ t.Fatalf("duplicate service called with source=%q", gotSourceID)
}
body := w.Body.String()
for _, want := range []string{`"source_id":"src"`, `"target_id":"copy-id"`, `"knowledge_base"`} {
@@ -95,7 +95,7 @@ func TestDuplicateHandler_RejectsCrossTenantSource(t *testing.T) {
byID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: id, TenantID: 2, Name: "Shared"}, nil
},
- duplicate: func(_ context.Context, _, _ string) (*types.KnowledgeBase, error) {
+ duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
calledDuplicate = true
return nil, nil
},
@@ -103,9 +103,7 @@ func TestDuplicateHandler_RejectsCrossTenantSource(t *testing.T) {
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate",
- strings.NewReader(`{}`))
- req.Header.Set("Content-Type", "application/json")
+ req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
@@ -115,3 +113,71 @@ func TestDuplicateHandler_RejectsCrossTenantSource(t *testing.T) {
t.Fatal("duplicate service must not be called when source KB is outside the caller tenant")
}
}
+
+func TestDuplicateHandler_SourceNotFound(t *testing.T) {
+ calledDuplicate := false
+ svc := &stubKBCopyService{
+ byID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return nil, repository.ErrKnowledgeBaseNotFound
+ },
+ duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ calledDuplicate = true
+ return nil, nil
+ },
+ }
+ r := newDuplicateRouter(svc)
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/missing/duplicate", nil)
+ r.ServeHTTP(w, req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for missing source, got %d body=%s", w.Code, w.Body.String())
+ }
+ if calledDuplicate {
+ t.Fatal("duplicate service must not be called when source KB is missing")
+ }
+}
+
+func TestDuplicateHandler_PropagatesServiceAppError(t *testing.T) {
+ svc := &stubKBCopyService{
+ byID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{ID: "src", TenantID: 1, Name: "Source"}, nil
+ },
+ duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return nil, apperrors.NewBadRequestError("invalid vector store binding")
+ },
+ }
+ r := newDuplicateRouter(svc)
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
+ r.ServeHTTP(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for service app error, got %d body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "invalid vector store binding") {
+ t.Fatalf("expected service error message in body: %s", w.Body.String())
+ }
+}
+
+func TestDuplicateHandler_ServiceUnexpectedError(t *testing.T) {
+ svc := &stubKBCopyService{
+ byID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{ID: "src", TenantID: 1, Name: "Source"}, nil
+ },
+ duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return nil, errors.New("database unavailable")
+ },
+ }
+ r := newDuplicateRouter(svc)
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
+ r.ServeHTTP(w, req)
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("expected 500 for unexpected service error, got %d body=%s", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/types/interfaces/knowledgebase.go b/internal/types/interfaces/knowledgebase.go
index a41cfb3df..20e9fe377 100644
--- a/internal/types/interfaces/knowledgebase.go
+++ b/internal/types/interfaces/knowledgebase.go
@@ -118,9 +118,8 @@ type KnowledgeBaseService interface {
// DuplicateKnowledgeBase creates a new settings-only knowledge base duplicate.
// It does not copy knowledge entries, chunks, FAQ rows, wiki pages, indexes,
- // data sources, shares, pins, or task state. targetID is optional; when empty
- // a new UUID is generated.
- DuplicateKnowledgeBase(ctx context.Context, src string, targetID string) (*types.KnowledgeBase, error)
+ // data sources, shares, pins, or task state. A new UUID is always generated.
+ DuplicateKnowledgeBase(ctx context.Context, src string) (*types.KnowledgeBase, error)
// GetRepository gets the knowledge base repository
// Parameters: