)
}
// ── Empty state for when nothing is selected ──────────────────────────────────
function SelectHint() {
return (
Click any marker on the chart or a post below to see details
)
}
// ── Main dashboard ─────────────────────────────────────────────────────────────
export default function DashboardClient({ initialPosts }: Props) {
const intlLocale = useLocale()
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const { asset, setAsset, timeframe, setTimeframe: _setTimeframe, setLivePrice, setSubscribed, setBotReadiness, setHlApiKeySet, setPaperMode, isSubscribed, hlApiKeySet, botReadiness, livePrices } = useDashboardStore()
function setTimeframe(tf: string) { _setTimeframe(tf as '5m' | '15m' | '1H' | '4H' | '1D' | '1W') }
const { address, isConnected } = useAccount()
const params = useParams()
const locale = (typeof params?.locale === 'string' ? params.locale : 'en')
const [posts, setPosts] = useState(initialPosts)
// Chart markers need actionable (buy/short) posts, but the 80-post
// first-paint slice is usually ALL hold/filtered — Trump posts are mostly
// off-topic, so the chart would render zero markers. Fetch signal posts
// separately and merge them in for the chart.
const [signalPosts, setSignalPosts] = useState([])
// Distinguishes "actionable fetch not done yet" from "loaded, zero
// actionable" — the auto-select effect waits on it before falling back.
const [signalPostsLoaded, setSignalPostsLoaded] = useState(false)
const [performance, setPerformance] = useState(undefined)
const [candles, setCandles] = useState([])
const [hideFiltered, setHideFiltered] = useState(false)
const [chartErr, setChartErr] = useState('')
const [chartReload, setChartReload] = useState(0)
const [selectedPostId, setSelectedPostId] = useState(null)
const railRef = useRef(null)
const [macro, setMacro] = useState(null)
const [kolDivergences, setKolDivergences] = useState([])
const [kolDigest, setKolDigest] = useState(null)
// For 1D: show all posts from selected day
const [selectedDayPosts, setSelectedDayPosts] = useState(null)
// Server-side aggregate counts. The Overview headline numbers (total tracked,
// actionable, Trump/Macro signals) must reflect the WHOLE feed, not the
// 80-post first-paint slice — otherwise a site with 1108 posts / 25 actionable
// Trump signals showed "80 tracked" and "—". Loaded once from /posts-paged
// which returns server-computed totals + counts without shipping the rows.
const [serverCounts, setServerCounts] = useState<{
total: number; actionable: number; trump: number; macro: number
} | null>(null)
// Backend degraded state. When the process isn't the singleton leader it
// runs NO background tasks (no scrapers, price feeds, scheduler) — the data
// is frozen and "Live" would be a lie. /api/health/deep returns 503 + a body
// with { status, is_leader } in that case.
const [degraded, setDegraded] = useState(false)
useEffect(() => {
// B42: cancel the in-flight getUserPublic if the wallet switches again
// before it resolves — prevents old wallet's data polluting new wallet's state.
let cancelled = false
if (!isConnected || !address) {
setSubscribed(false)
setHlApiKeySet(false)
setBotReadiness('unknown')
setPerformance(undefined)
return () => { cancelled = true }
}
// Clear account-scoped bot state immediately (setWallet already resets these
// via store, but DashboardClient may be rendered without a wallet switch —
// keep explicit resets here for clarity and safety).
setSubscribed(false)
setHlApiKeySet(false)
setBotReadiness('unknown')
// `snapAddr !== address` would be a stale-closure trap: both are the same
// closed-over value. Use `cancelled` (set by effect cleanup) as the sole guard.
getUserPublic(address.toLowerCase())
.then((user) => {
if (cancelled) return // effect cleaned up = wallet changed or unmounted
setSubscribed(user.active)
setHlApiKeySet(user.hl_api_key_set)
setBotReadiness(user.hl_api_key_set ? 'saved' : 'unknown')
setPaperMode(!!user.paper_mode)
})
.catch(() => {})
return () => { cancelled = true }
}, [address, isConnected, setSubscribed, setHlApiKeySet, setBotReadiness, setPaperMode])
useEffect(() => {
if (!isConnected || !address) {
setPerformance(undefined)
return
}
let cancelled = false
;(async () => {
try {
const env = getCachedViewEnvelope('view_performance', address)
?? getCachedViewEnvelope('view_user', address)
if (!env) {
if (!cancelled) setPerformance(undefined)
return
}
const data = await getPerformance(address, env)
if (!cancelled) setPerformance(data)
} catch {
if (!cancelled) setPerformance(undefined)
}
})()
return () => { cancelled = true }
}, [address, isConnected])
const [freshPostId, setFreshPostId] = useState(null)
usePriceSocket({
onPrice: (a, price) => setLivePrice(a, price),
onNewPost: (post) => {
const p = post as TrumpPost
// Dedup: WS may resend a post already in initialPosts or a prior push.
setPosts((prev) => prev.some(x => x.id === p.id) ? prev : [p, ...prev].slice(0, 500))
setFreshPostId(p.id)
// Keep a ref to the timer so we can cancel it if the component unmounts
// before it fires (avoids setState-after-unmount warning).
const timer = setTimeout(() => setFreshPostId((id) => (id === p.id ? null : id)), 1400)
return () => clearTimeout(timer) // returned but not used by usePriceSocket — see L1 note
},
})
useEffect(() => {
let cancelled = false
setCandles([])
setChartErr('')
const priceKey = `prices-${asset}-${timeframe}`
if (chartReload > 0) invalidateCache(priceKey)
swrFetch(
priceKey,
90_000,
() => getPrices(asset, timeframe),
fresh => { if (!cancelled) { setCandles(fresh); setChartErr('') } },
)
.then(c => { if (!cancelled) { setCandles(c); setChartErr('') } })
.catch(e => { if (!cancelled) setChartErr(e instanceof Error ? e.message : 'Failed to load price data') })
return () => { cancelled = true }
}, [asset, timeframe, chartReload])
// Auto-select the latest actionable signal once on load so the detail rail
// isn't an empty column until the user clicks something. Runs once; never
// re-selects after the user picks or closes a post.
const autoSelectedRef = useRef(false)
const skipRailScrollRef = useRef(false)
useEffect(() => {
if (autoSelectedRef.current) return
if (selectedPostId != null || selectedDayPosts) { autoSelectedRef.current = true; return }
const pool = [...posts, ...signalPosts]
const actionable = pool.filter(p => p.signal === 'buy' || p.signal === 'short')
// Prefer the latest actionable signal — but the actionable fetch is async,
// so wait for it before falling back to a (likely off-topic) recent post.
if (!actionable.length && !signalPostsLoaded) return
const pick = (actionable.length ? actionable : pool)
.slice()
.sort((a, b) => +new Date(b.published_at) - +new Date(a.published_at))[0]
if (!pick) return
autoSelectedRef.current = true
skipRailScrollRef.current = true // a load-time selection must not scroll the page
setSelectedPostId(pick.id)
}, [posts, signalPosts, signalPostsLoaded, selectedPostId, selectedDayPosts])
// On narrow viewports the layout stacks and the detail rail sits ABOVE the
// chart — a click on a post down in the list renders the detail card out of
// view and the selection looks like a no-op. Scroll it into view, but only
// when it's actually outside the viewport (no jump on desktop, where the
// rail is a sticky side column).
useEffect(() => {
if (selectedPostId == null && !selectedDayPosts) return
if (skipRailScrollRef.current) { skipRailScrollRef.current = false; return }
const el = railRef.current
if (!el) return
const r = el.getBoundingClientRect()
// The detail card renders at the TOP of the rail, so "visible" means the
// rail's top edge is on screen — a rail whose tail end pokes into the
// viewport still hides the card.
if (r.top < 0 || r.top > window.innerHeight - 120) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
}, [selectedPostId, selectedDayPosts])
// Actionable posts for the chart markers (see signalPosts above).
useEffect(() => {
let alive = true
swrFetch(
'posts-actionable-chart',
90_000,
() => getPostsPage(100, 1, undefined, { signal: 'actionable' }),
fresh => { if (alive) setSignalPosts(fresh.items) },
)
.then(r => { if (alive) { setSignalPosts(r.items); setSignalPostsLoaded(true) } })
.catch(() => { if (alive) setSignalPostsLoaded(true) })
return () => { alive = false }
}, [])
useEffect(() => {
let alive = true
function load() {
swrFetch(
'macro-snapshot',
10 * 60_000,
() => getMacroSnapshot(),
fresh => { if (alive) setMacro(fresh) },
)
.then((snap) => { if (alive) setMacro(snap) })
.catch(() => {})
}
load()
const id = setInterval(load, 10 * 60_000)
return () => { alive = false; clearInterval(id) }
}, [])
// Poll backend health so the "Live" chip can downgrade to "Delayed" when the
// process is a non-leader follower (read-only, no background tasks → data is
// frozen). The body is present on both 200 and 503, so read it regardless of
// status. Key ONLY on is_leader === false: a `degraded` status can also mean
// a single price feed briefly lagged, which would flap the chip even though
// the feed self-heals in seconds — that's noisier than it is useful.
useEffect(() => {
let alive = true
async function check() {
try {
const res = await fetch('/api/proxy/api/health/deep')
const body = await res.json().catch(() => null)
if (!alive || !body) return
setDegraded(body.is_leader === false)
} catch { /* network error — leave chip as-is */ }
}
check()
const id = setInterval(check, 60_000)
return () => { alive = false; clearInterval(id) }
}, [])
// Server-side aggregate counts for the Overview headline numbers. limit=1
// keeps the payload tiny — we only consume `total` and `counts`.
useEffect(() => {
let alive = true
;(async () => {
try {
const [global, trump, macro] = await Promise.all([
getPostsPage(1, 1),
getPostsPage(1, 1, 'truth'),
getPostsPage(1, 1, undefined, { sourceIn: ['btc_bottom_reversal', 'funding_reversal'] }),
])
if (!alive) return
setServerCounts({
total: global.total,
actionable: global.counts.actionable,
trump: trump.counts.actionable,
macro: macro.counts.actionable,
})
} catch { /* fall back to local-slice counts */ }
})()
return () => { alive = false }
}, [])
// KOL divergence + digest — loaded once, 30 min cache (changes daily)
useEffect(() => {
let alive = true
// KOL ingestion is daily and sparse — a 7d window is frequently empty
// (e.g. 7d=0 while 30d=196), which hid the whole sidebar card. Use a 30d
// window so the Overview reflects the data that actually exists.
swrFetch('kol-divergence-30d', 30 * 60_000, () => getKolDivergence({ days: 30 }), f => { if (alive) setKolDivergences(f.items ?? []) })
.then(r => { if (alive) setKolDivergences(r.items ?? []) })
.catch(() => {})
swrFetch('kol-digest-30d', 30 * 60_000, () => getKolDigest(30), f => { if (alive) setKolDigest(f) })
.then(r => { if (alive) setKolDigest(r) })
.catch(() => {})
return () => { alive = false }
}, [])
// Union of the recent-posts slice and the separately-fetched actionable
// posts (deduped) — feeds the chart so signal markers always render, and
// the detail lookup so clicking one of those markers resolves.
const chartPosts = (() => {
const seen = new Set(posts.map(p => p.id))
return [...posts, ...signalPosts.filter(p => !seen.has(p.id))]
})()
const selectedPost = chartPosts.find(p => p.id === selectedPostId) ?? null
// Show actionable signals first (buy/short), then most recent hold/neutral.
// Cap at 8 total so the list doesn't get too long. "Signals only" hides the
// hold/filtered (gray) posts entirely — same toggle as the Trump page.
const actionable = posts.filter(p => p.signal === 'buy' || p.signal === 'short').slice(0, hideFiltered ? 8 : 4)
const recentOthers = hideFiltered ? [] : posts.filter(p => p.signal !== 'buy' && p.signal !== 'short').slice(0, 4)
const recentPosts = [...actionable, ...recentOthers].slice(0, 8)
const lastCandle = candles[candles.length - 1]
// Live price beats the most recent candle close — the candle is only
// refreshed when the user changes asset/timeframe, so without WS the number
// is frozen at page load.
const livePrice = livePrices[asset]
const displayPrice = livePrice ?? lastCandle?.close ?? null
// 24-hour change. Picking by candle index is wrong (200×4H = 33 days).
// Find the candle whose `time` is closest to (now − 24h) and use its open.
const now = lastCandle ? lastCandle.time : Math.floor(Date.now() / 1000)
const target24h = now - 24 * 3600
let baseline24h: typeof lastCandle | undefined
if (candles.length) {
baseline24h = candles[0]
for (const c of candles) {
if (c.time <= target24h) baseline24h = c
else break
}
}
const priceChange =
displayPrice != null && baseline24h
? ((displayPrice - baseline24h.open) / baseline24h.open) * 100
: 0
// Prefer server-computed totals (whole feed); fall back to the local 80-post
// slice only until serverCounts loads (or if that fetch failed).
const totalPosts = serverCounts?.total ?? posts.length
const todayKey = new Date().toISOString().slice(0, 10)
const signalsToday = posts.filter(p => p.published_at?.slice(0, 10) === todayKey).length
const actionablePosts = serverCounts?.actionable ?? posts.filter(p => p.signal === 'buy' || p.signal === 'short').length
const trumpActionable = serverCounts?.trump ?? posts.filter(p => (p.source || '') === 'truth' && (p.signal === 'buy' || p.signal === 'short')).length
const macroActionable = serverCounts?.macro ?? posts.filter(p => ((p.source || '') === 'btc_bottom_reversal' || (p.source || '') === 'funding_reversal') && (p.signal === 'buy' || p.signal === 'short')).length
// Use actual KOL divergence count (divergence-flagged items from the API),
// not a source==='kol' post count (which never matches — source is 'substack'/'blog'/etc.).
const kolMentions = kolDivergences.filter(d => d.signal_type === 'divergence').length
const winRate = performance?.win_rate ?? 0
const netPnl = performance?.net_pnl_usd ?? 0
const hasPriceData = candles.length > 0
const hasPerformanceData = Boolean(performance)
const macroScore = macro?.composite_score ?? null
const macroRegime = macro?.regime_label ?? null
const macroPct = macroScore == null ? 50 : Math.max(0, Math.min(100, (macroScore + 100) / 2))
// Derive tone from the backend's regime_label, NOT a re-thresholded score.
// The backend uses ±20 for BULLISH/BEARISH; re-deriving with ±15 here made
// a score of e.g. 15.2 read "Supportive" in the card while the same card's
// regime label said NEUTRAL. Trusting regime_label keeps them consistent.
const macroTone =
macroRegime === 'BULL' || macroRegime === 'BULLISH' ? 'bull'
: macroRegime === 'BEAR' || macroRegime === 'BEARISH' ? 'bear'
: 'neutral' // covers NEUTRAL and the null/not-loaded case
const macroSummary =
macroScore == null ? 'Daily macro composite not loaded yet.'
: macroTone === 'bull' ? 'Supportive backdrop — trend setups have room.'
: macroTone === 'bear' ? 'Defensive backdrop — preserve size, downside moves are cleaner.'
: 'Mixed backdrop — context only, not a directional trigger.'
return (
{/* The big price lives in the market hero above — repeating it here
just duplicated the same number 32px tall. The chart's own price
axis label shows the live price; this header instead hosts the
asset/timeframe controls right next to the chart they drive. */}
Live chart · {asset} · signal markers
{(['5m', '15m', '1H', '4H', '1D'] as const).map(t => (
))}
{chartErr && (
⚠️ {asset} {timeframe} chart failed to load — {chartErr}{' '}
)}
{/* Loading overlay — shown while candles are fetching (candles=[] and no error).
Prevents the user from seeing a blank lightweight-charts canvas. */}
{!hasPriceData && !chartErr && (
Binance candles via backend API · click marker to inspect
{/* Recent signals list */}
Recent signals
{/* No count hint here — the page-head PageHint already shows
"X actionable · Y tracked" for the whole feed. */}
{recentPosts.map(p => (
{
// Clear the day-list view first: the right panel renders
// selectedDayPosts with higher priority than selectedPost,
// so without this the detail never appears while a candle's
// multi-post list is open.
setSelectedDayPosts(null)
setSelectedPostId(selectedPostId === p.id ? null : p.id)
}} />
))}
{/* Right rail */}
{/* Day-view: all posts from clicked day */}
{selectedDayPosts ? (
{selectedDayPosts.length} posts · this candle
{selectedDayPosts.map(p => {
const expanded = selectedPostId === p.id
const impact = p.price_impact
function fmtImpactPct(v: number | null | undefined) {
if (v == null || isNaN(v)) return '—'
const s = Math.abs(v).toFixed(2) + '%'
return v >= 0 ? '+' + s : '-' + s
}
return (