import React, { useCallback, useMemo, useState } from 'react'; import { View, Text, StyleSheet, Pressable, ScrollView, ActivityIndicator, } from 'react-native'; import { Colors, getMethodColor } from '../../ui/theme/colors'; import { FontSize, FontWeight, Radius, Spacing } from '../../ui/theme/layout'; import { CollapsibleSection } from '../../ui/shared/CollapsibleSection'; import { JsonView } from '../../ui/shared/JsonView'; import { CopyButton } from '../../ui/shared/CopyButton'; import { LogListScreen } from '../../ui/shared/LogListScreen'; import { LogRow, LogRowMetaText } from '../../ui/shared/LogRow'; import { safeStringify } from '../../utils/safeStringify'; import { fmt } from '../../utils/copyToComputer'; import { LEVEL_COLORS, LEVEL_ICONS } from '../../constants/logLevels'; import type { DebugFeature, DebugFeatureRenderProps, LogSession } from '../../types'; import { getLocale, t } from '../../i18n'; import { SESSION_HISTORY_LOG_KEYS, SESSION_LOG_COLORS, countSessionLogs, flattenSessionLogs, type DetailFilter, type FlatSessionLogEntry, type LogCounts, type LogFeatureKey, } from './sessionLogCatalog'; // ── Types ────────────────────────────────────────────────────────────── export interface SessionHistoryState { sessions: LogSession[]; currentSessionId: string; loading: boolean; selectedSession: SelectedSession | null; storageType: string; historyAvailable?: boolean; issues?: readonly { path: string; message: string }[]; logCounts: Record; } export interface SessionHistoryFeature extends DebugFeature { loadSession: (sessionId: string | null) => void; } export interface SelectedSession { sessionId: string; logs: Record; } // ── Helpers ──────────────────────────────────────────────────────────── function relativeTime(ts: number): string { const diff = Date.now() - ts; const mins = Math.floor(diff / 60000); if (mins < 1) return t('relative.justNow'); if (mins < 60) return t('relative.minutesAgo', { count: mins }); const hours = Math.floor(mins / 60); if (hours < 24) return t('relative.hoursAgo', { count: hours }); const days = Math.floor(hours / 24); if (days === 1) return t('relative.yesterday'); if (days < 7) return t('relative.daysAgo', { count: days }); return new Date(ts).toLocaleDateString(getLocale(), { month: 'short', day: 'numeric' }); } function formatTime(ts: number): string { return new Date(ts).toLocaleTimeString(getLocale(), { hour: '2-digit', minute: '2-digit' }); } function formatFullDate(ts: number): string { const d = new Date(ts); const now = new Date(); const isToday = d.toDateString() === now.toDateString(); const time = d.toLocaleTimeString(getLocale(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }); if (isToday) return `${t('relative.today')} ${time}`; return d.toLocaleDateString(getLocale(), { month: 'short', day: 'numeric' }) + ' ' + time; } function totalLogs(logs: Record): number { return Object.values(logs).reduce((sum, arr) => sum + arr.length, 0); } function shortId(id: string): string { return id.slice(-6).toUpperCase(); } function toRecord(entry: FlatSessionLogEntry): Record { return entry.raw as Record; } function shortenUrl(url: string): string { try { const u = new URL(url); return u.pathname + u.search; } catch { return url; } } function sessionLogLabel(key: LogFeatureKey): string { const keys: Record[0]> = { console_logs: 'feature.console', network_logs: 'feature.network', native_logs: 'feature.native', track_logs: 'feature.track', }; return t(keys[key]); } // ── Main Tab ─────────────────────────────────────────────────────────── export const SessionHistoryTab: React.FC> = React.memo( ({ snapshot, feature }) => { const { sessions, currentSessionId, loading, selectedSession, logCounts } = snapshot; const handleSelectSession = useCallback( (session: LogSession) => { if (session.id === currentSessionId) return; (feature as SessionHistoryFeature).loadSession(session.id); }, [feature, currentSessionId], ); const handleBack = useCallback(() => { (feature as SessionHistoryFeature).loadSession(null); }, [feature]); if (snapshot.historyAvailable === false) { return History unavailable{snapshot.issues?.map(issue => issue.message).join('\n') || 'Log history is disabled.'}; } if (loading) { return ( ); } if (selectedSession) { return ( ); } const previousSessions = sessions.filter((s) => s.id !== currentSessionId); const currentSession = sessions.find((s) => s.id === currentSessionId); if (previousSessions.length === 0) { return ( ⏱ {t('session.noHistory')} {t('session.description')} ); } return ( {currentSession && ( {t('session.current')} {formatFullDate(currentSession.startedAt)} )} {t('session.previous')} {previousSessions.map((session, idx) => { const counts = logCounts[session.id]; const total = counts ? countSessionLogs(counts) : 0; return ( handleSelectSession(session)} android_ripple={{ color: 'rgba(0,0,0,0.04)' }} > {idx < previousSessions.length - 1 && } {formatTime(session.startedAt)} {relativeTime(session.startedAt)} {counts && total > 0 ? ( {SESSION_HISTORY_LOG_KEYS.map((key) => { const c = counts[key] ?? 0; if (c === 0) return null; return ( {c} {sessionLogLabel(key)} ); })} ) : ( {t('session.noLogs')} )} #{shortId(session.id)} › ); })} ); }, ); // ── Session Detail (uses LogListScreen for tap-to-detail) ────────────── const SessionDetail: React.FC<{ logs: Record; sessionId: string; onBack: () => void; }> = React.memo(({ logs, sessionId, onBack }) => { const [filter, setFilter] = useState('all'); const total = totalLogs(logs); const flatEntries = useMemo(() => flattenSessionLogs(logs, filter), [logs, filter]); return ( ‹ {t('session.sessions')} #{shortId(sessionId)} ( setFilter('all')} color={Colors.text} /> {SESSION_HISTORY_LOG_KEYS.map((key) => { const c = (logs[key] ?? []).length; return ( setFilter(key)} color={SESSION_LOG_COLORS[key]} /> ); })} )} renderRow={(item) => } renderDetailHeader={(item) => } renderDetailBody={(item) => } /> ); }); // ── Filter Chips ─────────────────────────────────────────────────────── const FilterChip: React.FC<{ label: string; count: number; active: boolean; onPress: () => void; color: string; }> = React.memo(({ label, count, active, onPress, color }) => ( {label} {count} )); // ── Log List Row ─────────────────────────────────────────────────────── export function renderSessionLogRow(entry: FlatSessionLogEntry) { const e = toRecord(entry); if (entry.type === 'console_logs') { const level = e.level ?? 'log'; const msg = Array.isArray(e.data) ? e.data.map((d: any) => (typeof d === 'string' ? d : safeStringify(d))).join(' ') : safeStringify(e.data); return ( {LEVEL_ICONS[level] ?? '●'} )} trailingMetadata={( {new Date(e.timestamp).toLocaleTimeString()} )} /> ); } if (entry.type === 'native_logs') { const level = e.level ?? 'unknown'; const source = [e.platform, e.source, e.tag].filter(Boolean).join(' / '); return ( {String(level).slice(0, 1).toUpperCase()} {!!source && {source}} )} trailingMetadata={( {new Date(e.timestamp).toLocaleTimeString()} )} /> ); } if (entry.type === 'network_logs') { const method = e.request?.method ?? '?'; const url = e.request?.url ?? ''; const status = e.response?.status; const ok = !e.error && (!status || status < 400); return ( {method} {status != null && ( {status} )} )} trailingMetadata={( {new Date(e.timestamp).toLocaleTimeString()} )} /> ); } // track_logs const name = e.eventName ?? e.action ?? 'Event'; return ( } trailingMetadata={( {e.timestamp ? new Date(e.timestamp).toLocaleTimeString() : ''} )} /> ); } const SessionLogRow: React.FC<{ entry: FlatSessionLogEntry }> = React.memo(({ entry }) => ( renderSessionLogRow(entry) )); // ── Log Detail Header ────────────────────────────────────────────────── const LogDetailHeader: React.FC<{ entry: FlatSessionLogEntry }> = React.memo(({ entry }) => { const e = toRecord(entry); if (entry.type === 'console_logs') { const level = e.level ?? 'log'; return ( <> {level.toUpperCase()} {new Date(e.timestamp).toLocaleString()} ); } if (entry.type === 'network_logs') { const method = e.request?.method ?? '?'; const status = e.response?.status; const ok = !e.error && (!status || status < 400); return ( {method} {status != null && ( {status} )} {e.duration != null && {e.duration}ms} ); } return ( {new Date(e.timestamp).toLocaleString()} ); }); // ── Log Detail Body ──────────────────────────────────────────────────── const LogDetailBody: React.FC<{ entry: FlatSessionLogEntry }> = React.memo(({ entry }) => { const e = toRecord(entry); if (entry.type === 'console_logs') { const data = Array.isArray(e.data) ? e.data : [e.data]; return ( {data.map((d: any, i: number) => { const formatted = typeof d === 'object' && d !== null ? fmt(d) : String(d); return ( {typeof d === 'object' && d !== null ? ( ) : ( {String(d)} )} ); })} ); } if (entry.type === 'network_logs') { return ( {/* URL */} {e.request?.url} {/* Error */} {e.error && ( ⚠ {e.error} )} {/* Request Body */} {e.request?.body != null ? ( ) : ( {t('network.noRequestBody')} )} {/* Request Headers */} {e.request?.headers && ( )} {/* Response Body */} {e.response?.data != null ? ( ) : ( {t('network.noResponseBody')} )} {/* Response Headers */} {e.response?.headers && ( )} ); } return ( ); }); // ── Styles ───────────────────────────────────────────────────────────── const s = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.background }, scrollContent: { paddingTop: Spacing.MD, paddingBottom: 60 }, // Center (loading / empty) center: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: Colors.background, padding: 32 }, emptyClock: { width: 64, height: 64, borderRadius: 32, backgroundColor: Colors.surface, alignItems: 'center', justifyContent: 'center', borderWidth: 1, borderColor: Colors.border, marginBottom: Spacing.LG, }, emptyClockText: { fontSize: 28 }, emptyTitle: { fontSize: FontSize.LG, fontWeight: FontWeight.semibold, color: Colors.text, marginBottom: Spacing.XS }, emptySub: { fontSize: FontSize.MD, color: Colors.textSecondary, textAlign: 'center', lineHeight: 20 }, // Current session currentCard: { backgroundColor: Colors.primary, marginHorizontal: Spacing.LG, borderRadius: Radius.XL, padding: Spacing.LG, marginBottom: Spacing.XL, }, currentRow: { flexDirection: 'row', alignItems: 'center', marginBottom: Spacing.XS }, pulseDot: { width: 8, height: 8, borderRadius: 4, backgroundColor: Colors.success, marginRight: Spacing.SM }, currentLabel: { fontSize: FontSize.XS, fontWeight: FontWeight.bold, color: 'rgba(255,255,255,0.7)', letterSpacing: 0.8 }, currentTime: { fontSize: FontSize.LG, color: Colors.textInverse, fontWeight: FontWeight.medium }, // Timeline timelineSection: { paddingHorizontal: Spacing.LG }, timelineHeader: { fontSize: FontSize.XS, fontWeight: FontWeight.bold, color: Colors.textMuted, letterSpacing: 0.8, marginBottom: Spacing.MD }, timelineRow: { flexDirection: 'row' }, railCol: { width: 24, alignItems: 'center', paddingTop: Spacing.MD }, railDot: { width: 10, height: 10, borderRadius: 5, backgroundColor: Colors.surface, borderWidth: 2, borderColor: Colors.textMuted, zIndex: 1, }, railLine: { width: 2, flex: 1, backgroundColor: Colors.border, marginTop: -1 }, historyCard: { flex: 1, backgroundColor: Colors.surface, borderRadius: Radius.LG, padding: Spacing.MD, marginBottom: Spacing.SM, marginLeft: Spacing.SM, }, cardTop: { flexDirection: 'row', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: Spacing.SM }, cardTime: { fontSize: FontSize.LG, fontWeight: FontWeight.semibold, color: Colors.text }, cardRelative: { fontSize: FontSize.SM, color: Colors.textSecondary }, cardEmpty: { fontSize: FontSize.SM, color: Colors.textMuted, marginBottom: Spacing.XXS }, pillRow: { flexDirection: 'row', flexWrap: 'wrap', gap: Spacing.XS, marginBottom: Spacing.SM }, pill: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: Spacing.SM, paddingVertical: Spacing.XXS, borderRadius: Radius.SM }, pillDot: { width: 6, height: 6, borderRadius: 3, marginRight: Spacing.XS }, pillText: { fontSize: FontSize.XS, fontWeight: FontWeight.semibold }, cardFooter: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: Spacing.XXS }, cardId: { fontSize: FontSize.XS, color: Colors.textMuted, fontFamily: 'Courier', fontWeight: FontWeight.medium }, cardChevron: { fontSize: FontSize.XL, color: Colors.textMuted, fontWeight: FontWeight.regular }, // ── Session detail header ── sessionHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: Spacing.LG, paddingVertical: Spacing.SM, backgroundColor: Colors.surface, borderBottomWidth: 1, borderBottomColor: Colors.borderLight, }, headerBackBtn: { flexDirection: 'row', alignItems: 'center', paddingVertical: Spacing.XXS }, headerArrow: { fontSize: FontSize.XL, color: Colors.primary, fontWeight: FontWeight.regular, marginRight: Spacing.XXS }, headerBackLabel: { fontSize: FontSize.LG, color: Colors.primary, fontWeight: FontWeight.semibold }, headerMeta: { fontSize: FontSize.XS, color: Colors.textSecondary, fontFamily: 'Courier' }, // ── Filter bar ── filterBar: { flexDirection: 'row', paddingHorizontal: Spacing.MD, paddingVertical: Spacing.SM, backgroundColor: Colors.background, gap: Spacing.XS, }, chip: { paddingHorizontal: Spacing.MD, paddingVertical: Spacing.XS, borderRadius: Radius.MD, backgroundColor: Colors.surface }, chipLabel: { fontSize: FontSize.SM, fontWeight: FontWeight.medium, color: Colors.textSecondary }, chipLabelActive: { color: Colors.textInverse }, chipCount: { fontSize: FontSize.XS, fontWeight: FontWeight.semibold, color: Colors.textMuted }, chipCountActive: { color: 'rgba(255,255,255,0.8)' }, // ── Log rows (inside LogListScreen cards) ── levelDot: { width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center', }, levelIcon: { color: Colors.textInverse, fontSize: FontSize.XS, fontWeight: FontWeight.bold }, statusDot: { width: 8, height: 8, borderRadius: 4 }, rowMsg: { fontSize: FontSize.MD, color: Colors.text, lineHeight: 20 }, rowTime: { fontSize: FontSize.XS, color: Colors.textSecondary }, rowSource: { fontSize: FontSize.XS, color: Colors.textSecondary }, methodText: { fontSize: FontSize.SM, fontWeight: FontWeight.bold }, miniPill: { paddingHorizontal: Spacing.SM, paddingVertical: Spacing.XXS, borderRadius: Radius.XS }, miniPillText: { color: Colors.textInverse, fontSize: FontSize.XXS, fontWeight: FontWeight.bold }, trackDot: { width: 10, height: 10, borderRadius: 5, backgroundColor: Colors.primary }, // ── Log detail header ── levelBadge: { paddingHorizontal: Spacing.MD, paddingVertical: Spacing.XXS, borderRadius: Radius.SM }, levelBadgeText: { color: Colors.textInverse, fontSize: FontSize.SM, fontWeight: FontWeight.bold }, detailTimestamp: { flex: 1, fontSize: FontSize.SM, color: Colors.textSecondary, textAlign: 'right' }, networkHeaderBadges: { flexDirection: 'row', alignItems: 'center', gap: Spacing.SM, flex: 1 }, methodBadge: { paddingHorizontal: Spacing.MD, paddingVertical: Spacing.XXS, borderRadius: Radius.SM }, methodBadgeText: { color: Colors.textInverse, fontSize: FontSize.SM, fontWeight: FontWeight.bold }, statusPill: { paddingHorizontal: Spacing.SM, paddingVertical: Spacing.XXS, borderRadius: Radius.SM }, statusPillText: { color: Colors.textInverse, fontSize: FontSize.XS, fontWeight: FontWeight.bold }, durationText: { fontSize: FontSize.XS, color: Colors.textSecondary, fontWeight: FontWeight.medium }, // ── Log detail body ── detailBody: { flex: 1 }, detailBodyContent: { padding: Spacing.MD, paddingBottom: 40 }, sectionWithCopy: { gap: Spacing.SM }, plainText: { fontFamily: 'Courier', fontSize: FontSize.SM, color: Colors.text, lineHeight: 20 }, urlCard: { flexDirection: 'row', alignItems: 'center', backgroundColor: Colors.surface, borderRadius: Radius.LG, padding: Spacing.MD, marginBottom: Spacing.SM, gap: Spacing.SM, }, urlText: { flex: 1, fontSize: FontSize.SM, color: Colors.textSecondary, lineHeight: 18 }, emptySection: { fontSize: FontSize.SM, color: Colors.textMuted, paddingVertical: Spacing.XXS }, errorBox: { backgroundColor: Colors.errorDim, borderWidth: 1, borderColor: 'rgba(239,68,68,0.2)', borderRadius: Radius.LG, padding: Spacing.MD, marginBottom: Spacing.SM, flexDirection: 'row', alignItems: 'flex-start', gap: Spacing.SM, }, errorIcon: { fontSize: FontSize.MD, color: Colors.error }, errorText: { flex: 1, fontSize: FontSize.SM, color: Colors.error, lineHeight: 18 }, });