diff --git a/index.html b/index.html
index 7a0109d..a057676 100755
--- a/index.html
+++ b/index.html
@@ -192,6 +192,7 @@
flex: 1;
padding: 20px;
overflow-y: auto;
+ position: relative;
}
.message {
@@ -755,6 +756,9 @@
const params = new URLSearchParams(window.location.search);
console.log(params.get("userId"), 644);
const encodedUserId = params.get("userId");
+ const from = params.get("from");
+
+
// ✅ 先 URL 解码,再 Base64 解码,再 UTF-8 解码
const userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
@@ -871,17 +875,25 @@
function toggleSidebar() {
sidebar.classList.toggle("collapsed");
}
+ function scrollToBottom() {
+ const chatMessages = document.getElementById("chatMessages");
+ setTimeout(() => {
+ chatMessages.scrollTop = chatMessages.scrollHeight;
+ chatMessages.bottom = '0px';
+ }, 0);
+ }
+
function renderChatList(isNew) {
console.log(sessIdList);
- chatList.innerHTML = "";
+ chatList.innerHTML = '';
if (!sessIdList || sessIdList.length == 0) {
chatMessages.innerHTML = "";
return;
}
// if (isNew == "new") {
- activeChatId = sessIdList[sessIdList.length - 1];
+ activeChatId = sessIdList[sessIdList.length - 1].sessId;
// } else {
// activeChatId = sessIdList[0];
// }
@@ -891,19 +903,24 @@
console.log(item, activeChatId);
const item1 = document.createElement("div");
- item1.setAttribute("data-sessionid", item);
- item1.className = "chat-item" + (activeChatId == item ? " active" : "");
+ item1.setAttribute("data-sessionid", item.sessId);
+ item1.className = "chat-item" + (activeChatId == item.sessId ? " active" : "");
const title = document.createElement("div");
title.className = "chat-title";
- title.textContent = `新对话${index + 1}`;
- item1.onclick = () => switchChat(item);
+ if (item.title) {
+ title.textContent = item.title;
+ } else {
+ title.textContent = `新对话${index + 1}`;
+ }
+
+ item1.onclick = () => switchChat(item.sessId);
const del = document.createElement("span");
del.className = "delete-btn";
del.textContent = "✕";
del.onclick = (e) => {
e.stopPropagation();
- deleteChat(item);
+ deleteChat(item.sessId);
};
item1.appendChild(title);
item1.appendChild(del);
@@ -926,6 +943,7 @@
}
addMessage(msg.content, msg.role, msg.image_base64);
});
+ scrollToBottom();
}
// 内容 角色 图片 创造时间
function addMessage(content = '', role = "assistant", imgUrl = null, time = null) {
@@ -1050,20 +1068,39 @@
const data = line.slice(5).trim();
if (data === "[DONE]") {
// 更新聊天滚动条
- chatMessages.scrollTop = chatMessages.scrollHeight;
+ scrollToBottom();
+ // chatMessages.scrollTop = chatMessages.scrollHeight;
return;
}
try {
const obj = JSON.parse(data);
- if (obj.content) {
- // 每次追加内容到 AI 消息
- aiMsg.content += obj.content;
- msgDiv.innerHTML = marked.parse(aiMsg.content);
- // msgDiv.textContent = aiMsg.content;
- chatMessages.scrollTop = chatMessages.scrollHeight;
+ // if (obj.content && obj.type != 'title') {
+ // // 每次追加内容到 AI 消息
+ // 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);
+ 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) {
console.error("JSON parse error", data);
}
@@ -1074,7 +1111,7 @@
function newChat() {
const id = generateUniqueId16();
- sessIdList.push(id);
+ sessIdList.push({ sessId: id, title: "新对话" });
createSession(userId, id)
const chat = [{
id,
@@ -1112,7 +1149,7 @@
}).then(res => res.json()).then(data => {
if (data.code === 0) {
getSessionList();
- // renderChatList();
+ renderChatList();
console.log("删除成功:", data.message);
} else {
@@ -1217,6 +1254,12 @@
})
}
+ // sessIdList
+
+
+ function isWeChat() {
+ return /MicroMessenger/i.test(navigator.userAgent);
+ }
function getCookie(name) {
console.log(document.cookie, 8777222)
const value = `; ${document.cookie}`;
@@ -1224,25 +1267,31 @@
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
+ // gotoWeiXin();
function gotoWeiXin() {
- const appid = "wx549f4ae0f85eb3ea";
+ console.log(isWeChat(), 8888, navigator.userAgent);
+ if (isWeChat()) {
+ const appid = "wx549f4ae0f85eb3ea";
+ // 回调地址(必须和公众号后台配置的网页授权域名一致)
+ const redirect_uri = encodeURIComponent("http://ai.satabot.com/");
+ // 授权方式:snsapi_base(静默) 或 snsapi_userinfo(需要用户确认)
+ const scope = "snsapi_userinfo";
+ // 自定义参数,授权后会原样返回
+ 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`;
+ // 跳转到微信授权
+ window.location.href = authUrl;
+ }
- // 回调地址(必须和公众号后台配置的网页授权域名一致)
- const redirect_uri = encodeURIComponent("http://ai.satabot.com/");
-
- // 授权方式:snsapi_base(静默) 或 snsapi_userinfo(需要用户确认)
- const scope = "snsapi_userinfo";
-
- // 自定义参数,授权后会原样返回
- 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`;
-
- // 跳转到微信授权
- window.location.href = authUrl;
}
+ // if(from=="weixin"){
+ // gotoWeiXin();
+ // }else{
+
+ // }
+
getSessionList();
function getSessionList() {
diff --git a/server2.js b/server2.js
index 7cfcd52..7f74285 100755
--- a/server2.js
+++ b/server2.js
@@ -120,21 +120,33 @@ app.get("/sessions", async (req, res) => {
// return;
// 查该用户所有的会话,按最后活跃时间倒序
- const [rows] = await pool.query(
- `
- SELECT session_id, 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 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
+ FROM ai_chat_messages
+ WHERE user_id = ?
+ GROUP BY session_id
+ ) t ON m.session_id = t.session_id AND m.created_at = t.last_time
+ WHERE m.user_id = ?
+ ORDER BY t.last_time ASC
+ `, [userId, userId]);
res.json({
code: 0,
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)
@@ -156,7 +168,7 @@ app.get("/history", async (req, res) => {
// 查询数据库
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]
);
@@ -263,8 +275,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
console.log("analyze: ", logBody);
// console.log("analyze: ",req.body)
- if (!req.body?.userPrompt ||
- !req.body?.userId || !req.body?.sessionId)
+ if (!req.body?.userId || !req.body?.sessionId)
{
console.log("缺少必要参数");
return res.status(400).json({ error: "缺少必要参数" });
@@ -413,13 +424,42 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
res.write(
`data: ${JSON.stringify({ type: "llm", content: delta})}\n\n`
);
- }
-
+ }
+
+
// 保存 LLM 输出到数据库
- await pool.query(
- "INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)",
- [sessId, userId || null, llmText]
- );
+
+ try {
+ 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.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"));