feat: 添加会话历史管理功能

- 在 AI 教练聊天界面中新增会话历史查看和选择功能,用户可以查看和选择之前的会话记录
- 实现会话删除功能,用户可以删除不需要的会话记录
- 优化历史会话的加载和展示,提升用户体验
- 更新相关样式以适应新功能的展示和交互
This commit is contained in:
richarjiang
2025-08-14 10:15:02 +08:00
parent e3e2f1b8c6
commit 532cf251e2
3 changed files with 254 additions and 4 deletions

View File

@@ -4,10 +4,13 @@ import { useLocalSearchParams, useRouter } from 'expo-router';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
ActivityIndicator,
Alert,
FlatList,
Image,
KeyboardAvoidingView,
Modal,
Platform,
ScrollView,
StyleSheet,
Text,
TextInput,
@@ -21,9 +24,11 @@ import { HeaderBar } from '@/components/ui/HeaderBar';
import { Colors } from '@/constants/Colors';
import { useAppSelector } from '@/hooks/redux';
import { useColorScheme } from '@/hooks/useColorScheme';
import { deleteConversation, getConversationDetail, listConversations, type AiConversationListItem } from '@/services/aiCoach';
import { loadAiCoachSessionCache, saveAiCoachSessionCache } from '@/services/aiCoachSession';
import { api, getAuthToken, postTextStream } from '@/services/api';
import type { CheckinRecord } from '@/store/checkinSlice';
import dayjs from 'dayjs';
type Role = 'user' | 'assistant';
@@ -52,6 +57,11 @@ export default function AICoachChatScreen() {
role: 'assistant',
content: `你好,我是你的普拉提教练 ${coachName}。可以向我咨询训练、体态、康复、柔韧等问题~`,
}]);
const [historyVisible, setHistoryVisible] = useState(false);
const [historyLoading, setHistoryLoading] = useState(false);
const [historyPage, setHistoryPage] = useState(1);
const [historyTotal, setHistoryTotal] = useState(0);
const [historyItems, setHistoryItems] = useState<AiConversationListItem[]>([]);
const listRef = useRef<FlatList<ChatMessage>>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const didInitialScrollRef = useRef(false);
@@ -145,6 +155,70 @@ export default function AICoachChatScreen() {
.map((m) => ({ role: m.role, content: m.content }));
}
async function openHistory() {
if (isStreaming) {
try { streamAbortRef.current?.abort(); } catch { }
}
setHistoryVisible(true);
await refreshHistory(1);
}
async function refreshHistory(page = 1) {
try {
setHistoryLoading(true);
const resp = await listConversations(page, 20);
setHistoryPage(resp.page);
setHistoryTotal(resp.total);
setHistoryItems(resp.items || []);
} catch (e) {
Alert.alert('错误', (e as any)?.message || '获取会话列表失败');
} finally {
setHistoryLoading(false);
}
}
async function handleSelectConversation(id: string) {
try {
if (isStreaming) {
try { streamAbortRef.current?.abort(); } catch { }
}
const detail = await getConversationDetail(id);
if (!detail || !(detail as any).messages) {
Alert.alert('提示', '会话不存在或已删除');
return;
}
const mapped: ChatMessage[] = (detail.messages || [])
.filter((m) => m.role === 'user' || m.role === 'assistant')
.map((m, idx) => ({ id: `${m.role}_${idx}_${Date.now()}`, role: m.role as Role, content: m.content || '' }));
setConversationId(detail.conversationId);
setMessages(mapped.length ? mapped : [{ id: 'm_welcome', role: 'assistant', content: `你好,我是你的普拉提教练 ${coachName}。可以向我咨询训练、体态、康复、柔韧等问题~` }]);
setHistoryVisible(false);
setTimeout(scrollToEnd, 0);
} catch (e) {
Alert.alert('错误', (e as any)?.message || '加载会话失败');
}
}
function confirmDeleteConversation(id: string) {
Alert.alert('删除会话', '删除后将无法恢复,确定要删除该会话吗?', [
{ text: '取消', style: 'cancel' },
{
text: '删除', style: 'destructive', onPress: async () => {
try {
await deleteConversation(id);
if (conversationId === id) {
setConversationId(undefined);
setMessages([{ id: 'm_welcome', role: 'assistant', content: `你好,我是你的普拉提教练 ${coachName}。可以向我咨询训练、体态、康复、柔韧等问题~` }]);
}
await refreshHistory(historyPage);
} catch (e) {
Alert.alert('错误', (e as any)?.message || '删除失败');
}
}
}
]);
}
async function sendStream(text: string) {
const tokenExists = !!getAuthToken();
try { console.log('[AI_CHAT][ui] send start', { tokenExists, conversationId, textPreview: text.slice(0, 50) }); } catch { }
@@ -338,6 +412,11 @@ export default function AICoachChatScreen() {
onBack={() => router.back()}
tone="light"
transparent
right={(
<TouchableOpacity accessibilityRole="button" onPress={openHistory} style={[styles.backButton, { backgroundColor: 'rgba(187,242,70,0.2)' }]}>
<Ionicons name="time-outline" size={18} color={theme.onPrimary} />
</TouchableOpacity>
)}
/>
<FlatList
@@ -432,6 +511,53 @@ export default function AICoachChatScreen() {
<Ionicons name="chevron-down" size={18} color={theme.onPrimary} />
</TouchableOpacity>
)}
<Modal transparent visible={historyVisible} animationType="fade" onRequestClose={() => setHistoryVisible(false)}>
<TouchableOpacity activeOpacity={1} style={styles.modalBackdrop} onPress={() => setHistoryVisible(false)}>
<View style={[styles.modalSheet, { backgroundColor: '#FFFFFF' }]}>
<View style={styles.modalHeader}>
<Text style={styles.modalTitle}></Text>
<TouchableOpacity accessibilityRole="button" onPress={() => refreshHistory(historyPage)} style={styles.modalRefreshBtn}>
<Ionicons name="refresh" size={16} color="#192126" />
</TouchableOpacity>
</View>
{historyLoading ? (
<View style={{ paddingVertical: 20, alignItems: 'center' }}>
<ActivityIndicator />
<Text style={{ marginTop: 8, color: '#687076' }}>...</Text>
</View>
) : (
<ScrollView style={{ maxHeight: 360 }}>
{historyItems.length === 0 ? (
<Text style={{ padding: 16, color: '#687076' }}></Text>
) : (
historyItems.map((it) => (
<View key={it.conversationId} style={styles.historyRow}>
<TouchableOpacity
style={{ flex: 1 }}
onPress={() => handleSelectConversation(it.conversationId)}
>
<Text style={styles.historyTitle} numberOfLines={1}>{it.title || '未命名会话'}</Text>
<Text style={styles.historyMeta}>
{dayjs(it.lastMessageAt || it.createdAt).format('YYYY/MM/DD HH:mm')}
</Text>
</TouchableOpacity>
<TouchableOpacity accessibilityRole="button" onPress={() => confirmDeleteConversation(it.conversationId)} style={styles.historyDeleteBtn}>
<Ionicons name="trash-outline" size={16} color="#FF4444" />
</TouchableOpacity>
</View>
))
)}
</ScrollView>
)}
<View style={styles.modalFooter}>
<TouchableOpacity accessibilityRole="button" onPress={() => setHistoryVisible(false)} style={styles.modalCloseBtn}>
<Text style={{ color: '#192126', fontWeight: '600' }}></Text>
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
</Modal>
</View>
);
}
@@ -554,6 +680,74 @@ const styles = StyleSheet.create({
shadowRadius: 4,
elevation: 2,
},
modalBackdrop: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.35)',
padding: 16,
justifyContent: 'flex-end',
},
modalSheet: {
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
paddingHorizontal: 12,
paddingTop: 10,
paddingBottom: 12,
},
modalHeader: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 4,
paddingBottom: 8,
},
modalTitle: {
fontSize: 16,
fontWeight: '800',
color: '#192126',
},
modalRefreshBtn: {
width: 28,
height: 28,
borderRadius: 14,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(0,0,0,0.06)'
},
historyRow: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 10,
paddingHorizontal: 8,
borderRadius: 10,
},
historyTitle: {
fontSize: 15,
color: '#192126',
fontWeight: '600',
},
historyMeta: {
marginTop: 2,
fontSize: 12,
color: '#687076',
},
historyDeleteBtn: {
width: 28,
height: 28,
borderRadius: 14,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(255,68,68,0.08)'
},
modalFooter: {
paddingTop: 8,
alignItems: 'flex-end',
},
modalCloseBtn: {
paddingHorizontal: 14,
paddingVertical: 8,
borderRadius: 10,
backgroundColor: 'rgba(0,0,0,0.06)'
},
});