feat: 添加会话历史管理功能
- 在 AI 教练聊天界面中新增会话历史查看和选择功能,用户可以查看和选择之前的会话记录 - 实现会话删除功能,用户可以删除不需要的会话记录 - 优化历史会话的加载和展示,提升用户体验 - 更新相关样式以适应新功能的展示和交互
This commit is contained in:
@@ -4,10 +4,13 @@ import { useLocalSearchParams, useRouter } from 'expo-router';
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
|
Alert,
|
||||||
FlatList,
|
FlatList,
|
||||||
Image,
|
Image,
|
||||||
KeyboardAvoidingView,
|
KeyboardAvoidingView,
|
||||||
|
Modal,
|
||||||
Platform,
|
Platform,
|
||||||
|
ScrollView,
|
||||||
StyleSheet,
|
StyleSheet,
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
@@ -21,9 +24,11 @@ import { HeaderBar } from '@/components/ui/HeaderBar';
|
|||||||
import { Colors } from '@/constants/Colors';
|
import { Colors } from '@/constants/Colors';
|
||||||
import { useAppSelector } from '@/hooks/redux';
|
import { useAppSelector } from '@/hooks/redux';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
import { deleteConversation, getConversationDetail, listConversations, type AiConversationListItem } from '@/services/aiCoach';
|
||||||
import { loadAiCoachSessionCache, saveAiCoachSessionCache } from '@/services/aiCoachSession';
|
import { loadAiCoachSessionCache, saveAiCoachSessionCache } from '@/services/aiCoachSession';
|
||||||
import { api, getAuthToken, postTextStream } from '@/services/api';
|
import { api, getAuthToken, postTextStream } from '@/services/api';
|
||||||
import type { CheckinRecord } from '@/store/checkinSlice';
|
import type { CheckinRecord } from '@/store/checkinSlice';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
|
||||||
type Role = 'user' | 'assistant';
|
type Role = 'user' | 'assistant';
|
||||||
|
|
||||||
@@ -52,6 +57,11 @@ export default function AICoachChatScreen() {
|
|||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: `你好,我是你的普拉提教练 ${coachName}。可以向我咨询训练、体态、康复、柔韧等问题~`,
|
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 listRef = useRef<FlatList<ChatMessage>>(null);
|
||||||
const [isAtBottom, setIsAtBottom] = useState(true);
|
const [isAtBottom, setIsAtBottom] = useState(true);
|
||||||
const didInitialScrollRef = useRef(false);
|
const didInitialScrollRef = useRef(false);
|
||||||
@@ -145,6 +155,70 @@ export default function AICoachChatScreen() {
|
|||||||
.map((m) => ({ role: m.role, content: m.content }));
|
.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) {
|
async function sendStream(text: string) {
|
||||||
const tokenExists = !!getAuthToken();
|
const tokenExists = !!getAuthToken();
|
||||||
try { console.log('[AI_CHAT][ui] send start', { tokenExists, conversationId, textPreview: text.slice(0, 50) }); } catch { }
|
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()}
|
onBack={() => router.back()}
|
||||||
tone="light"
|
tone="light"
|
||||||
transparent
|
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
|
<FlatList
|
||||||
@@ -432,6 +511,53 @@ export default function AICoachChatScreen() {
|
|||||||
<Ionicons name="chevron-down" size={18} color={theme.onPrimary} />
|
<Ionicons name="chevron-down" size={18} color={theme.onPrimary} />
|
||||||
</TouchableOpacity>
|
</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>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -554,6 +680,74 @@ const styles = StyleSheet.create({
|
|||||||
shadowRadius: 4,
|
shadowRadius: 4,
|
||||||
elevation: 2,
|
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)'
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export function useCosUpload(defaultOptions?: UseCosUploadOptions) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const upload = useCallback(
|
const upload = useCallback(
|
||||||
async (file: { uri?: string; name?: string; type?: string; buffer?: any; blob?: Blob } | Blob | any, options?: UseCosUploadOptions) => {
|
async (file: { uri?: string; name?: string; type?: string; buffer?: any; blob?: Blob } | Blob | string | any, options?: UseCosUploadOptions) => {
|
||||||
const finalOptions = { ...(defaultOptions || {}), ...(options || {}) };
|
const finalOptions = { ...(defaultOptions || {}), ...(options || {}) };
|
||||||
const extGuess = (() => {
|
const extGuess = (() => {
|
||||||
const name = (file && (file.name || (file as any).filename)) || '';
|
const name = (file && (file.name || (file as any).filename)) || '';
|
||||||
@@ -31,11 +31,29 @@ export function useCosUpload(defaultOptions?: UseCosUploadOptions) {
|
|||||||
setProgress(0);
|
setProgress(0);
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
try {
|
try {
|
||||||
let body = (file as any)?.blob || (file as any)?.buffer || file;
|
let body: any = null;
|
||||||
// Expo ImagePicker 返回 { uri } 时,转换为 Blob
|
// 1) 直接可用类型:Blob 或 string
|
||||||
if (!body && (file as any)?.uri) {
|
if (typeof file === 'string') {
|
||||||
|
body = file;
|
||||||
|
} else if (typeof Blob !== 'undefined' && file instanceof Blob) {
|
||||||
|
body = file;
|
||||||
|
} else if ((file as any)?.blob && (typeof Blob === 'undefined' || (file as any).blob instanceof Blob || (file as any).blob?._data)) {
|
||||||
|
// 2) 已提供 blob 字段
|
||||||
|
body = (file as any).blob;
|
||||||
|
} else if ((file as any)?.buffer) {
|
||||||
|
// 3) ArrayBuffer/TypedArray -> Blob
|
||||||
|
const buffer = (file as any).buffer;
|
||||||
|
body = new Blob([buffer], { type: (file as any)?.type || finalOptions.contentType || 'application/octet-stream' });
|
||||||
|
} else if ((file as any)?.uri) {
|
||||||
|
// 4) Expo ImagePicker/文件:必须先转 Blob
|
||||||
const resp = await fetch((file as any).uri);
|
const resp = await fetch((file as any).uri);
|
||||||
body = await resp.blob();
|
body = await resp.blob();
|
||||||
|
} else {
|
||||||
|
// 兜底:尝试直接作为字符串,否则抛错
|
||||||
|
if (file && (typeof file === 'object')) {
|
||||||
|
throw new Error('无效的上传体:请提供 Blob/String,或包含 uri 的对象');
|
||||||
|
}
|
||||||
|
body = file;
|
||||||
}
|
}
|
||||||
const res = await uploadWithRetry({
|
const res = await uploadWithRetry({
|
||||||
key,
|
key,
|
||||||
|
|||||||
38
services/aiCoach.ts
Normal file
38
services/aiCoach.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { api } from '@/services/api';
|
||||||
|
|
||||||
|
export type AiConversationListItem = {
|
||||||
|
conversationId: string;
|
||||||
|
title?: string | null;
|
||||||
|
lastMessageAt?: string | null;
|
||||||
|
createdAt?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AiConversationListResponse = {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
items: AiConversationListItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AiConversationDetail = {
|
||||||
|
conversationId: string;
|
||||||
|
title?: string | null;
|
||||||
|
lastMessageAt?: string | null;
|
||||||
|
createdAt?: string | null;
|
||||||
|
messages: Array<{ role: 'user' | 'assistant' | 'system'; content: string; createdAt?: string | null }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listConversations(page = 1, pageSize = 20): Promise<AiConversationListResponse> {
|
||||||
|
const qs = `?page=${encodeURIComponent(page)}&pageSize=${encodeURIComponent(pageSize)}`;
|
||||||
|
return api.get<AiConversationListResponse>(`/api/ai-coach/conversations${qs}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getConversationDetail(conversationId: string): Promise<AiConversationDetail> {
|
||||||
|
return api.get<AiConversationDetail>(`/api/ai-coach/conversations/${encodeURIComponent(conversationId)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteConversation(conversationId: string): Promise<{ success: boolean }> {
|
||||||
|
return api.delete<{ success: boolean }>(`/api/ai-coach/conversations/${encodeURIComponent(conversationId)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user