76 lines
2.0 KiB
JavaScript
76 lines
2.0 KiB
JavaScript
|
|
const express = require('express');
|
|||
|
|
const router = express.Router();
|
|||
|
|
const db = require('../db');
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* GET /api/session/:id/history
|
|||
|
|
* 获取会话完整历史(用于文字↔语音切换时加载上下文)
|
|||
|
|
*/
|
|||
|
|
router.get('/:id/history', async (req, res) => {
|
|||
|
|
try {
|
|||
|
|
const { id } = req.params;
|
|||
|
|
const limit = parseInt(req.query.limit) || 20;
|
|||
|
|
const format = req.query.format || 'llm'; // 'llm' | 'full'
|
|||
|
|
|
|||
|
|
let messages;
|
|||
|
|
if (format === 'full') {
|
|||
|
|
messages = await db.getRecentMessages(id, limit);
|
|||
|
|
} else {
|
|||
|
|
messages = await db.getHistoryForLLM(id, limit);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const session = await db.getSession(id);
|
|||
|
|
|
|||
|
|
res.json({
|
|||
|
|
success: true,
|
|||
|
|
data: {
|
|||
|
|
sessionId: id,
|
|||
|
|
mode: session?.mode || null,
|
|||
|
|
messages,
|
|||
|
|
count: messages.length,
|
|||
|
|
},
|
|||
|
|
});
|
|||
|
|
} catch (err) {
|
|||
|
|
console.error('[Session] Get history failed:', err.message);
|
|||
|
|
res.status(500).json({ success: false, error: err.message });
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* POST /api/session/:id/switch
|
|||
|
|
* 切换会话模式(voice ↔ chat),返回上下文历史
|
|||
|
|
*/
|
|||
|
|
router.post('/:id/switch', async (req, res) => {
|
|||
|
|
try {
|
|||
|
|
const { id } = req.params;
|
|||
|
|
const { targetMode } = req.body; // 'voice' | 'chat'
|
|||
|
|
|
|||
|
|
if (!targetMode || !['voice', 'chat'].includes(targetMode)) {
|
|||
|
|
return res.status(400).json({ success: false, error: 'targetMode must be "voice" or "chat"' });
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 更新会话模式
|
|||
|
|
await db.updateSessionMode(id, targetMode);
|
|||
|
|
|
|||
|
|
// 返回最近的对话历史供新模式使用
|
|||
|
|
const history = await db.getHistoryForLLM(id, 20);
|
|||
|
|
|
|||
|
|
console.log(`[Session] Switched ${id} to ${targetMode}, history: ${history.length} messages`);
|
|||
|
|
|
|||
|
|
res.json({
|
|||
|
|
success: true,
|
|||
|
|
data: {
|
|||
|
|
sessionId: id,
|
|||
|
|
mode: targetMode,
|
|||
|
|
history,
|
|||
|
|
count: history.length,
|
|||
|
|
},
|
|||
|
|
});
|
|||
|
|
} catch (err) {
|
|||
|
|
console.error('[Session] Switch failed:', err.message);
|
|||
|
|
res.status(500).json({ success: false, error: err.message });
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
module.exports = router;
|