Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(knowledge): dedicated renameKnowledgeDocument mutation, lighter list

Sergey Kozyrenko942fb45c16d0
diff --git a/backend/pkg/database/knowledge.sql.go b/backend/pkg/database/knowledge.sql.go
index c11337d3..7f454205 100644
--- a/backend/pkg/database/knowledge.sql.go
+++ b/backend/pkg/database/knowledge.sql.go
@@ -453,3 +453,37 @@ func (q *Queries) UpdateKnowledgeDocument(ctx context.Context, arg UpdateKnowled
err := row.Scan(&i.ID, &i.Document, &i.Cmetadata)
return i, err
}
+
+const updateKnowledgeDocumentMetadata = `-- name: UpdateKnowledgeDocumentMetadata :one
+UPDATE langchain_pg_embedding
+SET cmetadata = $1::json
+WHERE uuid::text = $2
+ AND collection_id = (SELECT uuid FROM langchain_pg_collection WHERE name = 'langchain')
+RETURNING
+ uuid::text AS id,
+ COALESCE(document, '') AS document,
+ COALESCE(cmetadata::text, '{}') AS cmetadata
+`
+
+type UpdateKnowledgeDocumentMetadataParams struct {
+ Cmetadata pqtype.NullRawMessage `json:"cmetadata"`
+ Uuid sql.NullString `json:"uuid"`
+}
+
+type UpdateKnowledgeDocumentMetadataRow struct {
+ ID string `json:"id"`
+ Document string `json:"document"`
+ Cmetadata sql.NullString `json:"cmetadata"`
+}
+
+// Update only the document's metadata, leaving its text and embedding intact.
+// Used when an update changes no content (e.g. rename), so no embedder is needed.
+func (q *Queries) UpdateKnowledgeDocumentMetadata(ctx context.Context, arg UpdateKnowledgeDocumentMetadataParams) (UpdateKnowledgeDocumentMetadataRow, error) {
+ row := q.db.QueryRowContext(ctx, updateKnowledgeDocumentMetadata,
+ arg.Cmetadata,
+ arg.Uuid,
+ )
+ var i UpdateKnowledgeDocumentMetadataRow
+ err := row.Scan(&i.ID, &i.Document, &i.Cmetadata)
+ return i, err
+}
diff --git a/backend/pkg/database/knowledge/knowledge.go b/backend/pkg/database/knowledge/knowledge.go
index b8e13845..d066d9fd 100644
--- a/backend/pkg/database/knowledge/knowledge.go
+++ b/backend/pkg/database/knowledge/knowledge.go
@@ -49,6 +49,8 @@ type KnowledgeStore interface {
CreateDocument(ctx context.Context, userID int64, input model.CreateKnowledgeDocumentInput) (*model.KnowledgeDocument, error)
UpdateDocument(ctx context.Context, userID int64, id string, input model.UpdateKnowledgeDocumentInput) (*model.KnowledgeDocument, error)
UpdateUserDocument(ctx context.Context, userID int64, id string, input model.UpdateKnowledgeDocumentInput) (*model.KnowledgeDocument, error)
+ RenameDocument(ctx context.Context, userID int64, id, question string) (*model.KnowledgeDocument, error)
+ RenameUserDocument(ctx context.Context, userID int64, id, question string) (*model.KnowledgeDocument, error)
DeleteDocument(ctx context.Context, userID int64, id string) error
DeleteUserDocument(ctx context.Context, userID int64, id string) error
}
@@ -539,19 +541,16 @@ func (ks *knowledgeStore) UpdateUserDocument(ctx context.Context, userID int64,
return ks.doUpdate(ctx, userID, id, existing, input)
}
-func (ks *knowledgeStore) doUpdate(ctx context.Context, userID int64, id string, existing *model.KnowledgeDocument, input model.UpdateKnowledgeDocumentInput) (*model.KnowledgeDocument, error) {
- if err := ks.requireEmbedder(); err != nil {
- return nil, err
- }
-
- // Build updated metadata from existing document.
- // Preserve the original owner (UserID) — the caller's identity (userID) is
- // used only for event scoping via the publisher, not stored in cmetadata.
+// metaFromDoc keeps the document's original owner — a rename/update must not rewrite
+// UserID to the caller (whose id is used only for publisher event scoping).
+func metaFromDoc(existing *model.KnowledgeDocument) knowledgeMeta {
meta := knowledgeMeta{
- DocType: string(existing.DocType),
- UserID: existing.UserID,
- Manual: existing.Manual,
- Question: existing.Question,
+ DocType: string(existing.DocType),
+ UserID: existing.UserID,
+ Manual: existing.Manual,
+ Question: existing.Question,
+ PartSize: existing.PartSize,
+ TotalSize: existing.TotalSize,
}
if existing.FlowID != nil {
meta.FlowID = existing.FlowID
@@ -574,6 +573,57 @@ func (ks *knowledgeStore) doUpdate(ctx context.Context, userID int64, id string,
if existing.CodeLang != nil {
meta.CodeLang = *existing.CodeLang
}
+ return meta
+}
+
+// ---- RenameDocument (admin) -------------------------------------------------
+
+func (ks *knowledgeStore) RenameDocument(ctx context.Context, userID int64, id, question string) (*model.KnowledgeDocument, error) {
+ existing, err := ks.GetDocument(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ return ks.doRename(ctx, userID, id, existing, question)
+}
+
+// ---- RenameUserDocument (user-scoped) ---------------------------------------
+
+func (ks *knowledgeStore) RenameUserDocument(ctx context.Context, userID int64, id, question string) (*model.KnowledgeDocument, error) {
+ existing, err := ks.GetUserDocument(ctx, userID, id)
+ if err != nil {
+ return nil, err
+ }
+ return ks.doRename(ctx, userID, id, existing, question)
+}
+
+func (ks *knowledgeStore) doRename(ctx context.Context, userID int64, id string, existing *model.KnowledgeDocument, question string) (*model.KnowledgeDocument, error) {
+ meta := metaFromDoc(existing)
+ meta.Question = strings.TrimSpace(question)
+
+ cmJSON, err := metaToJSON(meta)
+ if err != nil {
+ return nil, fmt.Errorf("knowledge: marshal cmetadata: %w", err)
+ }
+
+ row, err := ks.db.UpdateKnowledgeDocumentMetadata(ctx, database.UpdateKnowledgeDocumentMetadataParams{
+ Uuid: nsOf(id),
+ Cmetadata: cmJSON,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("knowledge: rename document %s: %w", id, err)
+ }
+
+ doc := rowToModel(row.ID, row.Document, nullStr(row.Cmetadata), true)
+ ks.newKnp(userID).KnowledgeDocumentUpdated(ctx, doc)
+ return doc, nil
+}
+
+func (ks *knowledgeStore) doUpdate(ctx context.Context, userID int64, id string, existing *model.KnowledgeDocument, input model.UpdateKnowledgeDocumentInput) (*model.KnowledgeDocument, error) {
+ if err := ks.requireEmbedder(); err != nil {
+ return nil, err
+ }
+
+ meta := metaFromDoc(existing)
// Apply input fields.
content := strings.TrimSpace(input.Content)
diff --git a/backend/pkg/database/knowledge/knowledge_test.go b/backend/pkg/database/knowledge/knowledge_test.go
index 4e8be017..2a480f88 100644
--- a/backend/pkg/database/knowledge/knowledge_test.go
+++ b/backend/pkg/database/knowledge/knowledge_test.go
@@ -34,6 +34,7 @@ type mockDB struct {
listFlow func(ctx context.Context, flowID sql.NullString) ([]database.ListFlowKnowledgeDocumentsRow, error)
listUser func(ctx context.Context, userID sql.NullString) ([]database.ListUserKnowledgeDocumentsRow, error)
updateKnowledge func(ctx context.Context, arg database.UpdateKnowledgeDocumentParams) (database.UpdateKnowledgeDocumentRow, error)
+ updateKnowledgeMeta func(ctx context.Context, arg database.UpdateKnowledgeDocumentMetadataParams) (database.UpdateKnowledgeDocumentMetadataRow, error)
deleteKnowledge func(ctx context.Context, uuid sql.NullString) error
deleteUserKnowledge func(ctx context.Context, arg database.DeleteUserKnowledgeDocumentParams) error
searchKnowledge func(ctx context.Context, arg database.SearchKnowledgeDocumentsParams) ([]database.SearchKnowledgeDocumentsRow, error)
@@ -61,6 +62,9 @@ func (m *mockDB) ListUserKnowledgeDocuments(ctx context.Context, cmetadata sql.N
func (m *mockDB) UpdateKnowledgeDocument(ctx context.Context, arg database.UpdateKnowledgeDocumentParams) (database.UpdateKnowledgeDocumentRow, error) {
return m.updateKnowledge(ctx, arg)
}
+func (m *mockDB) UpdateKnowledgeDocumentMetadata(ctx context.Context, arg database.UpdateKnowledgeDocumentMetadataParams) (database.UpdateKnowledgeDocumentMetadataRow, error) {
+ return m.updateKnowledgeMeta(ctx, arg)
+}
func (m *mockDB) DeleteKnowledgeDocument(ctx context.Context, uuid sql.NullString) error {
return m.deleteKnowledge(ctx, uuid)
}
@@ -2258,3 +2262,135 @@ func TestUpdateUserDocument(t *testing.T) {
}
})
}
+
+func TestRenameDocument(t *testing.T) {
+ ctx := context.Background()
+ const userID = int64(7)
+
+ t.Run("metadata-only: question updated, content preserved, no embedder needed", func(t *testing.T) {
+ pub := &mockPublisher{}
+ var gotMeta database.UpdateKnowledgeDocumentMetadataParams
+
+ db := &mockDB{
+ getKnowledge: func(_ context.Context, uuid string) (database.GetKnowledgeDocumentRow, error) {
+ return makeRow(uuid, "PRESERVED CONTENT", `{"doc_type":"answer","answer_type":"vulnerability","question":"original","user_id":"7","manual":true}`), nil
+ },
+ updateKnowledgeMeta: func(_ context.Context, arg database.UpdateKnowledgeDocumentMetadataParams) (database.UpdateKnowledgeDocumentMetadataRow, error) {
+ gotMeta = arg
+ return database.UpdateKnowledgeDocumentMetadataRow{
+ ID: arg.Uuid.String,
+ Document: "PRESERVED CONTENT", // text untouched, not re-embedded
+ Cmetadata: sql.NullString{String: string(arg.Cmetadata.RawMessage), Valid: true},
+ }, nil
+ },
+ // updateKnowledge intentionally nil — the re-embed path must NOT run.
+ }
+ ks := &knowledgeStore{
+ db: db,
+ embedder: nil, // rename must not require a configured embedder
+ newKnp: newPublisherFactory(pub),
+ }
+
+ doc, err := ks.RenameDocument(ctx, userID, "doc-id", " RENAMED ")
+ if err != nil {
+ t.Fatalf("rename must not need an embedder: %v", err)
+ }
+ if doc.Content != "PRESERVED CONTENT" {
+ t.Fatalf("content must be preserved, got %q", doc.Content)
+ }
+ if doc.Question != "RENAMED" {
+ t.Fatalf("question: want RENAMED (trimmed), got %q", doc.Question)
+ }
+ meta := parseMeta(string(gotMeta.Cmetadata.RawMessage))
+ if meta.Question != "RENAMED" {
+ t.Fatalf("stored question: want RENAMED, got %q", meta.Question)
+ }
+ if meta.DocType != "answer" || meta.AnswerType != "vulnerability" {
+ t.Fatalf("other metadata not preserved: %+v", meta)
+ }
+ if len(pub.updatedDocs) != 1 {
+ t.Fatal("KnowledgeDocumentUpdated event not published")
+ }
+ })
+
+ t.Run("admin: get error propagates (missing document)", func(t *testing.T) {
+ db := &mockDB{
+ getKnowledge: func(_ context.Context, _ string) (database.GetKnowledgeDocumentRow, error) {
+ return database.GetKnowledgeDocumentRow{}, errors.New("not found")
+ },
+ // updateKnowledgeMeta intentionally nil — must not be reached.
+ }
+ ks := &knowledgeStore{db: db, embedder: nil}
+ if _, err := ks.RenameDocument(ctx, userID, "missing", "x"); err == nil {
+ t.Fatal("expected error when document does not exist")
+ }
+ })
+}
+
+func TestRenameUserDocument(t *testing.T) {
+ ctx := context.Background()
+ const userID = int64(30)
+
+ t.Run("uses GetUserDocument for ownership, then metadata-only update", func(t *testing.T) {
+ pub := &mockPublisher{}
+ var fetchedUserID string
+ var metaUpdated bool
+
+ db := &mockDB{
+ getUserKnowledge: func(_ context.Context, arg database.GetUserKnowledgeDocumentParams) (database.GetUserKnowledgeDocumentRow, error) {
+ fetchedUserID = arg.UserID.String
+ return database.GetUserKnowledgeDocumentRow{
+ ID: arg.Uuid,
+ Document: "kept",
+ Cmetadata: sql.NullString{String: `{"doc_type":"answer","question":"old","user_id":"30"}`, Valid: true},
+ }, nil
+ },
+ updateKnowledgeMeta: func(_ context.Context, arg database.UpdateKnowledgeDocumentMetadataParams) (database.UpdateKnowledgeDocumentMetadataRow, error) {
+ metaUpdated = true
+ return database.UpdateKnowledgeDocumentMetadataRow{
+ ID: arg.Uuid.String,
+ Document: "kept",
+ Cmetadata: sql.NullString{String: string(arg.Cmetadata.RawMessage), Valid: true},
+ }, nil
+ },
+ // re-embed path (updateKnowledge) intentionally nil — must not run.
+ }
+ ks := &knowledgeStore{db: db, embedder: nil, newKnp: newPublisherFactory(pub)}
+
+ doc, err := ks.RenameUserDocument(ctx, userID, "my-doc", "new title")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fetchedUserID != "30" {
+ t.Fatalf("ownership: GetUserDocument must receive userID 30, got %q", fetchedUserID)
+ }
+ if !metaUpdated {
+ t.Fatal("metadata update not called")
+ }
+ if doc.Content != "kept" || doc.Question != "new title" {
+ t.Fatalf("unexpected doc: content=%q question=%q", doc.Content, doc.Question)
+ }
+ })
+
+ // SECURITY: a non-owner's rename is blocked at GetUserDocument — no write happens.
+ t.Run("SECURITY: wrong owner blocks rename, no metadata write", func(t *testing.T) {
+ var metaCalled bool
+ db := &mockDB{
+ getUserKnowledge: func(_ context.Context, _ database.GetUserKnowledgeDocumentParams) (database.GetUserKnowledgeDocumentRow, error) {
+ return database.GetUserKnowledgeDocumentRow{}, errors.New("not found")
+ },
+ updateKnowledgeMeta: func(_ context.Context, _ database.UpdateKnowledgeDocumentMetadataParams) (database.UpdateKnowledgeDocumentMetadataRow, error) {
+ metaCalled = true
+ return database.UpdateKnowledgeDocumentMetadataRow{}, nil
+ },
+ }
+ ks := &knowledgeStore{db: db, embedder: nil}
+
+ if _, err := ks.RenameUserDocument(ctx, userID, "not-my-doc", "evil rename"); err == nil {
+ t.Fatal("SECURITY: rename of another user's document must be rejected")
+ }
+ if metaCalled {
+ t.Fatal("SECURITY: metadata must NOT be written when the ownership check fails")
+ }
+ })
+}
diff --git a/backend/pkg/database/querier.go b/backend/pkg/database/querier.go
index 8d80eb45..36d3143b 100644
--- a/backend/pkg/database/querier.go
+++ b/backend/pkg/database/querier.go
@@ -286,6 +286,7 @@ type Querier interface {
// embedding must be formatted as a PostgreSQL vector literal: '[f1,f2,...]'
// cmetadata must be valid JSON text.
UpdateKnowledgeDocument(ctx context.Context, arg UpdateKnowledgeDocumentParams) (UpdateKnowledgeDocumentRow, error)
+ UpdateKnowledgeDocumentMetadata(ctx context.Context, arg UpdateKnowledgeDocumentMetadataParams) (UpdateKnowledgeDocumentMetadataRow, error)
UpdateMsgChain(ctx context.Context, arg UpdateMsgChainParams) (Msgchain, error)
UpdateMsgChainUsage(ctx context.Context, arg UpdateMsgChainUsageParams) (Msgchain, error)
UpdateMsgLogResult(ctx context.Context, arg UpdateMsgLogResultParams) (Msglog, error)
diff --git a/backend/pkg/graph/generated.go b/backend/pkg/graph/generated.go
index 9ad89c98..9d5484d2 100644
--- a/backend/pkg/graph/generated.go
+++ b/backend/pkg/graph/generated.go
@@ -366,6 +366,7 @@ type ComplexityRoot struct {
FinishFlow func(childComplexity int, flowID int64) int
PutUserInput func(childComplexity int, flowID int64, input string, modelProvider *string, resourceIds []int64) int
RenameFlow func(childComplexity int, flowID int64, title string) int
+ RenameKnowledgeDocument func(childComplexity int, id string, question string) int
StopAssistant func(childComplexity int, flowID int64, assistantID int64) int
StopFlow func(childComplexity int, flowID int64) int
TestAgent func(childComplexity int, typeArg model.ProviderType, agentType model.AgentConfigType, agent model.AgentConfig) int
@@ -764,6 +765,7 @@ type MutationResolver interface {
DeleteFlowTemplate(ctx context.Context, templateID int64) (model.ResultType, error)
CreateKnowledgeDocument(ctx context.Context, input model.CreateKnowledgeDocumentInput) (*model.KnowledgeDocument, error)
UpdateKnowledgeDocument(ctx context.Context, id string, input model.UpdateKnowledgeDocumentInput) (*model.KnowledgeDocument, error)
+ RenameKnowledgeDocument(ctx context.Context, id string, question string) (*model.KnowledgeDocument, error)
DeleteKnowledgeDocument(ctx context.Context, id string) (model.ResultType, error)
AnonymizeText(ctx context.Context, text string) (string, error)
}
@@ -2489,6 +2491,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in
return e.complexity.Mutation.RenameFlow(childComplexity, args["flowId"].(int64), args["title"].(string)), true
+ case "Mutation.renameKnowledgeDocument":
+ if e.complexity.Mutation.RenameKnowledgeDocument == nil {
+ break
+ }
+
+ args, err := ec.field_Mutation_renameKnowledgeDocument_args(context.TODO(), rawArgs)
+ if err != nil {
+ return 0, false
+ }
+
+ return e.complexity.Mutation.RenameKnowledgeDocument(childComplexity, args["id"].(string), args["question"].(string)), true
+
case "Mutation.stopAssistant":
if e.complexity.Mutation.StopAssistant == nil {
break
@@ -6009,6 +6023,65 @@ func (ec *executionContext) field_Mutation_renameFlow_argsTitle(
return zeroVal, nil
}
+func (ec *executionContext) field_Mutation_renameKnowledgeDocument_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {
+ var err error
+ args := map[string]interface{}{}
+ arg0, err := ec.field_Mutation_renameKnowledgeDocument_argsID(ctx, rawArgs)
+ if err != nil {
+ return nil, err
+ }
+ args["id"] = arg0
+ arg1, err := ec.field_Mutation_renameKnowledgeDocument_argsQuestion(ctx, rawArgs)
+ if err != nil {
+ return nil, err
+ }
+ args["question"] = arg1
+ return args, nil
+}
+func (ec *executionContext) field_Mutation_renameKnowledgeDocument_argsID(
+ ctx context.Context,
+ rawArgs map[string]interface{},
+) (string, error) {
+ // We won't call the directive if the argument is null.
+ // Set call_argument_directives_with_null to true to call directives
+ // even if the argument is null.
+ _, ok := rawArgs["id"]
+ if !ok {
+ var zeroVal string
+ return zeroVal, nil
+ }
+
+ ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("id"))
+ if tmp, ok := rawArgs["id"]; ok {
+ return ec.unmarshalNString2string(ctx, tmp)
+ }
+
+ var zeroVal string
+ return zeroVal, nil
+}
+
+func (ec *executionContext) field_Mutation_renameKnowledgeDocument_argsQuestion(
+ ctx context.Context,
+ rawArgs map[string]interface{},
+) (string, error) {
+ // We won't call the directive if the argument is null.
+ // Set call_argument_directives_with_null to true to call directives
+ // even if the argument is null.
+ _, ok := rawArgs["question"]
+ if !ok {
+ var zeroVal string
+ return zeroVal, nil
+ }
+
+ ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("question"))
+ if tmp, ok := rawArgs["question"]; ok {
+ return ec.unmarshalNString2string(ctx, tmp)
+ }
+
+ var zeroVal string
+ return zeroVal, nil
+}
+
func (ec *executionContext) field_Mutation_stopAssistant_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {
var err error
args := map[string]interface{}{}
@@ -19559,6 +19632,93 @@ func (ec *executionContext) fieldContext_Mutation_updateKnowledgeDocument(ctx co
return fc, nil
}
+func (ec *executionContext) _Mutation_renameKnowledgeDocument(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
+ fc, err := ec.fieldContext_Mutation_renameKnowledgeDocument(ctx, field)
+ if err != nil {
+ return graphql.Null
+ }
+ ctx = graphql.WithFieldContext(ctx, fc)
+ defer func() {
+ if r := recover(); r != nil {
+ ec.Error(ctx, ec.Recover(ctx, r))
+ ret = graphql.Null
+ }
+ }()
+ resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
+ ctx = rctx // use context from middleware stack in children
+ return ec.resolvers.Mutation().RenameKnowledgeDocument(rctx, fc.Args["id"].(string), fc.Args["question"].(string))
+ })
+ if err != nil {
+ ec.Error(ctx, err)
+ return graphql.Null
+ }
+ if resTmp == nil {
+ if !graphql.HasFieldError(ctx, fc) {
+ ec.Errorf(ctx, "must not be null")
+ }
+ return graphql.Null
+ }
+ res := resTmp.(*model.KnowledgeDocument)
+ fc.Result = res
+ return ec.marshalNKnowledgeDocument2ᚖpentagiᚋpkgᚋgraphᚋmodelᚐKnowledgeDocument(ctx, field.Selections, res)
+}
+
+func (ec *executionContext) fieldContext_Mutation_renameKnowledgeDocument(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
+ fc = &graphql.FieldContext{
+ Object: "Mutation",
+ Field: field,
+ IsMethod: true,
+ IsResolver: true,
+ Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
+ switch field.Name {
+ case "id":
+ return ec.fieldContext_KnowledgeDocument_id(ctx, field)
+ case "docType":
+ return ec.fieldContext_KnowledgeDocument_docType(ctx, field)
+ case "content":
+ return ec.fieldContext_KnowledgeDocument_content(ctx, field)
+ case "question":
+ return ec.fieldContext_KnowledgeDocument_question(ctx, field)
+ case "description":
+ return ec.fieldContext_KnowledgeDocument_description(ctx, field)
+ case "userId":
+ return ec.fieldContext_KnowledgeDocument_userId(ctx, field)
+ case "flowId":
+ return ec.fieldContext_KnowledgeDocument_flowId(ctx, field)
+ case "taskId":
+ return ec.fieldContext_KnowledgeDocument_taskId(ctx, field)
+ case "subtaskId":
+ return ec.fieldContext_KnowledgeDocument_subtaskId(ctx, field)
+ case "guideType":
+ return ec.fieldContext_KnowledgeDocument_guideType(ctx, field)
+ case "answerType":
+ return ec.fieldContext_KnowledgeDocument_answerType(ctx, field)
+ case "codeLang":
+ return ec.fieldContext_KnowledgeDocument_codeLang(ctx, field)
+ case "partSize":
+ return ec.fieldContext_KnowledgeDocument_partSize(ctx, field)
+ case "totalSize":
+ return ec.fieldContext_KnowledgeDocument_totalSize(ctx, field)
+ case "manual":
+ return ec.fieldContext_KnowledgeDocument_manual(ctx, field)
+ }
+ return nil, fmt.Errorf("no field named %q was found under type KnowledgeDocument", field.Name)
+ },
+ }
+ defer func() {
+ if r := recover(); r != nil {
+ err = ec.Recover(ctx, r)
+ ec.Error(ctx, err)
+ }
+ }()
+ ctx = graphql.WithFieldContext(ctx, fc)
+ if fc.Args, err = ec.field_Mutation_renameKnowledgeDocument_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {
+ ec.Error(ctx, err)
+ return fc, err
+ }
+ return fc, nil
+}
+
func (ec *executionContext) _Mutation_deleteKnowledgeDocument(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
fc, err := ec.fieldContext_Mutation_deleteKnowledgeDocument(ctx, field)
if err != nil {
@@ -38762,6 +38922,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet)
if out.Values[i] == graphql.Null {
out.Invalids++
}
+ case "renameKnowledgeDocument":
+ out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
+ return ec._Mutation_renameKnowledgeDocument(ctx, field)
+ })
+ if out.Values[i] == graphql.Null {
+ out.Invalids++
+ }
case "deleteKnowledgeDocument":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Mutation_deleteKnowledgeDocument(ctx, field)
diff --git a/backend/pkg/graph/schema.graphqls b/backend/pkg/graph/schema.graphqls
index 46fb4734..f240c330 100644
--- a/backend/pkg/graph/schema.graphqls
+++ b/backend/pkg/graph/schema.graphqls
@@ -1049,6 +1049,7 @@ type Mutation {
# Knowledge (vector store) management
createKnowledgeDocument(input: CreateKnowledgeDocumentInput!): KnowledgeDocument!
updateKnowledgeDocument(id: String!, input: UpdateKnowledgeDocumentInput!): KnowledgeDocument!
+ renameKnowledgeDocument(id: String!, question: String!): KnowledgeDocument!
deleteKnowledgeDocument(id: String!): ResultType!
anonymizeText(text: String!): String!
}
diff --git a/backend/pkg/graph/schema.resolvers.go b/backend/pkg/graph/schema.resolvers.go
index 9f026e7b..b3467d3d 100644
--- a/backend/pkg/graph/schema.resolvers.go
+++ b/backend/pkg/graph/schema.resolvers.go
@@ -1156,6 +1156,25 @@ func (r *mutationResolver) UpdateKnowledgeDocument(ctx context.Context, id strin
return r.Knowledge.UpdateUserDocument(ctx, uid, id, input)
}
+// RenameKnowledgeDocument is the resolver for the renameKnowledgeDocument field.
+func (r *mutationResolver) RenameKnowledgeDocument(ctx context.Context, id string, question string) (*model.KnowledgeDocument, error) {
+ uid, admin, err := validatePermission(ctx, "knowledge.edit")
+ if err != nil {
+ return nil, err
+ }
+
+ r.Logger.WithFields(logrus.Fields{
+ "uid": uid,
+ "admin": admin,
+ "id": id,
+ }).Debug("rename knowledge document")
+
+ if admin {
+ return r.Knowledge.RenameDocument(ctx, uid, id, question)
+ }
+ return r.Knowledge.RenameUserDocument(ctx, uid, id, question)
+}
+
// DeleteKnowledgeDocument is the resolver for the deleteKnowledgeDocument field.
func (r *mutationResolver) DeleteKnowledgeDocument(ctx context.Context, id string) (model.ResultType, error) {
uid, admin, err := validatePermission(ctx, "knowledge.delete")
diff --git a/backend/sqlc/models/knowledge.sql b/backend/sqlc/models/knowledge.sql
index b06d18bc..15ecdf10 100644
--- a/backend/sqlc/models/knowledge.sql
+++ b/backend/sqlc/models/knowledge.sql
@@ -75,6 +75,20 @@ RETURNING
COALESCE(document, '') AS document,
COALESCE(cmetadata::text, '{}') AS cmetadata;
+-- name: UpdateKnowledgeDocumentMetadata :one
+-- Update only the document's metadata, leaving its text and embedding intact.
+-- Used when an update changes no content (e.g. rename) so re-embedding — and
+-- therefore a configured embedder — is unnecessary.
+-- cmetadata must be valid JSON text.
+UPDATE langchain_pg_embedding
+SET cmetadata = sqlc.arg(cmetadata)::json
+WHERE uuid::text = sqlc.arg(uuid)
+ AND collection_id = (SELECT uuid FROM langchain_pg_collection WHERE name = 'langchain')
+RETURNING
+ uuid::text AS id,
+ COALESCE(document, '') AS document,
+ COALESCE(cmetadata::text, '{}') AS cmetadata;
+
-- name: DeleteKnowledgeDocument :exec
-- Delete a knowledge document by UUID (admin — no user_id check).
DELETE FROM langchain_pg_embedding
diff --git a/frontend/graphql-schema.graphql b/frontend/graphql-schema.graphql
index b2a034ff..d886c4bb 100644
--- a/frontend/graphql-schema.graphql
+++ b/frontend/graphql-schema.graphql
@@ -1174,6 +1174,12 @@ mutation updateKnowledgeDocument($id: String!, $input: UpdateKnowledgeDocumentIn
}
}
+mutation renameKnowledgeDocument($id: String!, $question: String!) {
+ renameKnowledgeDocument(id: $id, question: $question) {
+ ...knowledgeDocumentFragment
+ }
+}
+
mutation deleteKnowledgeDocument($id: String!) {
deleteKnowledgeDocument(id: $id)
}
diff --git a/frontend/src/features/knowledges/knowledge-header.tsx b/frontend/src/features/knowledges/knowledge-header.tsx
index bedc1040..ddbacb39 100644
--- a/frontend/src/features/knowledges/knowledge-header.tsx
+++ b/frontend/src/features/knowledges/knowledge-header.tsx
@@ -81,7 +81,7 @@ export function KnowledgeHeader({
}: KnowledgeHeaderProps) {
const navigate = useNavigate();
const { isMobile } = useBreakpoint();
- const { deleteKnowledge, updateKnowledge } = useKnowledges();
+ const { deleteKnowledge, renameKnowledge } = useKnowledges();
const [isRenaming, setIsRenaming] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
@@ -94,7 +94,7 @@ export function KnowledgeHeader({
// Title source-of-truth is the server-side `question`. We intentionally do
// not read it from the form draft below — the inline rename flow in this
- // header writes through `updateKnowledge`, which refreshes `knowledge` via
+ // header writes through `renameKnowledge`, which refreshes `knowledge` via
// the cache, and the form picks up the new value separately.
const knowledgeName = knowledge?.question ?? null;
const canShowActions = !isNew && !!knowledge;
@@ -123,15 +123,9 @@ export function KnowledgeHeader({
setIsRenaming(true);
try {
- // Backend requires `content` on update (always re-embeds). We pass
- // the server's current `content` so an inline rename never
- // accidentally overwrites unsaved edits made in the form below.
- // The sibling form picks up the new `question` automatically via
- // `useForm({ values })` — no manual sync needed here.
- await updateKnowledge(knowledge.id, {
- content: knowledge.content,
- question: newQuestion,
- });
+ // The sibling edit form picks up the new `question` via
+ // `useForm({ values })` once the cache updates — no manual sync here.
+ await renameKnowledge(knowledge.id, newQuestion);
toast.success('Knowledge renamed successfully');
handleRenameCancel();
} catch {
@@ -139,7 +133,7 @@ export function KnowledgeHeader({
} finally {
setIsRenaming(false);
}
- }, [editingInputRef, handleRenameCancel, knowledge, updateKnowledge]);
+ }, [editingInputRef, handleRenameCancel, knowledge, renameKnowledge]);
const handleDelete = useCallback(async () => {
if (!knowledgeId) {
diff --git a/frontend/src/graphql/types.ts b/frontend/src/graphql/types.ts
index 18f8cfa8..79702936 100644
--- a/frontend/src/graphql/types.ts
+++ b/frontend/src/graphql/types.ts
@@ -1180,6 +1180,13 @@ export type UpdateKnowledgeDocumentMutationVariables = Exact<{
export type UpdateKnowledgeDocumentMutation = { updateKnowledgeDocument: KnowledgeDocumentFragmentFragment };
+export type RenameKnowledgeDocumentMutationVariables = Exact<{
+ id: string;
+ question: string;
+}>;
+
+export type RenameKnowledgeDocumentMutation = { renameKnowledgeDocument: KnowledgeDocumentFragmentFragment };
+
export type DeleteKnowledgeDocumentMutationVariables = Exact<{
id: string;
}>;
@@ -6137,6 +6144,55 @@ export type UpdateKnowledgeDocumentMutationOptions = ApolloReactCommon.BaseMutat
UpdateKnowledgeDocumentMutation,
UpdateKnowledgeDocumentMutationVariables
>;
+export const RenameKnowledgeDocumentDocument = gql`
+ mutation renameKnowledgeDocument($id: String!, $question: String!) {
+ renameKnowledgeDocument(id: $id, question: $question) {
+ ...knowledgeDocumentFragment
+ }
+ }
+ ${KnowledgeDocumentFragmentFragmentDoc}
+`;
+export type RenameKnowledgeDocumentMutationFn = ApolloReactCommon.MutationFunction<
+ RenameKnowledgeDocumentMutation,
+ RenameKnowledgeDocumentMutationVariables
+>;
+
+/**
+ * __useRenameKnowledgeDocumentMutation__
+ *
+ * To run a mutation, you first call `useRenameKnowledgeDocumentMutation` within a React component and pass it any options that fit your needs.
+ * When your component renders, `useRenameKnowledgeDocumentMutation` returns a tuple that includes:
+ * - A mutate function that you can call at any time to execute the mutation
+ * - An object with fields that represent the current status of the mutation's execution
+ *
+ * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
+ *
+ * @example
+ * const [renameKnowledgeDocumentMutation, { data, loading, error }] = useRenameKnowledgeDocumentMutation({
+ * variables: {
+ * id: // value for 'id'
+ * question: // value for 'question'
+ * },
+ * });
+ */
+export function useRenameKnowledgeDocumentMutation(
+ baseOptions?: ApolloReactHooks.MutationHookOptions<
+ RenameKnowledgeDocumentMutation,
+ RenameKnowledgeDocumentMutationVariables
+ >,
+) {
+ const options = { ...defaultOptions, ...baseOptions };
+ return ApolloReactHooks.useMutation<RenameKnowledgeDocumentMutation, RenameKnowledgeDocumentMutationVariables>(
+ RenameKnowledgeDocumentDocument,
+ options,
+ );
+}
+export type RenameKnowledgeDocumentMutationHookResult = ReturnType<typeof useRenameKnowledgeDocumentMutation>;
+export type RenameKnowledgeDocumentMutationResult = ApolloReactCommon.MutationResult<RenameKnowledgeDocumentMutation>;
+export type RenameKnowledgeDocumentMutationOptions = ApolloReactCommon.BaseMutationOptions<
+ RenameKnowledgeDocumentMutation,
+ RenameKnowledgeDocumentMutationVariables
+>;
export const DeleteKnowledgeDocumentDocument = gql`
mutation deleteKnowledgeDocument($id: String!) {
deleteKnowledgeDocument(id: $id)
diff --git a/frontend/src/pages/knowledges/knowledges.tsx b/frontend/src/pages/knowledges/knowledges.tsx
index fe8d67cf..d24973ac 100644
--- a/frontend/src/pages/knowledges/knowledges.tsx
+++ b/frontend/src/pages/knowledges/knowledges.tsx
@@ -57,7 +57,7 @@ const docTypeSubtype = (k: Knowledge): null | string => {
function Knowledges() {
const navigate = useNavigate();
const location = useLocation();
- const { deleteKnowledge, isLoading, knowledges, updateKnowledge } = useKnowledges();
+ const { deleteKnowledge, isLoading, knowledges, renameKnowledge } = useKnowledges();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [deletingKnowledge, setDeletingKnowledge] = useState<Knowledge | null>(null);
const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set());
@@ -142,12 +142,7 @@ function Knowledges() {
setIsRenameLoading(true);
try {
- // Backend requires `content` on update (it always re-embeds), so we
- // pass it through unchanged from the cached document.
- await updateKnowledge(editingKnowledgeId, {
- content: knowledge.content,
- question: newQuestion,
- });
+ await renameKnowledge(editingKnowledgeId, newQuestion);
toast.success('Knowledge renamed successfully');
setEditingKnowledgeId(null);
} catch {
@@ -155,7 +150,7 @@ function Knowledges() {
} finally {
setIsRenameLoading(false);
}
- }, [editingKnowledgeId, knowledges, updateKnowledge]);
+ }, [editingKnowledgeId, knowledges, renameKnowledge]);
const handleDelete = async () => {
if (!deletingKnowledge) {
@@ -258,29 +253,6 @@ function Knowledges() {
minSize: 180,
size: 280,
},
- {
- accessorKey: 'content',
- cell: ({ row }) => {
- const content = (row.getValue('content') as string) ?? '';
-
- return (
- <div
- className="text-muted-foreground truncate text-sm"
- title={content}
- >
- {content}
- </div>
- );
- },
- enableSorting: false,
- header: () => (
- <span className="text-muted-foreground inline-flex items-center text-sm font-medium">Preview</span>
- ),
- maxSize: 800,
- meta: { columnMenuLabel: 'Preview', searchable: true },
- minSize: 160,
- size: 380,
- },
{
cell: ({ row }) => {
const k = row.original;
diff --git a/frontend/src/providers/knowledges-provider.tsx b/frontend/src/providers/knowledges-provider.tsx
index 6068e936..81ad72d3 100644
--- a/frontend/src/providers/knowledges-provider.tsx
+++ b/frontend/src/providers/knowledges-provider.tsx
@@ -16,6 +16,7 @@ import {
useKnowledgeDocumentDeletedSubscription,
useKnowledgeDocumentsQuery,
useKnowledgeDocumentUpdatedSubscription,
+ useRenameKnowledgeDocumentMutation,
useSearchKnowledgeQuery,
useUpdateKnowledgeDocumentMutation,
} from '@/graphql/types';
@@ -37,6 +38,7 @@ interface KnowledgesContextValue {
getKnowledge: (id: string) => Knowledge | undefined;
isLoading: boolean;
knowledges: Knowledge[];
+ renameKnowledge: (id: string, question: string) => Promise<Knowledge | undefined>;
updateKnowledge: (id: string, input: UpdateKnowledgeDocumentInput) => Promise<Knowledge | undefined>;
}
@@ -88,7 +90,7 @@ export function KnowledgesProvider({ children }: KnowledgesProviderProps) {
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-and-network',
skip: !shouldFetch || inSearchMode,
- variables: { withContent: true },
+ variables: { withContent: false },
});
// `searchKnowledge` does not honour `withContent` — the backend always
@@ -105,6 +107,7 @@ export function KnowledgesProvider({ children }: KnowledgesProviderProps) {
const [createKnowledgeMutation] = useCreateKnowledgeDocumentMutation();
const [updateKnowledgeMutation] = useUpdateKnowledgeDocumentMutation();
+ const [renameKnowledgeMutation] = useRenameKnowledgeDocumentMutation();
const [deleteKnowledgeMutation] = useDeleteKnowledgeDocumentMutation();
// The Apollo subscription link (`createSubscriptionCacheLink` in
@@ -184,6 +187,22 @@ export function KnowledgesProvider({ children }: KnowledgesProviderProps) {
[updateKnowledgeMutation],
);
+ const renameKnowledge = useCallback(
+ async (id: string, question: string) => {
+ try {
+ const { data: result } = await renameKnowledgeMutation({ variables: { id, question } });
+
+ return result?.renameKnowledgeDocument;
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Failed to rename knowledge document';
+ toast.error('Failed to rename knowledge document', { description: errorMessage });
+ Log.error('Error renaming knowledge document:', error);
+ throw error;
+ }
+ },
+ [renameKnowledgeMutation],
+ );
+
const deleteKnowledge = useCallback(
async (id: string) => {
try {
@@ -205,9 +224,10 @@ export function KnowledgesProvider({ children }: KnowledgesProviderProps) {
getKnowledge,
isLoading,
knowledges,
+ renameKnowledge,
updateKnowledge,
}),
- [createKnowledge, deleteKnowledge, getKnowledge, isLoading, knowledges, updateKnowledge],
+ [createKnowledge, deleteKnowledge, getKnowledge, isLoading, knowledges, renameKnowledge, updateKnowledge],
);
return <KnowledgesContext.Provider value={value}>{children}</KnowledgesContext.Provider>;