diff --git a/index.html b/index.html index e7017d7..27c31f9 100755 --- a/index.html +++ b/index.html @@ -1182,6 +1182,41 @@ display: flex; } + .thinking-loading { + color: #888; + font-size: 13px; +} + +.thinking-box { + margin-bottom: 12px; + border: 1px dashed #ddd; + border-radius: 6px; + font-size: 13px; + color: #666; +} + +.thinking-header { + padding: 6px 10px; + cursor: pointer; + background: #f7f7f7; + user-select: none; +} + +.thinking-content { + padding: 8px 10px; + line-height: 1.6; +} + +.thinking-content.collapsed { + display: none; +} + +.answer-box { + font-size: 15px; + line-height: 1.7; +} + + @media (max-width: 768px) { .popbgc { @@ -2113,7 +2148,7 @@ if (msg.image_base64) { hasImage = true; // 只要有一个不为空,就置为 true } - addMessage(msg.content, msg.role, msg.image_base64); + addMessage(msg.content, msg.role, msg.image_base64,msg.thinking); }); scrollToBottom(); } @@ -2138,89 +2173,122 @@ } } // 内容 角色 图片 创造时间 - function addMessage(content = '', role = "assistant", imgUrl = null, time = null) { + function addMessage(content = '', role = "assistant", imgUrl = null, time = null,thinking='') { const msg = document.createElement("div"); - msg.className = `message ${role}`; - if (time) { - const timeNode = document.createElement("div"); - timeNode.textContent = time; - timeNode.style.fontSize = "12px"; - timeNode.style.color = "#999"; - timeNode.style.marginTop = "4px"; - // msg.appendChild(timeNode); - } - // 如果有文字内容,先创建文字节点 - if (content) { - const textNode = document.createElement("div"); - textNode.innerHTML = marked.parse(content); - msg.appendChild(textNode); - } + msg.className = `message ${role}`; - // 如果有图片,创建图片节点 - if (imgUrl) { - const img = document.createElement("img"); - img.src = imgUrl; - img.style.marginTop = content ? "8px" : "0"; // 如果有文字,图片加一点间距 - msg.appendChild(img); - } - // 如果是 assistant,添加分享按钮 - if (role === "assistant") { - const shareSpan = document.createElement("span"); - shareSpan.style.display = "inline-flex"; - shareSpan.style.alignItems = "center"; - shareSpan.style.cursor = "pointer"; - shareSpan.style.marginTop = "8px"; - shareSpan.style.opacity = "0.75"; - shareSpan.style.transition = "opacity .2s"; - shareSpan.title = "分享"; + // ========================= + // 时间 + // ========================= + if (time) { + const timeNode = document.createElement("div"); + timeNode.textContent = time; + timeNode.style.fontSize = "12px"; + timeNode.style.color = "#999"; + timeNode.style.marginBottom = "6px"; + msg.appendChild(timeNode); + } - shareSpan.onmouseenter = () => shareSpan.style.opacity = "1"; - shareSpan.onmouseleave = () => shareSpan.style.opacity = "0.75"; + // ========================= + // 思考过程(历史:已完成) + // ========================= + let thinkingContentDiv = null; - shareSpan.innerHTML = ` - - `; + if (role === "assistant" && thinking) { + const thinkingBox = document.createElement("div"); + thinkingBox.className = "thinking-box"; - shareSpan.onclick = () => { - generatePoster(content, imgUrl); - }; + const header = document.createElement("div"); + header.className = "thinking-header"; - msg.appendChild(shareSpan); - const copySpan = document.createElement("span"); - copySpan.style.display = "inline-flex"; - copySpan.style.alignItems = "center"; - copySpan.style.cursor = "pointer"; - copySpan.style.marginTop = "8px"; - copySpan.style.marginLeft = "10px"; - copySpan.style.opacity = "0.75"; - copySpan.style.transition = "opacity .2s"; - copySpan.title = "复制内容"; + const title = document.createElement("span"); + title.className = "thinking-title"; + title.textContent = ""; - copySpan.onmouseenter = () => copySpan.style.opacity = "1"; - copySpan.onmouseleave = () => copySpan.style.opacity = "0.75"; + const status = document.createElement("span"); + status.className = "thinking-status thinking-done"; + status.textContent = "已完成思考"; - copySpan.innerHTML = ` - - `; - copySpan.onclick = async () => { - try { - await navigator.clipboard.writeText(content); - copySpan.style.opacity = "1"; - showToast("复制成功") - copySpan.title = "复制成功"; - setTimeout(() => { copySpan.title = "复制内容"; }, 1200); - } catch (err) { - alert("复制失败,可能不支持 HTTPS 环境以外复制。"); - } - }; + const toggle = document.createElement("span"); + toggle.className = "thinking-toggle"; + toggle.textContent = "▶"; - msg.appendChild(copySpan); - } + thinkingContentDiv = document.createElement("div"); + thinkingContentDiv.className = "thinking-content collapsed"; + thinkingContentDiv.innerHTML = marked.parse(thinking); - // 如果有时间,可以显示 + header.onclick = () => { + thinkingContentDiv.classList.toggle("collapsed"); + toggle.textContent = + thinkingContentDiv.classList.contains("collapsed") ? "▶" : "⌄"; + }; - chatMessages.appendChild(msg); - chatMessages.scrollTop = chatMessages.scrollHeight; + header.appendChild(title); + header.appendChild(status); + header.appendChild(toggle); + + thinkingBox.appendChild(header); + thinkingBox.appendChild(thinkingContentDiv); + msg.appendChild(thinkingBox); + } + + // ========================= + // 最终结论(answer) + // ========================= + if (content) { + const textNode = document.createElement("div"); + textNode.className = "answer-content"; + textNode.innerHTML = marked.parse(content); + msg.appendChild(textNode); + } + + // ========================= + // 图片 + // ========================= + if (imgUrl) { + const img = document.createElement("img"); + img.src = imgUrl; + img.style.marginTop = "8px"; + msg.appendChild(img); + } + + // ========================= + // assistant 工具按钮 + // ========================= + if (role === "assistant") { + const shareSpan = document.createElement("span"); + shareSpan.style.display = "inline-flex"; + shareSpan.style.alignItems = "center"; + shareSpan.style.cursor = "pointer"; + shareSpan.style.marginTop = "8px"; + shareSpan.style.opacity = "0.75"; + shareSpan.title = "分享"; + + shareSpan.innerHTML = ``; + shareSpan.onclick = () => { + generatePoster(content, imgUrl); + }; + + const copySpan = document.createElement("span"); + copySpan.style.display = "inline-flex"; + copySpan.style.alignItems = "center"; + copySpan.style.cursor = "pointer"; + copySpan.style.marginLeft = "10px"; + copySpan.style.opacity = "0.75"; + copySpan.title = "复制内容"; + + copySpan.innerHTML = ``; + copySpan.onclick = async () => { + await navigator.clipboard.writeText(content); + showToast("复制成功"); + }; + + msg.appendChild(shareSpan); + msg.appendChild(copySpan); + } + + chatMessages.appendChild(msg); + chatMessages.scrollTop = chatMessages.scrollHeight; } function generatePoster(text, imgUrl) { @@ -2367,279 +2435,212 @@ }); } let reader; - const getAiResponse = async (img) => { +const getAiResponse = async (img) => { + deleteImg(); - deleteImg(); - const aiMsg = { role: "assistant", content: "", isImage: false }; - const msgDiv = document.createElement("div"); - msgDiv.className = "message assistant"; - msgDiv.textContent = '思考中'; - let dots = 0; - const interval = setInterval(() => { - dots = (dots + 1) % 4; // 0,1,2,3 - msgDiv.textContent = '思考中' + '.'.repeat(dots); - }, 200); + // ========================= + // 消息容器 + // ========================= + const msgDiv = document.createElement("div"); + msgDiv.className = "message assistant"; + chatMessages.appendChild(msgDiv); + scrollToBottom(); - msgDiv.className = "message assistant thinking "; - chatMessages.appendChild(msgDiv); - chatMessages.scrollTop = chatMessages.scrollHeight; - sessId = sendParam.sessionId; - sendParam.imageBase64 = img; - // sendParam.userId= encodedUserId; - sendParam.userId = decodeURIComponent(Number(escape(atob(encodedUserId)))); + // ========================= + // 状态变量 + // ========================= + let currentPhase = null; + let thinkingFinished = false; + let thinkingContentDiv = null; + let answerContentDiv = null; - // ✅ 创建 AbortController - controller = new AbortController(); - // sendParam.requestId = crypto.randomUUID(); - sendParam.requestId = uuid(); + let thinkingStatusSpan = null; + let thinkingToggleSpan = null; - const res = await fetch("https://serviceai.satabot.com/analyze", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(sendParam), - signal: controller.signal, // ✅ 加上 signal - }).catch(err => { - console.log("✅ 流被中断:", err.name); - clearInterval(interval); - if (controller) { - controller.abort(); - controller = null; - } + let thinkingBuffer = ""; + let answerBuffer = ""; + // ========================= + // loading(phase 前占位) + // ========================= + const loadingDiv = document.createElement("div"); + loadingDiv.className = "thinking-loading"; + loadingDiv.textContent = "深度思考中"; + msgDiv.appendChild(loadingDiv); + // ========================= + // DOM 工具函数 + // ========================= + const ensureThinkingBox = () => { + if (thinkingContentDiv) return; + loadingDiv?.remove(); - sendBtnImg.classList.remove('none'); - stopBtn.forEach(e => { - e.classList.add('none') - }) - return null; - }); + const box = document.createElement("div"); + box.className = "thinking-box"; - console.log(res, 7665) - if (!res) { + const header = document.createElement("div"); + header.className = "thinking-header"; + const title = document.createElement("span"); + title.className = "thinking-title"; - if (sendBtnImg.classList.contains("none")) { - sendBtnImg.classList.remove('none'); - } - stopBtn.forEach(e => { - if (!e.classList.contains('none')) { - e.classList.add('none') - } + thinkingStatusSpan = document.createElement("span"); + thinkingStatusSpan.className = "thinking-status thinking-running"; + thinkingStatusSpan.textContent = "深度思考中"; - }) + thinkingToggleSpan = document.createElement("span"); + thinkingToggleSpan.className = "thinking-toggle"; + thinkingToggleSpan.textContent = "⌄"; - return null; - } - if (res.status === 400) { - clearInterval(interval); - if (controller) { - controller.abort(); - controller = null; - } - if (sendBtnImg.classList.contains("none")) { - sendBtnImg.classList.remove('none'); + thinkingContentDiv = document.createElement("div"); + thinkingContentDiv.className = "thinking-content"; - } - stopBtn.forEach(e => { - if (!e.classList.contains("none")) { - e.classList.add('none') - } - }) - showpop(); - return; + header.onclick = () => { + thinkingContentDiv.classList.toggle("collapsed"); + thinkingToggleSpan.textContent = + thinkingContentDiv.classList.contains("collapsed") ? "▶" : "⌄"; + }; + + header.appendChild(title); + header.appendChild(thinkingStatusSpan); + header.appendChild(thinkingToggleSpan); + + box.appendChild(header); + box.appendChild(thinkingContentDiv); + msgDiv.appendChild(box); + }; + + const ensureAnswerBox = () => { + if (answerContentDiv) return; + + const box = document.createElement("answer-box"); + answerContentDiv = document.createElement("div"); + answerContentDiv.className = "answer-content"; + box.appendChild(answerContentDiv); + msgDiv.appendChild(box); + }; + + // ========================= + // 请求参数 + // ========================= + sessId = sendParam.sessionId; + sendParam.imageBase64 = img; + sendParam.userId = decodeURIComponent(Number(escape(atob(encodedUserId)))); + sendParam.requestId = uuid(); + + controller = new AbortController(); + + let res; + try { + res = await fetch("https://serviceai.satabot.com/analyze", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(sendParam), + signal: controller.signal, + }); + } catch (err) { + loadingDiv.textContent = "请求中断"; + return; + } + + if (!res?.body) { + loadingDiv.textContent = "无响应"; + return; + } + + // ========================= + // SSE 读取 + // ========================= + const reader = res.body.getReader(); + const decoder = new TextDecoder("utf-8"); + let buffer = ""; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop(); + + for (let line of lines) { + line = line.trim(); + if (!line.startsWith("data:")) continue; + + const data = line.slice(5).trim(); + if (data === "[DONE]") { + scrollToBottom(); + controller = null; + return; + } + + let obj; + try { + obj = JSON.parse(data); + } catch { + continue; + } + + // ========================= + // phase + // ========================= + if (obj.type === "phase") { + currentPhase = obj.content; + + if (currentPhase === "thinking") { + ensureThinkingBox(); } - - sendParam.imageBase64 = ''; - - reader = res.body.getReader(); - const decoder = new TextDecoder("utf-8"); - let buffer = ""; - msgDiv.classList.remove("thinking"); - showPop(userId); - clearInterval(interval); - console.log(isStopped, '是否点击停止') - - while (true) { - console.log("回答") - let result; - try { - result = await reader.read(); - } catch (e) { - console.log("流已中断:", e); - break; // ← 必须退出循环 - } - - const { done, value } = result; - if (done) { - controller = null; - - sendBtnImg.classList.add('none'); - stopBtn.forEach(e => { - e.classList.remove('none') - - }) - break; - }; - buffer += decoder.decode(value, { stream: true }); - - let lines = buffer.split("\n"); - buffer = lines.pop(); - - for (let line of lines) { - line = line.trim(); - if (!line.startsWith("data:")) continue; - - const data = line.slice(5).trim(); - if (data == "[DONE]") { - console.log("完成回答"); - controller = null; - // 更新聊天滚动条 - - sendBtnImg.classList.remove('none'); - stopBtn.forEach(e => { - e.classList.add('none') - - }) - // renderChatList(); - msgDiv.innerHTML = marked.parse(aiMsg.content); - // const shareSpan = document.createElement("span"); - // shareSpan.style.display = "inline-flex"; - // shareSpan.style.alignItems = "center"; - // shareSpan.style.cursor = "pointer"; - // shareSpan.style.marginTop = "8px"; - // shareSpan.style.opacity = "0.75"; - // shareSpan.style.transition = "opacity .2s"; - // shareSpan.title = "分享"; - - // shareSpan.onmouseenter = () => shareSpan.style.opacity = "1"; - // shareSpan.onmouseleave = () => shareSpan.style.opacity = "0.75"; - - // shareSpan.innerHTML = ` - // - // `; - - // shareSpan.onclick = () => { - // generatePoster(aiMsg.content); - // }; - - // if (role === "assistant") { - // 分享按钮 - const shareSpan = document.createElement("span"); - shareSpan.style.display = "inline-flex"; - shareSpan.style.alignItems = "center"; - shareSpan.style.cursor = "pointer"; - shareSpan.style.marginTop = "8px"; - shareSpan.style.opacity = "0.75"; - shareSpan.style.transition = "opacity .2s"; - shareSpan.title = "分享"; - - shareSpan.onmouseenter = () => shareSpan.style.opacity = "1"; - shareSpan.onmouseleave = () => shareSpan.style.opacity = "0.75"; - - shareSpan.innerHTML = ` - - `; - - - shareSpan.onclick = () => { - generatePoster(content, imgUrl); - }; - - // msg.appendChild(shareSpan); - - // ====================== - // ✅ 复制按钮(新增) - // ====================== - const copySpan = document.createElement("span"); - copySpan.style.display = "inline-flex"; - copySpan.style.alignItems = "center"; - copySpan.style.cursor = "pointer"; - copySpan.style.marginTop = "8px"; - copySpan.style.marginLeft = "10px"; - copySpan.style.opacity = "0.75"; - copySpan.style.transition = "opacity .2s"; - copySpan.title = "复制内容"; - - copySpan.onmouseenter = () => copySpan.style.opacity = "1"; - copySpan.onmouseleave = () => copySpan.style.opacity = "0.75"; - - copySpan.innerHTML = ` - - `; - - copySpan.onclick = async () => { - try { - await navigator.clipboard.writeText(content); - copySpan.style.opacity = "1"; - showToast("复制成功") - copySpan.title = "复制成功"; - setTimeout(() => { copySpan.title = "复制内容"; }, 1200); - } catch (err) { - alert("复制失败,可能不支持 HTTPS 环境以外复制。"); - } - }; - - // } - - setTimeout(() => { - msgDiv.appendChild(shareSpan); - msgDiv.appendChild(copySpan); - }, 1000) - - - console.log("shareSpan appended?", msgDiv.contains(shareSpan)); - - - scrollToBottom(); - - - return; - } - - try { - const obj = JSON.parse(data); - // 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) { - await new Promise(r => setTimeout(r, 5)); // 控制字速 - if (isStopped) return; - aiMsg.content += char; - smartRender(msgDiv, aiMsg.content); - - // msgDiv.insertAdjacentText("beforeend", char); - - // msgDiv.innerHTML = marked.parse(aiMsg.content); - - // chatMessages.scrollTop = chatMessages.scrollHeight; - // setTimeout(scrollToBottom, 0); - } - } - 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); - } + if (currentPhase === "answer") { + thinkingFinished = true; + if (thinkingStatusSpan) { + thinkingStatusSpan.textContent = "已完成思考"; + thinkingStatusSpan.classList.remove("thinking-running"); + thinkingStatusSpan.classList.add("thinking-done"); } + ensureAnswerBox(); } - }; + continue; + } + + // ========================= + // thinking 内容(不依赖 phase) + // ========================= + if (obj.type === "thinking" && obj.content) { + ensureThinkingBox(); + thinkingBuffer += obj.content; + thinkingContentDiv.innerHTML = marked.parse(thinkingBuffer); + scrollToBottom(); + } + + // ========================= + // answer 内容 + // ========================= + if (obj.type === "answer" && obj.content) { + ensureAnswerBox(); + answerBuffer += obj.content; + answerContentDiv.innerHTML = marked.parse(answerBuffer); + scrollToBottom(); + } + + // ========================= + // 标题 + // ========================= + if (obj.type === "title" && obj.content) { + const chatItem = document.querySelector( + `.chat-item[data-sessionid="${sessId}"]` + ); + if (chatItem) { + const chatTitle = chatItem.querySelector(".chat-title"); + if (chatTitle) chatTitle.textContent = obj.content; + } + } + } + } +}; + function newChat() { diff --git a/server2.js b/server2.js index bdcd11e..8ab7e88 100755 --- a/server2.js +++ b/server2.js @@ -1436,7 +1436,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => { console.log(existingTitle, rows?.[0], 9999, rows); const sessId = sessionId || Date.now().toString(); - + const MAX_HISTORY = 6; // ------------------ 获取历史对话(上下文) ------------------ const [historyRows] = await pool.query( "SELECT role, content, image_base64 FROM ai_chat_messages WHERE session_id = ? AND user_id = ? ORDER BY created_at ASC", @@ -1444,7 +1444,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => { ); // 构建历史消息数组 - const historyMessages = historyRows.map(row => { + const historyMessages = historyRows.slice(-MAX_HISTORY).map(row => { const message = { role: row.role, content: [] @@ -1532,7 +1532,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => { ]; const completion = await client.chat.completions.create({ - model: "gpt-4.1", + model: "gpt-4.1-mini", stream: true, messages: imageAnalysisMessages });