侧边标题功能完善
This commit is contained in:
85
index.html
85
index.html
@@ -192,6 +192,7 @@
|
|||||||
flex: 1;
|
flex: 1;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
.message {
|
.message {
|
||||||
@@ -755,6 +756,9 @@
|
|||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
console.log(params.get("userId"), 644);
|
console.log(params.get("userId"), 644);
|
||||||
const encodedUserId = params.get("userId");
|
const encodedUserId = params.get("userId");
|
||||||
|
const from = params.get("from");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// ✅ 先 URL 解码,再 Base64 解码,再 UTF-8 解码
|
// ✅ 先 URL 解码,再 Base64 解码,再 UTF-8 解码
|
||||||
const userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
|
const userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
|
||||||
@@ -871,17 +875,25 @@
|
|||||||
function toggleSidebar() {
|
function toggleSidebar() {
|
||||||
sidebar.classList.toggle("collapsed");
|
sidebar.classList.toggle("collapsed");
|
||||||
}
|
}
|
||||||
|
function scrollToBottom() {
|
||||||
|
const chatMessages = document.getElementById("chatMessages");
|
||||||
|
setTimeout(() => {
|
||||||
|
chatMessages.scrollTop = chatMessages.scrollHeight;
|
||||||
|
chatMessages.bottom = '0px';
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function renderChatList(isNew) {
|
function renderChatList(isNew) {
|
||||||
console.log(sessIdList);
|
console.log(sessIdList);
|
||||||
chatList.innerHTML = "";
|
chatList.innerHTML = '';
|
||||||
|
|
||||||
if (!sessIdList || sessIdList.length == 0) {
|
if (!sessIdList || sessIdList.length == 0) {
|
||||||
chatMessages.innerHTML = "";
|
chatMessages.innerHTML = "";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// if (isNew == "new") {
|
// if (isNew == "new") {
|
||||||
activeChatId = sessIdList[sessIdList.length - 1];
|
activeChatId = sessIdList[sessIdList.length - 1].sessId;
|
||||||
// } else {
|
// } else {
|
||||||
// activeChatId = sessIdList[0];
|
// activeChatId = sessIdList[0];
|
||||||
// }
|
// }
|
||||||
@@ -891,19 +903,24 @@
|
|||||||
console.log(item, activeChatId);
|
console.log(item, activeChatId);
|
||||||
|
|
||||||
const item1 = document.createElement("div");
|
const item1 = document.createElement("div");
|
||||||
item1.setAttribute("data-sessionid", item);
|
item1.setAttribute("data-sessionid", item.sessId);
|
||||||
item1.className = "chat-item" + (activeChatId == item ? " active" : "");
|
item1.className = "chat-item" + (activeChatId == item.sessId ? " active" : "");
|
||||||
const title = document.createElement("div");
|
const title = document.createElement("div");
|
||||||
title.className = "chat-title";
|
title.className = "chat-title";
|
||||||
|
if (item.title) {
|
||||||
|
title.textContent = item.title;
|
||||||
|
} else {
|
||||||
title.textContent = `新对话${index + 1}`;
|
title.textContent = `新对话${index + 1}`;
|
||||||
item1.onclick = () => switchChat(item);
|
}
|
||||||
|
|
||||||
|
item1.onclick = () => switchChat(item.sessId);
|
||||||
|
|
||||||
const del = document.createElement("span");
|
const del = document.createElement("span");
|
||||||
del.className = "delete-btn";
|
del.className = "delete-btn";
|
||||||
del.textContent = "✕";
|
del.textContent = "✕";
|
||||||
del.onclick = (e) => {
|
del.onclick = (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
deleteChat(item);
|
deleteChat(item.sessId);
|
||||||
};
|
};
|
||||||
item1.appendChild(title);
|
item1.appendChild(title);
|
||||||
item1.appendChild(del);
|
item1.appendChild(del);
|
||||||
@@ -926,6 +943,7 @@
|
|||||||
}
|
}
|
||||||
addMessage(msg.content, msg.role, msg.image_base64);
|
addMessage(msg.content, msg.role, msg.image_base64);
|
||||||
});
|
});
|
||||||
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
// 内容 角色 图片 创造时间
|
// 内容 角色 图片 创造时间
|
||||||
function addMessage(content = '', role = "assistant", imgUrl = null, time = null) {
|
function addMessage(content = '', role = "assistant", imgUrl = null, time = null) {
|
||||||
@@ -1050,20 +1068,39 @@
|
|||||||
const data = line.slice(5).trim();
|
const data = line.slice(5).trim();
|
||||||
if (data === "[DONE]") {
|
if (data === "[DONE]") {
|
||||||
// 更新聊天滚动条
|
// 更新聊天滚动条
|
||||||
chatMessages.scrollTop = chatMessages.scrollHeight;
|
scrollToBottom();
|
||||||
|
// chatMessages.scrollTop = chatMessages.scrollHeight;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const obj = JSON.parse(data);
|
const obj = JSON.parse(data);
|
||||||
if (obj.content) {
|
// if (obj.content && obj.type != 'title') {
|
||||||
// 每次追加内容到 AI 消息
|
// // 每次追加内容到 AI 消息
|
||||||
aiMsg.content += obj.content;
|
// aiMsg.content += obj.content;
|
||||||
|
// msgDiv.innerHTML = marked.parse(aiMsg.content);
|
||||||
|
// // msgDiv.textContent = aiMsg.content;
|
||||||
|
// chatMessages.scrollTop = chatMessages.scrollHeight;
|
||||||
|
// }
|
||||||
|
if (obj.content && obj.type !== "title") {
|
||||||
|
for (const char of obj.content) {
|
||||||
|
aiMsg.content += char;
|
||||||
msgDiv.innerHTML = marked.parse(aiMsg.content);
|
msgDiv.innerHTML = marked.parse(aiMsg.content);
|
||||||
// msgDiv.textContent = aiMsg.content;
|
|
||||||
chatMessages.scrollTop = chatMessages.scrollHeight;
|
chatMessages.scrollTop = chatMessages.scrollHeight;
|
||||||
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if (obj.content && obj.type == 'title') {
|
||||||
|
const chatItem = document.querySelector(`.chat-item[data-sessionid="${sessId}"]`);
|
||||||
|
if (chatItem) {
|
||||||
|
const chatTitle = chatItem.querySelector('.chat-title');
|
||||||
|
if (chatTitle) {
|
||||||
|
chatTitle.textContent = obj.content; // 设置标题
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("JSON parse error", data);
|
console.error("JSON parse error", data);
|
||||||
}
|
}
|
||||||
@@ -1074,7 +1111,7 @@
|
|||||||
|
|
||||||
function newChat() {
|
function newChat() {
|
||||||
const id = generateUniqueId16();
|
const id = generateUniqueId16();
|
||||||
sessIdList.push(id);
|
sessIdList.push({ sessId: id, title: "新对话" });
|
||||||
createSession(userId, id)
|
createSession(userId, id)
|
||||||
const chat = [{
|
const chat = [{
|
||||||
id,
|
id,
|
||||||
@@ -1112,7 +1149,7 @@
|
|||||||
}).then(res => res.json()).then(data => {
|
}).then(res => res.json()).then(data => {
|
||||||
if (data.code === 0) {
|
if (data.code === 0) {
|
||||||
getSessionList();
|
getSessionList();
|
||||||
// renderChatList();
|
renderChatList();
|
||||||
|
|
||||||
console.log("删除成功:", data.message);
|
console.log("删除成功:", data.message);
|
||||||
} else {
|
} else {
|
||||||
@@ -1217,6 +1254,12 @@
|
|||||||
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
// sessIdList
|
||||||
|
|
||||||
|
|
||||||
|
function isWeChat() {
|
||||||
|
return /MicroMessenger/i.test(navigator.userAgent);
|
||||||
|
}
|
||||||
function getCookie(name) {
|
function getCookie(name) {
|
||||||
console.log(document.cookie, 8777222)
|
console.log(document.cookie, 8777222)
|
||||||
const value = `; ${document.cookie}`;
|
const value = `; ${document.cookie}`;
|
||||||
@@ -1224,25 +1267,31 @@
|
|||||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
// gotoWeiXin();
|
||||||
function gotoWeiXin() {
|
function gotoWeiXin() {
|
||||||
|
console.log(isWeChat(), 8888, navigator.userAgent);
|
||||||
|
if (isWeChat()) {
|
||||||
const appid = "wx549f4ae0f85eb3ea";
|
const appid = "wx549f4ae0f85eb3ea";
|
||||||
|
|
||||||
// 回调地址(必须和公众号后台配置的网页授权域名一致)
|
// 回调地址(必须和公众号后台配置的网页授权域名一致)
|
||||||
const redirect_uri = encodeURIComponent("http://ai.satabot.com/");
|
const redirect_uri = encodeURIComponent("http://ai.satabot.com/");
|
||||||
|
|
||||||
// 授权方式:snsapi_base(静默) 或 snsapi_userinfo(需要用户确认)
|
// 授权方式:snsapi_base(静默) 或 snsapi_userinfo(需要用户确认)
|
||||||
const scope = "snsapi_userinfo";
|
const scope = "snsapi_userinfo";
|
||||||
|
|
||||||
// 自定义参数,授权后会原样返回
|
// 自定义参数,授权后会原样返回
|
||||||
const state = "123";
|
const state = "123";
|
||||||
|
|
||||||
// 拼接完整的授权链接
|
// 拼接完整的授权链接
|
||||||
const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
|
const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
|
||||||
|
|
||||||
// 跳转到微信授权
|
// 跳转到微信授权
|
||||||
window.location.href = authUrl;
|
window.location.href = authUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// if(from=="weixin"){
|
||||||
|
// gotoWeiXin();
|
||||||
|
// }else{
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
||||||
getSessionList();
|
getSessionList();
|
||||||
function getSessionList() {
|
function getSessionList() {
|
||||||
|
|
||||||
|
|||||||
110
server2.js
110
server2.js
@@ -120,21 +120,33 @@ app.get("/sessions", async (req, res) => {
|
|||||||
|
|
||||||
// return;
|
// return;
|
||||||
// 查该用户所有的会话,按最后活跃时间倒序
|
// 查该用户所有的会话,按最后活跃时间倒序
|
||||||
const [rows] = await pool.query(
|
// const [rows] = await pool.query(
|
||||||
`
|
// `
|
||||||
|
// SELECT session_id,title,MAX(created_at) AS last_time
|
||||||
|
// FROM ai_chat_messages
|
||||||
|
// WHERE user_id = ?
|
||||||
|
// GROUP BY session_id
|
||||||
|
// ORDER BY last_time DESC
|
||||||
|
// `,
|
||||||
|
// [userId]
|
||||||
|
// );
|
||||||
|
const [rows] = await pool.query(`
|
||||||
|
SELECT m.session_id, m.title
|
||||||
|
FROM ai_chat_messages m
|
||||||
|
INNER JOIN (
|
||||||
SELECT session_id, MAX(created_at) AS last_time
|
SELECT session_id, MAX(created_at) AS last_time
|
||||||
FROM ai_chat_messages
|
FROM ai_chat_messages
|
||||||
WHERE user_id = ?
|
WHERE user_id = ?
|
||||||
GROUP BY session_id
|
GROUP BY session_id
|
||||||
ORDER BY last_time DESC
|
) t ON m.session_id = t.session_id AND m.created_at = t.last_time
|
||||||
`,
|
WHERE m.user_id = ?
|
||||||
[userId]
|
ORDER BY t.last_time ASC
|
||||||
);
|
`, [userId, userId]);
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
code: 0,
|
code: 0,
|
||||||
userId,
|
userId,
|
||||||
sessions: rows.map((r) => r.session_id), // 只返回 session_id 列表
|
sessions: rows.map((r) => ({ sessId: r.session_id, title: r.title })), // 只返回 session_id 列表
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err)
|
||||||
@@ -156,7 +168,7 @@ app.get("/history", async (req, res) => {
|
|||||||
|
|
||||||
// 查询数据库
|
// 查询数据库
|
||||||
const [rows] = await pool.query(
|
const [rows] = await pool.query(
|
||||||
"SELECT user_id, role, content, image_base64, created_at FROM ai_chat_messages WHERE session_id = ? ORDER BY id ASC",
|
"SELECT user_id, role, content, image_base64, created_at,title FROM ai_chat_messages WHERE session_id = ? ORDER BY id ASC",
|
||||||
[sessionId]
|
[sessionId]
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -263,8 +275,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
console.log("analyze: ", logBody);
|
console.log("analyze: ", logBody);
|
||||||
|
|
||||||
// console.log("analyze: ",req.body)
|
// console.log("analyze: ",req.body)
|
||||||
if (!req.body?.userPrompt ||
|
if (!req.body?.userId || !req.body?.sessionId)
|
||||||
!req.body?.userId || !req.body?.sessionId)
|
|
||||||
{
|
{
|
||||||
console.log("缺少必要参数");
|
console.log("缺少必要参数");
|
||||||
return res.status(400).json({ error: "缺少必要参数" });
|
return res.status(400).json({ error: "缺少必要参数" });
|
||||||
@@ -415,12 +426,41 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 保存 LLM 输出到数据库
|
// 保存 LLM 输出到数据库
|
||||||
await pool.query(
|
|
||||||
"INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)",
|
try {
|
||||||
[sessId, userId || null, llmText]
|
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
|
||||||
|
用户问题: ${userPrompt}
|
||||||
|
AI回答: ${llmText}`;
|
||||||
|
|
||||||
|
const titleResp = await client1.chat.completions.create({
|
||||||
|
model: "gpt-5-mini",
|
||||||
|
messages: [
|
||||||
|
{ role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
|
||||||
|
{ role: "user", content: titlePrompt }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
|
||||||
|
res.write(
|
||||||
|
`data: ${JSON.stringify({ type: "title", content: title })}\n\n`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
console.log("生成的标题:", title);
|
||||||
|
|
||||||
|
// 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
|
||||||
|
await pool.query(
|
||||||
|
"INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
|
||||||
|
[sessId, userId || null, llmText,title]
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error("生成标题失败:", err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
res.write("data: [DONE]\n\n");
|
res.write("data: [DONE]\n\n");
|
||||||
res.end();
|
res.end();
|
||||||
|
|
||||||
@@ -439,6 +479,50 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
const APPID = "wx549f4ae0f85eb3ea";
|
||||||
|
const APPSECRET = "你的公众号APPSECRET";
|
||||||
|
|
||||||
|
// 获取微信授权回调接口
|
||||||
|
app.get("/callback", async (req, res) => {
|
||||||
|
const code = req.query.code;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 用 code 换 openid
|
||||||
|
const resp = await axios.get("https://api.weixin.qq.com/sns/oauth2/access_token", {
|
||||||
|
params: {
|
||||||
|
appid: APPID,
|
||||||
|
secret: APPSECRET,
|
||||||
|
code: code,
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = resp.data;
|
||||||
|
console.log("微信授权返回:", data);
|
||||||
|
|
||||||
|
if (data.openid) {
|
||||||
|
res.json({
|
||||||
|
code: 0,
|
||||||
|
openid:data.openid
|
||||||
|
})
|
||||||
|
// 判断数据库里是否已经有这个 openid
|
||||||
|
// 没有 → 注册;有 → 登录
|
||||||
|
// res.send(`授权成功,openid: ${data.openid}`);
|
||||||
|
} else {
|
||||||
|
res.json({
|
||||||
|
code: 500,
|
||||||
|
msg:"微信授权失败"+ JSON.stringify(data)
|
||||||
|
})
|
||||||
|
// res.send("授权失败: " + JSON.stringify(data));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
res.send("服务器错误");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 静态文件服务
|
// 静态文件服务
|
||||||
app.use("/uploads", express.static("uploads"));
|
app.use("/uploads", express.static("uploads"));
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user