Naufal Arhab commited on
Commit
b9d2e2b
·
1 Parent(s): fe8dffc

Feat: add dedicated Tanya AI (AI Terminal) page with shared pair watchlist, zero-refresh chat persistence, and quick prompts

Browse files
frontend/src/App.tsx CHANGED
@@ -1,6 +1,11 @@
 
1
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
2
  import { Dashboard } from './pages/Dashboard';
 
 
3
  import { ToastProvider } from './components/ui/Toast';
 
 
4
 
5
  const queryClient = new QueryClient({
6
  defaultOptions: {
@@ -11,11 +16,56 @@ const queryClient = new QueryClient({
11
  },
12
  });
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  export default function App() {
15
  return (
16
  <QueryClientProvider client={queryClient}>
17
  <ToastProvider>
18
- <Dashboard />
19
  </ToastProvider>
20
  </QueryClientProvider>
21
  );
 
1
+ import { useState } from 'react';
2
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
3
  import { Dashboard } from './pages/Dashboard';
4
+ import { AITerminal } from './pages/AITerminal';
5
+ import { Header } from './components/layout/Header';
6
  import { ToastProvider } from './components/ui/Toast';
7
+ import { useWebSocket } from './hooks/useWebSocket';
8
+ import { usePairs } from './hooks/usePairs';
9
 
10
  const queryClient = new QueryClient({
11
  defaultOptions: {
 
16
  },
17
  });
18
 
19
+ function MainApp() {
20
+ const [activeTab, setActiveTab] = useState<'signals' | 'ai'>('signals');
21
+ const [aiSelectedSymbol, setAiSelectedSymbol] = useState<string>('BTCUSDT');
22
+ const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false);
23
+
24
+ const { status: wsStatus, lastUpdated } = useWebSocket();
25
+ const { data: pairs = [] } = usePairs();
26
+ const activePairCount = pairs.filter((p) => p.is_active).length;
27
+
28
+ const handleNavigateToAI = (symbol: string) => {
29
+ setAiSelectedSymbol(symbol);
30
+ setActiveTab('ai');
31
+ };
32
+
33
+ return (
34
+ <div className="flex flex-col h-screen bg-bg-primary overflow-hidden">
35
+ <Header
36
+ wsStatus={wsStatus}
37
+ lastUpdated={lastUpdated}
38
+ activePairCount={activePairCount}
39
+ activeTab={activeTab}
40
+ onTabChange={setActiveTab}
41
+ onOpenMobileDrawer={() => setIsMobileDrawerOpen(true)}
42
+ />
43
+
44
+ {/* View 1: Live Sinyal (Dashboard) */}
45
+ <div className={activeTab === 'signals' ? 'flex flex-1 overflow-hidden' : 'hidden'}>
46
+ <Dashboard
47
+ onNavigateToAI={handleNavigateToAI}
48
+ isMobileDrawerOpen={isMobileDrawerOpen}
49
+ setIsMobileDrawerOpen={setIsMobileDrawerOpen}
50
+ />
51
+ </div>
52
+
53
+ {/* View 2: Tanya AI (AITerminal) */}
54
+ <div className={activeTab === 'ai' ? 'flex flex-1 overflow-hidden' : 'hidden'}>
55
+ <AITerminal
56
+ initialSymbol={aiSelectedSymbol}
57
+ onSelectSymbol={setAiSelectedSymbol}
58
+ />
59
+ </div>
60
+ </div>
61
+ );
62
+ }
63
+
64
  export default function App() {
65
  return (
66
  <QueryClientProvider client={queryClient}>
67
  <ToastProvider>
68
+ <MainApp />
69
  </ToastProvider>
70
  </QueryClientProvider>
71
  );
frontend/src/components/layout/Header.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import { useState, lazy, Suspense } from 'react';
2
- import { Zap, Wifi, RefreshCw, Clock, Bot, Settings, Menu } from 'lucide-react';
3
  import type { WSStatus } from '../../hooks/useWebSocket';
4
  import { useAISettings } from '../../hooks/useAISettings';
5
 
@@ -13,6 +13,8 @@ interface HeaderProps {
13
  lastUpdated: Date | null;
14
  onOpenMobileDrawer?: () => void;
15
  activePairCount?: number;
 
 
16
  }
17
 
18
  function WSIndicator({ status }: { status: WSStatus }) {
@@ -71,7 +73,14 @@ function formatTime(date: Date): string {
71
  });
72
  }
73
 
74
- export function Header({ wsStatus, lastUpdated, onOpenMobileDrawer, activePairCount = 0 }: HeaderProps) {
 
 
 
 
 
 
 
75
  const [isAISettingsOpen, setIsAISettingsOpen] = useState(false);
76
  const { settings, isConfigured } = useAISettings();
77
 
@@ -93,8 +102,8 @@ export function Header({ wsStatus, lastUpdated, onOpenMobileDrawer, activePairCo
93
  <header className="h-14 flex items-center justify-between px-3 sm:px-5 border-b border-border bg-bg-card shrink-0 gap-2">
94
  {/* Left: Mobile Menu + Logo */}
95
  <div className="flex items-center gap-2 sm:gap-2.5">
96
- {/* Mobile Pairs Drawer Button */}
97
- {onOpenMobileDrawer && (
98
  <button
99
  type="button"
100
  onClick={onOpenMobileDrawer}
@@ -113,16 +122,48 @@ export function Header({ wsStatus, lastUpdated, onOpenMobileDrawer, activePairCo
113
  <div className="w-8 h-8 rounded-lg bg-accent-blue/20 border border-accent-blue/30 flex items-center justify-center shrink-0">
114
  <Zap size={16} className="text-accent-blue" />
115
  </div>
116
- <div>
117
  <h1 className="text-sm font-bold text-text-primary font-mono tracking-tight leading-none">
118
  PerpsAI
119
  </h1>
120
  <p className="text-[9px] sm:text-[10px] text-text-muted leading-none mt-0.5">
121
- Signal Dashboard
122
  </p>
123
  </div>
124
  </div>
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  {/* Right side */}
127
  <div className="flex items-center gap-1.5 sm:gap-3">
128
  {/* Universal AI Settings Trigger (Mobile-Optimized) */}
 
1
  import { useState, lazy, Suspense } from 'react';
2
+ import { Zap, Wifi, RefreshCw, Clock, Bot, Settings, Menu, Activity } from 'lucide-react';
3
  import type { WSStatus } from '../../hooks/useWebSocket';
4
  import { useAISettings } from '../../hooks/useAISettings';
5
 
 
13
  lastUpdated: Date | null;
14
  onOpenMobileDrawer?: () => void;
15
  activePairCount?: number;
16
+ activeTab?: 'signals' | 'ai';
17
+ onTabChange?: (tab: 'signals' | 'ai') => void;
18
  }
19
 
20
  function WSIndicator({ status }: { status: WSStatus }) {
 
73
  });
74
  }
75
 
76
+ export function Header({
77
+ wsStatus,
78
+ lastUpdated,
79
+ onOpenMobileDrawer,
80
+ activePairCount = 0,
81
+ activeTab = 'signals',
82
+ onTabChange,
83
+ }: HeaderProps) {
84
  const [isAISettingsOpen, setIsAISettingsOpen] = useState(false);
85
  const { settings, isConfigured } = useAISettings();
86
 
 
102
  <header className="h-14 flex items-center justify-between px-3 sm:px-5 border-b border-border bg-bg-card shrink-0 gap-2">
103
  {/* Left: Mobile Menu + Logo */}
104
  <div className="flex items-center gap-2 sm:gap-2.5">
105
+ {/* Mobile Pairs Drawer Button (Only shown on Live Signals tab) */}
106
+ {onOpenMobileDrawer && activeTab === 'signals' && (
107
  <button
108
  type="button"
109
  onClick={onOpenMobileDrawer}
 
122
  <div className="w-8 h-8 rounded-lg bg-accent-blue/20 border border-accent-blue/30 flex items-center justify-center shrink-0">
123
  <Zap size={16} className="text-accent-blue" />
124
  </div>
125
+ <div className="hidden xs:block">
126
  <h1 className="text-sm font-bold text-text-primary font-mono tracking-tight leading-none">
127
  PerpsAI
128
  </h1>
129
  <p className="text-[9px] sm:text-[10px] text-text-muted leading-none mt-0.5">
130
+ Signal & AI Terminal
131
  </p>
132
  </div>
133
  </div>
134
 
135
+ {/* Center: Main View Navigation Switcher */}
136
+ {onTabChange && (
137
+ <div className="flex items-center bg-bg-elevated/90 p-1 rounded-xl border border-border shrink-0 shadow-inner">
138
+ <button
139
+ type="button"
140
+ onClick={() => onTabChange('signals')}
141
+ className={`flex items-center gap-1.5 px-2.5 sm:px-3.5 py-1 sm:py-1.5 rounded-lg text-xs font-semibold transition-all ${
142
+ activeTab === 'signals'
143
+ ? 'bg-accent-blue text-white shadow-sm shadow-accent-blue/30'
144
+ : 'text-text-secondary hover:text-text-primary'
145
+ }`}
146
+ >
147
+ <Activity size={13} />
148
+ <span className="hidden xs:inline">Live Sinyal</span>
149
+ <span className="xs:hidden">Sinyal</span>
150
+ </button>
151
+ <button
152
+ type="button"
153
+ onClick={() => onTabChange('ai')}
154
+ className={`flex items-center gap-1.5 px-2.5 sm:px-3.5 py-1 sm:py-1.5 rounded-lg text-xs font-semibold transition-all ${
155
+ activeTab === 'ai'
156
+ ? 'bg-purple-600 text-white shadow-sm shadow-purple-600/30'
157
+ : 'text-text-secondary hover:text-purple-300'
158
+ }`}
159
+ >
160
+ <Bot size={13} />
161
+ <span className="hidden xs:inline">Tanya AI</span>
162
+ <span className="xs:hidden">AI</span>
163
+ </button>
164
+ </div>
165
+ )}
166
+
167
  {/* Right side */}
168
  <div className="flex items-center gap-1.5 sm:gap-3">
169
  {/* Universal AI Settings Trigger (Mobile-Optimized) */}
frontend/src/components/signals/SignalCard.tsx CHANGED
@@ -17,6 +17,7 @@ const AIAnalysisPanel = lazy(() =>
17
 
18
  interface SignalCardProps {
19
  signal: Signal;
 
20
  }
21
 
22
  function formatTimeAgo(dateStr: string): string {
@@ -43,7 +44,7 @@ const pulseClass: Record<string, string> = {
43
  NEUTRAL: '',
44
  };
45
 
46
- function SignalCardComponent({ signal }: SignalCardProps) {
47
  const [expanded, setExpanded] = useState(false);
48
  const [copied, setCopied] = useState(false);
49
  const [showAIPanel, setShowAIPanel] = useState(false);
@@ -204,16 +205,18 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`;
204
 
205
  <div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
206
  <button
207
- onClick={() => setShowAIPanel((v) => !v)}
208
- className={`px-2.5 py-1 sm:py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all shadow-sm active:scale-95 cursor-pointer border ${
209
- showAIPanel
210
- ? 'bg-purple-600 text-white border-purple-400 shadow-purple-500/20'
211
- : 'bg-gradient-to-r from-purple-500/20 to-blue-500/20 hover:from-purple-500/30 hover:to-blue-500/30 border-purple-500/40 hover:border-purple-400 text-purple-300 hover:text-white'
212
- }`}
213
- title={showAIPanel ? 'Tutup Panel Analisa AI' : 'Buka Analisa AI Terpisah di Halaman Ini'}
 
 
214
  >
215
- <Sparkles size={11} className={showAIPanel ? '' : 'text-purple-400 animate-pulse'} />
216
- <span>{showAIPanel ? 'Tutup AI' : 'Tanya AI'}</span>
217
  </button>
218
  <Button
219
  variant="ghost"
@@ -299,6 +302,7 @@ export const SignalCard = memo(SignalCardComponent, (prevProps, nextProps) => {
299
  prevProps.signal.direction === nextProps.signal.direction &&
300
  prevProps.signal.score === nextProps.signal.score &&
301
  prevProps.signal.quick_verdict === nextProps.signal.quick_verdict &&
302
- prevProps.signal.action === nextProps.signal.action
 
303
  );
304
  });
 
17
 
18
  interface SignalCardProps {
19
  signal: Signal;
20
+ onNavigateToAI?: (symbol: string) => void;
21
  }
22
 
23
  function formatTimeAgo(dateStr: string): string {
 
44
  NEUTRAL: '',
45
  };
46
 
47
+ function SignalCardComponent({ signal, onNavigateToAI }: SignalCardProps) {
48
  const [expanded, setExpanded] = useState(false);
49
  const [copied, setCopied] = useState(false);
50
  const [showAIPanel, setShowAIPanel] = useState(false);
 
205
 
206
  <div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
207
  <button
208
+ onClick={() => {
209
+ if (onNavigateToAI) {
210
+ onNavigateToAI(signal.symbol);
211
+ } else {
212
+ setShowAIPanel((v) => !v);
213
+ }
214
+ }}
215
+ className="px-2.5 py-1 sm:py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all shadow-sm active:scale-95 cursor-pointer border bg-gradient-to-r from-purple-500/20 to-blue-500/20 hover:from-purple-500/30 hover:to-blue-500/30 border-purple-500/40 hover:border-purple-400 text-purple-300 hover:text-white"
216
+ title="Buka Halaman Tanya AI Khusus untuk Pair Ini"
217
  >
218
+ <Sparkles size={11} className="text-purple-400 animate-pulse" />
219
+ <span>Tanya AI</span>
220
  </button>
221
  <Button
222
  variant="ghost"
 
302
  prevProps.signal.direction === nextProps.signal.direction &&
303
  prevProps.signal.score === nextProps.signal.score &&
304
  prevProps.signal.quick_verdict === nextProps.signal.quick_verdict &&
305
+ prevProps.signal.action === nextProps.signal.action &&
306
+ prevProps.onNavigateToAI === nextProps.onNavigateToAI
307
  );
308
  });
frontend/src/pages/AITerminal.tsx ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useMemo, useRef, useEffect, lazy, Suspense } from 'react';
2
+ import {
3
+ Sparkles,
4
+ Send,
5
+ RefreshCw,
6
+ Copy,
7
+ Check,
8
+ ChevronDown,
9
+ ChevronUp,
10
+ Bot,
11
+ Activity,
12
+ Zap,
13
+ Settings,
14
+ AlertCircle,
15
+ Search,
16
+ Flame,
17
+ ArrowUpRight,
18
+ ArrowDownRight,
19
+ Trash2,
20
+ } from 'lucide-react';
21
+ import { usePairs } from '../hooks/usePairs';
22
+ import { useSignals } from '../hooks/useSignals';
23
+ import { useAISettings } from '../hooks/useAISettings';
24
+ import { useToast } from '../components/ui/Toast';
25
+ import { aiApi } from '../api/ai';
26
+ import { Button } from '../components/ui/Button';
27
+ import type { AIAnalysisResponse } from '../types';
28
+
29
+ // Lazy-load settings modal
30
+ const GlobalAISettingsModal = lazy(() =>
31
+ import('../components/ui/GlobalAISettingsModal').then((m) => ({ default: m.GlobalAISettingsModal }))
32
+ );
33
+
34
+ interface ChatMessage {
35
+ id: string;
36
+ role: 'user' | 'assistant';
37
+ content: string;
38
+ timestamp: string;
39
+ bias?: string;
40
+ model?: string;
41
+ isCached?: boolean;
42
+ cacheAgeSeconds?: number;
43
+ dataSnapshot?: AIAnalysisResponse['data_snapshot'];
44
+ }
45
+
46
+ interface ChatSession {
47
+ messages: ChatMessage[];
48
+ isLoading: boolean;
49
+ error: string | null;
50
+ }
51
+
52
+ interface AITerminalProps {
53
+ initialSymbol?: string;
54
+ onSelectSymbol?: (symbol: string) => void;
55
+ }
56
+
57
+ const QUICK_PROMPTS = [
58
+ { label: '⚡ Setup Scalp 15m', prompt: 'Berikan analisa scalping timeframe 15m, apakah ada momentum masuk saat ini dan di level berapa entry amannya?' },
59
+ { label: '🧲 Cek Likuidasi & Trap', prompt: 'Analisa kolam likuidasi (magnet harga) dan apakah ada jebakan leverage trap antara Spot vs Futures CVD?' },
60
+ { label: '🛡️ Validasi Fake Breakout', prompt: 'Periksa apakah ada tanda-tanda manipulasi harga, fake pump/dump, atau wick sweep pada pair ini?' },
61
+ { label: '📋 Rencana Trading Lengkap', prompt: 'Buatkan rencana trading institusional: Entry Zone terkonfirmasi, Stop Loss ketat, Take Profit 1 & 2, serta kondisi pembatalan setup.' },
62
+ ];
63
+
64
+ function biasBadgeColor(bias?: string): string {
65
+ if (!bias) return 'bg-gray-500/20 text-gray-300 border-gray-500/30';
66
+ const b = bias.toUpperCase();
67
+ if (b.includes('STRONG LONG') || b.includes('STRONG BUY')) {
68
+ return 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40';
69
+ }
70
+ if (b.includes('LONG')) {
71
+ return 'bg-signal-long/20 text-signal-long border-signal-long/30';
72
+ }
73
+ if (b.includes('STRONG SHORT') || b.includes('STRONG SELL')) {
74
+ return 'bg-rose-500/20 text-rose-300 border-rose-500/40';
75
+ }
76
+ if (b.includes('SHORT')) {
77
+ return 'bg-signal-short/20 text-signal-short border-signal-short/30';
78
+ }
79
+ return 'bg-amber-500/20 text-amber-300 border-amber-500/30';
80
+ }
81
+
82
+ export function AITerminal({ initialSymbol = 'BTCUSDT' }: AITerminalProps) {
83
+ const { data: pairs = [], isLoading: pairsLoading } = usePairs();
84
+ const { data: signals = [] } = useSignals();
85
+ const { settings, isConfigured } = useAISettings();
86
+ const { toast } = useToast();
87
+
88
+ const activePairs = useMemo(() => pairs.filter((p) => p.is_active), [pairs]);
89
+
90
+ // Determine current active symbol
91
+ const [selectedSymbol, setSelectedSymbol] = useState<string>(() => {
92
+ if (initialSymbol && pairs.some((p) => p.symbol === initialSymbol)) {
93
+ return initialSymbol;
94
+ }
95
+ return activePairs[0]?.symbol || 'BTCUSDT';
96
+ });
97
+
98
+ // Keep selectedSymbol synced if initialSymbol changes
99
+ useEffect(() => {
100
+ if (initialSymbol && initialSymbol !== selectedSymbol) {
101
+ setSelectedSymbol(initialSymbol);
102
+ }
103
+ }, [initialSymbol]);
104
+
105
+ // Filter & Search in Pair List
106
+ const [searchQuery, setSearchQuery] = useState('');
107
+ const [filterMode, setFilterMode] = useState<'ALL' | 'HOT' | 'LONG' | 'SHORT'>('ALL');
108
+
109
+ // Multi-session chat storage per symbol (100% persistent across tab switching & zero refresh flicker)
110
+ const [sessions, setSessions] = useState<Record<string, ChatSession>>({});
111
+ const [inputPrompt, setInputPrompt] = useState('');
112
+ const [isSettingsOpen, setIsSettingsOpen] = useState(false);
113
+ const [copiedId, setCopiedId] = useState<string | null>(null);
114
+ const [expandedSnapshots, setExpandedSnapshots] = useState<Record<string, boolean>>({});
115
+
116
+ const chatEndRef = useRef<HTMLDivElement | null>(null);
117
+
118
+ // Active signal & market stats for the current symbol
119
+ const activeSignal = useMemo(
120
+ () => signals.find((s) => s.symbol === selectedSymbol),
121
+ [signals, selectedSymbol]
122
+ );
123
+
124
+ const signalMap = useMemo(() => new Map(signals.map((s) => [s.symbol, s])), [signals]);
125
+
126
+ // Filtered pairs list for the left sidebar
127
+ const filteredPairs = useMemo(() => {
128
+ return activePairs.filter((p) => {
129
+ const matchSearch =
130
+ p.symbol.toLowerCase().includes(searchQuery.toLowerCase().trim()) ||
131
+ p.display_name.toLowerCase().includes(searchQuery.toLowerCase().trim());
132
+ if (!matchSearch) return false;
133
+
134
+ const sig = signalMap.get(p.symbol);
135
+ if (filterMode === 'HOT') return (sig?.conviction ?? 0) >= 4;
136
+ if (filterMode === 'LONG') return sig?.direction === 'LONG';
137
+ if (filterMode === 'SHORT') return sig?.direction === 'SHORT';
138
+ return true;
139
+ });
140
+ }, [activePairs, searchQuery, filterMode, signalMap]);
141
+
142
+ const currentSession: ChatSession = sessions[selectedSymbol] || {
143
+ messages: [],
144
+ isLoading: false,
145
+ error: null,
146
+ };
147
+
148
+ // Scroll to bottom when messages update
149
+ useEffect(() => {
150
+ chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
151
+ }, [currentSession.messages.length, currentSession.isLoading]);
152
+
153
+ // Send message / Run analysis
154
+ const handleSendMessage = async (customText?: string, forceRefresh = false) => {
155
+ const questionText = (customText !== undefined ? customText : inputPrompt).trim();
156
+ if (!questionText && currentSession.messages.length > 0 && !forceRefresh) return;
157
+
158
+ if (!isConfigured) {
159
+ setIsSettingsOpen(true);
160
+ toast('Silakan masukkan API Key AI Anda terlebih dahulu', 'error');
161
+ return;
162
+ }
163
+
164
+ const userMessageId = `user-${Date.now()}`;
165
+ const userMsg: ChatMessage | null = questionText
166
+ ? {
167
+ id: userMessageId,
168
+ role: 'user',
169
+ content: questionText,
170
+ timestamp: new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
171
+ }
172
+ : null;
173
+
174
+ // Update state to show loading and user message immediately
175
+ setSessions((prev) => {
176
+ const current = prev[selectedSymbol] || { messages: [], isLoading: false, error: null };
177
+ return {
178
+ ...prev,
179
+ [selectedSymbol]: {
180
+ ...current,
181
+ messages: userMsg ? [...current.messages, userMsg] : current.messages,
182
+ isLoading: true,
183
+ error: null,
184
+ },
185
+ };
186
+ });
187
+
188
+ if (!customText) {
189
+ setInputPrompt('');
190
+ }
191
+
192
+ try {
193
+ const res = await aiApi.analyze({
194
+ symbol: selectedSymbol,
195
+ provider: settings.provider,
196
+ model: settings.model,
197
+ api_key: settings.api_key,
198
+ base_url: settings.base_url,
199
+ question: questionText || undefined,
200
+ force_refresh: forceRefresh,
201
+ });
202
+
203
+ const assistantMsg: ChatMessage = {
204
+ id: `ai-${Date.now()}`,
205
+ role: 'assistant',
206
+ content: res.analysis,
207
+ timestamp: new Date().toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }),
208
+ bias: res.bias,
209
+ model: res.model,
210
+ isCached: res.is_cached,
211
+ cacheAgeSeconds: res.cache_age_seconds,
212
+ dataSnapshot: res.data_snapshot,
213
+ };
214
+
215
+ setSessions((prev) => {
216
+ const current = prev[selectedSymbol] || { messages: [], isLoading: false, error: null };
217
+ return {
218
+ ...prev,
219
+ [selectedSymbol]: {
220
+ ...current,
221
+ messages: [...current.messages, assistantMsg],
222
+ isLoading: false,
223
+ error: null,
224
+ },
225
+ };
226
+ });
227
+ } catch (err: any) {
228
+ const errorDetail = err?.response?.data?.detail || err?.message || 'Gagal menghubungi server AI';
229
+ setSessions((prev) => {
230
+ const current = prev[selectedSymbol] || { messages: [], isLoading: false, error: null };
231
+ return {
232
+ ...prev,
233
+ [selectedSymbol]: {
234
+ ...current,
235
+ isLoading: false,
236
+ error: errorDetail,
237
+ },
238
+ };
239
+ });
240
+ toast(errorDetail, 'error');
241
+ }
242
+ };
243
+
244
+ const handleClearSession = () => {
245
+ setSessions((prev) => ({
246
+ ...prev,
247
+ [selectedSymbol]: { messages: [], isLoading: false, error: null },
248
+ }));
249
+ toast(`Riwayat tanya jawab untuk ${selectedSymbol} dibersihkan`, 'success');
250
+ };
251
+
252
+ const handleCopyText = (text: string, id: string) => {
253
+ navigator.clipboard.writeText(text);
254
+ setCopiedId(id);
255
+ toast('Teks analisa berhasil disalin ke clipboard', 'success');
256
+ setTimeout(() => setCopiedId(null), 2000);
257
+ };
258
+
259
+ const toggleSnapshot = (msgId: string) => {
260
+ setExpandedSnapshots((prev) => ({ ...prev, [msgId]: !prev[msgId] }));
261
+ };
262
+
263
+ // Format AI text to clean readability
264
+ const renderFormattedAnalysis = (content: string) => {
265
+ return (
266
+ <div className="space-y-3 leading-relaxed text-xs sm:text-sm font-sans text-text-primary whitespace-pre-line">
267
+ {content.split('\n\n').map((paragraph, idx) => {
268
+ if (paragraph.startsWith('### ')) {
269
+ return (
270
+ <h4 key={idx} className="font-bold text-xs sm:text-sm text-purple-300 pt-2 pb-1 border-b border-border/40 font-mono flex items-center gap-1.5">
271
+ {paragraph.replace('### ', '')}
272
+ </h4>
273
+ );
274
+ }
275
+ if (paragraph.startsWith('- **') || paragraph.startsWith('• **')) {
276
+ return (
277
+ <div key={idx} className="space-y-1.5 pl-2">
278
+ {paragraph.split('\n').map((line, lIdx) => (
279
+ <p key={lIdx} className="text-text-primary">
280
+ {line}
281
+ </p>
282
+ ))}
283
+ </div>
284
+ );
285
+ }
286
+ return <p key={idx}>{paragraph}</p>;
287
+ })}
288
+ </div>
289
+ );
290
+ };
291
+
292
+ return (
293
+ <div className="flex flex-1 h-[calc(100vh-3.5rem)] overflow-hidden bg-bg-primary">
294
+ {/* ── Left Sidebar: Pair Selection (Desktop) ────────────────────────── */}
295
+ <aside className="hidden md:flex w-64 lg:w-72 flex-col border-r border-border bg-bg-card shrink-0 select-none">
296
+ {/* Header & Search */}
297
+ <div className="p-3 border-b border-border space-y-2">
298
+ <div className="flex items-center justify-between">
299
+ <span className="text-xs font-bold text-text-secondary uppercase tracking-wider flex items-center gap-1.5">
300
+ <Bot size={14} className="text-purple-400" />
301
+ Pilih Pair Analisa
302
+ </span>
303
+ <span className="text-[10px] font-mono text-purple-400 bg-purple-500/10 px-1.5 py-0.5 rounded border border-purple-500/20">
304
+ {activePairs.length} Pair
305
+ </span>
306
+ </div>
307
+
308
+ <div className="relative">
309
+ <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted" />
310
+ <input
311
+ type="text"
312
+ value={searchQuery}
313
+ onChange={(e) => setSearchQuery(e.target.value)}
314
+ placeholder="Cari pair (e.g. BTC, SOL)..."
315
+ className="w-full bg-bg-elevated border border-border rounded-lg pl-8 pr-2.5 py-1.5 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500/50"
316
+ />
317
+ </div>
318
+
319
+ {/* Quick Filters */}
320
+ <div className="flex items-center gap-1 overflow-x-auto no-scrollbar pt-0.5">
321
+ <button
322
+ onClick={() => setFilterMode('ALL')}
323
+ className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 ${
324
+ filterMode === 'ALL'
325
+ ? 'bg-purple-600 text-white'
326
+ : 'bg-bg-elevated text-text-secondary hover:text-text-primary'
327
+ }`}
328
+ >
329
+ Semua
330
+ </button>
331
+ <button
332
+ onClick={() => setFilterMode('HOT')}
333
+ className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${
334
+ filterMode === 'HOT'
335
+ ? 'bg-amber-500/20 text-amber-300 border border-amber-500/40'
336
+ : 'bg-bg-elevated text-text-secondary hover:text-amber-300'
337
+ }`}
338
+ >
339
+ <Flame size={10} />
340
+ Hot ≥4
341
+ </button>
342
+ <button
343
+ onClick={() => setFilterMode('LONG')}
344
+ className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${
345
+ filterMode === 'LONG'
346
+ ? 'bg-signal-long/20 text-signal-long border border-signal-long/40'
347
+ : 'bg-bg-elevated text-text-secondary hover:text-signal-long'
348
+ }`}
349
+ >
350
+ <ArrowUpRight size={10} />
351
+ Long
352
+ </button>
353
+ <button
354
+ onClick={() => setFilterMode('SHORT')}
355
+ className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all shrink-0 flex items-center gap-1 ${
356
+ filterMode === 'SHORT'
357
+ ? 'bg-signal-short/20 text-signal-short border border-signal-short/40'
358
+ : 'bg-bg-elevated text-text-secondary hover:text-signal-short'
359
+ }`}
360
+ >
361
+ <ArrowDownRight size={10} />
362
+ Short
363
+ </button>
364
+ </div>
365
+ </div>
366
+
367
+ {/* Pair List */}
368
+ <div className="flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1">
369
+ {pairsLoading && (
370
+ <div className="p-4 text-center text-xs text-text-muted">Memuat daftar pair...</div>
371
+ )}
372
+
373
+ {!pairsLoading && filteredPairs.length === 0 && (
374
+ <div className="p-4 text-center text-xs text-text-muted">Tidak ada pair yang cocok</div>
375
+ )}
376
+
377
+ {filteredPairs.map((pair) => {
378
+ const sig = signalMap.get(pair.symbol);
379
+ const isSelected = pair.symbol === selectedSymbol;
380
+ const messageCount = sessions[pair.symbol]?.messages?.length || 0;
381
+
382
+ const dirColor =
383
+ sig?.direction === 'LONG'
384
+ ? 'text-signal-long bg-signal-long/10 border-signal-long/30'
385
+ : sig?.direction === 'SHORT'
386
+ ? 'text-signal-short bg-signal-short/10 border-signal-short/30'
387
+ : 'text-text-muted bg-bg-elevated border-border';
388
+
389
+ return (
390
+ <button
391
+ key={pair.symbol}
392
+ type="button"
393
+ onClick={() => setSelectedSymbol(pair.symbol)}
394
+ className={`w-full flex items-center justify-between p-2 rounded-xl text-xs transition-all text-left ${
395
+ isSelected
396
+ ? 'bg-purple-600/15 border border-purple-500/50 shadow-sm text-text-primary'
397
+ : 'hover:bg-bg-elevated/70 border border-transparent text-text-secondary hover:text-text-primary'
398
+ }`}
399
+ >
400
+ <div className="flex items-center gap-2 min-w-0">
401
+ <span className={`w-2 h-2 rounded-full shrink-0 ${
402
+ sig?.direction === 'LONG'
403
+ ? 'bg-signal-long shadow-sm shadow-signal-long/50'
404
+ : sig?.direction === 'SHORT'
405
+ ? 'bg-signal-short shadow-sm shadow-signal-short/50'
406
+ : 'bg-gray-500'
407
+ }`} />
408
+ <div className="truncate">
409
+ <p className={`font-mono font-bold truncate ${isSelected ? 'text-purple-300' : 'text-text-primary'}`}>
410
+ {pair.display_name}
411
+ </p>
412
+ <p className="text-[10px] text-text-muted">
413
+ {sig?.trade_levels?.entry_price ? `$${sig.trade_levels.entry_price}` : sig?.active_timeframe || 'Perps'}
414
+ </p>
415
+ </div>
416
+ </div>
417
+
418
+ <div className="flex items-center gap-1.5 shrink-0">
419
+ {messageCount > 0 && (
420
+ <span className="text-[9px] px-1 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 font-mono">
421
+ {messageCount}
422
+ </span>
423
+ )}
424
+ {sig && (
425
+ <span className={`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold border ${dirColor}`}>
426
+ {sig.conviction}/10
427
+ </span>
428
+ )}
429
+ </div>
430
+ </button>
431
+ );
432
+ })}
433
+ </div>
434
+ </aside>
435
+
436
+ {/* ── Main Area: Dedicated AI Terminal Workspace ──────────────────────── */}
437
+ <section className="flex-1 flex flex-col h-full overflow-hidden bg-bg-primary">
438
+ {/* Top Bar for Selected Pair */}
439
+ <div className="px-3 sm:px-5 py-2.5 border-b border-border bg-bg-card flex flex-col sm:flex-row sm:items-center justify-between gap-2 shrink-0">
440
+ {/* Pair badge & market status */}
441
+ <div className="flex items-center gap-2 min-w-0">
442
+ <div className="p-2 rounded-xl bg-purple-500/15 border border-purple-500/30 text-purple-400 shrink-0">
443
+ <Bot size={18} />
444
+ </div>
445
+ <div className="min-w-0">
446
+ <div className="flex items-center gap-2 flex-wrap">
447
+ <h2 className="font-mono font-bold text-sm sm:text-base text-text-primary truncate">
448
+ {selectedSymbol}
449
+ </h2>
450
+ {activeSignal && (
451
+ <span className={`px-2 py-0.5 rounded-full text-[10px] font-mono font-bold border ${
452
+ activeSignal.direction === 'LONG'
453
+ ? 'bg-signal-long/15 text-signal-long border-signal-long/30'
454
+ : activeSignal.direction === 'SHORT'
455
+ ? 'bg-signal-short/15 text-signal-short border-signal-short/30'
456
+ : 'bg-gray-500/15 text-text-muted border-border'
457
+ }`}>
458
+ {activeSignal.direction} • {activeSignal.conviction}/10
459
+ </span>
460
+ )}
461
+ {activeSignal?.active_timeframe && (
462
+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-bg-elevated border border-border text-text-muted">
463
+ TF: {activeSignal.active_timeframe.toUpperCase()}
464
+ </span>
465
+ )}
466
+ </div>
467
+ <p className="text-[10px] text-text-muted truncate">
468
+ {activeSignal?.quick_verdict || 'Data live bursa tersambung & siap dianalisa AI'}
469
+ </p>
470
+ </div>
471
+ </div>
472
+
473
+ {/* Action buttons on top bar */}
474
+ <div className="flex items-center gap-1.5 sm:gap-2 self-end sm:self-auto shrink-0">
475
+ <button
476
+ type="button"
477
+ onClick={() => handleSendMessage(undefined, true)}
478
+ disabled={currentSession.isLoading}
479
+ className="flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium border border-border bg-bg-elevated hover:bg-bg-card text-text-secondary hover:text-text-primary transition-colors disabled:opacity-50"
480
+ title="Paksa hitung ulang analisa dengan token baru"
481
+ >
482
+ <RefreshCw size={11} className={currentSession.isLoading ? 'animate-spin' : ''} />
483
+ <span className="hidden xs:inline">Analisa Ulang</span>
484
+ </button>
485
+
486
+ {currentSession.messages.length > 0 && (
487
+ <button
488
+ type="button"
489
+ onClick={handleClearSession}
490
+ className="p-1.5 rounded-lg border border-border bg-bg-elevated hover:bg-red-500/20 hover:text-red-300 text-text-muted transition-colors"
491
+ title="Bersihkan riwayat percakapan pair ini"
492
+ >
493
+ <Trash2 size={13} />
494
+ </button>
495
+ )}
496
+
497
+ <button
498
+ type="button"
499
+ onClick={() => setIsSettingsOpen(true)}
500
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs border border-purple-500/30 bg-purple-500/10 hover:bg-purple-500/20 text-purple-200 transition-colors"
501
+ title="Atur Model AI & API Key"
502
+ >
503
+ <Settings size={12} className="text-purple-400" />
504
+ <span className="font-mono text-[11px] truncate max-w-[100px]">
505
+ {settings.model.split('/')[1] || settings.model}
506
+ </span>
507
+ </button>
508
+ </div>
509
+ </div>
510
+
511
+ {/* Mobile Horizontal Pair Scroll Chips (Mobile Only) */}
512
+ <div className="md:hidden flex items-center gap-1.5 px-3 py-2 bg-bg-elevated/80 border-b border-border overflow-x-auto no-scrollbar shrink-0">
513
+ <span className="text-[10px] text-text-muted uppercase font-semibold shrink-0">Pair:</span>
514
+ {activePairs.map((p) => {
515
+ const isSelected = p.symbol === selectedSymbol;
516
+ const sig = signalMap.get(p.symbol);
517
+ return (
518
+ <button
519
+ key={p.symbol}
520
+ onClick={() => setSelectedSymbol(p.symbol)}
521
+ className={`px-2.5 py-1 rounded-lg text-xs font-mono shrink-0 transition-all ${
522
+ isSelected
523
+ ? 'bg-purple-600 text-white font-bold shadow-sm'
524
+ : 'bg-bg-card border border-border text-text-secondary hover:text-text-primary'
525
+ }`}
526
+ >
527
+ {p.symbol.replace('USDT', '')}
528
+ {sig && (
529
+ <span className={`ml-1 text-[10px] ${sig.direction === 'LONG' ? 'text-signal-long' : sig.direction === 'SHORT' ? 'text-signal-short' : 'text-gray-400'}`}>
530
+ {sig.conviction}
531
+ </span>
532
+ )}
533
+ </button>
534
+ );
535
+ })}
536
+ </div>
537
+
538
+ {/* ── Scrollable Chat / AI Conversation View ──────────────────────── */}
539
+ <div className="flex-1 overflow-y-auto p-3 sm:p-5 space-y-4 custom-scrollbar">
540
+ {/* Empty state: No messages yet */}
541
+ {currentSession.messages.length === 0 && !currentSession.isLoading && (
542
+ <div className="flex flex-col items-center justify-center min-h-[50vh] text-center max-w-xl mx-auto space-y-4 p-4 animate-fade-in">
543
+ <div className="w-14 h-14 rounded-2xl bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-400 shadow-lg shadow-purple-500/10">
544
+ <Sparkles size={28} />
545
+ </div>
546
+ <div className="space-y-1.5">
547
+ <h3 className="text-base sm:text-lg font-bold text-text-primary">
548
+ Asisten Kuantitatif Institusi untuk {selectedSymbol}
549
+ </h3>
550
+ <p className="text-xs text-text-secondary max-w-md mx-auto leading-relaxed">
551
+ Tanyakan setup trading, validasi likuidasi, atau jalankan analisa menyeluruh.
552
+ Data multi-exchange (Binance, Bybit, OKX, Hyperliquid, Spot vs Fut CVD) akan disintesis otomatis secara objektif dan anti-halusinasi.
553
+ </p>
554
+ </div>
555
+
556
+ {/* Primary Call to Action */}
557
+ <div className="pt-2">
558
+ <Button
559
+ variant="primary"
560
+ size="md"
561
+ onClick={() => handleSendMessage()}
562
+ icon={<Zap size={14} />}
563
+ className="bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/25 px-5 py-2.5 rounded-xl font-semibold text-xs sm:text-sm"
564
+ >
565
+ Mulai Analisa Lengkap {selectedSymbol}
566
+ </Button>
567
+ </div>
568
+
569
+ {/* Quick Prompts Grid */}
570
+ <div className="pt-4 w-full">
571
+ <p className="text-[11px] font-semibold text-text-muted uppercase tracking-wider mb-2">
572
+ Atau Pilih Topik Cepat:
573
+ </p>
574
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-left">
575
+ {QUICK_PROMPTS.map((qp, idx) => (
576
+ <button
577
+ key={idx}
578
+ type="button"
579
+ onClick={() => handleSendMessage(qp.prompt)}
580
+ className="p-2.5 rounded-xl border border-border bg-bg-card hover:bg-bg-elevated hover:border-purple-500/40 text-xs transition-all flex items-start gap-2 text-left group"
581
+ >
582
+ <span className="font-semibold text-text-primary group-hover:text-purple-300">
583
+ {qp.label}
584
+ </span>
585
+ </button>
586
+ ))}
587
+ </div>
588
+ </div>
589
+ </div>
590
+ )}
591
+
592
+ {/* Conversation Messages */}
593
+ {currentSession.messages.map((msg) => {
594
+ if (msg.role === 'user') {
595
+ return (
596
+ <div key={msg.id} className="flex justify-end animate-fade-in">
597
+ <div className="max-w-[85%] sm:max-w-[75%] rounded-2xl rounded-tr-sm bg-purple-600 text-white p-3.5 shadow-md shadow-purple-600/10 space-y-1">
598
+ <p className="text-xs sm:text-sm font-sans">{msg.content}</p>
599
+ <p className="text-[10px] text-purple-200 text-right">{msg.timestamp}</p>
600
+ </div>
601
+ </div>
602
+ );
603
+ }
604
+
605
+ // Assistant AI Message
606
+ return (
607
+ <div key={msg.id} className="flex flex-col space-y-2 animate-fade-in max-w-[95%] sm:max-w-[90%]">
608
+ <div className="rounded-2xl rounded-tl-sm bg-bg-card border border-border/90 p-4 sm:p-5 space-y-3.5 shadow-sm">
609
+ {/* Assistant Header Banner */}
610
+ <div className="flex flex-wrap items-center justify-between gap-2 pb-2.5 border-b border-border/60">
611
+ <div className="flex items-center gap-2">
612
+ <span className="p-1 rounded-md bg-purple-500/20 text-purple-400">
613
+ <Bot size={14} />
614
+ </span>
615
+ <span className="text-xs font-bold font-mono text-purple-300">
616
+ AI Quantitative Digest
617
+ </span>
618
+ {msg.bias && (
619
+ <span className={`px-2 py-0.5 rounded text-[11px] font-mono font-bold border ${biasBadgeColor(msg.bias)}`}>
620
+ {msg.bias}
621
+ </span>
622
+ )}
623
+ </div>
624
+
625
+ <div className="flex items-center gap-1.5">
626
+ {msg.isCached && (
627
+ <span className="text-[10px] font-mono text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded">
628
+ Hemat Token (Cache)
629
+ </span>
630
+ )}
631
+ <button
632
+ type="button"
633
+ onClick={() => handleCopyText(msg.content, msg.id)}
634
+ className="px-2 py-1 rounded text-[10px] border border-border text-text-secondary hover:text-text-primary flex items-center gap-1 hover:bg-bg-elevated transition-colors"
635
+ title="Salin Analisa Lengkap"
636
+ >
637
+ {copiedId === msg.id ? (
638
+ <>
639
+ <Check size={11} className="text-signal-long" />
640
+ <span className="text-signal-long">Tersalin</span>
641
+ </>
642
+ ) : (
643
+ <>
644
+ <Copy size={11} />
645
+ <span>Salin</span>
646
+ </>
647
+ )}
648
+ </button>
649
+ </div>
650
+ </div>
651
+
652
+ {/* Formatted Content */}
653
+ {renderFormattedAnalysis(msg.content)}
654
+
655
+ {/* Collapsible Raw Telemetry Data */}
656
+ {msg.dataSnapshot && (
657
+ <div className="pt-2 border-t border-border/50">
658
+ <button
659
+ type="button"
660
+ onClick={() => toggleSnapshot(msg.id)}
661
+ className="text-[11px] text-text-secondary hover:text-purple-300 flex items-center gap-1 transition-colors"
662
+ >
663
+ <Activity size={11} />
664
+ <span>{expandedSnapshots[msg.id] ? 'Sembunyikan Telemetry Data Mentah' : 'Lihat Telemetry Data Mentah yang Dikirim ke AI'}</span>
665
+ {expandedSnapshots[msg.id] ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
666
+ </button>
667
+
668
+ {expandedSnapshots[msg.id] && (
669
+ <div className="mt-2 p-3 rounded-xl bg-bg-elevated border border-border/80 text-[10px] font-mono grid grid-cols-2 sm:grid-cols-4 gap-2.5 animate-fade-in">
670
+ <div>
671
+ <span className="text-text-muted block text-[9px]">MARK PRICE</span>
672
+ <span className="text-text-primary font-bold">{msg.dataSnapshot.mark_price_str || `$${msg.dataSnapshot.mark_price}`}</span>
673
+ </div>
674
+ <div>
675
+ <span className="text-text-muted block text-[9px]">3-EXCHANGE SPREAD</span>
676
+ <span className="text-text-primary">{msg.dataSnapshot.triangulation_spread_pct.toFixed(4)}%</span>
677
+ </div>
678
+ <div>
679
+ <span className="text-text-muted block text-[9px]">BINANCE FR</span>
680
+ <span className="text-text-primary">{msg.dataSnapshot.binance_fr}</span>
681
+ </div>
682
+ <div>
683
+ <span className="text-text-muted block text-[9px]">BYBIT FR</span>
684
+ <span className="text-text-primary">{msg.dataSnapshot.bybit_fr}</span>
685
+ </div>
686
+ <div>
687
+ <span className="text-text-muted block text-[9px]">OKX FR</span>
688
+ <span className="text-text-primary">{msg.dataSnapshot.okx_fr}</span>
689
+ </div>
690
+ <div>
691
+ <span className="text-text-muted block text-[9px]">HYPERLIQUID FR</span>
692
+ <span className="text-text-primary">{msg.dataSnapshot.hyperliquid_fr}</span>
693
+ </div>
694
+ <div>
695
+ <span className="text-text-muted block text-[9px]">SPOT CVD</span>
696
+ <span className="text-text-primary">{msg.dataSnapshot.spot_cvd}</span>
697
+ </div>
698
+ <div>
699
+ <span className="text-text-muted block text-[9px]">FUTURES CVD</span>
700
+ <span className="text-text-primary">{msg.dataSnapshot.futures_cvd}</span>
701
+ </div>
702
+ <div className="col-span-2">
703
+ <span className="text-text-muted block text-[9px]">LIQUIDATION MAGNETS</span>
704
+ <span className="text-text-primary">{msg.dataSnapshot.upper_magnet} / {msg.dataSnapshot.lower_magnet}</span>
705
+ </div>
706
+ <div className="col-span-2">
707
+ <span className="text-text-muted block text-[9px]">ORDERBOOK PRESSURE</span>
708
+ <span className="text-text-primary">{msg.dataSnapshot.resting_pressure}</span>
709
+ </div>
710
+ </div>
711
+ )}
712
+ </div>
713
+ )}
714
+
715
+ {/* Message Footer Info */}
716
+ <div className="flex items-center justify-between text-[10px] text-text-muted pt-1">
717
+ <span>Model: {msg.model || settings.model}</span>
718
+ <span>{msg.timestamp}</span>
719
+ </div>
720
+ </div>
721
+ </div>
722
+ );
723
+ })}
724
+
725
+ {/* Loading indicator */}
726
+ {currentSession.isLoading && (
727
+ <div className="flex items-start gap-3 p-4 rounded-2xl bg-bg-card border border-purple-500/20 max-w-md animate-fade-in">
728
+ <div className="w-8 h-8 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin shrink-0" />
729
+ <div className="space-y-1">
730
+ <p className="text-xs font-bold text-text-primary flex items-center gap-1.5">
731
+ <Sparkles size={13} className="text-purple-400 animate-pulse" />
732
+ Menganalisa Aliran Modal {selectedSymbol}...
733
+ </p>
734
+ <p className="text-[10px] text-text-muted">
735
+ Menyintesis data orderbook, likuidasi, Spot vs Futures CVD ke {settings.model}...
736
+ </p>
737
+ </div>
738
+ </div>
739
+ )}
740
+
741
+ {/* Error notice */}
742
+ {currentSession.error && !currentSession.isLoading && (
743
+ <div className="p-3.5 rounded-xl bg-red-500/10 border border-red-500/30 flex items-start gap-2.5 text-xs text-red-200">
744
+ <AlertCircle size={16} className="text-red-400 shrink-0 mt-0.5" />
745
+ <div className="space-y-1 flex-1">
746
+ <p className="font-bold text-red-300">Gagal Mendapatkan Analisa AI</p>
747
+ <p className="text-[11px] text-red-200/90">{currentSession.error}</p>
748
+ <div className="pt-1 flex items-center gap-2">
749
+ <button
750
+ onClick={() => handleSendMessage(undefined, true)}
751
+ className="text-[10px] px-2 py-0.5 rounded bg-red-500/20 hover:bg-red-500/30 text-red-100 font-semibold border border-red-500/40"
752
+ >
753
+ Coba Lagi
754
+ </button>
755
+ <button
756
+ onClick={() => setIsSettingsOpen(true)}
757
+ className="text-[10px] text-purple-300 hover:underline"
758
+ >
759
+ Buka Pengaturan AI
760
+ </button>
761
+ </div>
762
+ </div>
763
+ </div>
764
+ )}
765
+
766
+ <div ref={chatEndRef} />
767
+ </div>
768
+
769
+ {/* ── Fixed Bottom Chat Input Bar ──────────────────────────────────── */}
770
+ <div className="p-3 sm:p-4 border-t border-border bg-bg-card/95 shrink-0">
771
+ {/* Quick Prompts (if chat already active) */}
772
+ {currentSession.messages.length > 0 && (
773
+ <div className="flex items-center gap-1.5 overflow-x-auto no-scrollbar pb-2 mb-1">
774
+ {QUICK_PROMPTS.map((qp, idx) => (
775
+ <button
776
+ key={idx}
777
+ type="button"
778
+ onClick={() => handleSendMessage(qp.prompt)}
779
+ disabled={currentSession.isLoading}
780
+ className="px-2.5 py-1 rounded-lg text-[10px] font-medium bg-bg-elevated hover:bg-purple-600/20 hover:text-purple-300 border border-border text-text-secondary transition-all shrink-0 disabled:opacity-50"
781
+ >
782
+ {qp.label}
783
+ </button>
784
+ ))}
785
+ </div>
786
+ )}
787
+
788
+ <form
789
+ onSubmit={(e) => {
790
+ e.preventDefault();
791
+ handleSendMessage();
792
+ }}
793
+ className="flex items-center gap-2"
794
+ >
795
+ <input
796
+ type="text"
797
+ value={inputPrompt}
798
+ onChange={(e) => setInputPrompt(e.target.value)}
799
+ placeholder={`Tanyakan analisa teknikal, validasi trap, atau scalping untuk ${selectedSymbol}...`}
800
+ disabled={currentSession.isLoading}
801
+ className="flex-1 bg-bg-elevated border border-border focus:border-purple-500/60 rounded-xl px-3.5 py-2.5 text-xs sm:text-sm text-text-primary placeholder:text-text-muted focus:outline-none transition-colors"
802
+ />
803
+
804
+ <Button
805
+ type="submit"
806
+ variant="primary"
807
+ size="md"
808
+ loading={currentSession.isLoading}
809
+ disabled={currentSession.isLoading || !inputPrompt.trim()}
810
+ icon={<Send size={14} />}
811
+ className="bg-purple-600 hover:bg-purple-500 text-white rounded-xl px-4 py-2.5 shadow-sm shadow-purple-600/30 shrink-0"
812
+ >
813
+ <span className="hidden xs:inline">Kirim</span>
814
+ </Button>
815
+ </form>
816
+ </div>
817
+ </section>
818
+
819
+ {/* Settings Modal */}
820
+ {isSettingsOpen && (
821
+ <Suspense fallback={null}>
822
+ <GlobalAISettingsModal isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
823
+ </Suspense>
824
+ )}
825
+ </div>
826
+ );
827
+ }
frontend/src/pages/Dashboard.tsx CHANGED
@@ -1,6 +1,5 @@
1
  import { useState, useMemo, useEffect, lazy, Suspense } from 'react';
2
  import { Plus, TrendingUp, RefreshCw, Flame, ArrowUpRight, ArrowDownRight, Layers, ArrowLeft } from 'lucide-react';
3
- import { Header } from '../components/layout/Header';
4
  import { Sidebar } from '../components/layout/Sidebar';
5
  import { MobileDrawer } from '../components/layout/MobileDrawer';
6
  import { SignalCard } from '../components/signals/SignalCard';
@@ -9,7 +8,6 @@ import { CardSkeleton, Spinner } from '../components/ui/Spinner';
9
  import { Button } from '../components/ui/Button';
10
  import { usePairs } from '../hooks/usePairs';
11
  import { useSignals, useRefreshSignal } from '../hooks/useSignals';
12
- import { useWebSocket } from '../hooks/useWebSocket';
13
 
14
  // Lazy-load modal to keep initial bundle ultra-lightweight
15
  const AddPairModal = lazy(() =>
@@ -19,14 +17,22 @@ const AddPairModal = lazy(() =>
19
  type FilterMode = 'ALL' | 'HOT' | 'LONG' | 'SHORT';
20
  type SortMode = 'STABLE' | 'CONVICTION';
21
 
22
- export function Dashboard() {
 
 
 
 
 
 
 
 
 
 
23
  const [selectedSymbol, setSelectedSymbol] = useState<string | null>(null);
24
  const [filterMode, setFilterMode] = useState<FilterMode>('ALL');
25
  const [sortMode, setSortMode] = useState<SortMode>('STABLE');
26
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
27
- const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false);
28
 
29
- const { status: wsStatus, lastUpdated } = useWebSocket();
30
  const { data: pairs = [], isLoading: pairsLoading } = usePairs();
31
  const { data: signals = [], isLoading: signalsLoading } = useSignals();
32
  const { mutate: refreshSignal, isPending: isRefreshing } = useRefreshSignal();
@@ -82,14 +88,7 @@ export function Dashboard() {
82
  const shortCount = useMemo(() => allSortedSignals.filter((s) => s.direction === 'SHORT').length, [allSortedSignals]);
83
 
84
  return (
85
- <div className="flex flex-col h-screen bg-bg-primary overflow-hidden">
86
- <Header
87
- wsStatus={wsStatus}
88
- lastUpdated={lastUpdated}
89
- onOpenMobileDrawer={() => setIsMobileDrawerOpen(true)}
90
- activePairCount={activePairs.length}
91
- />
92
-
93
  <div className="flex flex-1 overflow-hidden">
94
  {/* Desktop Sidebar — hidden on mobile */}
95
  <div className="hidden md:flex">
@@ -326,7 +325,11 @@ export function Dashboard() {
326
  {!isInitialLoading && displayedSignals.length > 0 && (
327
  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4">
328
  {displayedSignals.map((signal) => (
329
- <SignalCard key={signal.symbol} signal={signal} />
 
 
 
 
330
  ))}
331
  </div>
332
  )}
 
1
  import { useState, useMemo, useEffect, lazy, Suspense } from 'react';
2
  import { Plus, TrendingUp, RefreshCw, Flame, ArrowUpRight, ArrowDownRight, Layers, ArrowLeft } from 'lucide-react';
 
3
  import { Sidebar } from '../components/layout/Sidebar';
4
  import { MobileDrawer } from '../components/layout/MobileDrawer';
5
  import { SignalCard } from '../components/signals/SignalCard';
 
8
  import { Button } from '../components/ui/Button';
9
  import { usePairs } from '../hooks/usePairs';
10
  import { useSignals, useRefreshSignal } from '../hooks/useSignals';
 
11
 
12
  // Lazy-load modal to keep initial bundle ultra-lightweight
13
  const AddPairModal = lazy(() =>
 
17
  type FilterMode = 'ALL' | 'HOT' | 'LONG' | 'SHORT';
18
  type SortMode = 'STABLE' | 'CONVICTION';
19
 
20
+ export interface DashboardProps {
21
+ onNavigateToAI?: (symbol: string) => void;
22
+ isMobileDrawerOpen: boolean;
23
+ setIsMobileDrawerOpen: (open: boolean) => void;
24
+ }
25
+
26
+ export function Dashboard({
27
+ onNavigateToAI,
28
+ isMobileDrawerOpen,
29
+ setIsMobileDrawerOpen,
30
+ }: DashboardProps) {
31
  const [selectedSymbol, setSelectedSymbol] = useState<string | null>(null);
32
  const [filterMode, setFilterMode] = useState<FilterMode>('ALL');
33
  const [sortMode, setSortMode] = useState<SortMode>('STABLE');
34
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
 
35
 
 
36
  const { data: pairs = [], isLoading: pairsLoading } = usePairs();
37
  const { data: signals = [], isLoading: signalsLoading } = useSignals();
38
  const { mutate: refreshSignal, isPending: isRefreshing } = useRefreshSignal();
 
88
  const shortCount = useMemo(() => allSortedSignals.filter((s) => s.direction === 'SHORT').length, [allSortedSignals]);
89
 
90
  return (
91
+ <div className="flex flex-1 h-full overflow-hidden bg-bg-primary">
 
 
 
 
 
 
 
92
  <div className="flex flex-1 overflow-hidden">
93
  {/* Desktop Sidebar — hidden on mobile */}
94
  <div className="hidden md:flex">
 
325
  {!isInitialLoading && displayedSignals.length > 0 && (
326
  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4">
327
  {displayedSignals.map((signal) => (
328
+ <SignalCard
329
+ key={signal.symbol}
330
+ signal={signal}
331
+ onNavigateToAI={onNavigateToAI}
332
+ />
333
  ))}
334
  </div>
335
  )}