package v1 import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "strconv" "testing" "github.com/gin-gonic/gin" "github.com/gochat/gochat/internal/llm" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" ) func setupCaptainAssistantHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB) { t.Helper() gin.SetMode(gin.TestMode) dbName := fmt.Sprintf("file:%s?mode=memory&cache=private", t.Name()) db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{}) require.NoError(t, err) require.NoError(t, db.AutoMigrate( &model.Account{}, &model.Inbox{}, &model.CaptainAssistant{}, &model.CaptainInbox{}, )) t.Cleanup(func() { sqlDB, _ := db.DB() sqlDB.Close() }) assistantRepo := repository.NewCaptainAssistantRepo(db) inboxRepo := repository.NewCaptainInboxRepo(db) documentRepo := repository.NewCaptainDocumentRepo(db) responseRepo := repository.NewCaptainAssistantResponseRepo(db) svc := service.NewCaptainAssistantService(assistantRepo, inboxRepo, documentRepo, responseRepo, nil) handler := NewCaptainAssistantHandler(svc) router := gin.New() assistants := router.Group("/api/v1/accounts/:account_id/captain/assistants") assistants.GET("/", handler.List) assistants.POST("/", handler.Create) assistants.GET("/tools", handler.Tools) assistants.GET("/:assistant_id", handler.Get) assistants.PUT("/:assistant_id", handler.Update) assistants.DELETE("/:assistant_id", handler.Delete) assistants.POST("/:assistant_id/playground", handler.GenerateResponse) assistants.GET("/:assistant_id/inboxes", handler.ListInboxes) assistants.POST("/:assistant_id/inboxes", handler.AssociateInbox) assistants.DELETE("/:assistant_id/inboxes/:inbox_id", handler.DissociateInbox) return router, db } func setupCaptainAssistantHandlerTestWithProvider(t *testing.T, provider llm.Provider) (*gin.Engine, *gorm.DB) { t.Helper() gin.SetMode(gin.TestMode) dbName := fmt.Sprintf("file:%s-provider?mode=memory&cache=private", t.Name()) db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{}) require.NoError(t, err) require.NoError(t, db.AutoMigrate( &model.Account{}, &model.Inbox{}, &model.CaptainAssistant{}, &model.CaptainInbox{}, )) t.Cleanup(func() { sqlDB, _ := db.DB() sqlDB.Close() }) assistantRepo := repository.NewCaptainAssistantRepo(db) inboxRepo := repository.NewCaptainInboxRepo(db) documentRepo := repository.NewCaptainDocumentRepo(db) responseRepo := repository.NewCaptainAssistantResponseRepo(db) svc := service.NewCaptainAssistantService(assistantRepo, inboxRepo, documentRepo, responseRepo, provider) handler := NewCaptainAssistantHandler(svc) router := gin.New() assistants := router.Group("/api/v1/accounts/:account_id/captain/assistants") assistants.POST("/:assistant_id/playground", handler.GenerateResponse) return router, db } func seedCaptainAssistantAccount(t *testing.T, db *gorm.DB, name string) *model.Account { t.Helper() account := &model.Account{Name: name, Locale: "en", Active: true} require.NoError(t, db.Create(account).Error) return account } func captainAssistantJSONRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder { t.Helper() var reader *bytes.Reader if body == nil { reader = bytes.NewReader(nil) } else { payload, err := json.Marshal(body) require.NoError(t, err) reader = bytes.NewReader(payload) } w := httptest.NewRecorder() req := httptest.NewRequest(method, path, reader) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) return w } func TestCaptainAssistantHandler_CRUDUsesChatwootPayloadShape(t *testing.T) { router, db := setupCaptainAssistantHandlerTest(t) account := seedCaptainAssistantAccount(t, db, "Captain Org") basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants" createBody := map[string]any{ "assistant": map[string]any{ "name": "Fin", "description": "Support copilot", "config": map[string]any{ "product_name": "GoChat", "temperature": 0.2, }, "guardrails": []string{"never ask for passwords"}, "response_guidelines": []string{"be concise"}, }, } w := captainAssistantJSONRequest(t, router, http.MethodPost, basePath+"/", createBody) assert.Equal(t, http.StatusOK, w.Code) var created map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &created)) assert.NotContains(t, created, "success") assert.NotContains(t, created, "data") assert.Equal(t, float64(account.ID), created["account_id"]) assert.Equal(t, "Fin", created["name"]) assert.Equal(t, "Support copilot", created["description"]) assert.Equal(t, "GoChat", created["config"].(map[string]any)["product_name"]) assistantID := uint(created["id"].(float64)) w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/", nil) assert.Equal(t, http.StatusOK, w.Code) var listResp map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &listResp)) assert.Len(t, listResp["payload"], 1) assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["total_count"]) assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["page"]) updateBody := map[string]any{"assistant": map[string]any{"name": "Fin Prime", "description": "Updated"}} w = captainAssistantJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, assistantID), updateBody) assert.Equal(t, http.StatusOK, w.Code) var updated map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &updated)) assert.Equal(t, "Fin Prime", updated["name"]) assert.Equal(t, "Updated", updated["description"]) w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", basePath, assistantID), nil) assert.Equal(t, http.StatusOK, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, assistantID), nil) assert.Equal(t, http.StatusNoContent, w.Code) } func TestCaptainAssistantHandler_AccountScopedShowAndInboxBinding(t *testing.T) { router, db := setupCaptainAssistantHandlerTest(t) account := seedCaptainAssistantAccount(t, db, "Account One") otherAccount := seedCaptainAssistantAccount(t, db, "Account Two") assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive} require.NoError(t, db.Create(assistant).Error) inbox := &model.Inbox{AccountID: account.ID, Name: "Primary", ChannelType: "web_widget"} require.NoError(t, db.Create(inbox).Error) otherInbox := &model.Inbox{AccountID: otherAccount.ID, Name: "Other", ChannelType: "web_widget"} require.NoError(t, db.Create(otherInbox).Error) basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants" otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/assistants" w := captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, assistant.ID), nil) assert.Equal(t, http.StatusNotFound, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/tools", nil) assert.Equal(t, http.StatusOK, w.Code) var tools []map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &tools)) assert.Len(t, tools, 7) assert.Equal(t, "add_contact_note", tools[0]["id"]) bindBody := map[string]any{"inbox": map[string]any{"inbox_id": inbox.ID}} w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), bindBody) assert.Equal(t, http.StatusOK, w.Code) var bound map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &bound)) assert.Equal(t, float64(inbox.ID), bound["id"]) assert.NotContains(t, bound, "success") w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), nil) assert.Equal(t, http.StatusOK, w.Code) var inboxList map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &inboxList)) assert.Len(t, inboxList["payload"], 1) wrongBindBody := map[string]any{"inbox": map[string]any{"inbox_id": otherInbox.ID}} w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), wrongBindBody) assert.Equal(t, http.StatusNotFound, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", otherBasePath, assistant.ID, inbox.ID), nil) assert.Equal(t, http.StatusNotFound, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", basePath, assistant.ID, inbox.ID), nil) assert.Equal(t, http.StatusNoContent, w.Code) } func TestCaptainAssistantHandler_PlaygroundLegacyNoLLMFallback(t *testing.T) { router, db := setupCaptainAssistantHandlerTest(t) account := seedCaptainAssistantAccount(t, db, "Captain Org") assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{"model":"gpt-test"}`), Status: model.AssistantStatusActive} require.NoError(t, db.Create(assistant).Error) body := map[string]any{ "message_content": "Hello assistant", "message_history": []map[string]any{ {"role": "user", "content": "Previous message"}, {"role": "assistant", "content": "Previous response", "agent_name": "billing_scenario"}, }, } w := captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/captain/assistants/%d/playground", account.ID, assistant.ID), body) assert.Equal(t, http.StatusOK, w.Code) var payload map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload)) assert.NotContains(t, payload, "success") assert.NotContains(t, payload, "data") assert.Equal(t, "Captain assistant response generation is not configured for this account.", payload["content"]) assert.NotContains(t, payload, "response") } func TestCaptainAssistantHandler_PlaygroundDefaultsHistoryAndScopesAccount(t *testing.T) { router, db := setupCaptainAssistantHandlerTest(t) account := seedCaptainAssistantAccount(t, db, "Account One") otherAccount := seedCaptainAssistantAccount(t, db, "Account Two") assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive} require.NoError(t, db.Create(assistant).Error) body := map[string]any{"message_content": "Hello assistant"} w := captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/captain/assistants/%d/playground", account.ID, assistant.ID), body) assert.Equal(t, http.StatusOK, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/captain/assistants/%d/playground", otherAccount.ID, assistant.ID), body) assert.Equal(t, http.StatusNotFound, w.Code) } func TestCaptainAssistantHandler_PlaygroundV2AppendsCurrentMessageOnce(t *testing.T) { provider := &captainPlaygroundFakeProvider{content: "Assistant response"} router, db := setupCaptainAssistantHandlerTestWithProvider(t, provider) account := seedCaptainAssistantAccount(t, db, "Captain Org") account.FeatureFlags = `{"captain_integration_v2":true}` require.NoError(t, db.Save(account).Error) assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{"model":"gpt-test","temperature":0.2}`), Status: model.AssistantStatusActive} require.NoError(t, db.Create(assistant).Error) body := map[string]any{ "message_content": "Hello assistant", "message_history": []map[string]any{ {"role": "user", "content": "Previous message"}, {"role": "assistant", "content": "Previous response", "agent_name": "billing_scenario"}, }, } w := captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/captain/assistants/%d/playground", account.ID, assistant.ID), body) assert.Equal(t, http.StatusOK, w.Code) var payload map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(t, "Assistant response", payload["response"]) assert.NotContains(t, payload, "content") require.Len(t, provider.lastRequest.Messages, 4) assert.Equal(t, "Previous message", provider.lastRequest.Messages[1].Content) assert.Equal(t, "Previous response", provider.lastRequest.Messages[2].Content) assert.Equal(t, "Hello assistant", provider.lastRequest.Messages[3].Content) body = map[string]any{ "message_content": "Hello assistant", "message_history": []map[string]any{{"role": "user", "content": "Hello assistant"}}, } w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/captain/assistants/%d/playground", account.ID, assistant.ID), body) assert.Equal(t, http.StatusOK, w.Code) require.Len(t, provider.lastRequest.Messages, 2) assert.Equal(t, "Hello assistant", provider.lastRequest.Messages[1].Content) } type captainPlaygroundFakeProvider struct { content string lastRequest llm.ChatRequest } func (p *captainPlaygroundFakeProvider) ChatCompletion(ctx context.Context, req llm.ChatRequest) (*llm.ChatResponse, error) { p.lastRequest = req return &llm.ChatResponse{Choices: []llm.ChatChoice{{Message: llm.ChatMessage{Role: "assistant", Content: p.content}}}}, nil } func (p *captainPlaygroundFakeProvider) CreateEmbedding(ctx context.Context, req llm.EmbeddingRequest) (*llm.EmbeddingResponse, error) { return &llm.EmbeddingResponse{}, nil } func (p *captainPlaygroundFakeProvider) ChatCompletionStream(ctx context.Context, req llm.ChatRequest, onChunk func(llm.StreamChunk) error) error { return nil }