feat: chatbot
This commit is contained in:
@@ -84,7 +84,7 @@ export default function ChatWidget() {
|
||||
refresh_context: pendingRefresh,
|
||||
})
|
||||
setPendingRefresh(false)
|
||||
setMessages(prev => [...prev, { role: 'assistant', content: res.reply }])
|
||||
setMessages(prev => [...prev, { role: 'assistant', content: res.reply, trade_proposal: res.trade_proposal }])
|
||||
} catch (e: any) {
|
||||
const msg = e?.response?.data?.detail ?? 'Erreur — vérifie la clé API OpenAI dans Configuration.'
|
||||
setMessages(prev => [...prev, { role: 'assistant', content: `⚠️ ${msg}` }])
|
||||
@@ -164,13 +164,18 @@ export default function ChatWidget() {
|
||||
</div>
|
||||
)}
|
||||
{messages.map((m, i) => (
|
||||
<div key={i} className={clsx('flex', m.role === 'user' ? 'justify-end' : 'justify-start')}>
|
||||
<div key={i} className={clsx('flex flex-col', m.role === 'user' ? 'items-end' : 'items-start')}>
|
||||
<div className={clsx(
|
||||
'max-w-[85%] rounded-lg px-3 py-2 text-xs whitespace-pre-wrap leading-relaxed',
|
||||
m.role === 'user' ? 'bg-blue-600 text-white' : 'bg-dark-700/80 border border-slate-700/40 text-slate-200',
|
||||
)}>
|
||||
{m.content}
|
||||
</div>
|
||||
{m.trade_proposal && (
|
||||
<div className="mt-1 text-[10px] px-2 py-1 rounded bg-emerald-900/30 border border-emerald-700/40 text-emerald-400">
|
||||
✅ Idée ajoutée → Trade Ideas ({m.trade_proposal.title})
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{isPending && (
|
||||
|
||||
@@ -2,11 +2,11 @@ import { useState, useMemo, useEffect, Fragment } from 'react'
|
||||
import {
|
||||
useAllPatterns, useLastScores, useScorePatterns, useAiStatus,
|
||||
usePortfolioPositions, useTradeMtm, useRiskProfiles, useMacroRegime, useAddPosition,
|
||||
useConfig,
|
||||
useConfig, useAiTradeProposals, useConfirmAiTradeProposal, useRejectAiTradeProposal,
|
||||
} from '../hooks/useApi'
|
||||
import {
|
||||
Target, Brain, Plus, RefreshCw, ChevronDown, ChevronUp, CheckCircle2,
|
||||
LayoutGrid, List, Terminal,
|
||||
LayoutGrid, List, Terminal, Bot, Check, X as XIcon,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { format } from 'date-fns'
|
||||
@@ -683,6 +683,72 @@ export function TradeRow({ item, onAdd, macroInfo, addedInfo, profiles, rank }:
|
||||
)
|
||||
}
|
||||
|
||||
// ── AI-proposed trades — awaiting explicit user confirmation ──────────────────
|
||||
// Created by the chat widget's propose_trade tool call. Deliberately kept
|
||||
// separate from TradeCard/TradeItem (those are derived from scored patterns —
|
||||
// grafting an AI-sourced item onto that shape would be fragile).
|
||||
function AiProposedTradesSection() {
|
||||
const { data: proposals } = useAiTradeProposals('pending')
|
||||
const { mutate: confirmProposal, isPending: confirming } = useConfirmAiTradeProposal()
|
||||
const { mutate: rejectProposal, isPending: rejecting } = useRejectAiTradeProposal()
|
||||
const [pendingId, setPendingId] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
if (!proposals || proposals.length === 0) return null
|
||||
|
||||
const handleConfirm = (id: string) => {
|
||||
setPendingId(id); setError(null)
|
||||
confirmProposal(id, {
|
||||
onError: (e: any) => setError(e?.response?.data?.detail ?? 'Erreur lors de la confirmation.'),
|
||||
onSettled: () => setPendingId(null),
|
||||
})
|
||||
}
|
||||
const handleReject = (id: string) => {
|
||||
setPendingId(id)
|
||||
rejectProposal(id, { onSettled: () => setPendingId(null) })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card border-blue-500/30">
|
||||
<h3 className="section-title flex items-center gap-1.5 mb-3">
|
||||
<Bot className="w-3.5 h-3.5 text-blue-400" /> Idées proposées par l'IA
|
||||
<span className="text-slate-600 font-normal">({proposals.length} en attente)</span>
|
||||
</h3>
|
||||
{error && <div className="text-xs text-red-400 mb-2">{error}</div>}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{proposals.map(p => (
|
||||
<div key={p.id} className="rounded-lg border border-slate-700/40 bg-dark-900/60 p-3 space-y-2">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-white">{p.title}</div>
|
||||
<div className="text-[11px] text-slate-500">{p.underlying} · {p.strategy} · {p.capital_invested.toLocaleString('fr-FR')} €</div>
|
||||
</div>
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-900/40 text-blue-300 shrink-0">🤖 IA</span>
|
||||
</div>
|
||||
{p.rationale && <div className="text-[11px] text-slate-400 leading-snug">{p.rationale}</div>}
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<button
|
||||
onClick={() => handleConfirm(p.id)}
|
||||
disabled={confirming && pendingId === p.id}
|
||||
className="flex-1 flex items-center justify-center gap-1 text-xs px-2 py-1.5 rounded bg-emerald-600/20 text-emerald-400 hover:bg-emerald-600/30 disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<Check className="w-3 h-3" /> Confirmer
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleReject(p.id)}
|
||||
disabled={rejecting && pendingId === p.id}
|
||||
className="flex-1 flex items-center justify-center gap-1 text-xs px-2 py-1.5 rounded bg-slate-700/40 text-slate-400 hover:bg-slate-700/60 disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<XIcon className="w-3 h-3" /> Rejeter
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Self-contained Trade Ideas Tab ────────────────────────────────────────────
|
||||
export function TradeIdeasTab() {
|
||||
const { data: allPatternsData } = useAllPatterns()
|
||||
@@ -862,6 +928,8 @@ export function TradeIdeasTab() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<AiProposedTradesSection />
|
||||
|
||||
{/* Toolbar */}
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
|
||||
@@ -1429,7 +1429,7 @@ export function useScoreText() {
|
||||
|
||||
// ── AI Chat widget — free-form, read-only, context-aware conversation ────────
|
||||
|
||||
export interface ChatMessage { role: 'user' | 'assistant'; content: string; created_at?: string }
|
||||
export interface ChatMessage { role: 'user' | 'assistant'; content: string; created_at?: string; trade_proposal?: TradeProposalRef | null }
|
||||
|
||||
export const useChatContextBlocks = () =>
|
||||
useQuery({
|
||||
@@ -1446,13 +1446,61 @@ export const useChatHistory = (sessionId: string) =>
|
||||
staleTime: Infinity,
|
||||
})
|
||||
|
||||
export interface TradeProposalRef { id: string; title?: string; underlying?: string; strategy?: string }
|
||||
|
||||
export const useSendChatMessage = () =>
|
||||
useMutation({
|
||||
mutationFn: (body: { session_id: string; message: string; enabled_blocks?: string[]; refresh_context?: boolean }) =>
|
||||
api.post('/ai-chat/', body).then(r => r.data as { reply: string; blocks_included: string[] }),
|
||||
api.post('/ai-chat/', body).then(r => r.data as { reply: string; blocks_included: string[]; trade_proposal: TradeProposalRef | null }),
|
||||
})
|
||||
|
||||
export const useClearChatSession = () =>
|
||||
useMutation({
|
||||
mutationFn: (sessionId: string) => api.post('/ai-chat/clear', { session_id: sessionId }).then(r => r.data),
|
||||
})
|
||||
|
||||
// ── AI Chat widget — trade proposals (pending confirmation) ──────────────────
|
||||
|
||||
export interface AiTradeProposal {
|
||||
id: string
|
||||
session_id: string
|
||||
created_at: string
|
||||
status: 'pending' | 'confirmed' | 'rejected'
|
||||
title: string
|
||||
underlying: string
|
||||
strategy: string
|
||||
asset_class: string
|
||||
expiry_days: number
|
||||
capital_invested: number
|
||||
legs: Array<{ strike: number; option_type: string; quantity: number; position: string }>
|
||||
geo_trigger: string
|
||||
rationale: string
|
||||
portfolio_id?: string | null
|
||||
}
|
||||
|
||||
export const useAiTradeProposals = (status: string = 'pending') =>
|
||||
useQuery({
|
||||
queryKey: ['ai-trade-proposals', status],
|
||||
queryFn: () => api.get('/ai-chat/trade-proposals', { params: { status } }).then(r => r.data.proposals as AiTradeProposal[]),
|
||||
refetchInterval: 30000,
|
||||
})
|
||||
|
||||
export const useConfirmAiTradeProposal = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (proposalId: string) => api.post(`/ai-chat/trade-proposals/${proposalId}/confirm`).then(r => r.data),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['ai-trade-proposals'] })
|
||||
qc.invalidateQueries({ queryKey: ['portfolio'] })
|
||||
qc.invalidateQueries({ queryKey: ['portfolio-summary'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useRejectAiTradeProposal = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (proposalId: string) => api.post(`/ai-chat/trade-proposals/${proposalId}/reject`).then(r => r.data),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['ai-trade-proposals'] }),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@ import clsx from 'clsx'
|
||||
// ── Types ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface SignalParam {
|
||||
type: 'int' | 'float' | 'pairs'
|
||||
type: 'int' | 'float' | 'pairs' | 'select'
|
||||
label: string
|
||||
default: number | number[][]
|
||||
default: number | number[][] | string
|
||||
min?: number
|
||||
max?: number
|
||||
options?: string[]
|
||||
@@ -263,6 +263,20 @@ function SignalToggle({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (p.type === 'select') {
|
||||
return (
|
||||
<div key={key} className="flex items-center gap-3">
|
||||
<label className="text-xs text-slate-400 w-28 shrink-0">{p.label}</label>
|
||||
<select
|
||||
value={value[key] ?? p.default}
|
||||
onChange={e => update(key, e.target.value)}
|
||||
className="w-32 bg-dark-900 border border-slate-700/40 rounded px-2 py-1 text-xs text-white"
|
||||
>
|
||||
{(p.options ?? []).map(o => <option key={o} value={o}>{o}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div key={key} className="flex items-center gap-3">
|
||||
<label className="text-xs text-slate-400 w-28 shrink-0">{p.label}</label>
|
||||
|
||||
Reference in New Issue
Block a user