feat: add feature to speak with the AI and create report from contexts

This commit is contained in:
2026-04-19 18:27:42 +02:00
parent eb1fb5ca78
commit 7ef93276e1
19 changed files with 656 additions and 33 deletions

View File

@ -10,7 +10,14 @@
"Bash(/home/anthony/go/bin/go build *)", "Bash(/home/anthony/go/bin/go build *)",
"Bash(npm install *)", "Bash(npm install *)",
"Bash(/home/anthony/.config/JetBrains/WebStorm2026.1/node/versions/24.14.1/bin/npm install *)", "Bash(/home/anthony/.config/JetBrains/WebStorm2026.1/node/versions/24.14.1/bin/npm install *)",
"Bash(npm run *)" "Bash(npm run *)",
"Bash(go build *)",
"Bash(npx tsc *)",
"Bash(node_modules/.bin/tsc --noEmit)",
"Bash(/usr/bin/node node_modules/.bin/tsc --noEmit)",
"Bash(fish -c \"which node\")",
"Read(//opt/**)",
"Bash(/home/anthony/.config/JetBrains/WebStorm2026.1/node/versions/24.14.1/bin/node node_modules/.bin/tsc --noEmit)"
] ]
} }
} }

View File

@ -6,6 +6,7 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"sync/atomic"
"time" "time"
"github.com/tradarr/backend/internal/crypto" "github.com/tradarr/backend/internal/crypto"
@ -26,12 +27,17 @@ Structure ton résumé ainsi :
type Pipeline struct { type Pipeline struct {
repo *models.Repository repo *models.Repository
enc *crypto.Encryptor enc *crypto.Encryptor
generating atomic.Bool
} }
func NewPipeline(repo *models.Repository, enc *crypto.Encryptor) *Pipeline { func NewPipeline(repo *models.Repository, enc *crypto.Encryptor) *Pipeline {
return &Pipeline{repo: repo, enc: enc} return &Pipeline{repo: repo, enc: enc}
} }
func (p *Pipeline) IsGenerating() bool {
return p.generating.Load()
}
func (p *Pipeline) BuildProvider(name, apiKey, endpoint string) (Provider, error) { func (p *Pipeline) BuildProvider(name, apiKey, endpoint string) (Provider, error) {
provider, err := p.repo.GetActiveAIProvider() provider, err := p.repo.GetActiveAIProvider()
if err != nil { if err != nil {
@ -45,6 +51,8 @@ func (p *Pipeline) BuildProvider(name, apiKey, endpoint string) (Provider, error
} }
func (p *Pipeline) GenerateForUser(ctx context.Context, userID string) (*models.Summary, error) { func (p *Pipeline) GenerateForUser(ctx context.Context, userID string) (*models.Summary, error) {
p.generating.Store(true)
defer p.generating.Store(false)
providerCfg, err := p.repo.GetActiveAIProvider() providerCfg, err := p.repo.GetActiveAIProvider()
if err != nil { if err != nil {
return nil, fmt.Errorf("get active provider: %w", err) return nil, fmt.Errorf("get active provider: %w", err)
@ -97,9 +105,10 @@ func (p *Pipeline) GenerateForUser(ctx context.Context, userID string) (*models.
// Passe 1 : filtrage par pertinence sur les titres si trop d'articles // Passe 1 : filtrage par pertinence sur les titres si trop d'articles
if len(articles) > maxArticles { if len(articles) > maxArticles {
fmt.Printf("pipeline: %d articles → filtering to %d via AI\n", len(articles), maxArticles) fmt.Printf("[pipeline] Passe 1 — filtrage : %d articles → sélection des %d plus pertinents…\n", len(articles), maxArticles)
t1 := time.Now()
articles = p.filterByRelevance(ctx, provider, symbols, articles, maxArticles) articles = p.filterByRelevance(ctx, provider, symbols, articles, maxArticles)
fmt.Printf("pipeline: %d articles retained after filtering\n", len(articles)) fmt.Printf("[pipeline] Passe 1 — terminée en %s : %d articles retenus\n", time.Since(t1).Round(time.Second), len(articles))
} }
systemPrompt, _ := p.repo.GetSetting("ai_system_prompt") systemPrompt, _ := p.repo.GetSetting("ai_system_prompt")
@ -108,11 +117,14 @@ func (p *Pipeline) GenerateForUser(ctx context.Context, userID string) (*models.
} }
// Passe 2 : résumé complet // Passe 2 : résumé complet
fmt.Printf("[pipeline] Passe 2 — résumé : génération sur %d articles…\n", len(articles))
t2 := time.Now()
prompt := buildPrompt(systemPrompt, symbols, articles) prompt := buildPrompt(systemPrompt, symbols, articles)
summary, err := provider.Summarize(ctx, prompt) summary, err := provider.Summarize(ctx, prompt)
if err != nil { if err != nil {
return nil, fmt.Errorf("AI summarize: %w", err) return nil, fmt.Errorf("AI summarize: %w", err)
} }
fmt.Printf("[pipeline] Passe 2 — terminée en %s\n", time.Since(t2).Round(time.Second))
return p.repo.CreateSummary(userID, summary, &providerCfg.ID) return p.repo.CreateSummary(userID, summary, &providerCfg.ID)
} }
@ -123,13 +135,13 @@ func (p *Pipeline) filterByRelevance(ctx context.Context, provider Provider, sym
prompt := buildFilterPrompt(symbols, articles, max) prompt := buildFilterPrompt(symbols, articles, max)
response, err := provider.Summarize(ctx, prompt) response, err := provider.Summarize(ctx, prompt)
if err != nil { if err != nil {
fmt.Printf("pipeline: filter AI call failed (%v), falling back to truncation\n", err) fmt.Printf("[pipeline] Passe 1 — échec (%v), repli sur troncature\n", err)
return articles[:max] return articles[:max]
} }
indices := parseIndexArray(response, len(articles)) indices := parseIndexArray(response, len(articles))
if len(indices) == 0 { if len(indices) == 0 {
fmt.Printf("pipeline: could not parse filter response, falling back to truncation\n") fmt.Printf("[pipeline] Passe 1 — réponse non parseable, repli sur troncature\n")
return articles[:max] return articles[:max]
} }
@ -201,6 +213,58 @@ func (p *Pipeline) GenerateForAll(ctx context.Context) error {
return nil return nil
} }
// GenerateReportAsync crée le rapport en DB (status=generating) et lance la génération en arrière-plan.
func (p *Pipeline) GenerateReportAsync(reportID, excerpt, question string, mgr *ReportManager) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
mgr.Register(reportID, cancel)
go func() {
defer cancel()
defer mgr.Remove(reportID)
answer, err := p.callProviderForReport(ctx, excerpt, question)
if err != nil {
if ctx.Err() != nil {
// annulé volontairement — le rapport est supprimé par le handler
return
}
_ = p.repo.UpdateReport(reportID, "error", "", err.Error())
return
}
_ = p.repo.UpdateReport(reportID, "done", answer, "")
}()
}
func (p *Pipeline) callProviderForReport(ctx context.Context, excerpt, question string) (string, error) {
providerCfg, err := p.repo.GetActiveAIProvider()
if err != nil {
return "", fmt.Errorf("get active provider: %w", err)
}
if providerCfg == nil {
return "", fmt.Errorf("no active AI provider configured")
}
apiKey := ""
if providerCfg.APIKeyEncrypted != "" {
apiKey, err = p.enc.Decrypt(providerCfg.APIKeyEncrypted)
if err != nil {
return "", fmt.Errorf("decrypt API key: %w", err)
}
}
provider, err := NewProvider(providerCfg.Name, apiKey, providerCfg.Model, providerCfg.Endpoint)
if err != nil {
return "", fmt.Errorf("build provider: %w", err)
}
prompt := fmt.Sprintf(
"Tu es un assistant financier expert. L'utilisateur a sélectionné les extraits suivants d'un résumé de marché :\n\n%s\n\nQuestion de l'utilisateur : %s\n\nRéponds en français, de façon précise et orientée trading.",
excerpt, question,
)
return provider.Summarize(ctx, prompt)
}
func buildPrompt(systemPrompt string, symbols []string, articles []models.Article) string { func buildPrompt(systemPrompt string, symbols []string, articles []models.Article) string {
var sb strings.Builder var sb strings.Builder
sb.WriteString(systemPrompt) sb.WriteString(systemPrompt)

View File

@ -0,0 +1,37 @@
package ai
import (
"context"
"sync"
)
// ReportManager tracks in-flight report goroutines so they can be cancelled.
type ReportManager struct {
mu sync.Mutex
cancels map[string]context.CancelFunc
}
func NewReportManager() *ReportManager {
return &ReportManager{cancels: make(map[string]context.CancelFunc)}
}
func (m *ReportManager) Register(id string, cancel context.CancelFunc) {
m.mu.Lock()
defer m.mu.Unlock()
m.cancels[id] = cancel
}
func (m *ReportManager) Cancel(id string) {
m.mu.Lock()
defer m.mu.Unlock()
if cancel, ok := m.cancels[id]; ok {
cancel()
delete(m.cancels, id)
}
}
func (m *ReportManager) Remove(id string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.cancels, id)
}

View File

@ -16,6 +16,7 @@ type Handler struct {
registry *scraper.Registry registry *scraper.Registry
pipeline *ai.Pipeline pipeline *ai.Pipeline
scheduler *scheduler.Scheduler scheduler *scheduler.Scheduler
reportManager *ai.ReportManager
} }
func New( func New(
@ -33,5 +34,6 @@ func New(
registry: registry, registry: registry,
pipeline: pipeline, pipeline: pipeline,
scheduler: sched, scheduler: sched,
reportManager: ai.NewReportManager(),
} }
} }

View File

@ -0,0 +1,84 @@
package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/httputil"
)
type reportRequest struct {
SummaryID string `json:"summary_id"`
Excerpts []string `json:"excerpts" binding:"required,min=1"`
Question string `json:"question" binding:"required"`
}
func (h *Handler) CreateReport(c *gin.Context) {
userID := c.GetString("userID")
var req reportRequest
if err := c.ShouldBindJSON(&req); err != nil {
httputil.BadRequest(c, err)
return
}
var summaryID *string
if req.SummaryID != "" {
summaryID = &req.SummaryID
}
// Joindre les extraits avec un séparateur visuel
excerpt := buildExcerptContext(req.Excerpts)
// Créer le rapport en DB avec status=generating, retourner immédiatement
report, err := h.repo.CreatePendingReport(userID, summaryID, excerpt, req.Question)
if err != nil {
httputil.InternalError(c, err)
return
}
// Lancer la génération en arrière-plan
h.pipeline.GenerateReportAsync(report.ID, excerpt, req.Question, h.reportManager)
c.JSON(http.StatusCreated, report)
}
func (h *Handler) ListReports(c *gin.Context) {
userID := c.GetString("userID")
reports, err := h.repo.ListReports(userID)
if err != nil {
httputil.InternalError(c, err)
return
}
httputil.OK(c, reports)
}
func (h *Handler) DeleteReport(c *gin.Context) {
userID := c.GetString("userID")
id := c.Param("id")
// Annuler la goroutine si elle tourne encore
h.reportManager.Cancel(id)
if err := h.repo.DeleteReport(id, userID); err != nil {
httputil.InternalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *Handler) GetGeneratingStatus(c *gin.Context) {
httputil.OK(c, gin.H{"generating": h.pipeline.IsGenerating()})
}
func buildExcerptContext(excerpts []string) string {
if len(excerpts) == 1 {
return excerpts[0]
}
var sb strings.Builder
for i, e := range excerpts {
if i > 0 {
sb.WriteString("\n\n---\n\n")
}
sb.WriteString(e)
}
return sb.String()
}

View File

@ -7,7 +7,11 @@ import (
) )
func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine { func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
r := gin.Default() r := gin.New()
r.Use(gin.Recovery())
r.Use(gin.LoggerWithConfig(gin.LoggerConfig{
SkipPaths: []string{"/api/summaries/status"},
}))
r.Use(func(c *gin.Context) { r.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Origin", "*")
@ -39,8 +43,13 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
authed.GET("/articles/:id", h.GetArticle) authed.GET("/articles/:id", h.GetArticle)
authed.GET("/summaries", h.ListSummaries) authed.GET("/summaries", h.ListSummaries)
authed.GET("/summaries/status", h.GetGeneratingStatus)
authed.POST("/summaries/generate", h.GenerateSummary) authed.POST("/summaries/generate", h.GenerateSummary)
authed.GET("/reports", h.ListReports)
authed.POST("/reports", h.CreateReport)
authed.DELETE("/reports/:id", h.DeleteReport)
// Admin // Admin
admin := authed.Group("/admin") admin := authed.Group("/admin")
admin.Use(auth.AdminOnly()) admin.Use(auth.AdminOnly())

View File

@ -0,0 +1 @@
DROP TABLE IF EXISTS reports;

View File

@ -0,0 +1,9 @@
CREATE TABLE reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
summary_id UUID REFERENCES summaries(id) ON DELETE SET NULL,
context_excerpt TEXT NOT NULL,
question TEXT NOT NULL,
answer TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

View File

@ -0,0 +1,4 @@
ALTER TABLE reports
DROP COLUMN IF EXISTS status,
DROP COLUMN IF EXISTS error_msg,
ALTER COLUMN answer DROP DEFAULT;

View File

@ -0,0 +1,4 @@
ALTER TABLE reports
ALTER COLUMN answer SET DEFAULT '',
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'done',
ADD COLUMN error_msg TEXT NOT NULL DEFAULT '';

View File

@ -104,3 +104,15 @@ type ScheduleSlot struct {
Hour int `json:"hour"` Hour int `json:"hour"`
Minute int `json:"minute"` Minute int `json:"minute"`
} }
type Report struct {
ID string `json:"id"`
UserID string `json:"user_id"`
SummaryID *string `json:"summary_id"`
ContextExcerpt string `json:"context_excerpt"`
Question string `json:"question"`
Answer string `json:"answer"`
Status string `json:"status"` // generating | done | error
ErrorMsg string `json:"error_msg"`
CreatedAt time.Time `json:"created_at"`
}

View File

@ -187,20 +187,28 @@ func (r *Repository) UpdateSource(id string, enabled bool) error {
// ── Articles ─────────────────────────────────────────────────────────────── // ── Articles ───────────────────────────────────────────────────────────────
func (r *Repository) UpsertArticle(sourceID, title, content, url string, publishedAt *time.Time) (*Article, error) { // InsertArticleIfNew insère l'article uniquement s'il n'existe pas déjà (par URL).
a := &Article{} // Retourne (article, true, nil) si inséré, (nil, false, nil) si déjà présent.
func (r *Repository) InsertArticleIfNew(sourceID, title, content, url string, publishedAt *time.Time) (*Article, bool, error) {
var pa sql.NullTime var pa sql.NullTime
if publishedAt != nil { if publishedAt != nil {
pa = sql.NullTime{Time: *publishedAt, Valid: true} pa = sql.NullTime{Time: *publishedAt, Valid: true}
} }
a := &Article{}
err := r.db.QueryRow(` err := r.db.QueryRow(`
INSERT INTO articles (source_id, title, content, url, published_at) INSERT INTO articles (source_id, title, content, url, published_at)
VALUES ($1, $2, $3, $4, $5) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (url) DO UPDATE SET title=EXCLUDED.title, content=EXCLUDED.content ON CONFLICT (url) DO NOTHING
RETURNING id, source_id, title, content, url, published_at, created_at`, RETURNING id, source_id, title, content, url, published_at, created_at`,
sourceID, title, content, url, pa, sourceID, title, content, url, pa,
).Scan(&a.ID, &a.SourceID, &a.Title, &a.Content, &a.URL, &a.PublishedAt, &a.CreatedAt) ).Scan(&a.ID, &a.SourceID, &a.Title, &a.Content, &a.URL, &a.PublishedAt, &a.CreatedAt)
return a, err if err == sql.ErrNoRows {
return nil, false, nil // déjà présent
}
if err != nil {
return nil, false, err
}
return a, true, nil
} }
func (r *Repository) AddArticleSymbol(articleID, symbol string) error { func (r *Repository) AddArticleSymbol(articleID, symbol string) error {
@ -260,7 +268,7 @@ func (r *Repository) GetRecentArticles(hours int) ([]Article, error) {
SELECT a.id, a.source_id, s.name, a.title, a.content, a.url, a.published_at, a.created_at SELECT a.id, a.source_id, s.name, a.title, a.content, a.url, a.published_at, a.created_at
FROM articles a FROM articles a
JOIN sources s ON s.id = a.source_id JOIN sources s ON s.id = a.source_id
WHERE a.created_at > NOW() - ($1 * INTERVAL '1 hour') WHERE COALESCE(a.published_at, a.created_at) > NOW() - ($1 * INTERVAL '1 hour')
ORDER BY a.published_at DESC NULLS LAST, a.created_at DESC`, hours) ORDER BY a.published_at DESC NULLS LAST, a.created_at DESC`, hours)
if err != nil { if err != nil {
return nil, err return nil, err
@ -581,3 +589,48 @@ func (r *Repository) ListSettings() ([]Setting, error) {
} }
return settings, nil return settings, nil
} }
// ── Reports ────────────────────────────────────────────────────────────────
func (r *Repository) CreatePendingReport(userID string, summaryID *string, excerpt, question string) (*Report, error) {
rep := &Report{}
err := r.db.QueryRow(`
INSERT INTO reports (user_id, summary_id, context_excerpt, question, answer, status)
VALUES ($1, $2, $3, $4, '', 'generating')
RETURNING id, user_id, summary_id, context_excerpt, question, answer, status, error_msg, created_at`,
userID, summaryID, excerpt, question,
).Scan(&rep.ID, &rep.UserID, &rep.SummaryID, &rep.ContextExcerpt, &rep.Question, &rep.Answer, &rep.Status, &rep.ErrorMsg, &rep.CreatedAt)
return rep, err
}
func (r *Repository) UpdateReport(id, status, answer, errorMsg string) error {
_, err := r.db.Exec(`
UPDATE reports SET status=$1, answer=$2, error_msg=$3 WHERE id=$4`,
status, answer, errorMsg, id)
return err
}
func (r *Repository) ListReports(userID string) ([]Report, error) {
rows, err := r.db.Query(`
SELECT id, user_id, summary_id, context_excerpt, question, answer, status, error_msg, created_at
FROM reports WHERE user_id=$1
ORDER BY created_at DESC`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var reports []Report
for rows.Next() {
var rep Report
if err := rows.Scan(&rep.ID, &rep.UserID, &rep.SummaryID, &rep.ContextExcerpt, &rep.Question, &rep.Answer, &rep.Status, &rep.ErrorMsg, &rep.CreatedAt); err != nil {
return nil, err
}
reports = append(reports, rep)
}
return reports, nil
}
func (r *Repository) DeleteReport(id, userID string) error {
_, err := r.db.Exec(`DELETE FROM reports WHERE id=$1 AND user_id=$2`, id, userID)
return err
}

View File

@ -72,11 +72,11 @@ func (r *Registry) Run(sourceID string) error {
return scrapeErr return scrapeErr
} }
// Persister les articles // Persister uniquement les nouveaux articles
count := 0 count := 0
for _, a := range articles { for _, a := range articles {
saved, err := r.repo.UpsertArticle(sourceID, a.Title, a.Content, a.URL, a.PublishedAt) saved, isNew, err := r.repo.InsertArticleIfNew(sourceID, a.Title, a.Content, a.URL, a.PublishedAt)
if err != nil { if err != nil || !isNew {
continue continue
} }
count++ count++

View File

@ -0,0 +1,20 @@
import { api } from './client'
export interface Report {
id: string
user_id: string
summary_id: string | null
context_excerpt: string
question: string
answer: string
status: 'generating' | 'done' | 'error'
error_msg: string
created_at: string
}
export const reportsApi = {
list: () => api.get<Report[]>('/reports'),
create: (data: { summary_id?: string; excerpts: string[]; question: string }) =>
api.post<Report>('/reports', data),
delete: (id: string) => api.delete<void>(`/reports/${id}`),
}

View File

@ -11,4 +11,5 @@ export interface Summary {
export const summariesApi = { export const summariesApi = {
list: (limit = 10) => api.get<Summary[]>(`/summaries?limit=${limit}`), list: (limit = 10) => api.get<Summary[]>(`/summaries?limit=${limit}`),
generate: () => api.post<Summary>('/summaries/generate'), generate: () => api.post<Summary>('/summaries/generate'),
status: () => api.get<{ generating: boolean }>('/summaries/status'),
} }

View File

@ -1,5 +1,5 @@
import { NavLink } from 'react-router-dom' import { NavLink } from 'react-router-dom'
import { LayoutDashboard, Newspaper, Star, Settings, Key, Cpu, Database, ClipboardList, Users, LogOut, TrendingUp, CalendarDays } from 'lucide-react' import { LayoutDashboard, Newspaper, Star, Settings, Key, Cpu, Database, ClipboardList, Users, LogOut, TrendingUp, CalendarDays, FileText } from 'lucide-react'
import { useAuth } from '@/lib/auth' import { useAuth } from '@/lib/auth'
import { cn } from '@/lib/cn' import { cn } from '@/lib/cn'
@ -7,6 +7,7 @@ const navItems = [
{ to: '/', icon: LayoutDashboard, label: 'Dashboard' }, { to: '/', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/feed', icon: Newspaper, label: 'Actualités' }, { to: '/feed', icon: Newspaper, label: 'Actualités' },
{ to: '/watchlist', icon: Star, label: 'Watchlist' }, { to: '/watchlist', icon: Star, label: 'Watchlist' },
{ to: '/reports', icon: FileText, label: 'Rapports' },
] ]
const adminItems = [ const adminItems = [

View File

@ -12,6 +12,7 @@ import { Jobs } from '@/pages/admin/Jobs'
import { AdminUsers } from '@/pages/admin/AdminUsers' import { AdminUsers } from '@/pages/admin/AdminUsers'
import { AdminSettings } from '@/pages/admin/AdminSettings' import { AdminSettings } from '@/pages/admin/AdminSettings'
import { Schedule } from '@/pages/admin/Schedule' import { Schedule } from '@/pages/admin/Schedule'
import { Reports } from '@/pages/Reports'
export const router = createBrowserRouter([ export const router = createBrowserRouter([
{ path: '/login', element: <Login /> }, { path: '/login', element: <Login /> },
@ -21,6 +22,7 @@ export const router = createBrowserRouter([
{ path: '/', element: <Dashboard /> }, { path: '/', element: <Dashboard /> },
{ path: '/feed', element: <Feed /> }, { path: '/feed', element: <Feed /> },
{ path: '/watchlist', element: <Watchlist /> }, { path: '/watchlist', element: <Watchlist /> },
{ path: '/reports', element: <Reports /> },
{ {
path: '/admin', path: '/admin',
element: <AdminLayout />, element: <AdminLayout />,

View File

@ -1,6 +1,7 @@
import { useState, useEffect } from 'react' import { useState, useEffect, useRef, useCallback } from 'react'
import { TrendingUp, Clock, Sparkles } from 'lucide-react' import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send } from 'lucide-react'
import { summariesApi, type Summary } from '@/api/summaries' import { summariesApi, type Summary } from '@/api/summaries'
import { reportsApi } from '@/api/reports'
import { assetsApi, type Asset } from '@/api/assets' import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@ -8,10 +9,127 @@ import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner' import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth' import { useAuth } from '@/lib/auth'
// ── Text-selection floating button ─────────────────────────────────────────
function useTextSelection(containerRef: React.RefObject<HTMLElement>) {
const [selection, setSelection] = useState<{ text: string; x: number; y: number } | null>(null)
useEffect(() => {
function onMouseUp() {
const sel = window.getSelection()
const text = sel?.toString().trim()
if (!text || !containerRef.current) { setSelection(null); return }
const range = sel!.getRangeAt(0)
const rect = range.getBoundingClientRect()
const containerRect = containerRef.current.getBoundingClientRect()
setSelection({
text,
x: rect.left - containerRect.left + rect.width / 2,
y: rect.top - containerRect.top - 8,
})
}
function onMouseDown(e: MouseEvent) {
if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
}
document.addEventListener('mouseup', onMouseUp)
document.addEventListener('mousedown', onMouseDown)
return () => {
document.removeEventListener('mouseup', onMouseUp)
document.removeEventListener('mousedown', onMouseDown)
}
}, [containerRef])
return selection
}
// ── Context panel (extraits + question) ────────────────────────────────────
function ContextPanel({
excerpts,
onRemove,
onClear,
onSubmit,
}: {
excerpts: string[]
onRemove: (i: number) => void
onClear: () => void
onSubmit: (question: string) => Promise<void>
}) {
const [question, setQuestion] = useState('')
const [submitting, setSubmitting] = useState(false)
const [submitted, setSubmitted] = useState(false)
async function submit() {
if (!question.trim() || submitting) return
setSubmitting(true)
try {
await onSubmit(question)
setSubmitted(true)
setQuestion('')
setTimeout(() => setSubmitted(false), 2000)
} finally {
setSubmitting(false)
}
}
return (
<div className="fixed bottom-4 right-4 z-40 w-96 max-h-[70vh] flex flex-col bg-card border rounded-xl shadow-2xl overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
<span className="text-sm font-semibold flex items-center gap-2">
<MessageSquarePlus className="h-4 w-4 text-primary" />
Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
</span>
<button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
Tout effacer
</button>
</div>
{/* Extraits */}
<div className="flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0">
{excerpts.map((e, i) => (
<div key={i} className="flex items-start gap-2 group">
<div className="flex-1 rounded bg-muted/60 px-2 py-1.5 text-xs text-muted-foreground italic line-clamp-3">
«&nbsp;{e}&nbsp;»
</div>
<button
onClick={() => onRemove(i)}
className="mt-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
{/* Question */}
<div className="border-t px-4 py-3 space-y-2">
<textarea
className="w-full rounded border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"
rows={2}
placeholder="Votre question…"
value={question}
onChange={e => setQuestion(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }}
/>
<Button size="sm" className="w-full" onClick={submit} disabled={!question.trim() || submitting || submitted}>
{submitting
? <><Loader2 className="h-3 w-3 animate-spin" /> Envoi</>
: submitted
? 'Envoyé !'
: <><Send className="h-3 w-3" /> Envoyer (Ctrl+Entrée)</>}
</Button>
</div>
</div>
)
}
// ── Summary content renderer ────────────────────────────────────────────────
function SummaryContent({ content }: { content: string }) { function SummaryContent({ content }: { content: string }) {
const lines = content.split('\n') const lines = content.split('\n')
return ( return (
<div className="space-y-2 text-sm leading-relaxed"> <div className="space-y-2 text-sm leading-relaxed select-text">
{lines.map((line, i) => { {lines.map((line, i) => {
if (line.startsWith('## ')) return <h2 key={i} className="text-base font-semibold mt-4 first:mt-0">{line.slice(3)}</h2> if (line.startsWith('## ')) return <h2 key={i} className="text-base font-semibold mt-4 first:mt-0">{line.slice(3)}</h2>
if (line.startsWith('### ')) return <h3 key={i} className="font-medium mt-3">{line.slice(4)}</h3> if (line.startsWith('### ')) return <h3 key={i} className="font-medium mt-3">{line.slice(4)}</h3>
@ -24,6 +142,8 @@ function SummaryContent({ content }: { content: string }) {
) )
} }
// ── Dashboard ───────────────────────────────────────────────────────────────
export function Dashboard() { export function Dashboard() {
const { user } = useAuth() const { user } = useAuth()
const [summaries, setSummaries] = useState<Summary[]>([]) const [summaries, setSummaries] = useState<Summary[]>([])
@ -31,9 +151,26 @@ export function Dashboard() {
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [generating, setGenerating] = useState(false) const [generating, setGenerating] = useState(false)
const [current, setCurrent] = useState<Summary | null>(null) const [current, setCurrent] = useState<Summary | null>(null)
const [excerpts, setExcerpts] = useState<string[]>([])
const summaryRef = useRef<HTMLDivElement>(null)
const textSel = useTextSelection(summaryRef as React.RefObject<HTMLElement>)
useEffect(() => { load() }, []) useEffect(() => { load() }, [])
// Poll generating status every 5s
useEffect(() => {
const interval = setInterval(async () => {
try {
const status = await summariesApi.status()
const wasGenerating = generating
setGenerating(status.generating)
if (wasGenerating && !status.generating) load()
} catch { /* ignore */ }
}, 5000)
return () => clearInterval(interval)
}, [generating])
async function load() { async function load() {
setLoading(true) setLoading(true)
try { try {
@ -55,8 +192,31 @@ export function Dashboard() {
} finally { setGenerating(false) } } finally { setGenerating(false) }
} }
const addExcerpt = useCallback(() => {
if (!textSel) return
setExcerpts(prev => [...prev, textSel.text])
window.getSelection()?.removeAllRanges()
}, [textSel])
async function submitQuestion(question: string) {
await reportsApi.create({
summary_id: current?.id,
excerpts,
question,
})
setExcerpts([])
}
return ( return (
<div className="p-4 md:p-6 space-y-6"> <div className="p-4 md:p-6 space-y-6">
{/* Generating banner */}
{generating && (
<div className="flex items-center gap-3 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
<Loader2 className="h-4 w-4 animate-spin shrink-0" />
Génération d'un résumé IA en cours — cela peut prendre plusieurs minutes…
</div>
)}
{/* Header */} {/* Header */}
<div className="flex flex-wrap items-start justify-between gap-4"> <div className="flex flex-wrap items-start justify-between gap-4">
<div> <div>
@ -105,7 +265,23 @@ export function Dashboard() {
</div> </div>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div ref={summaryRef} className="relative">
<SummaryContent content={current.content} /> <SummaryContent content={current.content} />
{textSel && (
<button
data-context-action
onClick={addExcerpt}
className="absolute z-10 flex items-center gap-1 rounded-full bg-primary text-primary-foreground text-xs px-2 py-1 shadow-lg hover:bg-primary/90 transition-colors"
style={{ left: textSel.x, top: textSel.y, transform: 'translate(-50%, -100%)' }}
>
<Plus className="h-3 w-3" />
Ajouter au contexte
</button>
)}
</div>
<p className="text-xs text-muted-foreground mt-4 italic">
Sélectionnez du texte pour l'ajouter au contexte, puis posez une question dans le panneau qui apparaît.
</p>
</CardContent> </CardContent>
</Card> </Card>
) : ( ) : (
@ -141,6 +317,16 @@ export function Dashboard() {
</div> </div>
)} )}
</div> </div>
{/* Panneau contexte flottant */}
{excerpts.length > 0 && (
<ContextPanel
excerpts={excerpts}
onRemove={i => setExcerpts(prev => prev.filter((_, idx) => idx !== i))}
onClear={() => setExcerpts([])}
onSubmit={submitQuestion}
/>
)}
</div> </div>
) )
} }

View File

@ -0,0 +1,127 @@
import { useState, useEffect, useCallback } from 'react'
import { Trash2, FileText, Clock, Loader2, XCircle, AlertCircle } from 'lucide-react'
import { reportsApi, type Report } from '@/api/reports'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import { Badge } from '@/components/ui/badge'
function StatusBadge({ status }: { status: Report['status'] }) {
if (status === 'generating') return (
<Badge variant="secondary" className="gap-1 text-xs">
<Loader2 className="h-3 w-3 animate-spin" /> En cours
</Badge>
)
if (status === 'error') return (
<Badge variant="destructive" className="gap-1 text-xs">
<AlertCircle className="h-3 w-3" /> Erreur
</Badge>
)
return null
}
export function Reports() {
const [reports, setReports] = useState<Report[]>([])
const [loading, setLoading] = useState(true)
const load = useCallback(async () => {
try { setReports((await reportsApi.list()) ?? []) }
finally { setLoading(false) }
}, [])
useEffect(() => { load() }, [load])
// Poll toutes les 3s tant qu'il y a des rapports en cours
useEffect(() => {
const hasGenerating = reports.some(r => r.status === 'generating')
if (!hasGenerating) return
const interval = setInterval(load, 3000)
return () => clearInterval(interval)
}, [reports, load])
async function remove(id: string) {
await reportsApi.delete(id)
setReports(prev => prev.filter(r => r.id !== id))
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
return (
<div className="p-4 md:p-6 space-y-6">
<div>
<h1 className="text-2xl font-bold">Rapports IA</h1>
<p className="text-muted-foreground text-sm">
Vos questions posées sur des extraits de résumés, avec les réponses de l'IA.
</p>
</div>
{reports.length === 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 text-center text-muted-foreground">
<FileText className="h-8 w-8 mx-auto mb-3 opacity-50" />
<p>Aucun rapport enregistré</p>
<p className="text-xs mt-1">Sélectionnez du texte dans un résumé et posez une question à l'IA.</p>
</CardContent>
</Card>
) : (
<div className="space-y-4">
{reports.map(r => (
<Card key={r.id} className={r.status === 'generating' ? 'border-primary/30' : ''}>
<CardContent className="pt-4 pb-4 space-y-3">
{/* Meta */}
<div className="flex items-start justify-between gap-4">
<div className="flex items-center gap-2 flex-wrap">
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Clock className="h-3 w-3" />
{new Date(r.created_at).toLocaleString('fr-FR')}
</div>
<StatusBadge status={r.status} />
</div>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive shrink-0"
onClick={() => remove(r.id)}
title={r.status === 'generating' ? 'Annuler' : 'Supprimer'}
>
{r.status === 'generating'
? <XCircle className="h-3 w-3" />
: <Trash2 className="h-3 w-3" />}
</Button>
</div>
{/* Extraits de contexte */}
{r.context_excerpt.split('\n\n---\n\n').map((excerpt, i) => (
<div key={i} className="rounded bg-muted/60 px-3 py-2 text-xs text-muted-foreground italic">
«&nbsp;{excerpt}&nbsp;»
</div>
))}
{/* Question */}
<p className="text-sm font-medium">{r.question}</p>
{/* Réponse */}
{r.status === 'generating' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
L'IA génère la réponse…
</div>
)}
{r.status === 'done' && (
<div className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed border-t pt-3">
{r.answer}
</div>
)}
{r.status === 'error' && (
<div className="text-sm text-destructive border-t pt-3">
Erreur : {r.error_msg || 'Une erreur est survenue lors de la génération.'}
</div>
)}
</CardContent>
</Card>
))}
</div>
)}
</div>
)
}