feat(ai): add personal summary models and retire Q&A

Add an admin-managed provider model catalog with per-user summary selection, migration backfill, and generation snapshots. Retire report creation and messaging while preserving owner-scoped history.

Refs #15 #16

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 20:45:21 +01:00
parent ac17d27f51
commit 989996fbd6
53 changed files with 2228 additions and 979 deletions

View File

@ -0,0 +1,135 @@
package api_test
import (
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"strings"
"testing"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
type selectionFeed struct{ calls int }
func (*selectionFeed) Name() string { return "test-only" }
func (f *selectionFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
f.calls++
return []scraper.Article{{Title: "private-candidate-title", Content: "private-candidate-body", URL: "https://fixture.invalid/private"}}, nil
}
type selectionLaya struct{ calls int }
func (r *selectionLaya) Rank(_ context.Context, _ string, _ []models.UserAsset, c []generation.Candidate) ([]generation.Candidate, error) {
r.calls++
return c, nil
}
type selectionProvider struct{ model string }
func (*selectionProvider) Name() string { return "test-summary" }
func (*selectionProvider) ListModels(context.Context) ([]string, error) { return nil, nil }
func (p *selectionProvider) Summarize(context.Context, string, ai.GenOptions) (string, error) {
return "Safe summary from " + p.model, nil
}
func TestManualGenerationResolvesAccountModelsAndSnapshotsWithoutGlobalFallbackPostgres(t *testing.T) {
db := ticket14DB(t)
for _, q := range []string{
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,language TEXT DEFAULT 'en',ranking_mode TEXT DEFAULT 'title',summary_model_id UUID,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,api_key_encrypted TEXT DEFAULT '',model TEXT,endpoint TEXT,is_active BOOLEAN DEFAULT false)`,
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID REFERENCES ai_providers(id),model TEXT,enabled BOOLEAN DEFAULT true)`,
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
`INSERT INTO settings VALUES('summary_max_articles','50'),('ai_role_summary_provider','legacy-must-not-resolve'),('ai_role_summary_model','legacy-must-not-resolve'),('ai_role_filter_provider','legacy-must-not-resolve')`,
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,created_at TIMESTAMPTZ DEFAULT NOW(),article_limit INT,source_key TEXT)`,
`INSERT INTO sources VALUES('00000000-0000-0000-0000-000000001599','Yahoo Finance','stocktwits',true,NOW(),20,'yahoo_finance')`,
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID,content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ,summary_model_id UUID,provider_name TEXT,model_name TEXT)`,
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID,outcome JSONB,created_at TIMESTAMPTZ)`,
`INSERT INTO ai_providers VALUES('` + ticket14ProviderA + `','openai','','legacy-default-a','private-endpoint-a',false),('` + ticket14ProviderB + `','ollama','','legacy-default-b','private-endpoint-b',true)`,
`INSERT INTO ai_provider_models VALUES('` + ticket14ModelA + `','` + ticket14ProviderA + `','account-model-a',true),('` + ticket14ModelB + `','` + ticket14ProviderB + `','account-model-b',true)`,
`INSERT INTO users(id,email,password_hash,role,summary_model_id) VALUES('` + ticket14UserA + `','a@example.test','hash','user','` + ticket14ModelA + `'),('` + ticket14UserB + `','b@example.test','hash','user','` + ticket14ModelB + `'),('` + ticket14Admin + `','none@example.test','hash','user',NULL)`,
} {
if _, err := db.Exec(q); err != nil {
t.Fatal(err)
}
}
repo := models.NewRepository(db)
feed := &selectionFeed{}
laya := &selectionLaya{}
resolved := []models.ResolvedSummaryModel{}
factory := func(m models.ResolvedSummaryModel) (ai.Provider, error) {
resolved = append(resolved, m)
return &selectionProvider{model: m.Model}, nil
}
pipeline := ai.NewPipeline(repo, nil)
feeds := map[string]scraper.Scraper{models.SourceYahooFinance: feed}
useCase := pipeline.NewGenerationUseCaseWithFactory(feeds, laya, factory)
h := handlers.New(repo, &config.Config{}, nil, nil, pipeline, nil)
h.SetGenerationUseCase(useCase)
const secret = "selection-test-only"
router := api.SetupRouter(h, secret)
generate := func(user string, status int) generation.Result {
t.Helper()
token, _ := auth.GenerateToken(user, "fixture@example.test", "user", secret)
request := httptest.NewRequest("POST", "/api/summaries/generate", strings.NewReader(`{"user_id":"not-the-owner"}`))
request.Header.Set("Authorization", "Bearer "+token)
w := httptest.NewRecorder()
router.ServeHTTP(w, request)
if w.Code != status {
t.Fatalf("status=%d want=%d body=%s", w.Code, status, w.Body.String())
}
var response struct{ Data generation.Result }
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
return response.Data
}
for _, tc := range []struct{ user, provider, model string }{{ticket14UserA, "openai", "account-model-a"}, {ticket14UserB, "ollama", "account-model-b"}} {
result := generate(tc.user, 201)
if result.Summary == nil || result.Summary.ProviderName == nil || *result.Summary.ProviderName != tc.provider || result.Summary.ModelName == nil || *result.Summary.ModelName != tc.model {
t.Fatalf("wrong actual snapshot: %+v", result.Summary)
}
var provider, model string
if err := db.QueryRow(`SELECT provider_name,model_name FROM summaries WHERE user_id=$1`, tc.user).Scan(&provider, &model); err != nil || provider != tc.provider || model != tc.model {
t.Fatalf("stored snapshot=(%s,%s) err=%v", provider, model, err)
}
}
for _, user := range []string{ticket14Admin, ticket14UserB} {
if user == ticket14UserB {
if _, err := db.Exec(`UPDATE ai_provider_models SET enabled=false WHERE id=$1`, ticket14ModelB); err != nil {
t.Fatal(err)
}
}
result := generate(user, 502)
if result.Summary != nil || result.Outcome.FailureCode != "summary_model_unavailable" {
t.Fatalf("unsafe missing/disabled selection: %+v", result)
}
}
if feed.calls != 2 || laya.calls != 2 || len(resolved) != 2 {
t.Fatalf("preflight failed: scrape=%d laya=%d resolve=%d", feed.calls, laya.calls, len(resolved))
}
// A configured model cannot replace a missing dedicated Laya engine.
h.SetGenerationUseCase(pipeline.NewGenerationUseCaseWithFactory(feeds, nil, factory))
result := generate(ticket14UserA, 502)
if result.Outcome.FailureCode != "laya_unavailable" || feed.calls != 2 || laya.calls != 2 {
t.Fatal("missing Laya reached collection or fell back", result)
}
var count int
if err := db.QueryRow(`SELECT count(*) FROM summaries`).Scan(&count); err != nil || count != 2 {
t.Fatal("failed preflight wrote summaries", count, err)
}
for _, entry := range resolved {
if entry.Model == "legacy-must-not-resolve" {
t.Fatal(fmt.Sprint("legacy role resolved"))
}
}
}