RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
feat(channels): support agent workflows and isolate startup failures (#22031)
Sbaaoui Idriss21032357b931
diff --git a/internal/channels/bootstrap.go b/internal/channels/bootstrap.goindex 0f46295ee0..e6807b5610 100644--- a/internal/channels/bootstrap.go+++ b/internal/channels/bootstrap.go@@ -52,9 +52,10 @@ type failedChannel struct {}type Runtime struct {- mu sync.Mutex- running map[string]runningChannel- failed map[string]failedChannel+ agentService *service.AgentService+ mu sync.Mutex+ running map[string]runningChannel+ failed map[string]failedChannel}// NewRuntime creates an empty chat-channel runtime reconciler.@@ -66,12 +67,13 @@ func NewRuntime() *Runtime {}// Start launches the chat-channel runtime reconciler in the background.-func Start(ctx context.Context) (*Runtime, error) {+func Start(ctx context.Context, agentService *service.AgentService) (*Runtime, error) {channelRuntime := NewRuntime()+ channelRuntime.agentService = agentServiceservice.SetChatChannelRuntimeProvider(whatsappRuntimeSnapshotMap)- if err := channelRuntime.Reconcile(ctx); err != nil {- return channelRuntime, fmt.Errorf("failed to reconcile channel: %w", err)+ if _, err := desiredChannels(ctx); err != nil {+ return channelRuntime, fmt.Errorf("failed to load chat channels: %w", err)}go channelRuntime.Run(ctx)@@ -134,7 +136,7 @@ func (r *Runtime) Reconcile(ctx context.Context) error {break}}- if err = syncWhatsAppGateway(ctx, activeWhatsApp); err != nil && activeWhatsApp {+ if err := syncWhatsAppGateway(ctx, activeWhatsApp); err != nil && activeWhatsApp {common.Error("failed to sync WhatsApp gateway", err)reconcileErr = fmt.Errorf("sync WhatsApp gateway: %w", err)}@@ -149,7 +151,7 @@ func (r *Runtime) Reconcile(ctx context.Context) error {if isRunning || retryPending {continue}- if err = r.startChannel(ctx, accountID, wanted); err != nil {+ if err := r.startChannel(ctx, accountID, wanted); err != nil {common.Error("failed to start chat channel", err, zap.String("account_id", accountID), zap.String("channel", wanted.channel))r.recordStartFailure(accountID, wanted.fingerprint, now)if reconcileErr == nil {@@ -259,6 +261,9 @@ func (r *Runtime) startChannel(ctx context.Context, accountID string, wanted des}channelService := service.NewChatChannelService()+ if r.agentService != nil {+ channelService = service.NewChatChannelServiceWithAgentService(r.agentService)+ }ch.SetMessageHandler(func(ctx context.Context, msg core.IncomingMessage) error {answer, err := channelService.HandleIncomingMessage(ctx, service.ChatChannelIncomingMessage{Channel: msg.Channel,diff --git a/internal/channels/bootstrap_test.go b/internal/channels/bootstrap_test.goindex e323369ce2..a59054d585 100644--- a/internal/channels/bootstrap_test.go+++ b/internal/channels/bootstrap_test.go@@ -26,9 +26,74 @@ import ("testing""time"+ "github.com/glebarez/sqlite"+ "gorm.io/gorm"+"ragflow/internal/channels/core"+ "ragflow/internal/dao"+ "ragflow/internal/entity")+func TestStartIsolatesMalformedChannelAndKeepsReconciling(t *testing.T) {+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatal(err)+ }+ if err := db.AutoMigrate(&entity.ChatChannel{}); err != nil {+ t.Fatal(err)+ }+ if err := db.Create(&entity.ChatChannel{+ ID: "invalid", TenantID: "tenant", Name: "invalid", Channel: "telegram",+ Config: entity.JSONMap{}, Status: 1,+ }).Error; err != nil {+ t.Fatal(err)+ }+ originalDB := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = originalDB })+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ runtime, err := Start(ctx, nil)+ if err != nil {+ t.Fatalf("Start() error = %v, want isolated channel failure", err)+ }+ deadline := time.NewTimer(5 * time.Second)+ defer deadline.Stop()+ ticker := time.NewTicker(time.Millisecond)+ defer ticker.Stop()+ for {+ runtime.mu.Lock()+ failure, ok := runtime.failed["invalid"]+ if ok {+ cancel()+ runtime.mu.Unlock()+ if failure.attempts != 1 {+ t.Fatalf("failed channel attempts = %d, want 1", failure.attempts)+ }+ break+ }+ runtime.mu.Unlock()+ select {+ case <-ticker.C:+ case <-deadline.C:+ t.Fatal("background reconciliation did not record channel failure")+ }+ }+}++func TestStartReturnsDatabaseFailure(t *testing.T) {+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatal(err)+ }+ originalDB := dao.DB+ dao.DB = db+ defer func() { dao.DB = originalDB }()+ if _, err := Start(t.Context(), nil); err == nil {+ t.Fatal("Start() succeeded without the channel table")+ }+}+func TestStartRetryDelay(t *testing.T) {tests := []struct {name stringdiff --git a/internal/dao/chat_channel.go b/internal/dao/chat_channel.goindex 51f6320e55..ed774c6a6f 100644--- a/internal/dao/chat_channel.go+++ b/internal/dao/chat_channel.go@@ -63,8 +63,9 @@ func (dao *ChatChannelDAO) ListByIDs(ctx context.Context, db *gorm.DB, ids []str}err := db.WithContext(ctx).Table("chat_channel").- Select("chat_channel.id, chat_channel.name, chat_channel.channel, chat_channel.chat_id, chat_channel.status, dialog.name as dialog_name").+ Select("chat_channel.id, chat_channel.name, chat_channel.channel, chat_channel.chat_id, chat_channel.agent_id, chat_channel.status, dialog.name as dialog_name, user_canvas.title as agent_name").Joins("LEFT JOIN dialog ON dialog.id = chat_channel.chat_id").+ Joins("LEFT JOIN user_canvas ON user_canvas.id = chat_channel.agent_id").Where("chat_channel.id IN ?", ids).Order("chat_channel.create_time DESC").Scan(&results).Errordiff --git a/internal/dao/chat_channel_test.go b/internal/dao/chat_channel_test.goindex c985e1f0fd..b31fc6d8ea 100644--- a/internal/dao/chat_channel_test.go+++ b/internal/dao/chat_channel_test.go@@ -27,6 +27,27 @@ import ("ragflow/internal/entity")+func TestChatChannelAgentColumnMigration(t *testing.T) {+ db := setupChatChannelTestDB(t)+ if err := db.Migrator().DropColumn(&entity.ChatChannel{}, "AgentID"); err != nil {+ t.Fatal(err)+ }+ if err := db.Exec("INSERT INTO chat_channel (id, tenant_id, name, channel, config, chat_id, status) VALUES (?, ?, ?, ?, ?, ?, ?)",+ "existing", "owner", "old channel", "telegram", "{}", "chat", 1).Error; err != nil {+ t.Fatal(err)+ }+ if err := db.AutoMigrate(&entity.ChatChannel{}); err != nil {+ t.Fatal(err)+ }+ row, err := NewChatChannel().GetByID(t.Context(), db, "existing")+ if err != nil || row.ChatID == nil || *row.ChatID != "chat" || row.AgentID != nil {+ t.Fatalf("existing record changed: %+v %v", row, err)+ }+ if err := db.Model(row).Update("agent_id", "agent").Error; err != nil {+ t.Fatalf("new agent column unavailable: %v", err)+ }+}+// setupChatChannelTestDB initializes an in-memory SQLite database for ChatChannel DAO tests.func setupChatChannelTestDB(t *testing.T) *gorm.DB {t.Helper()@@ -39,7 +60,7 @@ func setupChatChannelTestDB(t *testing.T) *gorm.DB {}// Migrate chat_channel and dialog (entity.Chat) tables- if err = db.AutoMigrate(&entity.ChatChannel{}, &entity.Chat{}); err != nil {+ if err = db.AutoMigrate(&entity.ChatChannel{}, &entity.Chat{}, &entity.UserCanvas{}); err != nil {t.Fatalf("failed to migrate: %v", err)}diff --git a/internal/entity/chat_channel.go b/internal/entity/chat_channel.goindex d2be17a240..3b673fa730 100644--- a/internal/entity/chat_channel.go+++ b/internal/entity/chat_channel.go@@ -25,6 +25,7 @@ type ChatChannel struct {Channel string `gorm:"column:channel;size:128;not null;index" json:"channel"`Config JSONMap `gorm:"column:config;type:longtext;not null" json:"config"`ChatID *string `gorm:"column:chat_id;size:32;index" json:"chat_id,omitempty"`+ AgentID *string `gorm:"column:agent_id;size:32;index" json:"agent_id,omitempty"`Status int `gorm:"column:status;index;default:1" json:"status,omitempty"`BaseModel}@@ -39,6 +40,8 @@ type ChatChannelListResponse struct {Name string `json:"name"`Channel string `json:"channel"`ChatID *string `json:"chat_id"`+ AgentID *string `json:"agent_id"`+ AgentName *string `json:"agent_name"`Status int `json:"status"`DialogName *string `json:"dialog_name"` // Dialog.name.alias("dialog_name")}diff --git a/internal/handler/chat_channel.go b/internal/handler/chat_channel.goindex 03b1557bd2..3b8121b722 100644--- a/internal/handler/chat_channel.go+++ b/internal/handler/chat_channel.go@@ -26,7 +26,7 @@ import ()type ChatChannelService interface {- CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error)+ CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID, agentID *string) (*entity.ChatChannel, error)List(ctx context.Context) ([]*entity.ChatChannelListResponse, error)GetChatChannel(ctx context.Context, channelID string) (*entity.ChatChannel, common.ErrorCode, error)UpdateChatChannel(ctx context.Context, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error)@@ -52,6 +52,7 @@ type CreateChatChannelRequest struct {Channel string `json:"channel" binding:"required"`Config entity.JSONMap `json:"config"`ChatID *string `json:"chat_id"`+ AgentID *string `json:"agent_id"`}// CreateChatChannel handles POST /chat-channels.@@ -69,6 +70,10 @@ func (h *ChatChannelHandler) CreateChatChannel(c *gin.Context) {common.RespondError(c, common.CodeDataError, err.Error())return}+ if req.ChatID != nil && strings.TrimSpace(*req.ChatID) != "" && req.AgentID != nil && strings.TrimSpace(*req.AgentID) != "" {+ common.RespondError(c, common.CodeDataError, "chat_id and agent_id are mutually exclusive")+ return+ }ctx := c.Request.Context()@@ -78,6 +83,7 @@ func (h *ChatChannelHandler) CreateChatChannel(c *gin.Context) {req.Channel,req.Config,req.ChatID,+ req.AgentID,)if err != nil {if respondPermissionErrorIf(c, err, true) {diff --git a/internal/handler/chat_channel_test.go b/internal/handler/chat_channel_test.goindex 8ee12a3008..75bba4c70a 100644--- a/internal/handler/chat_channel_test.go+++ b/internal/handler/chat_channel_test.go@@ -17,7 +17,7 @@ import ()type fakeChatChannelService struct {- createFn func(context.Context, string, string, entity.JSONMap, *string) (*entity.ChatChannel, error)+ createFn func(context.Context, string, string, entity.JSONMap, *string, *string) (*entity.ChatChannel, error)listFn func(context.Context) ([]*entity.ChatChannelListResponse, error)getFn func(context.Context, string) (*entity.ChatChannel, common.ErrorCode, error)updateFn func(context.Context, string, map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error)@@ -25,11 +25,11 @@ type fakeChatChannelService struct {deleteFn func(context.Context, string) (bool, common.ErrorCode, error)}-func (f fakeChatChannelService) CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {+func (f fakeChatChannelService) CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID, agentID *string) (*entity.ChatChannel, error) {if f.createFn == nil {return nil, errors.New("unexpected CreateChatChannel call")}- return f.createFn(ctx, name, channelType, config, chatID)+ return f.createFn(ctx, name, channelType, config, chatID, agentID)}func (f fakeChatChannelService) List(ctx context.Context) ([]*entity.ChatChannelListResponse, error) {@@ -71,6 +71,44 @@ func setChatChannelHandlerIdentity(c *gin.Context) {c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "tenant-1", "tenant-1"))}+func TestChatChannelHandlerAgentCreate(t *testing.T) {+ for _, body := range []string{+ `{"name":"workflow","channel":"telegram","agent_id":"agent"}`,+ `{"name":"invalid","channel":"telegram","chat_id":"chat","agent_id":"agent"}`,+ } {+ t.Run(body, func(t *testing.T) {+ called := false+ h := NewChatChannelHandler(fakeChatChannelService{+ createFn: func(ctx context.Context, name, channel string, config entity.JSONMap, chatID, agentID *string) (*entity.ChatChannel, error) {+ called = true+ if chatID != nil || agentID == nil || *agentID != "agent" {+ t.Fatalf("binding lost: chat=%v agent=%v", chatID, agentID)+ }+ return &entity.ChatChannel{AgentID: agentID}, nil+ },+ })+ recorder := httptest.NewRecorder()+ ctx, _ := gin.CreateTestContext(recorder)+ ctx.Request = httptest.NewRequest(http.MethodPost, "/api/v1/chat-channels", strings.NewReader(body))+ ctx.Request.Header.Set("Content-Type", "application/json")+ h.CreateChatChannel(ctx)+ var response struct {+ Code common.ErrorCode `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if strings.Contains(body, `"chat_id"`) {+ if called || response.Code != common.CodeDataError {+ t.Fatalf("invalid binding accepted: %s", recorder.Body.String())+ }+ } else if !called || response.Code != common.CodeSuccess {+ t.Fatalf("agent binding rejected: %s", recorder.Body.String())+ }+ })+ }+}+func TestChatChannelHandlerCreateSuccess(t *testing.T) {gin.SetMode(gin.TestMode)@@ -80,7 +118,7 @@ func TestChatChannelHandlerCreateSuccess(t *testing.T) {h := &ChatChannelHandler{chatChannelService: fakeChatChannelService{- createFn: func(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {+ createFn: func(ctx context.Context, name, channelType string, config entity.JSONMap, chatID, agentID *string) (*entity.ChatChannel, error) {gotTenantID = permission.TenantIDFromContext(ctx)gotName = namegotChannel = channelType@@ -140,7 +178,7 @@ func TestChatChannelHandlerCreateInvalidRequestStopsEarly(t *testing.T) {called := falseh := &ChatChannelHandler{chatChannelService: fakeChatChannelService{- createFn: func(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {+ createFn: func(ctx context.Context, name, channelType string, config entity.JSONMap, chatID, agentID *string) (*entity.ChatChannel, error) {called = truereturn nil, nil},diff --git a/internal/server/api/server.go b/internal/server/api/server.goindex 70356ebf10..c993848bde 100644--- a/internal/server/api/server.go+++ b/internal/server/api/server.go@@ -368,7 +368,7 @@ func startServer(ctx context.Context, serverName string, arguments *bootstrap.Se// Setup routesr.Setup(ginEngine)- _, err := channels.Start(ctx)+ _, err := channels.Start(ctx, agentService)if err != nil {return fmt.Errorf("start chat-channel: %w", err)}diff --git a/internal/service/chat_channel.go b/internal/service/chat_channel.goindex f9ee366432..a1d7cbfbb6 100644--- a/internal/service/chat_channel.go+++ b/internal/service/chat_channel.go@@ -20,6 +20,7 @@ import ("fmt""strings""sync"+ "time""go.uber.org/zap"@@ -35,6 +36,7 @@ type ChatChannelService struct {chatChannelDAO *dao.ChatChannelDAOchatDAO *dao.ChatDAOchatSessionSvc *ChatSessionService+ agentRunner chatChannelAgentRunner}func NewChatChannelService() *ChatChannelService {@@ -42,9 +44,17 @@ func NewChatChannelService() *ChatChannelService {chatChannelDAO: dao.NewChatChannel(),chatDAO: dao.NewChatDAO(),chatSessionSvc: NewChatSessionService(),+ agentRunner: NewAgentService(),}}+// NewChatChannelServiceWithAgentService shares the API's agent run infrastructure.+func NewChatChannelServiceWithAgentService(agentService *AgentService) *ChatChannelService {+ s := NewChatChannelService()+ s.agentRunner = agentService+ return s+}+type ChatChannelIncomingMessage struct {Channel stringAccountID string@@ -92,7 +102,7 @@ func (s *ChatChannelService) List(ctx context.Context) ([]*entity.ChatChannelLisreturn s.chatChannelDAO.ListByIDs(ctx, dao.DB, channelIDs)}-func (s *ChatChannelService) CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {+func (s *ChatChannelService) CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID, agentID *string) (*entity.ChatChannel, error) {userID := permission.UserIDFromContext(ctx)tenantID, err := requireCurrentTenantID(ctx)if err != nil {@@ -101,10 +111,12 @@ func (s *ChatChannelService) CreateChatChannel(ctx context.Context, name, channeif err := permission.NewDatabaseChecker(dao.DB).CheckFeature(ctx, "chat", permission.ActionWrite); err != nil {return nil, err}- if chatID != nil && *chatID != "" {- if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: *chatID}, permission.OperationUse); err != nil {- return nil, err- }+ chatID, agentID = normalizedChannelTarget(chatID), normalizedChannelTarget(agentID)+ if err := validateChannelBinding(ctx, chatID, agentID); err != nil {+ return nil, err+ }+ if err := validateChannelBinding(permission.WithIdentity(ctx, tenantID, tenantID), chatID, agentID); err != nil {+ return nil, err}name = strings.TrimSpace(name)if err := common.ValidateNameRunes(name, common.NameLimit128); err != nil {@@ -118,6 +130,7 @@ func (s *ChatChannelService) CreateChatChannel(ctx context.Context, name, channeChannel: channelType,Config: config,ChatID: chatID,+ AgentID: agentID,Status: 1,}@@ -194,29 +207,37 @@ func (s *ChatChannelService) UpdateChatChannel(ctx context.Context, channelID st}}- if value, exists := req["chat_id"]; exists {- if value == nil {- updates["chat_id"] = nil- } else {- chatID, ok := value.(string)- if !ok {- return nil, common.CodeDataError, errors.New("chat_id must be string or null")- }- if chatID != "" {- if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationUse); err != nil {- code, normalizedErr := permissionresponse.NormalizeHidden(err)- return nil, code, normalizedErr- }- if channel.TenantID != strings.TrimSpace(permission.UserIDFromContext(ctx)) {- ownerCtx := permission.WithIdentity(ctx, channel.TenantID, channel.TenantID)- if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ownerCtx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationUse); err != nil {- code, normalizedErr := permissionresponse.NormalizeHidden(err)- return nil, code, normalizedErr- }+ chatID, agentID := channel.ChatID, channel.AgentID+ bindingChanged := false+ for _, field := range []string{"chat_id", "agent_id"} {+ if value, exists := req[field]; exists {+ bindingChanged = true+ var id *string+ if value != nil {+ text, ok := value.(string)+ if !ok {+ return nil, common.CodeDataError, fmt.Errorf("%s must be string or null", field)}+ id = normalizedChannelTarget(&text)+ }+ if field == "chat_id" {+ chatID = id+ } else {+ agentID = id+ }+ }+ }+ if bindingChanged {+ if chatID != nil && agentID != nil {+ return nil, common.CodeDataError, errors.New("chat_id and agent_id are mutually exclusive")+ }+ for _, bindingCtx := range []context.Context{ctx, permission.WithIdentity(ctx, channel.TenantID, channel.TenantID)} {+ if err := validateChannelBinding(bindingCtx, chatID, agentID); err != nil {+ code, normalizedErr := permissionresponse.NormalizeHidden(err)+ return nil, code, normalizedErr}- updates["chat_id"] = chatID}+ updates["chat_id"], updates["agent_id"] = chatID, agentID}if len(updates) > 0 {@@ -276,6 +297,18 @@ func (s *ChatChannelService) HandleIncomingMessage(ctx context.Context, msg Chat}return "", err}+ if channel.Status != 1 {+ return "", nil+ }+ ownerCtx := permission.WithIdentity(ctx, channel.TenantID, channel.TenantID)+ if err := validateChannelBinding(ownerCtx, channel.ChatID, channel.AgentID); err != nil {+ return "", err+ }+ if channel.AgentID != nil {+ ctx, cancel := context.WithTimeout(ownerCtx, 5*time.Minute)+ defer cancel()+ return s.handleChannelAgentMessage(ctx, channel, msg)+ }if channel.ChatID == nil || strings.TrimSpace(*channel.ChatID) == "" {return "", nil}@@ -293,6 +326,8 @@ func (s *ChatChannelService) HandleIncomingMessage(ctx context.Context, msg Chatreturn "", err}+ // Channel chat sessions are owned by the dialog tenant; authorization above+ // separately enforces the channel owner's current access to that dialog.completionCtx := permission.WithIdentity(ctx, dialog.TenantID, dialog.TenantID)result, err := s.chatSessionSvc.ChatCompletions(completionCtx,diff --git a/internal/service/chat_channel_agent.go b/internal/service/chat_channel_agent.gonew file mode 100644index 0000000000..9ab333e911--- /dev/null+++ b/internal/service/chat_channel_agent.go@@ -0,0 +1,122 @@+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package service++import (+ "context"+ "encoding/json/v2"+ "errors"+ "strings"++ "ragflow/internal/agent/canvas"+ "ragflow/internal/dao"+ "ragflow/internal/entity"+ "ragflow/internal/permission"+)++type chatChannelAgentRunner interface {+ RunAgent(context.Context, string, string, string, any, []map[string]any) (<-chan canvas.RunEvent, error)+}++func normalizedChannelTarget(id *string) *string {+ if id == nil || strings.TrimSpace(*id) == "" {+ return nil+ }+ return new(strings.TrimSpace(*id))+}++func validateChannelBinding(ctx context.Context, chatID, agentID *string) error {+ if chatID != nil && agentID != nil {+ return errors.New("chat_id and agent_id are mutually exclusive")+ }+ ref := permission.ResourceRef{Kind: permission.ResourceKindChat}+ operation := permission.OperationUse+ switch {+ case chatID != nil:+ ref.ID = *chatID+ case agentID != nil:+ ref.Kind, ref.ID, operation = permission.ResourceKindCanvas, *agentID, permission.OperationRun+ default:+ return nil+ }+ return permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, ref, operation)+}++func (s *ChatChannelService) handleChannelAgentMessage(ctx context.Context, channel *entity.ChatChannel, msg ChatChannelIncomingMessage) (string, error) {+ sessionID := channelSessionID(*channel.AgentID, channel.ID, msg.ChatID)+ // RunAgent creates and authorizes the persisted session; this boundary only+ // supplies its stable identity for the first message and subsequent turns.+ ctx = WithAgentSessionID(ctx, sessionID)+ events, err := s.agentRunner.RunAgent(ctx, *channel.AgentID, sessionID, "", msg.Text, nil)+ if err != nil {+ return "", err+ }+ var answer strings.Builder+ var runErr error+ thinking := false+ for {+ select {+ case <-ctx.Done():+ return "", ctx.Err()+ case ev, ok := <-events:+ if !ok {+ if runErr != nil {+ return "", runErr+ }+ return answer.String(), nil+ }+ switch ev.Type {+ case "message":+ var data canvas.MessageEvent+ if err := json.Unmarshal([]byte(ev.Data), &data); err != nil {+ return "", err+ }+ if data.StartToThink {+ thinking = true+ }+ if data.EndToThink {+ thinking = false+ continue+ }+ if !thinking {+ answer.WriteString(data.Content)+ }+ case "waiting_for_user":+ var data canvas.WaitingForUserEvent+ if err := json.Unmarshal([]byte(ev.Data), &data); err != nil {+ return "", err+ }+ if len(data.Inputs) > 1 {+ answer.Reset()+ answer.WriteString("This workflow requires structured input. Please continue in RAGFlow.")+ continue+ }+ if answer.Len() > 0 && data.Tips != "" {+ answer.WriteString("\n")+ }+ answer.WriteString(data.Tips)+ if answer.Len() == 0 {+ answer.WriteString("Please reply to continue.")+ }+ case "error":+ // Provider/internal errors may contain credentials or implementation+ // details; adapters receive an error, never that raw event payload.+ runErr = errors.New("channel workflow execution failed")+ case "cancelled":+ runErr = context.Canceled+ }+ }+ }+}diff --git a/internal/service/chat_channel_agent_test.go b/internal/service/chat_channel_agent_test.gonew file mode 100644index 0000000000..1e33ca2316--- /dev/null+++ b/internal/service/chat_channel_agent_test.go@@ -0,0 +1,194 @@+package service++import (+ "context"+ "errors"+ "strings"+ "testing"+ "time"++ "github.com/redis/go-redis/v9"++ "ragflow/internal/agent/canvas"+ "ragflow/internal/common"+ "ragflow/internal/entity"+ "ragflow/internal/permission"+)++func TestChatChannelAgentBindingRoundTrip(t *testing.T) {+ db := setupChatChannelServiceTestDB(t)+ ctx := serviceTestContext(t, "owner", "owner")+ if err := db.Create(&entity.UserCanvas{ID: "agent", UserID: "owner", Title: new("Workflow")}).Error; err != nil {+ t.Fatal(err)+ }+ createServiceTestDialog(t, db, "chat", "owner", "Chat")+ svc := NewChatChannelService()+ channel, err := svc.CreateChatChannel(ctx, "channel", "telegram", entity.JSONMap{}, nil, new("agent"))+ if err != nil {+ t.Fatal(err)+ }+ rows, err := svc.List(ctx)+ if err != nil || len(rows) != 1 || rows[0].AgentID == nil || *rows[0].AgentID != "agent" || rows[0].AgentName == nil || *rows[0].AgentName != "Workflow" {+ t.Fatalf("list = %+v, %v", rows, err)+ }+ for _, binding := range []map[string]any{+ {"chat_id": "chat", "agent_id": nil},+ {"chat_id": nil, "agent_id": "agent"},+ {"chat_id": nil, "agent_id": nil},+ } {+ row, code, err := svc.UpdateChatChannel(ctx, channel.ID, binding)+ if err != nil || code != common.CodeSuccess {+ t.Fatalf("switch %+v: %+v %v", binding, row, err)+ }+ if (row.ChatID != nil) != (binding["chat_id"] != nil) || (row.AgentID != nil) != (binding["agent_id"] != nil) {+ t.Fatalf("binding did not persist: %+v", row)+ }+ }+ for _, binding := range []map[string]any{+ {"chat_id": "chat", "agent_id": "agent"},+ {"agent_id": 42},+ {"agent_id": "missing"},+ } {+ if _, code, err := svc.UpdateChatChannel(ctx, channel.ID, binding); err == nil || code == common.CodeSuccess {+ t.Fatalf("accepted invalid binding %+v", binding)+ }+ }+ if _, err := svc.CreateChatChannel(ctx, "invalid", "telegram", entity.JSONMap{}, new("chat"), new("agent")); err == nil {+ t.Fatal("create accepted two targets")+ }+}++func TestChatChannelRejectsCrossTenantBindingAndExecution(t *testing.T) {+ db := setupChatChannelServiceTestDB(t)+ createServiceTestDialog(t, db, "private", "actor", "Private")+ ctx := serviceTestContext(t, "actor", "other", "other")+ svc := NewChatChannelService()+ if _, err := svc.CreateChatChannel(ctx, "invalid", "telegram", entity.JSONMap{}, new("private"), nil); err == nil {+ t.Fatal("accepted a target unavailable to the channel tenant")+ }+ createServiceTestChannel(t, db, &entity.ChatChannel{+ ID: "historical", TenantID: "other", Channel: "telegram", Config: entity.JSONMap{}, ChatID: new("private"), Status: 1,+ })+ if _, err := svc.HandleIncomingMessage(t.Context(), ChatChannelIncomingMessage{AccountID: "historical", ChatID: "external", Text: "hello"}); !errors.Is(err, permission.ErrPermissionDenied) {+ t.Fatalf("historical unauthorized binding: %v", err)+ }+}++func TestChatChannelAgentRevokedAccess(t *testing.T) {+ db := setupChatChannelServiceTestDB(t)+ ctx := serviceTestContext(t, "owner", "owner")+ agent := &entity.UserCanvas{ID: "shared", UserID: "creator", TenantID: new("owner"), Permission: string(entity.TenantPermissionTeam)}+ if err := db.Create(agent).Error; err != nil {+ t.Fatal(err)+ }+ svc := NewChatChannelService()+ channel, err := svc.CreateChatChannel(ctx, "channel", "telegram", entity.JSONMap{}, nil, new("shared"))+ if err != nil {+ t.Fatal(err)+ }+ if err := db.Model(agent).Update("permission", string(entity.TenantPermissionMe)).Error; err != nil {+ t.Fatal(err)+ }+ svc.agentRunner = channelAgentRunnerFunc(func(context.Context, string, string, string, any, []map[string]any) (<-chan canvas.RunEvent, error) {+ t.Fatal("revoked workflow must not execute")+ return nil, nil+ })+ if _, err := svc.HandleIncomingMessage(t.Context(), ChatChannelIncomingMessage{AccountID: channel.ID, ChatID: "external", Text: "hello"}); !errors.Is(err, permission.ErrPermissionDenied) {+ t.Fatalf("revoked workflow binding: %v", err)+ }+}++func TestChatChannelAgentRealEngineContinuationAndResume(t *testing.T) {+ db := setupServiceTestDB(t)+ pushServiceDB(t, db)+ if err := db.AutoMigrate(&entity.ChatChannel{}, &entity.Chat{}, &entity.APIToken{},+ &entity.TenantModelProvider{}, &entity.TenantModelInstance{}, &entity.TenantModel{}); err != nil {+ t.Fatal(err)+ }+ ctx := serviceTestContext(t, "owner", "owner")+ dsl := map[string]any{+ "components": map[string]any{+ "begin": map[string]any{"obj": map[string]any{"component_name": "Begin", "params": map[string]any{}}, "downstream": []any{"fill"}},+ "fill": map[string]any{+ "obj": map[string]any{"component_name": "UserFillUp", "params": map[string]any{"enable_tips": true, "tips": "Your answer?"}},+ "upstream": []any{"begin"}, "downstream": []any{"message"},+ },+ "message": map[string]any{+ "obj": map[string]any{"component_name": "Message", "params": map[string]any{"text": "got: {{fill@user_input}}"}},+ "upstream": []any{"fill"},+ },+ },+ "path": []any{"begin", "fill", "message"},+ }+ makeCanvasWithDSL(t, "workflow", "owner", "owner", "version", dsl)+ tracker, mr := newRunTrackerForTest(t, time.Hour)+ client := redis.NewClient(&redis.Options{Addr: mr.Addr()})+ t.Cleanup(func() { _ = client.Close() })+ runner := NewAgentServiceWithOptions(canvas.NewKvrocksCheckPointStoreWithClient(client, time.Hour), nil, tracker)+ svc := NewChatChannelServiceWithAgentService(runner)+ channel, err := svc.CreateChatChannel(ctx, "channel", "telegram", entity.JSONMap{}, nil, new("workflow"))+ if err != nil {+ t.Fatal(err)+ }+ msg := ChatChannelIncomingMessage{AccountID: channel.ID, ChatID: "external-one", Text: "start"}+ answer, err := svc.HandleIncomingMessage(t.Context(), msg)+ if err != nil || !strings.Contains(answer, "Your answer?") {+ t.Fatalf("waiting: %q %v", answer, err)+ }+ msg.Text = "hello"+ answer, err = svc.HandleIncomingMessage(t.Context(), msg)+ if err != nil || answer != "got: hello" {+ t.Fatalf("resume: %q %v", answer, err)+ }+ msg.ChatID = "external-two"+ answer, err = svc.HandleIncomingMessage(t.Context(), msg)+ if err != nil || !strings.Contains(answer, "Your answer?") {+ t.Fatalf("isolated conversation: %q %v", answer, err)+ }+ var count int64+ db.Model(&entity.API4Conversation{}).Count(&count)+ if count != 2 {+ t.Fatalf("sessions = %d, want 2", count)+ }+ if err := db.Model(&entity.ChatChannel{}).Where("id = ?", channel.ID).Update("status", 0).Error; err != nil {+ t.Fatalf("disable: %v", err)+ }+ if answer, err := svc.HandleIncomingMessage(t.Context(), msg); answer != "" || err != nil {+ t.Fatalf("disabled channel: %q %v", answer, err)+ }+}++type channelAgentRunnerFunc func(context.Context, string, string, string, any, []map[string]any) (<-chan canvas.RunEvent, error)++func (f channelAgentRunnerFunc) RunAgent(ctx context.Context, agent, session, version string, input any, files []map[string]any) (<-chan canvas.RunEvent, error) {+ return f(ctx, agent, session, version, input, files)+}++func TestChatChannelAgentErrorAndThinking(t *testing.T) {+ for _, tc := range []struct {+ name string+ events []canvas.RunEvent+ want string+ failed bool+ }{+ {"text", []canvas.RunEvent{{Type: "message", Data: `{"start_to_think":true}`}, {Type: "message", Data: `{"content":"private reasoning"}`}, {Type: "message", Data: `{"end_to_think":true}`}, {Type: "message", Data: `{"content":"answer"}`}}, "answer", false},+ {"error", []canvas.RunEvent{{Type: "error", Data: `{"message":"sensitive provider failure"}`}}, "", true},+ {"cancelled", []canvas.RunEvent{{Type: "message", Data: `{"content":"partial"}`}, {Type: "cancelled"}}, "", true},+ {"form", []canvas.RunEvent{{Type: "waiting_for_user", Data: `{"inputs":{"a":{},"b":{}}}`}}, "This workflow requires structured input. Please continue in RAGFlow.", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ svc := &ChatChannelService{agentRunner: channelAgentRunnerFunc(func(ctx context.Context, agent, session, version string, input any, files []map[string]any) (<-chan canvas.RunEvent, error) {+ events := make(chan canvas.RunEvent, len(tc.events))+ for _, ev := range tc.events {+ events <- ev+ }+ close(events)+ return events, nil+ })}+ answer, err := svc.handleChannelAgentMessage(t.Context(), &entity.ChatChannel{ID: "channel", AgentID: new("agent")}, ChatChannelIncomingMessage{ChatID: "chat", Text: "hello"})+ if answer != tc.want || (err != nil) != tc.failed {+ t.Fatalf("answer=%q err=%v", answer, err)+ }+ })+ }+}diff --git a/internal/service/chat_channel_test.go b/internal/service/chat_channel_test.goindex 9bd2aa30a5..ed6347a8f7 100644--- a/internal/service/chat_channel_test.go+++ b/internal/service/chat_channel_test.go@@ -25,7 +25,7 @@ func setupChatChannelServiceTestDB(t *testing.T) *gorm.DB {t.Fatalf("failed to open sqlite: %v", err)}- if err = db.AutoMigrate(&entity.ChatChannel{}, &entity.Chat{}, &entity.User{}, &entity.UserTenant{}); err != nil {+ if err = db.AutoMigrate(&entity.ChatChannel{}, &entity.Chat{}, &entity.UserCanvas{}, &entity.User{}, &entity.UserTenant{}); err != nil {t.Fatalf("failed to migrate test schema: %v", err)}@@ -98,7 +98,7 @@ func TestChatChannelServiceCreateAndList(t *testing.T) {"bot-a","dingtalk",entity.JSONMap{"token": "abc"},- &chatID,+ &chatID, nil,)if err != nil {t.Fatalf("CreateChatChannel failed: %v", err)@@ -215,6 +215,7 @@ func TestChatChannelServiceCreateRejectsOverlongName(t *testing.T) {"dingtalk",entity.JSONMap{},nil,+ nil,)if err == nil || !strings.Contains(err.Error(), "larger than") {t.Fatalf("CreateChatChannel overlong name error = %v, want length error", err)