204 lines
7.7 KiB
Go
204 lines
7.7 KiB
Go
package v1
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"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/require"
|
|
"gorm.io/datatypes"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
type captainPreferenceFixture struct {
|
|
db *gorm.DB
|
|
router *gin.Engine
|
|
account *model.Account
|
|
}
|
|
|
|
func newCaptainPreferenceFixture(t *testing.T) *captainPreferenceFixture {
|
|
t.Helper()
|
|
gin.SetMode(gin.TestMode)
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
|
require.NoError(t, err)
|
|
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.CaptainPreference{}, &model.InstallationConfig{}))
|
|
|
|
account := &model.Account{Name: "Captain Preferences", Active: true, CaptainModels: datatypes.JSON(`{}`), CaptainFeatures: datatypes.JSON(`{}`)}
|
|
require.NoError(t, db.Create(account).Error)
|
|
|
|
prefRepo := repository.NewCaptainPreferenceRepo(db)
|
|
accountRepo := repository.NewAccountRepo(db)
|
|
installationConfigRepo := repository.NewInstallationConfigRepo(db)
|
|
manager := llm.NewProviderManager()
|
|
copilotConfigService := service.NewCopilotConfigService(installationConfigRepo, manager)
|
|
preferenceService := service.NewCaptainPreferenceService(prefRepo, accountRepo)
|
|
preferenceService.SetCopilotConfigService(copilotConfigService)
|
|
handler := NewCaptainPreferenceHandler(preferenceService)
|
|
router := gin.New()
|
|
router.GET("/api/v1/accounts/:account_id/captain/preferences", handler.Get)
|
|
router.PUT("/api/v1/accounts/:account_id/captain/preferences", func(c *gin.Context) {
|
|
c.Set("role", "administrator")
|
|
handler.Update(c)
|
|
})
|
|
router.PUT("/api/v1/accounts/:account_id/captain/preferences/as-agent", func(c *gin.Context) {
|
|
c.Set("role", "agent")
|
|
handler.Update(c)
|
|
})
|
|
|
|
t.Cleanup(func() {
|
|
sqlDB, dbErr := db.DB()
|
|
require.NoError(t, dbErr)
|
|
require.NoError(t, sqlDB.Close())
|
|
})
|
|
return &captainPreferenceFixture{db: db, router: router, account: account}
|
|
}
|
|
|
|
func (f *captainPreferenceFixture) path(suffix string) string {
|
|
return "/api/v1/accounts/" + strconv.FormatUint(uint64(f.account.ID), 10) + "/captain/preferences" + suffix
|
|
}
|
|
|
|
func (f *captainPreferenceFixture) request(method, path string, body any) *httptest.ResponseRecorder {
|
|
var raw []byte
|
|
if body != nil {
|
|
raw, _ = json.Marshal(body)
|
|
}
|
|
recorder := httptest.NewRecorder()
|
|
req, _ := http.NewRequest(method, path, bytes.NewReader(raw))
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
f.router.ServeHTTP(recorder, req)
|
|
return recorder
|
|
}
|
|
|
|
func decodeCaptainPreferencePayload(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
|
|
t.Helper()
|
|
var payload map[string]any
|
|
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
|
|
return payload
|
|
}
|
|
|
|
func TestCaptainPreferencesGetReturnsRawChatwootConfig(t *testing.T) {
|
|
f := newCaptainPreferenceFixture(t)
|
|
|
|
w := f.request(http.MethodGet, f.path(""), nil)
|
|
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
|
payload := decodeCaptainPreferencePayload(t, w)
|
|
require.Nil(t, payload["success"])
|
|
require.Contains(t, payload, "providers")
|
|
require.Contains(t, payload, "models")
|
|
require.Contains(t, payload, "features")
|
|
require.Contains(t, payload, "provider_config")
|
|
|
|
features := payload["features"].(map[string]any)
|
|
editor := features["editor"].(map[string]any)
|
|
require.Equal(t, true, editor["enabled"])
|
|
require.Equal(t, "gpt-4o-mini", editor["default"])
|
|
require.Equal(t, "gpt-4o-mini", editor["selected"])
|
|
require.NotEmpty(t, editor["models"].([]any))
|
|
}
|
|
|
|
func TestCaptainPreferencesCannotUpdatePlatformProviderConfiguration(t *testing.T) {
|
|
f := newCaptainPreferenceFixture(t)
|
|
|
|
w := f.request(http.MethodPut, f.path(""), map[string]any{
|
|
"provider_config": map[string]any{
|
|
"provider": "openai_compatible",
|
|
"base_url": "https://llm.example.com/v1",
|
|
"model": "example-model",
|
|
"api_key": "secret-key-value",
|
|
},
|
|
})
|
|
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
|
payload := decodeCaptainPreferencePayload(t, w)
|
|
providerConfig := payload["provider_config"].(map[string]any)
|
|
require.Equal(t, false, providerConfig["configured"])
|
|
require.NotContains(t, w.Body.String(), "secret-key-value")
|
|
}
|
|
|
|
func TestCaptainPreferencesUpdateMergesAccountModelsAndFeatures(t *testing.T) {
|
|
f := newCaptainPreferenceFixture(t)
|
|
require.NoError(t, f.db.Model(&model.Account{}).Where("id = ?", f.account.ID).Updates(map[string]any{
|
|
"captain_models": datatypes.JSON(`{"editor":"gpt-4.1-mini","assistant":"gpt-5.1"}`),
|
|
"captain_features": datatypes.JSON(`{"editor":true,"assistant":false}`),
|
|
}).Error)
|
|
|
|
w := f.request(http.MethodPut, f.path(""), map[string]any{
|
|
"captain_models": map[string]any{"editor": "gpt-4.1"},
|
|
"captain_features": map[string]any{"editor": false},
|
|
})
|
|
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
|
payload := decodeCaptainPreferencePayload(t, w)
|
|
features := payload["features"].(map[string]any)
|
|
require.Equal(t, "gpt-4.1", features["editor"].(map[string]any)["selected"])
|
|
require.Equal(t, false, features["editor"].(map[string]any)["enabled"])
|
|
require.Equal(t, "gpt-5.1", features["assistant"].(map[string]any)["selected"])
|
|
require.Equal(t, false, features["assistant"].(map[string]any)["enabled"])
|
|
|
|
var account model.Account
|
|
require.NoError(t, f.db.First(&account, f.account.ID).Error)
|
|
var models map[string]string
|
|
var featureValues map[string]bool
|
|
require.NoError(t, json.Unmarshal(account.CaptainModels, &models))
|
|
require.NoError(t, json.Unmarshal(account.CaptainFeatures, &featureValues))
|
|
require.Equal(t, "gpt-4.1", models["editor"])
|
|
require.Equal(t, "gpt-5.1", models["assistant"])
|
|
require.False(t, featureValues["editor"])
|
|
require.False(t, featureValues["assistant"])
|
|
}
|
|
|
|
func TestCaptainPreferencesUpdateRejectsNonAdminAndAcceptsCustomModel(t *testing.T) {
|
|
f := newCaptainPreferenceFixture(t)
|
|
|
|
w := f.request(http.MethodPut, f.path("/as-agent"), map[string]any{"captain_models": map[string]any{"editor": "gpt-4.1"}})
|
|
require.Equal(t, http.StatusUnauthorized, w.Code, w.Body.String())
|
|
|
|
w = f.request(http.MethodPut, f.path(""), map[string]any{"captain_models": map[string]any{"editor": "not-a-model"}})
|
|
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
|
features := decodeCaptainPreferencePayload(t, w)["features"].(map[string]any)
|
|
require.Equal(t, "not-a-model", features["editor"].(map[string]any)["selected"])
|
|
}
|
|
|
|
func TestCaptainPreferencesInvalidAccountID(t *testing.T) {
|
|
f := newCaptainPreferenceFixture(t)
|
|
|
|
w := f.request(http.MethodGet, "/api/v1/accounts/abc/captain/preferences", nil)
|
|
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
|
|
}
|
|
|
|
func TestCaptainPreferencesUpdateAndClearBehavior(t *testing.T) {
|
|
f := newCaptainPreferenceFixture(t)
|
|
|
|
w := f.request(http.MethodPut, f.path(""), map[string]any{
|
|
"behavior": map[string]any{
|
|
"tone": "friendly",
|
|
"language": "auto",
|
|
"max_response_length": 750,
|
|
"custom_prompt_suffix": "Use short steps",
|
|
"auto_label_enabled": true,
|
|
"auto_follow_up_enabled": true,
|
|
"auto_reply_enabled": false,
|
|
},
|
|
})
|
|
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
|
behavior := decodeCaptainPreferencePayload(t, w)["behavior"].(map[string]any)
|
|
require.Equal(t, "Use short steps", behavior["custom_prompt_suffix"])
|
|
|
|
w = f.request(http.MethodPut, f.path(""), map[string]any{
|
|
"behavior": map[string]any{"custom_prompt_suffix": ""},
|
|
})
|
|
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
|
behavior = decodeCaptainPreferencePayload(t, w)["behavior"].(map[string]any)
|
|
require.Equal(t, "", behavior["custom_prompt_suffix"])
|
|
}
|