diff --git a/.gitignore b/.gitignore index f45dd04..f9cb6e4 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,10 @@ config/shops.json config/shops/ config/mail.json +# 本机登录态与界面状态,不进仓库 +config/auth.json +config/ui.json + # Optional local runtime files. *.pid diff --git a/extension/content.js b/extension/content.js index a585151..fab527b 100644 --- a/extension/content.js +++ b/extension/content.js @@ -11,6 +11,8 @@ const IMAGE_BURST_MAX_ROUNDS = 4; // 纯图片会话在该时长内只确认一次,100 张图也不会刷出上百条回复 const IMAGE_ACK_COOLDOWN_MS = 60000; + // 「已回复」分组里的会话(常见于别人转接过来的)确认过一次后,短时间内不再重复打开 + const ANSWERED_QUIET_MS = 60000; const selectors = { urgentLists: ["ul.five-minute", "ul.timeout-unreply"], @@ -26,6 +28,12 @@ paused: false, minimized: false, configOpen: false, + // 人工介入时是否自动回退到调试模式,以及按什么信号判定 + humanFallback: true, + humanFallbackTrigger: "both", // send=只看人工发送,input=只看人工输入/点输入框,both=两者 + // 本软件正在往输入框写内容时为 true,用来忽略自己产生的事件 + writingReply: false, + lastFilledText: "", processing: false, serverBase: DEFAULT_SERVER_BASE, shopId: "default", @@ -52,10 +60,18 @@ position: { right: 18, bottom: 18 }, manualConversationKeys: new Set(), cardOnlyConversationKeys: new Set(), + // 已回复分组里的会话:key -> 冷却截止时间,避免反复打开同一会话 + answeredQuietUntil: new Map(), + // 确认没有新买家消息的会话:会话标识 -> 上次处理时的消息预览,预览没变就不必再点开 + handledConversationSnapshot: new Map(), + // 会话标识 -> 已回复过的买家消息指纹,避免同一批消息被反复回复 + repliedBuyerFingerprint: new Map(), + duplicateLogAt: 0, logLines: [], // 归档设置从本地服务拉取(模型页改完立即生效,不用重建 EXE) runtime: { historyLimit: 6, + historyAll: false, imageOutputDir: "", imageSaveEnabled: true, imageAssignMode: "hybrid", @@ -63,6 +79,10 @@ imageBatchGapMs: 180000, imageHistoryLeadMs: 600000, imageCountCheck: true, + // 商品关键词固定张数:每行「关键词 = 张数」,命中后整单按固定值校验 + imageKeywordFixedCount: "", + // 买家以文件形式(如 001.jpg)发送的图片也按聊天图片识别 + imageFileAsImage: true, imageReviewEnabled: true, imageKeepOrderTab: true, // 数量不符时是否给买家回复差值(文案可配置) @@ -88,6 +108,8 @@ // 切换页签/页面时的随机等待区间(毫秒) minPageDelayMs: 150, maxPageDelayMs: 400, + // 个人订单缓存时长(毫秒),0 表示每轮都重读 + orderCacheMs: 300000, // 参与归属与模型上下文的订单状态(正常/已完成/退款售后) orderStatusNormal: true, orderStatusDone: true, @@ -101,6 +123,11 @@ greetedOrders: new Set(), // 仅图片会话最近一次确认回复的时间,避免连发图片时反复回复 imageAckAt: new Map(), + // 人工回复检测:会话标识 -> 本软件成功发出去的文字 + ownTexts: new Map(), + // 会话标识 -> 上次看到的客服侧消息,用来判断有没有新的人工回复 + lastSysSeen: new Map(), + currentConversationIdentity: "", imageAckLogAt: 0, // 图片数量不符时待回复买家的差值通知 receiptNotes: [], @@ -113,6 +140,8 @@ lastAdjustReply: null, // 当前这一轮处理的日志与对话,结束后按「日期/店铺/用户」落盘 activeRunLog: null, + // 订单面板缓存:避免每轮都切换右侧页签造成闪动 + orderCache: null, archivedImageUrls: new Set() }; @@ -155,6 +184,7 @@ resetConfigDraftFromState(); buildWidget(); renderWidget(); + attachHumanInputWatch(); startWatching(); startRemoteControlPolling(); log("助手已启动,正在监听新会话。"); @@ -166,6 +196,10 @@ if (!raw) return; const saved = JSON.parse(raw); if (saved.mode === "debug" || saved.mode === "auto") state.mode = saved.mode; + if (typeof saved.humanFallback === "boolean") state.humanFallback = saved.humanFallback; + if (["send", "input", "both"].includes(saved.humanFallbackTrigger)) { + state.humanFallbackTrigger = saved.humanFallbackTrigger; + } if (typeof saved.paused === "boolean") state.paused = saved.paused; if (typeof saved.minimized === "boolean") state.minimized = saved.minimized; if (typeof saved.configOpen === "boolean") state.configOpen = saved.configOpen; @@ -188,6 +222,8 @@ STORE_KEY, JSON.stringify({ mode: state.mode, + humanFallback: state.humanFallback, + humanFallbackTrigger: state.humanFallbackTrigger, paused: state.paused, minimized: state.minimized, configOpen: state.configOpen, @@ -306,6 +342,42 @@ ui.shopNameInput = createConfigInput("店铺名", "汉鼎主店", "text", "shopName"); ui.shopTokenInput = createConfigInput("店铺Token", "与服务端 shops.json 一致", "password", "shopToken"); + // 人工介入自动回退:开关 + 判定依据,用户可自由选择 + ui.humanFallbackRow = document.createElement("label"); + ui.humanFallbackRow.className = "pdd-ra-field"; + ui.humanFallbackHint = document.createElement("span"); + ui.humanFallbackHint.textContent = "人工介入时回退调试模式"; + ui.humanFallbackCheck = document.createElement("input"); + ui.humanFallbackCheck.type = "checkbox"; + ui.humanFallbackCheck.addEventListener("change", () => { + state.humanFallback = ui.humanFallbackCheck.checked; + saveState(); + log(`已${state.humanFallback ? "开启" : "关闭"}人工介入自动回退调试模式。`); + }); + ui.humanFallbackRow.append(ui.humanFallbackHint, ui.humanFallbackCheck); + + ui.humanTriggerRow = document.createElement("label"); + ui.humanTriggerRow.className = "pdd-ra-field"; + ui.humanTriggerLabel = document.createElement("span"); + ui.humanTriggerLabel.textContent = "人工介入判定"; + ui.humanTriggerSelect = document.createElement("select"); + [ + { value: "send", label: "仅人工发送消息" }, + { value: "input", label: "仅人工输入/点输入框" }, + { value: "both", label: "发送或输入都算" } + ].forEach((option) => { + const item = document.createElement("option"); + item.value = option.value; + item.textContent = option.label; + ui.humanTriggerSelect.append(item); + }); + ui.humanTriggerSelect.addEventListener("change", () => { + state.humanFallbackTrigger = ui.humanTriggerSelect.value; + saveState(); + log(`人工介入判定已改为:${ui.humanTriggerSelect.selectedOptions[0]?.textContent || ""}。`); + }); + ui.humanTriggerRow.append(ui.humanTriggerLabel, ui.humanTriggerSelect); + ui.saveConfigBtn = document.createElement("button"); ui.saveConfigBtn.className = "pdd-ra-button is-primary"; ui.saveConfigBtn.type = "button"; @@ -317,6 +389,8 @@ ui.shopIdInput.wrapper, ui.shopNameInput.wrapper, ui.shopTokenInput.wrapper, + ui.humanFallbackRow, + ui.humanTriggerRow, ui.saveConfigBtn ); @@ -474,6 +548,8 @@ syncInputValue(ui.shopIdInput.input, state.configDraft.shopId); syncInputValue(ui.shopNameInput.input, state.configDraft.shopName); syncInputValue(ui.shopTokenInput.input, state.configDraft.shopToken); + if (ui.humanFallbackCheck) ui.humanFallbackCheck.checked = Boolean(state.humanFallback); + if (ui.humanTriggerSelect) ui.humanTriggerSelect.value = state.humanFallbackTrigger; } function syncInputValue(input, value) { @@ -650,8 +726,9 @@ async function checkForNewConversation() { if (state.paused || state.processing) return; - const row = findFirstUrgentConversation(); - if (!row) return; + const candidate = findFirstUrgentConversation(); + if (!candidate) return; + const row = candidate.row; state.processing = true; const runId = ++state.runId; @@ -659,6 +736,7 @@ state.activeAbortController = abortController; // 每轮处理单独记录,结束后写入「日期/店铺/用户」目录,方便按用户复盘 state.currentConversationKey = getConversationKey(row); + state.currentConversationIdentity = getConversationIdentity(row); state.activeRunLog = { key: state.currentConversationKey, user: conversationDisplayName(row, state.currentConversationKey), @@ -682,7 +760,7 @@ await waitForStableChat(beforeChatSignature, row); ensureTaskActive(runId); - const payload = await buildConversationPayload(); + let payload = await buildConversationPayload(); if (state.activeRunLog && Array.isArray(payload?.msgList)) { state.activeRunLog.messages = payload.msgList.map((item) => ({ usertype: item.usertype, @@ -691,6 +769,21 @@ })); state.activeRunLog.orderCount = Array.isArray(payload.orders) ? payload.orders.length : 0; } + // 「已回复」分组里的会话只有在最后一条对话是买家消息时才处理(别人转接过来的很常见); + // 真正已经回复过的会话直接跳过,避免重复回复 + if (candidate.answered && !lastDialogueIsCustomer(payload?.msgList)) { + state.processing = false; + if (state.activeAbortController === abortController) state.activeAbortController = null; + if (state.activeRunLog) { + state.activeRunLog.outcome = "已回复分组里没有待回复消息,跳过"; + } + renderWidget(); + scheduleCheck(800); + return; + } + if (candidate.answered) { + log("兜底分组里发现最后一条是买家消息的会话(可能是别的客服转接过来的),按未回复处理。"); + } if (payload?.skip) { const waitingImage = payload.reason === "waiting-adjust-image"; if (!waitingImage) markCardOnlyConversation(row); @@ -713,6 +806,35 @@ // 买家连发图片/视频时,同一会话在冷却期内只确认一次,避免上百张刷出上百条回复 const conversationKey = getConversationKey(row); + // 这一批买家消息回复过就记住指纹;只要买家没有新消息,就不再重复回复 + const conversationIdentity = getConversationIdentity(row); + const buyerFingerprint = buyerMessageFingerprint(payload.msgList); + // 自动模式下发现有人在客服台手动回复了,就让位:切回调试模式,本轮不再自动回复 + if (state.humanFallback && state.mode === "auto" && conversationIdentity + && (state.humanFallbackTrigger === "send" || state.humanFallbackTrigger === "both")) { + const humanReply = detectHumanReply(payload.msgList, conversationIdentity); + if (humanReply) { + fallbackToDebug(`检测到人工回复「${humanReply.slice(0, 12)}」`); + markConversationHandled(row); + state.processing = false; + if (state.activeAbortController === abortController) state.activeAbortController = null; + if (state.activeRunLog) state.activeRunLog.outcome = "检测到人工回复,已自动回退调试模式"; + renderWidget(); + scheduleCheck(2000); + return; + } + } + if (conversationIdentity && buyerFingerprint + && state.repliedBuyerFingerprint.get(conversationIdentity) === buyerFingerprint) { + markConversationHandled(row); + state.processing = false; + if (state.activeAbortController === abortController) state.activeAbortController = null; + if (state.activeRunLog) state.activeRunLog.outcome = "这批买家消息已回复过,等待新消息"; + log("买家这批消息已经回复过,等待新消息,不再重复回复。"); + renderWidget(); + scheduleCheck(2500); + return; + } const onlyMedia = isMediaOnlyBatch(payload.msgList); const pendingNote = onlyMedia ? state.receiptNotes.find((note) => note.key === conversationKey) @@ -730,7 +852,7 @@ const adjustReceipt = Boolean(adjustNote && buildReceiptText(adjustNote)); // 有数量差值要回复时不受连发冷却限制,保证买家能看到最新数量 if (!pendingReceipt && !adjustReceipt && onlyMedia - && Date.now() - (state.imageAckAt.get(conversationKey) || 0) < IMAGE_ACK_COOLDOWN_MS) { + && Date.now() - (state.imageAckAt.get(conversationIdentity) || 0) < IMAGE_ACK_COOLDOWN_MS) { if (Date.now() - state.imageAckLogAt > 20000) { state.imageAckLogAt = Date.now(); log("买家还在连续发送图片/视频,冷却期内本轮不重复回复。"); @@ -749,7 +871,10 @@ if (state.activeRunLog) state.activeRunLog.reply = noteText; await sendReceiptNotes(runId); ensureTaskActive(runId); - state.imageAckAt.set(conversationKey, Date.now()); + state.imageAckAt.set(conversationIdentity, Date.now()); + if (conversationIdentity && buyerFingerprint) { + state.repliedBuyerFingerprint.set(conversationIdentity, buyerFingerprint); + } log(adjustReceipt ? "图片替换已生效,已直接回复确认,不再发送其他文字。" : "图片数量与规格不符,已直接回复差值,不再发送其他文字。"); @@ -774,8 +899,61 @@ return; } + // 聊天记录最后一条是客服发的,说明这轮已经没有待回复内容; + // 此时再请求只会拿旧的买家消息重新生成,把上次的回复又发一遍。 + // 但会话列表已经显示更新的预览时,说明买家新消息还没渲染进聊天区 + // (只发一个「嗯」时很常见),等一小段重新读取一次,避免漏回。 + if (!hasPendingCustomerReply(payload.msgList)) { + // 只有会话列表确实显示了更新的内容,才值得再读一次聊天区; + // 否则重复读取会反复滚动消息列表,看起来就是聊天区上下乱跳。 + if (conversationPreviewShowsNewer(row, payload.msgList)) { + await sleep(pageDelayMs() + 500); + ensureTaskActive(runId); + const refreshed = await buildConversationPayload(); + if (!refreshed?.skip && hasPendingCustomerReply(refreshed.msgList)) { + payload = refreshed; + if (state.activeRunLog && Array.isArray(payload.msgList)) { + state.activeRunLog.messages = payload.msgList.map((item) => ({ + usertype: item.usertype, + msg: item.msg, + t: item.t || 0 + })); + } + log("买家新消息刚刚渲染出来,已按最新内容回复。"); + } + } + } + if (!hasPendingCustomerReply(payload.msgList)) { + if (Date.now() - state.duplicateLogAt > 20000) { + state.duplicateLogAt = Date.now(); + log("买家还没有新消息,等待新消息,避免重复回复。"); + } + // 预览和聊天区一致,说明确实没有新消息;记住这个快照,之后预览不变就不再点开 + if (!conversationPreviewShowsNewer(row, payload.msgList)) markConversationHandled(row); + state.processing = false; + if (state.activeAbortController === abortController) state.activeAbortController = null; + if (state.activeRunLog) state.activeRunLog.outcome = "无新买家消息,跳过重复回复"; + renderWidget(); + scheduleCheck(2500); + return; + } + const result = await requestReply(payload, abortController.signal); ensureTaskActive(runId); + // 服务端确认最近一条客服消息之后没有买家内容,本轮无需回复 + if (result?.action === "skip") { + if (Date.now() - state.duplicateLogAt > 20000) { + state.duplicateLogAt = Date.now(); + log("本轮没有新的买家消息,暂不回复。"); + } + if (!conversationPreviewShowsNewer(row, payload.msgList)) markConversationHandled(row); + state.processing = false; + if (state.activeAbortController === abortController) state.activeAbortController = null; + if (state.activeRunLog) state.activeRunLog.outcome = "无新买家消息,跳过重复回复"; + renderWidget(); + scheduleCheck(2500); + return; + } if (isManualRequired(result)) { // 高危意图是否停止该会话的自动回复由设置决定;模型判定转人工时始终停止 const hitRisk = Array.isArray(result.riskIntents) && result.riskIntents.length > 0; @@ -808,9 +986,10 @@ const greeting = state.mode === "auto" ? pickGreeting(payload, row) : null; if (greeting) { if (greeting.text) { - await fillReply(greeting.text); + if (!(await fillReply(greeting.text))) throw new Error("开场说明未能写入输入框"); ensureTaskActive(runId); if (!(await sendReplyAndVerify(greeting.text))) throw new Error("开场说明发送未确认成功"); + rememberOwnText(greeting.text, conversationIdentity); log("已先发送开场说明文字。"); await sleep(pageDelayMs() + 200); ensureTaskActive(runId); @@ -823,8 +1002,19 @@ } } - if (reply) await fillReply(reply); - else await clearReplyInput(); + if (reply) { + if (!(await fillReply(reply))) { + // 输入框里可能残留着上一次的回复,宁可不发也不能把旧内容重复发出去 + if (state.activeRunLog) state.activeRunLog.outcome = "回复未能写入输入框,已跳过发送"; + state.processing = false; + if (state.activeAbortController === abortController) state.activeAbortController = null; + renderWidget(); + scheduleCheck(1500); + return; + } + } else { + await clearReplyInput(); + } ensureTaskActive(runId); if (state.mode === "auto") { let sent = true; @@ -835,8 +1025,12 @@ } ensureTaskActive(runId); if (sent) { + if (conversationIdentity && buyerFingerprint) { + state.repliedBuyerFingerprint.set(conversationIdentity, buyerFingerprint); + } + rememberOwnText(reply, conversationIdentity); // 纯媒体批次记一次确认时间,后续连发的图片/视频不再逐条回复 - if (onlyMedia) state.imageAckAt.set(conversationKey, Date.now()); + if (onlyMedia) state.imageAckAt.set(conversationIdentity, Date.now()); await sendReceiptNotes(runId); log("已确认自动发送成功,恢复监听。"); if (state.activeRunLog) state.activeRunLog.outcome = "已自动回复并确认发送"; @@ -931,17 +1125,225 @@ function findFirstUrgentConversation() { for (const list of getUrgentConversationLists()) { - const rows = getConversationRows(list).filter((item) => !isManualConversation(item) && !isCardOnlyConversation(item)); - if (rows.length) return rows[0]; + const rows = getConversationRows(list).filter((item) => + !isManualConversation(item) && !isCardOnlyConversation(item) && !isConversationHandled(item)); + if (rows.length) return { row: rows[0], answered: false }; const fallbackItems = Array.from(list.children) - .filter((item) => isVisible(item) && !isManualConversation(item) && !isCardOnlyConversation(item)); - if (fallbackItems.length) return fallbackItems[0]; + .filter((item) => isVisible(item) && !isManualConversation(item) && + !isCardOnlyConversation(item) && !isConversationHandled(item)); + if (fallbackItems.length) return { row: fallbackItems[0], answered: false }; + } + + // 「待回复」等分组没有固定类名(转接过来的会话常落在这里),按 DOM 顺序扫一遍 + // 其它可见的左侧会话列表;打开后再确认最后一条对话确实是买家发的。 + // 兜底扫描只在自动模式做,避免调试模式频繁切会话打断人工。 + if (state.mode === "auto") { + for (const list of getOtherConversationLists()) { + const rows = getConversationRows(list).filter((item) => + !isManualConversation(item) && !isCardOnlyConversation(item) && + !isAnsweredQuiet(item) && !isConversationHandled(item)); + if (rows.length) { + markAnsweredQuiet(rows[0]); + return { row: rows[0], answered: true }; + } + } + + // 最后兜底「已回复」分组 + for (const list of getAnsweredConversationLists()) { + const rows = getConversationRows(list).filter((item) => + !isManualConversation(item) && !isCardOnlyConversation(item) && + !isAnsweredQuiet(item) && !isConversationHandled(item)); + if (rows.length) { + markAnsweredQuiet(rows[0]); + return { row: rows[0], answered: true }; + } + } } return null; } + function getAnsweredConversationLists() { + return Array.from(document.querySelectorAll(selectors.answeredList)) + .filter((list) => list && isVisible(list)); + } + + // 除已知分组外的其它会话列表(例如「待回复」)。只认左侧区域、较窄、且直接子项 + // 像会话行的 ul,避免把右侧订单/商品列表当成会话列表去点。 + function getOtherConversationLists() { + const known = new Set([...getUrgentConversationLists(), ...getAnsweredConversationLists()]); + const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0; + return Array.from(document.querySelectorAll("ul, [role='list']")) + .filter((list) => { + if (!list || known.has(list) || !isVisible(list)) return false; + const rect = list.getBoundingClientRect(); + if (rect.left > viewportWidth * 0.45 || rect.width < 180) return false; + return Array.from(list.children).some((child) => isConversationRow(child)); + }); + } + + // 已回复分组里的会话很可能真的已经回复过,用冷却避免每轮都把同一个会话重新打开 + function isAnsweredQuiet(row) { + const key = getConversationStateKey(row); + if (!key) return false; + return Date.now() < (state.answeredQuietUntil.get(key) || 0); + } + + function markAnsweredQuiet(row) { + const key = getConversationStateKey(row); + if (key) state.answeredQuietUntil.set(key, Date.now() + ANSWERED_QUIET_MS); + } + + // 会话的稳定标识:优先用平台给的 data 属性,退回到「头像 + 昵称」。 + // 不能用 getConversationKey,它带着最新消息预览,买家一发新消息就会变。 + function getConversationIdentity(row) { + for (const attr of ["data-id", "data-uid", "data-user-id", "data-conversation-id", "data-session-id"]) { + const value = row.getAttribute?.(attr); + if (value) return `${attr}:${value}`; + } + const imgSrc = row.querySelector?.("img")?.getAttribute("src") || ""; + const name = String(row.innerText || row.textContent || "") + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .filter((line) => !/^\d{1,2}:\d{2}(:\d{2})?$/.test(line)) + .filter((line) => !/^\d+$/.test(line))[0] || ""; + return imgSrc || name ? `${imgSrc}|${name.slice(0, 40)}` : ""; + } + + // 会话状态(人工标记、冷却、已处理)统一用稳定标识; + // getConversationKey 带着最新消息预览,买家再发一句就会变,状态会丢 + function getConversationStateKey(row) { + return getConversationIdentity(row) || getConversationKey(row); + } + + // 记下本软件成功发出去的文字,用来区分「自己回的」和「人工回的」 + function rememberOwnText(text, identity) { + const value = normalizeText(text || ""); + const id = identity || state.currentConversationIdentity; + if (!value || !id) return; + const own = state.ownTexts.get(id) || new Set(); + own.add(value); + if (own.size > 20) own.delete(own.values().next().value); + state.ownTexts.set(id, own); + state.lastSysSeen.set(id, value); + } + + function isSystemNotice(text) { + return /系统消息|会话已结束|已结束会话|已超时|超时提醒|已接入|正在为您转接|自动回复/.test(text); + } + + // 聊天最后一条是客服发的文字,但不是本软件发出的:说明人工在客服台接手了。 + // 第一次见到某个会话时只记基线,避免把历史回复误判成人工操作。 + function detectHumanReply(msgList, identity) { + const list = Array.isArray(msgList) ? msgList : []; + if (!identity) return ""; + let text = ""; + for (let index = list.length - 1; index >= 0; index -= 1) { + const item = list[index]; + if (!item || !item.msg) continue; + if (item.usertype === "cus") return ""; + text = normalizeText(item.msg); + break; + } + if (!text || isSystemNotice(text)) return ""; + const own = state.ownTexts.get(identity); + if (own && own.has(text)) return ""; + const seen = state.lastSysSeen.get(identity); + state.lastSysSeen.set(identity, text); + if (seen === undefined || seen === text) return ""; + return text; + } + + // 人工介入后自动让位:切回调试模式,只生成内容回填,不再自动发送 + function fallbackToDebug(reason) { + if (state.mode === "debug") return; + state.mode = "debug"; + saveState(); + log(`${reason},已自动回退到调试模式:只回填内容,需人工确认发送。`); + renderWidget(); + syncPauseStateToServer("human-fallback"); + } + + // 监听人工在输入框里的打字/点击输入框。 + // 只认真实事件,且本软件正在写入时直接忽略——用标志位判断,不靠时间窗。 + function attachHumanInputWatch() { + const handler = (event) => { + if (!state.humanFallback) return; + if (state.humanFallbackTrigger !== "input" && state.humanFallbackTrigger !== "both") return; + if (!event.isTrusted || state.writingReply) return; + if (!(event.target instanceof Element)) return; + if (ui.root && ui.root.contains(event.target)) return; + if (!event.target.closest(selectors.replyTextarea)) return; + if (state.mode === "auto") fallbackToDebug("检测到人工输入"); + }; + document.addEventListener("input", handler, true); + document.addEventListener("pointerdown", handler, true); + } + + // 处理过一轮后记住当时的消息预览;预览没变说明没有新消息,不用再点开读取历史 + function isConversationHandled(row) { + const id = getConversationIdentity(row); + const snapshot = normalizeConversationPreview(row); + if (!id || !snapshot) return false; + return state.handledConversationSnapshot.get(id) === snapshot; + } + + function markConversationHandled(row) { + const id = getConversationIdentity(row); + const snapshot = normalizeConversationPreview(row); + if (id && snapshot) state.handledConversationSnapshot.set(id, snapshot); + } + + // 会话列表的预览是否比聊天区读到的最后一条更新(说明聊天区还没渲染出来) + function conversationPreviewShowsNewer(row, msgList) { + const preview = normalizeConversationPreview(row); + if (!preview) return false; + const list = Array.isArray(msgList) ? msgList : []; + for (let index = list.length - 1; index >= 0; index -= 1) { + const item = list[index]; + if (!item || !item.msg) continue; + const text = normalizeText(item.msg).replace(/…|\.{3}/g, ""); + if (!text) return true; + return !preview.includes(text.slice(0, 10)); + } + return true; + } + + // 忽略系统提示(转接、超时提醒等),看最后一条真正参与对话的消息是谁发的 + function lastDialogueIsCustomer(msgList) { + const list = Array.isArray(msgList) ? msgList : []; + for (let index = list.length - 1; index >= 0; index -= 1) { + const item = list[index]; + if (!item || !item.msg) continue; + if (item.usertype === "sys") continue; + return item.usertype === "cus"; + } + return false; + } + + // 直接按聊天记录判断:最后一条真实消息是买家发的,才算有待回复内容。 + // 不拿文字去猜「是不是自己发的」——那种比对要靠长度阈值兜底,单字回复会被漏掉。 + function hasPendingCustomerReply(msgList) { + const list = Array.isArray(msgList) ? msgList : []; + for (let index = list.length - 1; index >= 0; index -= 1) { + const item = list[index]; + if (!item || !item.msg) continue; + return item.usertype === "cus"; + } + return false; + } + + // 买家消息指纹:只拼买家发的内容,客服自己的回复不会影响它。 + // 指纹没变就说明买家没有新消息,不必再请求一次回复。 + function buyerMessageFingerprint(msgList) { + return (Array.isArray(msgList) ? msgList : []) + .filter((item) => item && item.usertype === "cus" && item.msg) + .map((item) => normalizeText(item.msg)) + .join("\u0001"); + } + function getUrgentConversationLists() { return selectors.urgentLists .flatMap((selector) => Array.from(document.querySelectorAll(selector))) @@ -973,14 +1375,14 @@ function isManualConversation(row) { if (!row) return false; if (row.dataset && row.dataset.pddRaManual === "1") return true; - const key = getConversationKey(row); + const key = getConversationStateKey(row); return key ? state.manualConversationKeys.has(key) : false; } function markManualConversation(row) { if (!row) return; if (row.dataset) row.dataset.pddRaManual = "1"; - const key = getConversationKey(row); + const key = getConversationStateKey(row); if (key) state.manualConversationKeys.add(key); } @@ -1211,9 +1613,9 @@ if (state.runtime.historyLimit === 0) await expandMessageHistory(); // 订单面板数据同时给「图片归属」和「模型上下文」,只读一次 - const orders = await readOrderPanelWithAutoSwitch().catch(() => []); - log(orders.length ? `订单面板:读取到 ${orders.length} 个订单。` : "订单面板:未读取到订单。"); const messageItems = collectMessageItems(); + const orders = await readOrdersCached(hasOrderHint(messageItems)).catch(() => []); + log(orders.length ? `订单面板:读取到 ${orders.length} 个订单。` : "订单面板:未读取到订单。"); // 纯图片/视频批次先把归档做完,数量差值回复才能在本轮直接发出去,避免先冒出一段无关文字; // 带图片调整指令的会话也要等归档完成再决定怎么回复。 @@ -1234,14 +1636,18 @@ const latestItem = getLatestConversationItem(messageItems); const hasPendingCustomerText = hasPendingCustomerMessage(messageItems); + const buyerSentCard = latestItem?.type === "product-card" && latestItem.usertype === "cus"; - if (latestItem?.type === "product-card" && !hasPendingCustomerText) { + if (latestItem?.type === "product-card" && !hasPendingCustomerText && !buyerSentCard) { return { skip: true, reason: "latest-product-card", latestProductCard: latestItem.product }; } + if (buyerSentCard && !hasPendingCustomerText) { + log("买家发来商品链接,按待回复处理。"); + } if (latestItem?.type === "product-card" && hasPendingCustomerText) { log("检测到客户文字后有平台商品卡提醒,继续按客户文字处理。"); } @@ -1250,10 +1656,17 @@ const limit = state.runtime.historyLimit; const msgList = extractMessages(limit, messageItems); if (latestProductCard?.message) { - msgList.unshift({ - usertype: "cus", - msg: latestProductCard.message - }); + // 商品卡片里的价格、商品ID 也要进对话,模型回答价格/规格问题时才有依据 + const cardDetail = []; + if (latestProductCard.price) cardDetail.push(`价格 ${latestProductCard.price}`); + if (latestProductCard.productId) cardDetail.push(`商品ID ${latestProductCard.productId}`); + const cardText = cardDetail.length + ? `[商品卡片] ${latestProductCard.message}(${cardDetail.join(",")})` + : `[商品卡片] ${latestProductCard.message}`; + const cardMessage = { usertype: "cus", msg: cardText }; + // 买家最后发的是商品链接时,要让后端看到它是最后一条买家消息 + if (buyerSentCard && !hasPendingCustomerText) msgList.push(cardMessage); + else msgList.unshift(cardMessage); } // 商品卡片也占一条,保证发给后端的总数不超过设置的条数 if (limit > 0 && msgList.length > limit) msgList.splice(0, msgList.length - limit); @@ -1379,6 +1792,10 @@ const root = document.querySelector(selectors.messageList); if (!root) return []; + // 商品卡也要区分是谁发的:买家自己发来的商品链接必须回复, + // 平台/客服侧的商品卡提醒才跳过。 + const rootRect = root.getBoundingClientRect(); + const rootCenterX = rootRect.left + rootRect.width / 2; return Array.from(root.querySelectorAll(selectors.productCards)) .filter((element) => isVisible(element)) .map((element) => { @@ -1390,6 +1807,7 @@ top: rect.top, bottom: rect.bottom, left: rect.left, + usertype: rect.left + rect.width / 2 < rootCenterX ? "cus" : "sys", product }; }) @@ -1431,7 +1849,8 @@ } function parseProductCardInfo(element) { - const lines = normalizeText(element.innerText || element.textContent || "") + const rawText = normalizeText(element.innerText || element.textContent || ""); + const lines = rawText .split(/\n+/) .map((line) => cleanupProductCardLine(line)) .filter(Boolean) @@ -1451,10 +1870,16 @@ ? `这款${title}的${model}` : `这款${title}`; + // 价格和商品ID 会被当成噪声过滤掉,但它们对回答价格/规格问题有用,单独抓出来 + const priceMatch = rawText.match(/[¥¥]\s*\d+(?:\.\d+)?/); + const idMatch = rawText.match(/商品ID[::]?\s*(\d+)/i); + return { name: title, model, - message + message, + price: priceMatch ? priceMatch[0].replace(/¥/, "¥") : "", + productId: idMatch ? idMatch[1] : "" }; } @@ -1630,11 +2055,12 @@ return false; } - function collectVideoPlaceholders(videos, rootRect) { + function collectVideoPlaceholders(videos, rootRect, isAutoNode) { const rootCenterX = rootRect.left + rootRect.width / 2; const out = []; const sorted = videos.slice().sort((a, b) => a.top - b.top || a.left - b.left); for (const video of sorted) { + if (isAutoNode && isAutoNode(video.element)) continue; const centerX = (video.left + video.right) / 2; const usertype = centerX > rootCenterX ? "sys" : "cus"; const last = out[out.length - 1]; @@ -1655,10 +2081,29 @@ const videoScopes = collectVideoScopes(videos, root); const raw = []; + // 平台的自动回复、以及「当前用户来自商品详情页」+ 订单卡片都是整行插入的 + // 系统内容,不是买家说的话、也不是客服的真实答复。整行排除:否则订单卡片 + // 会被拆成「查看详情 / ¥6.17 / 标题 / 无售后 / 待发货」好几条买家消息, + // 把买家真正的「ok」挤出历史窗口,快捷回复就命中不到了。 + const autoRows = new Set(); + for (const row of Array.from(root.querySelectorAll('li.onemsg, [id^="middlePanel_list_"]'))) { + if (row === root) continue; + const rowRect = row.getBoundingClientRect(); + // 防误判:命中的行必须只是单条消息,不能是包着整个列表的容器 + if (rowRect.height > rootRect.height * 0.6) continue; + const rowText = String(row.innerText || row.textContent || ""); + if (/自动回复/.test(rowText) || isPlatformCardRow(rowText)) autoRows.add(row); + } + const isAutoNode = (element) => { + const row = element.closest?.('li.onemsg, [id^="middlePanel_list_"]'); + return Boolean(row && autoRows.has(row)); + }; + for (const element of all) { if (!isVisible(element)) continue; if (isInsideSpecificProductCard(element)) continue; if (isInsideVideoScope(element, videoScopes, root)) continue; + if (isAutoNode(element)) continue; const text = normalizeText(element.innerText || element.textContent || ""); if (!isLikelyChatText(text)) continue; if (hasChildWithSameText(element, text)) continue; @@ -1683,8 +2128,8 @@ } // 图片和视频都没有文字,补占位让模型知道对方发过媒体 - raw.push(...collectImagePlaceholders(root, rootRect)); - raw.push(...collectVideoPlaceholders(videos, rootRect)); + raw.push(...collectImagePlaceholders(root, rootRect, isAutoNode)); + raw.push(...collectVideoPlaceholders(videos, rootRect, isAutoNode)); raw.sort((a, b) => a.top - b.top || a.left - b.left); @@ -1753,7 +2198,10 @@ if (!response.ok) return; const d = await response.json(); const n = Number(d.historyLimit); - state.runtime.historyLimit = Number.isInteger(n) && n >= 0 && n <= 500 ? n : 6; + state.runtime.historyAll = d.historyAll === true; + state.runtime.historyLimit = state.runtime.historyAll + ? 0 + : (Number.isInteger(n) && n >= 0 && n <= 500 ? n : 6); state.runtime.imageOutputDir = String(d.imageOutputDir || ""); state.runtime.imageSaveEnabled = d.imageSaveEnabled !== false; const mode = String(d.imageAssignMode || ""); @@ -1773,6 +2221,8 @@ state.runtime.imageHistoryLeadMs = historyLead; } state.runtime.imageCountCheck = d.imageCountCheck !== false; + state.runtime.imageKeywordFixedCount = String(d.imageKeywordFixedCount || ""); + state.runtime.imageFileAsImage = d.imageFileAsImage !== false; state.runtime.imageReviewEnabled = d.imageReviewEnabled !== false; state.runtime.imageKeepOrderTab = d.imageKeepOrderTab !== false; state.runtime.imageReceiptReplyEnabled = d.imageReceiptReplyEnabled === true; @@ -1805,6 +2255,10 @@ if (Number.isFinite(pageMax) && pageMax >= 0 && pageMax <= 60000) { state.runtime.maxPageDelayMs = pageMax; } + const orderCache = Number(d.orderCacheMs); + if (Number.isFinite(orderCache) && orderCache >= 0 && orderCache <= 3600000) { + state.runtime.orderCacheMs = orderCache; + } state.runtime.orderStatusNormal = d.orderStatusNormal !== false; state.runtime.orderStatusDone = d.orderStatusDone !== false; state.runtime.orderStatusRefund = d.orderStatusRefund !== false; @@ -1851,6 +2305,12 @@ if (!root) return; const scroller = findScrollParent(root); const saved = scroller ? scroller.scrollTop : 0; + // 历史是往聊天区顶部插入的,按像素记 scrollTop 会跑到别的消息上。 + // 会话刚点开、平台还没滚到底时 scrollTop 是 0,直接恢复就会停在最顶部; + // 所以记「距底部距离」,原本在底部(或还没定位)就恢复到最新消息。 + const fromBottom = scroller + ? Math.max(0, scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight) + : 0; let last = -1; let stable = 0; for (let round = 0; round < 20; round++) { @@ -1862,7 +2322,19 @@ last = count; if (stable >= 3) break; } - if (scroller) scroller.scrollTop = saved; + if (!scroller) return; + const stayAtBottom = saved <= 2 || fromBottom <= 40; + const restore = () => { + scroller.scrollTop = stayAtBottom + ? scroller.scrollHeight + : Math.max(0, scroller.scrollHeight - scroller.clientHeight - fromBottom); + }; + restore(); + // 平台插入历史是异步的,插入后可能把滚动位置重置回顶部,这里补几次 + for (let i = 0; i < 3; i++) { + await sleep(120); + restore(); + } } const IMAGE_MIN_SIZE = 60; @@ -1887,6 +2359,54 @@ return isVideoMessageRow(element.closest('li.onemsg, [id^="middlePanel_list_"]')); } + // 买家把图片当「文件」发送时,气泡里只有「文件名 + 下载」,不是聊天图片。 + // 开关打开时,从文件名气泡里找可下载地址:优先链接,其次气泡内的缩略图。 + const IMAGE_FILE_NAME_RE = /^([^\s\\/:*?"<>|]{1,80}\.(?:jpe?g|png|gif|webp|bmp|heic|heif|avif|tiff?))\s*(?:[\d.,]+\s*[KMG]B?)?$/i; + const IMAGE_FILE_EXT_RE = /\.(?:jpe?g|png|gif|webp|bmp|heic|heif|avif|tiff?)(?:$|\?)/i; + + function collectFileImageItems(root) { + const out = []; + if (state.runtime && state.runtime.imageFileAsImage === false) return out; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const handled = new Set(); + let node = walker.nextNode(); + while (node) { + const text = String(node.nodeValue || "").trim(); + if (text && text.length <= 120) { + const nameMatch = text.match(IMAGE_FILE_NAME_RE); + const host = node.parentElement; + if (nameMatch && host && !handled.has(host) && !host.closest(selectors.productCards)) { + handled.add(host); + let bubble = host; + let url = ""; + for (let depth = 0; depth < 6 && bubble && bubble !== root; depth += 1, bubble = bubble.parentElement) { + const link = bubble.matches && bubble.matches("a[href]") ? bubble : bubble.querySelector("a[href]"); + const href = link ? String(link.getAttribute("href") || "") : ""; + if (/^https?:/i.test(href) && IMAGE_FILE_EXT_RE.test(href.split("?")[0])) { url = href; break; } + const img = bubble.querySelector("img"); + if (img && isVisible(img)) { + const src = img.currentSrc || img.src || img.getAttribute("data-src") || + img.getAttribute("data-original") || ""; + const rect = img.getBoundingClientRect(); + if (/^https?:/i.test(src) && !isDecorativeImage(img, src) && + rect.width >= 24 && rect.height >= 24) { url = src; break; } + } + } + if (url) { + const target = bubble || host; + const rect = target.getBoundingClientRect(); + if (rect.width >= 1 && rect.height >= 1) { + out.push({ url, top: rect.top, bottom: rect.bottom, left: rect.left, + right: rect.right, element: target, filename: nameMatch[1] }); + } + } + } + } + node = walker.nextNode(); + } + return out; + } + function collectChatImages(root) { const out = []; const seen = new Set(); @@ -1919,15 +2439,19 @@ const m = bg.match(/url\(["']?(https?:\/\/[^"')]+)["']?\)/i); if (m) push(m[1], r, el); }); + + // 文件形式的图片(气泡里只有文件名)也按买家图片收集 + collectFileImageItems(root).forEach((item) => push(item.url, item, item.element)); return out; } // 聊天图片在纯文本里没有任何痕迹:转成「[图片]」占位条目,模型才知道有人发过图 - function collectImagePlaceholders(root, rootRect) { + function collectImagePlaceholders(root, rootRect, isAutoNode) { const rootCenterX = rootRect.left + rootRect.width / 2; const images = collectChatImages(root).slice().sort((a, b) => a.top - b.top || a.left - b.left); const out = []; for (const img of images) { + if (isAutoNode && isAutoNode(img.element)) continue; const centerX = (img.left + img.right) / 2; const usertype = centerX > rootCenterX ? "sys" : "cus"; const last = out[out.length - 1]; @@ -1962,7 +2486,40 @@ return Number.isFinite(n) && n > 0 && n <= 9999 ? n : 0; } + // 商品关键词固定张数:每行一条「关键词 = 张数」,例如「证件照 = 1」。 + // 命中的订单直接用这个固定值作为应发图片张数,不再解析规格里的「N张」, + // 也不按件数累加——像「证件照 12张」里的 12 是制作数量,买家只需发 1 张原图。 + function parseKeywordFixedRules(text) { + const rules = []; + for (const line of String(text || "").split(/\r?\n/)) { + const m = line.match(/^\s*(.+?)\s*[=::]\s*(\d{1,4})\s*$/); + if (!m) continue; + const word = m[1].trim(); + const count = Number(m[2]); + if (word && count > 0 && count <= 9999) { + rules.push({ word: word.toLowerCase(), count }); + } + } + return rules; + } + + function fixedSheetCountByKeyword(goods) { + const rules = parseKeywordFixedRules(state.runtime.imageKeywordFixedCount); + if (!rules.length) return 0; + // 按填写顺序判定,命中多条时以最上面那条为准 + for (const rule of rules) { + for (const item of goods) { + const text = (String(item.name || "") + " " + String(item.spec || "")).toLowerCase(); + if (text.includes(rule.word)) return rule.count; + } + } + return 0; + } + function expectedSheetCount(goods) { + const fixed = fixedSheetCountByKeyword(goods); + if (fixed > 0) return fixed; + let total = 0; let matched = false; for (const item of goods) { @@ -2029,6 +2586,34 @@ }; } + // 每轮读订单都要点开「个人订单」页签再点回去,轮询时就表现为右侧一直闪。 + // 缓存时长可在「高级设置 → 个人订单缓存」里配(0 表示每轮都重读); + // 切换会话一定重读,买家提到下单/付款时也强制重读。 + const ORDER_HINT = /下单|拍了|付款|支付|订单编号|已买|买好|下单了|付款了|支付了|待发货/; + + function hasOrderHint(messageItems) { + for (let i = messageItems.length - 1; i >= 0; i -= 1) { + const item = messageItems[i]; + if (item.usertype !== "cus" || !item.msg) continue; + return ORDER_HINT.test(item.msg); + } + return false; + } + + async function readOrdersCached(force = false) { + const key = state.currentConversationKey || ""; + const cache = state.orderCache; + const ttl = Math.max(0, Number(state.runtime.orderCacheMs) || 0); + // 换了会话就必须重新读,哪怕还在缓存时间内 + const switched = !cache || cache.key !== key; + if (!force && !switched && Date.now() - cache.at < ttl) { + return cache.orders; + } + const orders = await readOrderPanelWithAutoSwitch(); + state.orderCache = { key, at: Date.now(), orders }; + return orders; + } + function readOrderPanel() { let containers = Array.from(document.querySelectorAll(".order-item-list")); if (!containers.length) containers = Array.from(document.querySelectorAll(".right-panel")); @@ -2313,7 +2898,7 @@ const orders = Array.isArray(prefetchedOrders) ? prefetchedOrders - : await readOrderPanelWithAutoSwitch(); + : await readOrdersCached(); // 买家说「第2张替换掉 / 第3张删掉」时调整已保存的图片;删除不需要新图 const adjust = await resolveImageAdjustment(messageItems); @@ -2768,9 +3353,22 @@ return Boolean(element.closest?.(selectors.productCards)); } + // 平台在买家消息后自动插入的商品/订单卡片:带订单状态、售后状态和商品入口, + // 整行都不是聊天内容。买家自己发的商品链接只有标题+价格,没有这些订单字段。 + function isPlatformCardRow(text) { + if (!text) return false; + if (/当前用户来自/.test(text)) return true; + const hasOrderField = /订单编号|实收|待发货|已发货|已完成|待收货|无售后|有售后|售后状态/.test(text); + const hasCardMarker = /查看详情|查看商品规格|咨询商品规格/.test(text); + const hasPrice = /[¥¥]\s*\d+(?:\.\d+)?/.test(text); + return hasOrderField && (hasCardMarker || hasPrice); + } + function isLikelyChatText(text) { if (!text) return false; if (text.length > 600) return false; + if (/^[¥¥]\s*\d+(?:\.\d+)?$/.test(text)) return false; + if (/^(查看详情|待发货|无售后|有售后|已发货|已完成|待收货)$/.test(text)) return false; if (/^\d{4}年\d{1,2}月\d{1,2}日/.test(text)) return false; if (/^\d{1,2}:\d{2}(:\d{2})?$/.test(text)) return false; if (/^(未读|已读|来自手机端|主账号|发送)$/.test(text)) return false; @@ -2834,24 +3432,60 @@ async function fillReply(reply) { const textarea = await waitForElement(selectors.replyTextarea, 5000); - textarea.focus(); - await sleep(80); - setTextareaValue(textarea, ""); - dispatchTextInputEvents(textarea, ""); - - const trustedInput = await requestTrustedTextInput(reply); - await sleep(180); - if (trustedInput && normalizeText(textarea.value || "").includes(normalizeText(reply).slice(0, 20))) { - log("已使用真实输入事件写入回复。"); - return; + // 输入框里有人工写的内容、又不是本软件上次回填的,就不要覆盖 + const existing = normalizeText(textarea.value || ""); + const ownFilled = normalizeText(state.lastFilledText || ""); + const target = normalizeText(reply || ""); + if (existing && existing !== ownFilled && existing !== target) { + log("输入框里已有人工输入的内容,已跳过回填,避免覆盖。"); + return false; } + // 用标志位区分「自己写」和「人工写」:写入期间置位,写完立即复位。 + // 人工的输入事件一定发生在复位之后,不依赖任何时间窗。 + state.writingReply = true; + try { + textarea.focus(); + await sleep(80); + setTextareaValue(textarea, ""); + dispatchTextInputEvents(textarea, ""); - if (trustedInput) { - log("真实输入事件未写入到输入框,改用页面脚本回填。"); + const trustedInput = await requestTrustedTextInput(reply); + await sleep(180); + if (trustedInput && normalizeText(textarea.value || "").includes(normalizeText(reply).slice(0, 20))) { + log("已使用真实输入事件写入回复。"); + state.lastFilledText = reply; + return true; + } + + if (trustedInput) { + log("真实输入事件未写入到输入框,改用页面脚本回填。"); + } + setTextareaValue(textarea, reply); + dispatchTextInputEvents(textarea, reply); + await sleep(180); + + // 写入失败时输入框里可能还留着上一条回复,必须校验后再发送, + // 否则客户发来一句「嗯」时会把上一次的内容原样再发一遍 + if (!composerHasReply(textarea, reply)) { + setTextareaValue(textarea, reply); + dispatchTextInputEvents(textarea, reply); + await sleep(160); + } + if (!composerHasReply(textarea, reply)) { + log("回复未能写入输入框,已取消本次发送,避免把上一条内容重复发出去。"); + return false; + } + state.lastFilledText = reply; + return true; + } finally { + state.writingReply = false; } - setTextareaValue(textarea, reply); - dispatchTextInputEvents(textarea, reply); - await sleep(180); + } + + function composerHasReply(textarea, reply) { + const target = normalizeForMatch(reply).slice(0, 20); + if (!target) return false; + return normalizeForMatch(textarea.value || "").includes(target); } function setTextareaValue(textarea, value) { @@ -2897,6 +3531,12 @@ return false; } + // 输入框内容必须就是本次要发的回复;不一致说明写入失败、里面还是上一次的内容 + if (!composerHasReply(textarea, reply)) { + log("输入框内容与本次回复不一致,已取消自动发送,避免重复发送上一条回复。"); + return false; + } + await clickSendButton(); const buttonSent = await waitForSendSuccess({ reply, @@ -2907,6 +3547,13 @@ }); if (buttonSent) return true; + // 输入框已被清空通常说明按钮点击其实已经发出去了,只是校验没及时命中; + // 这时再按一次回车,就会把同一条消息重复发出去 + if (!normalizeText(textarea.value || "")) { + log("输入框已清空,判定已经发送成功,不再回车重发。"); + return true; + } + log("按钮发送未确认成功,尝试使用回车发送。"); await pressEnterToSend(textarea); return waitForSendSuccess({ @@ -3110,6 +3757,7 @@ log(`订单 ${note.orderNo} 的图片说明回复未确认成功,已跳过。`); continue; } + rememberOwnText(text, state.currentConversationIdentity); log(`已回复买家订单 ${note.orderNo} 的图片相关说明。`); await sleep(pageDelayMs() + 200); ensureTaskActive(runId); diff --git a/native/build.bat b/native/build.bat index ff01b1c..9c51850 100644 --- a/native/build.bat +++ b/native/build.bat @@ -18,19 +18,21 @@ echo [2/3] 编译源码 if exist "%OUT%\PddAI.exe" del /f /q "%OUT%\PddAI.exe" >nul 2>&1 set SUBSYS=WINDOWS if /i "%1"=="console" set SUBSYS=CONSOLE -set SRCS=src\main.cpp src\Resources.cpp src\Log.cpp src\Util.cpp src\Config.cpp src\Server.cpp src\Pipeline.cpp src\Http.cpp src\Smtp.cpp src\Stats.cpp src\Cdp.cpp src\Browser.cpp src\WebConsole.cpp +set SRCS=src\main.cpp src\Resources.cpp src\Log.cpp src\Util.cpp src\Config.cpp src\Server.cpp src\Pipeline.cpp src\Http.cpp src\Smtp.cpp src\Stats.cpp src\Cdp.cpp src\Browser.cpp src\WebConsole.cpp src\Auth.cpp src\Update.cpp set CFLAGS=/nologo /std:c++17 /EHsc /O2 /MT /W3 /utf-8 /DUNICODE /D_UNICODE /DWIN32 /D_WINDOWS /D_CRT_SECURE_NO_WARNINGS set INC=/I"src" /I"thirdparty" /I"%WV2%\include" cl %CFLAGS% %INC% /Fo"%OUT%\\" /Fd"%OUT%\pddai.pdb" %SRCS% /link /OUT:"%OUT%\PddAI.exe" ^ /SUBSYSTEM:%SUBSYS% /MACHINE:X64 ^ "%OUT%\app.res" "%WV2%\x64\WebView2LoaderStatic.lib" ^ - user32.lib gdi32.lib ole32.lib oleaut32.lib shell32.lib shlwapi.lib advapi32.lib comdlg32.lib version.lib ws2_32.lib iphlpapi.lib winhttp.lib secur32.lib windowscodecs.lib + user32.lib gdi32.lib ole32.lib oleaut32.lib shell32.lib shlwapi.lib advapi32.lib comdlg32.lib version.lib ws2_32.lib iphlpapi.lib winhttp.lib secur32.lib bcrypt.lib windowscodecs.lib winmm.lib if errorlevel 1 goto :fail -echo [3/3] 完成 -echo 产物: %OUT%\PddAI.exe -if exist "%OUT%\PddAI.exe" dir "%OUT%\PddAI.exe" +echo [3/4] 重命名为中文程序名 +powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; $d = Join-Path (Get-Location) 'bin'; $n = [string][char]0x62FC + [char]0x591A + [char]0x591A + [char]0x5BA2 + [char]0x670D + [char]0x52A9 + [char]0x624B + '.exe'; $dst = Join-Path $d $n; if (Test-Path -LiteralPath $dst) { Remove-Item -LiteralPath $dst -Force }; Rename-Item -LiteralPath (Join-Path $d 'PddAI.exe') -NewName $n; $f = Get-Item -LiteralPath $dst; Write-Output ('OK ' + $f.FullName + ' ' + $f.Length)" +if errorlevel 1 goto :fail + +echo [4/4] 完成 endlocal exit /b 0 diff --git a/native/res/app.rc b/native/res/app.rc index 61d8243..5051e2c 100644 --- a/native/res/app.rc +++ b/native/res/app.rc @@ -9,10 +9,11 @@ IDR_INJECT_CONTENT_CSS RCDATA "..\\..\\extension\\content.css" IDR_EXT_MANIFEST RCDATA "..\\..\\extension\\manifest.json" IDR_EXT_BACKGROUND RCDATA "..\\..\\extension\\background.js" IDR_INJECT_STEALTH_JS RCDATA "..\\..\\extension\\stealth.js" +IDI_APP_ICON ICON "..\\..\\res\\黑色.ico" VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,0 - PRODUCTVERSION 1,0,0,0 + FILEVERSION 1,1,2,0 + PRODUCTVERSION 1,1,2,0 FILEFLAGSMASK 0x3fL FILEFLAGS 0x0L FILEOS 0x40004L @@ -24,12 +25,12 @@ BEGIN BLOCK "080404b0" BEGIN VALUE "CompanyName", "PddAI" - VALUE "FileDescription", "PddAI 客服助手" - VALUE "FileVersion", "1.0.0" + VALUE "FileDescription", "拼多多客服助手" + VALUE "FileVersion", "1.1.2" VALUE "InternalName", "PddAI" - VALUE "OriginalFilename", "PddAI.exe" - VALUE "ProductName", "PddAI 客服助手" - VALUE "ProductVersion", "1.0.0" + VALUE "OriginalFilename", "拼多多客服助手.exe" + VALUE "ProductName", "拼多多客服助手" + VALUE "ProductVersion", "1.1.2" END END BLOCK "VarFileInfo" diff --git a/native/src/Auth.cpp b/native/src/Auth.cpp new file mode 100644 index 0000000..5fbe80c --- /dev/null +++ b/native/src/Auth.cpp @@ -0,0 +1,384 @@ +#include "Auth.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include "Config.h" +#include "Http.h" +#include "Log.h" +#include "Util.h" + +namespace pddai { +namespace { + +constexpr const char* kStateFile = "auth.json"; +// 验证服务地址、应用 appKey、AES 密钥全部内置,不支持环境变量或配置文件覆盖 +constexpr const char* kBaseUrl = "https://v.viaeon.com"; +constexpr const char* kAppKey = "f26091ac15457317f59af0c01ef698b9"; +constexpr const char* kEncryptKey = "289cbdcf5ce206f7c5a8a8533bc368f4031dd87f1fa3ece014a1cd691ef5fcb2"; +constexpr int kTimeoutMs = 10000; + +std::mutex g_mutex; +json g_state = json::object(); +bool g_loaded = false; + +std::string Str(const json& obj, const char* key) { + if (!obj.is_object()) return ""; + const auto it = obj.find(key); + return it != obj.end() && it->is_string() ? it->get() : std::string(); +} + +// 与 verify 服务端 padKey 一致:长度不是 16/24/32 时按原字符循环补齐到 32 字节 +std::string NormalizeAesKey(const std::string& key) { + if (key.size() == 16 || key.size() == 24 || key.size() == 32) return key; + if (key.empty()) return std::string(); + std::string padded(32, '\0'); + for (size_t i = 0; i < padded.size(); ++i) padded[i] = key[i % key.size()]; + return padded; +} + +// 解密 verify 的 AES-GCM 响应:Base64(nonce(12) + 密文 + tag(16)),无附加认证数据 +bool AesGcmDecrypt(const std::string& key, const std::string& cipherText, std::string& plain) { + constexpr size_t kNonceSize = 12; + constexpr size_t kTagSize = 16; + const std::string raw = Base64Decode(cipherText); + if (raw.size() <= kNonceSize + kTagSize) return false; + + const std::string keyBytes = NormalizeAesKey(key); + if (keyBytes.empty()) return false; + + BCRYPT_ALG_HANDLE alg = nullptr; + BCRYPT_KEY_HANDLE handle = nullptr; + bool ok = false; + do { + if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0))) break; + if (!BCRYPT_SUCCESS(BCryptSetProperty( + alg, BCRYPT_CHAINING_MODE, + reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)), + sizeof(BCRYPT_CHAIN_MODE_GCM), 0))) { + break; + } + + DWORD objectLength = 0, written0 = 0; + if (!BCRYPT_SUCCESS(BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, + reinterpret_cast(&objectLength), + sizeof(objectLength), &written0, 0))) { + break; + } + std::vector object(objectLength); + if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey( + alg, &handle, object.data(), objectLength, + reinterpret_cast(const_cast(keyBytes.data())), + static_cast(keyBytes.size()), 0))) { + break; + } + + BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; + BCRYPT_INIT_AUTH_MODE_INFO(info); + info.pbNonce = reinterpret_cast(const_cast(raw.data())); + info.cbNonce = static_cast(kNonceSize); + info.pbTag = reinterpret_cast(const_cast(raw.data() + raw.size() - kTagSize)); + info.cbTag = static_cast(kTagSize); + + std::vector buffer(raw.size()); + ULONG written = 0; + const ULONG cipherLength = static_cast(raw.size() - kNonceSize - kTagSize); + const NTSTATUS status = BCryptDecrypt( + handle, reinterpret_cast(const_cast(raw.data() + kNonceSize)), cipherLength, + &info, nullptr, 0, buffer.data(), static_cast(buffer.size()), &written, 0); + if (!BCRYPT_SUCCESS(status)) break; + + plain.assign(reinterpret_cast(buffer.data()), written); + ok = true; + } while (false); + + if (handle) BCryptDestroyKey(handle); + if (alg) BCryptCloseAlgorithmProvider(alg, 0); + return ok; +} + +// 记住的密码做轻量混淆,避免在 auth.json 里直接暴露明文(防窥屏,不是加密) +std::string Obfuscate(const std::string& text) { + std::string mixed = text; + for (size_t i = 0; i < mixed.size(); ++i) { + mixed[i] = static_cast(mixed[i] ^ (0x5B + static_cast((i * 7) % 31))); + } + return Base64Encode(mixed); +} + +std::string Deobfuscate(const std::string& text) { + if (text.empty()) return std::string(); + std::string mixed = Base64Decode(text); + for (size_t i = 0; i < mixed.size(); ++i) { + mixed[i] = static_cast(mixed[i] ^ (0x5B + static_cast((i * 7) % 31))); + } + return mixed; +} + +// 卷序列号 + 计算机名做 FNV-1a,保证同一台机器重启后 device_id 不变 +std::string MakeDeviceId() { + const std::wstring exe = ExeDir(); + std::wstring root = L"C:\\"; + if (exe.size() >= 2 && exe[1] == L':') root = exe.substr(0, 2) + L"\\"; + + DWORD serial = 0; + wchar_t volume[256]{}, fs[256]{}; + DWORD maxComponent = 0, flags = 0; + if (!::GetVolumeInformationW(root.c_str(), volume, 256, &serial, &maxComponent, &flags, fs, 256)) { + serial = 0; + } + + unsigned long long hash = 14695981039346656037ull; + const std::string seed = std::to_string(serial) + "|" + ComputerNameUtf8(); + for (const unsigned char c : seed) { + hash ^= c; + hash *= 1099511628211ull; + } + char buf[32]{}; + std::snprintf(buf, sizeof(buf), "%016llx", hash); + return std::string(buf); +} + +// 下面三个函数都要求调用方已持有 g_mutex +json LoadLocked() { + if (!g_loaded) { + try { + const json saved = Config::GetJsonGlobal(kStateFile, json::object()); + if (saved.is_object()) g_state = saved; + } catch (const std::exception& error) { + Log::Error(std::string("读取验证配置失败: ") + error.what()); + } + g_loaded = true; + } + if (!g_state.is_object()) g_state = json::object(); + return g_state; +} + +void SaveLocked(const json& state) { + g_state = state; + g_loaded = true; + try { + Config::WriteTextGlobal(kStateFile, g_state.dump(2)); + } catch (const std::exception& error) { + Log::Error(std::string("保存验证配置失败: ") + error.what()); + } +} + +json Ensure() { + std::lock_guard lock(g_mutex); + json state = LoadLocked(); + bool changed = false; + // 旧版本写在 auth.json 里的连接配置已不再使用,读到就清理掉 + for (const char* legacy : {"baseUrl", "appKey", "encryptKey"}) { + if (state.contains(legacy)) { state.erase(legacy); changed = true; } + } + if (Str(state, "device_id").empty()) { state["device_id"] = MakeDeviceId(); changed = true; } + if (changed) SaveLocked(state); + return state; +} + +std::string Endpoint(const std::string& leaf) { + return std::string(kBaseUrl) + "/api/v1/app/" + kAppKey + "/" + leaf; +} + +std::string EncryptKey() { + return kEncryptKey; +} + +// 开启加密时整个响应被包成 {"data":""},这里解包成内部真实的 {code,message,data} +bool UnwrapEncrypted(const std::string& key, const json& doc, json& out) { + if (!doc.is_object() || doc.size() != 1) return false; + const auto it = doc.find("data"); + if (it == doc.end() || !it->is_string()) return false; + + std::string plain; + if (!AesGcmDecrypt(key, it->get(), plain)) return false; + out = json::parse(plain, nullptr, false); + return !out.is_discarded(); +} + +AuthResult Call(const std::string& leaf, const json& body, const std::string& token, bool get) { + AuthResult out; + const std::string url = Endpoint(leaf); + + Http::Headers headers; + if (!token.empty()) headers.emplace_back("Authorization", "Bearer " + token); + + try { + const HttpResponse resp = get + ? Http::GetJson(url, headers, kTimeoutMs, std::string()) + : Http::PostJson(url, headers, body, kTimeoutMs, std::string()); + out.status = resp.status; + + json doc = resp.data; + if (UnwrapEncrypted(EncryptKey(), doc, doc)) { + // 解包成功,按内部结构解析 + } else if (resp.status == 200 && doc.is_object() && doc.size() == 1 && + doc.contains("data") && doc["data"].is_string()) { + out.message = "验证服务响应解密失败,请检查 AES 密钥是否与后台一致"; + return out; + } + + if (doc.is_object()) { + out.message = Str(doc, "message"); + const auto code = doc.find("code"); + if (code != doc.end() && code->is_number_integer()) out.status = code->get(); + const auto data = doc.find("data"); + if (data != doc.end()) out.data = *data; + } + out.ok = out.status == 200; + if (out.message.empty()) { + out.message = out.ok ? "操作成功" : ("请求失败(" + std::to_string(out.status) + ")"); + } + } catch (const std::exception& error) { + out.status = 0; + out.message = "无法连接验证服务器:" + std::string(error.what()); + } + return out; +} + +json CommonBody(const json& state, const std::string& username) { + json body = json::object(); + body["username"] = username; + body["device_id"] = Str(state, "device_id"); + body["device_name"] = ComputerNameUtf8(); + body["device_type"] = "windows"; + return body; +} + +} // namespace + +json Auth::State() { + std::lock_guard lock(g_mutex); + return LoadLocked(); +} + +void Auth::ClearSession() { + std::lock_guard lock(g_mutex); + json state = LoadLocked(); + state["token"] = ""; + state["user_id"] = 0; + state["last_ok"] = 0; + SaveLocked(state); +} + +void Auth::RememberCredentials(const std::string& username, const std::string& password) { + std::lock_guard lock(g_mutex); + json state = LoadLocked(); + state["remember"] = true; + state["saved_username"] = username; + state["saved_password"] = Obfuscate(password); + SaveLocked(state); +} + +void Auth::ForgetCredentials() { + std::lock_guard lock(g_mutex); + json state = LoadLocked(); + state["remember"] = false; + state["saved_username"] = ""; + state["saved_password"] = ""; + SaveLocked(state); +} + +bool Auth::Remembered() { + std::lock_guard lock(g_mutex); + const json state = LoadLocked(); + return state.value("remember", false); +} + +std::string Auth::SavedUsername() { + std::lock_guard lock(g_mutex); + const json state = LoadLocked(); + return state.value("remember", false) ? Str(state, "saved_username") : std::string(); +} + +std::string Auth::SavedPassword() { + std::lock_guard lock(g_mutex); + const json state = LoadLocked(); + if (!state.value("remember", false)) return std::string(); + return Deobfuscate(Str(state, "saved_password")); +} + +AuthResult Auth::Register(const std::string& username, const std::string& password) { + const json state = Ensure(); + json body = CommonBody(state, username); + body["password"] = password; + return Call("register", body, std::string(), false); +} + +AuthResult Auth::Login(const std::string& username, const std::string& password) { + const json state = Ensure(); + json body = CommonBody(state, username); + body["password"] = password; + AuthResult result = Call("login", body, std::string(), false); + if (result.ok) { + const std::string token = Str(result.data, "token"); + if (token.empty()) { + result.ok = false; + result.message = "登录响应缺少 token"; + } else { + std::lock_guard lock(g_mutex); + json saved = LoadLocked(); + saved["username"] = username; + saved["user_id"] = result.data.value("user_id", 0); + saved["token"] = token; + saved["last_ok"] = static_cast(std::time(nullptr)); + SaveLocked(saved); + } + } + return result; +} + +AuthResult Auth::Recharge(const std::string& username, const std::string& cardKey) { + const json state = Ensure(); + json body = json::object(); + body["username"] = username; + body["card_key"] = cardKey; + body["device_id"] = Str(state, "device_id"); + return Call("recharge", body, std::string(), false); +} + +AuthResult Auth::Heartbeat() { + const json state = Ensure(); + const std::string token = Str(state, "token"); + if (token.empty()) { + AuthResult out; + out.status = 401; + out.message = "尚未登录"; + return out; + } + AuthResult result = Call("heartbeat", json::object(), token, false); + // token 失效或余额/订阅异常时清掉本地登录态;只在 token 未被并发登录替换时清 + if (!result.ok && (result.status == 401 || result.status == 403)) { + std::lock_guard lock(g_mutex); + json saved = LoadLocked(); + if (Str(saved, "token") == token) { + saved["token"] = ""; + SaveLocked(saved); + } + } + return result; +} + +AuthResult Auth::Info() { + return Call("info", json::object(), std::string(), true); +} + +AuthResult Auth::CheckUpdate(const std::string& version) { + return Call("check-update?version=" + version, json::object(), std::string(), true); +} + +std::string Auth::ResolveUrl(const std::string& url) { + if (url.empty()) return url; + if (url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0) return url; + if (url[0] == '/') return std::string(kBaseUrl) + url; + return std::string(kBaseUrl) + "/" + url; +} + +} diff --git a/native/src/Auth.h b/native/src/Auth.h new file mode 100644 index 0000000..1dfe4d9 --- /dev/null +++ b/native/src/Auth.h @@ -0,0 +1,44 @@ +#pragma once + +#include + +#include "Json.h" + +namespace pddai { + +struct AuthResult { + bool ok = false; + int status = 0; // HTTP 状态码;0 表示网络层失败 + std::string message; // 服务端 message 或本地错误说明 + json data; // 响应中的 data 字段 +}; + +// 对接验证平台 /api/v1/app/{appKey}/* 的公开接口与心跳。 +// 所有网络调用都是同步的,调用方需放在工作线程里执行。 +class Auth { +public: + // 缓存的本地状态(config/auth.json),不含密码与卡密 + static json State(); + + // 退出登录:只清 token / user_id,保留账号名与设备标识 + static void ClearSession(); + + // 记住账号密码:密码做轻量混淆后随登录态一起写入 auth.json + static void RememberCredentials(const std::string& username, const std::string& password); + static void ForgetCredentials(); + static bool Remembered(); + static std::string SavedUsername(); + static std::string SavedPassword(); + + static AuthResult Register(const std::string& username, const std::string& password); + static AuthResult Login(const std::string& username, const std::string& password); + static AuthResult Recharge(const std::string& username, const std::string& cardKey); + static AuthResult Heartbeat(); + static AuthResult Info(); + // 版本检测:version 为当前客户端版本号 + static AuthResult CheckUpdate(const std::string& version); + // 把服务端返回的相对地址(如 /uploads/xxx.zip)补全为完整 URL + static std::string ResolveUrl(const std::string& url); +}; + +} diff --git a/native/src/Pipeline.cpp b/native/src/Pipeline.cpp index f2afce5..7874cc3 100644 --- a/native/src/Pipeline.cpp +++ b/native/src/Pipeline.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -279,6 +280,8 @@ json NormalizeMessages(const json& raw) { const json config = Config::GetJson("server.json", json::object()); long long historyLimit = 6; + // 全部历史:不截断 + if (config.is_object() && config.value("historyAll", false)) historyLimit = 0; const json limit = config.is_object() ? config.value("historyLimit", json()) : json(); if (limit.is_number_integer()) { const long long value = limit.get(); @@ -471,15 +474,28 @@ void ApplyMatchedImages(json& data, const json& images) { if (!withText) data["reply"] = ""; } -// 返回 {name, reply, images?} 或 null +// 随机回复:命中后从 replies 里随机取一条,没配则用 reply 单条 +std::string PickQuickReplyText(const json& rule) { + std::vector candidates; + for (const std::string& line : StringArray(GetMember(rule, "replies"))) { + if (!line.empty()) candidates.push_back(line); + } + if (candidates.empty()) return JsString(GetMember(rule, "reply")); + + static thread_local std::mt19937 rng(std::random_device{}()); + std::uniform_int_distribution dist(0, candidates.size() - 1); + return candidates[dist(rng)]; +} + json MatchQuickReply(const std::string& text, const json& quickReplies, const json& imageLibrary) { const std::string normalized = NormalizeForQuickReply(text); if (normalized.empty() || !quickReplies.is_array()) return json(); for (const json& rule : quickReplies) { if (!rule.is_object()) continue; + // 默认按包含关键词匹配(关键词是买家消息的一部分即可),只有显式写 exact 才要求整句一致 const std::string matchMode = JsString(GetMember(rule, "match")); - const bool includesMode = matchMode == "includes"; + const bool includesMode = matchMode != "exact"; bool matched = false; for (const std::string& keyword : StringArray(GetMember(rule, "keywords"))) { @@ -497,7 +513,7 @@ json MatchQuickReply(const std::string& text, const json& quickReplies, const js std::string name = JsString(GetMember(rule, "name")); if (name.empty()) name = "quick-reply"; out["name"] = name; - out["reply"] = JsString(GetMember(rule, "reply")); + out["reply"] = PickQuickReplyText(rule); json images = json::array(); for (const std::string& key : StringArray(GetMember(rule, "imageIds"))) { @@ -1963,6 +1979,32 @@ std::string BuildCozeProductContext(const json& context) { for (const std::string& part : parts) { if (seen.insert(part).second) unique.push_back(part); } + + // 商品属性(是否换底、是否裁切、规格、工艺等)必须一起给模型, + // 否则模型只能靠通用常识猜,容易把别的商品规则套过来。 + const json product = GetMember(context, "product"); + bool hasAttributes = false; + if (product.is_object()) { + const std::string name = JsString(GetMember(product, "name")); + if (!name.empty()) unique.push_back("商品名称:" + name); + const json attributes = GetMember(product, "attributes"); + if (attributes.is_object()) { + std::vector items; + for (auto it = attributes.begin(); it != attributes.end(); ++it) { + const std::string value = JsString(it.value()); + if (value.empty()) continue; + items.push_back(it.key() + ":" + value); + if (items.size() >= 30) break; + } + if (!items.empty()) { + unique.push_back("商品属性:" + JoinStrings(items, ";")); + hasAttributes = true; + } + } + } + if (!hasAttributes) { + unique.push_back("商品属性:未提供,不要自行推断能否换底、裁切或其它工艺限制"); + } return JoinStrings(unique, "\n"); } @@ -2066,6 +2108,8 @@ std::string BuildCozeCustomerQuery(const std::string& requestId, const json& con "如果客户最新问题是通用问题或标准话术问题,例如正品、防伪、发货、售后配节、价格、赠品、包装、发票、优惠、保修等,请优先检索并参考知识库文件“标准FAQ.md”。", "如果“标准FAQ.md”中有同义或近似问题,优先使用其中的标准回答和语气,再结合商品上下文做必要补充。", "知识库检索时必须优先使用“当前商品卡片信息”和“客户最新问题”共同判断商品型号/规格。", + "回答换底色、裁剪、尺寸、材质、工艺等商品能力问题时,必须以“当前商品卡片信息”里的商品属性为准,不要用其它商品的规则代替。", + "商品属性里没有写的,不要断言“不能换底”“不做裁剪”这类限制;确实需要确认时,用不确定的语气请客户稍等核实。", "如果当前商品卡片信息包含型号、米数、套餐、规格,请优先匹配对应型号的话术;不要笼统回复“规格参数未提供”。", "只有当前商品为0且最近聊天也没有商品线索时,才可以说明需要客户提供具体规格。", "如果 orders 中有当前买家订单,买家询问订单号、下单时间、商品、订单状态或售后时,直接引用其中的真实数据,不要要求买家提供订单号。", @@ -2403,6 +2447,15 @@ json Pipeline::Run(const json& payload, const json& shop) { productCandidates.push_back(rankedCandidates[i]); } + // 属性有没有随请求带给模型,直接看日志就能确认 + if (product.is_object()) { + const json attributes = GetMember(product, "attributes"); + Log::Info("商品匹配:" + JsString(GetMember(product, "name")) + ",属性=" + + std::to_string(attributes.is_object() ? attributes.size() : 0) + " 项"); + } else { + Log::Info("商品匹配:未匹配到商品,回复不推断换底/裁切等工艺"); + } + std::string latestCustomerMessage; for (size_t i = messages.size(); i > 0; --i) { const json& item = messages[i - 1]; @@ -2413,7 +2466,45 @@ json Pipeline::Run(const json& payload, const json& shop) { } // 1) 快捷回复 - const json quickReply = MatchQuickReply(latestCustomerMessage, quickReplies, imageLibrary); + // 只看最近一条客服消息之后买家发的内容:买家连发「你好」+图片时,前面那句文字也要参与命中 + std::vector pendingCustomerTexts; + for (size_t i = messages.size(); i > 0; --i) { + const json& item = messages[i - 1]; + const std::string usertype = JsString(GetMember(item, "usertype")); + if (usertype == "sys") break; + if (usertype != "cus") continue; + pendingCustomerTexts.push_back(JsString(GetMember(item, "msg"))); + } + // 末尾是客服/系统消息时说明买家上一条已经回复过,不能再把那条旧消息 + // 塞回来命中快捷回复,否则会把上一次的回复内容原样再发一遍。 + // latestCustomerMessage 仍用于后面的高危意图与模型上下文,不受影响。 + + Log::Info("快捷回复检查:规则=" + std::to_string(quickReplies.is_array() ? quickReplies.size() : 0) + + ",待回复买家消息=" + JoinStrings(pendingCustomerTexts, " | ")); + + // 最近一条客服消息之后没有买家内容,说明这一轮没有新消息要回。 + // 不能再拿更早的买家消息去命中快捷回复或让模型生成,否则会把上次的回复原样再发一遍。 + if (pendingCustomerTexts.empty()) { + json data = json::object(); + data["requestId"] = requestId; + data["action"] = "skip"; + data["reason"] = "no-pending-message"; + data["manualRequired"] = false; + data["reply"] = ""; + data["shopId"] = shopId; + data["shopName"] = shopName; + data["pid"] = pid; + data["riskIntents"] = json::array(); + data["source"] = "no-pending-message"; + return data; + } + + json quickReply; + for (const std::string& text : pendingCustomerTexts) { + if (text.empty() || text == "[图片]" || text == "[视频]") continue; + quickReply = MatchQuickReply(text, quickReplies, imageLibrary); + if (quickReply.is_object()) break; + } if (quickReply.is_object()) { json data = json::object(); data["requestId"] = requestId; diff --git a/native/src/Server.cpp b/native/src/Server.cpp index 6d2fd9d..8ed0837 100644 --- a/native/src/Server.cpp +++ b/native/src/Server.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -625,6 +626,8 @@ bool IsTrustedOrigin(const httplib::Request& req) { } long long RuntimeHistoryLimit(const json& config) { + // historyAll:读取全部历史,等价于 0 + if (config.is_object() && config.value("historyAll", false)) return 0; const json value = config.is_object() ? config.value("historyLimit", json()) : json(); if (!value.is_number_integer()) return 6; const long long limit = value.get(); @@ -852,8 +855,11 @@ void HandleRuntimeConfig(const httplib::Request& req, httplib::Response& res) { json data = json::object(); data["ok"] = true; data["historyLimit"] = RuntimeHistoryLimit(config); + data["historyAll"] = config.is_object() && config.value("historyAll", false); data["imageOutputDir"] = PickString(config, "imageOutputDir"); data["imageSaveEnabled"] = PickBool(config, "imageSaveEnabled", true); + // 买家把图片当文件发送时,也按聊天图片识别、下载、计数 + data["imageFileAsImage"] = PickBool(config, "imageFileAsImage", true); const std::string mode = PickString(config, "imageAssignMode"); data["imageAssignMode"] = (mode == "time" || mode == "sequence" || mode == "sequence-reverse" || mode == "hybrid") ? mode : "hybrid"; @@ -864,6 +870,8 @@ void HandleRuntimeConfig(const httplib::Request& req, httplib::Response& res) { data["imageHistoryLeadMs"] = (std::max)(60000LL, (std::min)(86400000LL, PickIntMs(config, "imageHistoryLeadMs", 600000))); data["imageCountCheck"] = PickBool(config, "imageCountCheck", true); + // 商品关键词固定张数:命中后整单按固定值校验,忽略规格里的「N张」 + data["imageKeywordFixedCount"] = PickString(config, "imageKeywordFixedCount"); data["imageReviewEnabled"] = PickBool(config, "imageReviewEnabled", true); data["imageKeepOrderTab"] = PickBool(config, "imageKeepOrderTab", true); // 数量不符时给订单文件夹加备注、并自动回复买家差值 @@ -906,6 +914,8 @@ void HandleRuntimeConfig(const httplib::Request& req, httplib::Response& res) { ? Config::DefaultAdjustDeleteReply() : adjustDeleteReply; data["minPageDelayMs"] = (std::max)(0LL, (std::min)(60000LL, PickIntMs(config, "minPageDelayMs", 150))); data["maxPageDelayMs"] = (std::max)(0LL, (std::min)(60000LL, PickIntMs(config, "maxPageDelayMs", 400))); + // 个人订单面板缓存时长:读一次要点开页签再点回去,太频繁会看到右侧闪动;0 表示每轮都重读 + data["orderCacheMs"] = (std::max)(0LL, (std::min)(3600000LL, PickIntMs(config, "orderCacheMs", 300000))); // 命中高危意图后,是否把该会话标记为转人工(后续消息不再自动回复) data["riskStopOnHit"] = PickBool(config, "riskStopOnHit", true); // 开场说明:首次咨询 / 有新订单时,先单独发一段规则说明 @@ -2213,6 +2223,18 @@ json HandleReplyCore(const json& payload, const json& shop) { return Pipeline::Run(payload, shop); } +// 命中风险意图时按店铺配置播放提醒声音(mail.json 的 riskSoundEnabled / riskSoundPath) +void PlayRiskSound() { + try { + const json mail = Config::GetJson("mail.json", json::object()); + if (!mail.is_object() || !mail.value("riskSoundEnabled", false)) return; + const std::string path = mail.value("riskSoundPath", std::string()); + PlayAudioFile(path); + Log::Info("命中风险意图,已播放提醒声音"); + } catch (const std::exception&) { + } +} + // 只做计数,不影响任何返回给插件的字段 void RecordReplyStats(const json& result) { if (!result.is_object()) return; @@ -2258,6 +2280,9 @@ void HandleReply(const httplib::Request& req, httplib::Response& res) { const json result = HandleReplyCore(body, shop); RecordReplyStats(result); + const auto riskIt = result.find("riskIntents"); + if (riskIt != result.end() && riskIt->is_array() && !riskIt->empty()) PlayRiskSound(); + const long long targetDelay = PickReplyDelayMs(); const auto elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - started) diff --git a/native/src/Update.cpp b/native/src/Update.cpp new file mode 100644 index 0000000..7084318 --- /dev/null +++ b/native/src/Update.cpp @@ -0,0 +1,458 @@ +#include "Update.h" + +#include +#include +#include + +#include +#include +#include +#include + +#include "Auth.h" +#include "Json.h" +#include "Log.h" +#include "Util.h" + +namespace pddai { + +namespace { + +constexpr int kTimeoutMs = 15000; + +std::wstring ExePath() { + std::vector buf(MAX_PATH); + for (;;) { + const DWORD n = ::GetModuleFileNameW(nullptr, buf.data(), static_cast(buf.size())); + if (n == 0) return std::wstring(); + if (n < buf.size() - 1) break; + buf.resize(buf.size() * 2); + } + return std::wstring(buf.data()); +} + +std::string Str(const json& obj, const char* key) { + const auto it = obj.find(key); + if (it == obj.end() || !it->is_string()) return std::string(); + return it->get(); +} + +long long Int64(const json& obj, const char* key) { + const auto it = obj.find(key); + if (it == obj.end() || !it->is_number()) return 0; + return static_cast(it->get()); +} + +bool EnsureDir(const std::wstring& dir) { + if (::CreateDirectoryW(dir.c_str(), nullptr)) return true; + return ::GetLastError() == ERROR_ALREADY_EXISTS; +} + +struct UrlParts { + bool https = false; + std::wstring host; + int port = 0; + std::wstring path; +}; + +bool CrackUrl(const std::string& url, UrlParts& out) { + const std::wstring wide = Utf8ToWide(url); + URL_COMPONENTSW comp{}; + comp.dwStructSize = sizeof(comp); + wchar_t scheme[32]{}; + wchar_t host[512]{}; + wchar_t path[8192]{}; + wchar_t extra[8192]{}; + comp.lpszScheme = scheme; + comp.dwSchemeLength = 32; + comp.lpszHostName = host; + comp.dwHostNameLength = 512; + comp.lpszUrlPath = path; + comp.dwUrlPathLength = 8192; + comp.lpszExtraInfo = extra; + comp.dwExtraInfoLength = 8192; + if (!::WinHttpCrackUrl(wide.c_str(), static_cast(wide.size()), 0, &comp)) return false; + out.https = comp.nScheme == INTERNET_SCHEME_HTTPS; + out.host.assign(host, comp.dwHostNameLength); + out.port = static_cast(comp.nPort); + out.path.assign(path, comp.dwUrlPathLength); + out.path.append(extra, comp.dwExtraInfoLength); + if (out.path.empty()) out.path = L"/"; + return true; +} + +struct HandleGuard { + HINTERNET h = nullptr; + ~HandleGuard() { + if (h) ::WinHttpCloseHandle(h); + } +}; + +// 流式下载到文件,失败时 error 带 Win32 码 +bool DownloadFile(const std::string& url, const std::wstring& destPath, + const std::function& progress, std::string& error) { + UrlParts parts; + if (!CrackUrl(url, parts)) { + error = "下载地址无效:" + url; + return false; + } + + HandleGuard session{::WinHttpOpen(L"PddAI-Updater/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY, + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)}; + if (!session.h) { + error = "初始化下载失败"; + return false; + } + ::WinHttpSetTimeouts(session.h, kTimeoutMs, kTimeoutMs, kTimeoutMs, 60000); + + HandleGuard connect{::WinHttpConnect(session.h, parts.host.c_str(), + static_cast(parts.port), 0)}; + if (!connect.h) { + error = "连接更新服务器失败"; + return false; + } + + HandleGuard request{::WinHttpOpenRequest(connect.h, L"GET", parts.path.c_str(), nullptr, + WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, + parts.https ? WINHTTP_FLAG_SECURE : 0)}; + if (!request.h) { + error = "创建下载请求失败"; + return false; + } + if (!::WinHttpSendRequest(request.h, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, + 0, 0, 0) || + !::WinHttpReceiveResponse(request.h, nullptr)) { + error = "下载请求失败,Win32=" + std::to_string(::GetLastError()); + return false; + } + + DWORD status = 0; + DWORD size = sizeof(status); + ::WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX); + if (status != 200) { + error = "下载失败,HTTP " + std::to_string(status); + return false; + } + + long long total = 0; + wchar_t lengthText[64]{}; + size = sizeof(lengthText); + if (::WinHttpQueryHeaders(request.h, WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX, + lengthText, &size, WINHTTP_NO_HEADER_INDEX)) { + total = _wtoi64(lengthText); + } + + HANDLE file = ::CreateFileW(destPath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + error = "无法创建更新文件"; + return false; + } + + std::vector buffer(64 * 1024); + long long received = 0; + bool ok = true; + for (;;) { + DWORD read = 0; + if (!::WinHttpReadData(request.h, buffer.data(), static_cast(buffer.size()), &read)) { + error = "下载中断,Win32=" + std::to_string(::GetLastError()); + ok = false; + break; + } + if (read == 0) break; + DWORD written = 0; + if (!::WriteFile(file, buffer.data(), read, &written, nullptr) || written != read) { + error = "写入更新文件失败"; + ok = false; + break; + } + received += read; + if (total > 0 && progress) { + progress(static_cast(received * 100 / total)); + } + } + ::CloseHandle(file); + + if (ok && received == 0) { + error = "更新包内容为空"; + ok = false; + } + return ok; +} + +bool ReadWholeFile(const std::wstring& path, std::string& out) { + HANDLE file = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}; + if (!::GetFileSizeEx(file, &size) || size.QuadPart > 512LL * 1024 * 1024) { + ::CloseHandle(file); + return false; + } + out.resize(static_cast(size.QuadPart)); + DWORD read = 0; + const bool ok = out.empty() || + (::ReadFile(file, out.data(), static_cast(out.size()), &read, nullptr) && + read == out.size()); + ::CloseHandle(file); + return ok; +} + +bool RunHiddenAndWait(const std::wstring& commandLine, std::string& error) { + // 把子进程输出重定向到文件,失败时便于把真实原因带回去 + const std::wstring logPath = DataDir() + L"\\update\\extract.log"; + HANDLE log = ::CreateFileW(logPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + + STARTUPINFOW si{}; + si.cb = sizeof(si); + if (log != INVALID_HANDLE_VALUE) { + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); + si.hStdOutput = log; + si.hStdError = log; + } + + PROCESS_INFORMATION pi{}; + std::wstring cmd = commandLine; + if (!::CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, log != INVALID_HANDLE_VALUE, + CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) { + if (log != INVALID_HANDLE_VALUE) ::CloseHandle(log); + error = "无法启动解压进程,Win32=" + std::to_string(::GetLastError()); + return false; + } + ::WaitForSingleObject(pi.hProcess, 120000); + DWORD code = 1; + ::GetExitCodeProcess(pi.hProcess, &code); + ::CloseHandle(pi.hThread); + ::CloseHandle(pi.hProcess); + if (log != INVALID_HANDLE_VALUE) ::CloseHandle(log); + + if (code != 0) { + error = "解压更新包失败"; + std::string text; + if (ReadWholeFile(logPath, text) && !text.empty()) { + if (text.size() > 300) text = text.substr(text.size() - 300); + error += ":" + text; + } + return false; + } + return true; +} + +// 用系统自带 Expand-Archive 解压,避免引入第三方解压库 +bool ExtractZip(const std::wstring& zip, const std::wstring& dest, std::string& error) { + std::wstring cmd = L"powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "; + cmd += L"\"Expand-Archive -LiteralPath '" + zip + L"' -DestinationPath '" + dest + L"' -Force\""; + return RunHiddenAndWait(cmd, error); +} + +std::wstring FileNameOf(const std::wstring& path) { + const size_t pos = path.find_last_of(L"\\/"); + return pos == std::wstring::npos ? path : path.substr(pos + 1); +} + +std::wstring FindExeInDir(const std::wstring& dir, const std::wstring& preferred, int depth = 0) { + if (depth > 4) return std::wstring(); + WIN32_FIND_DATAW data{}; + HANDLE find = ::FindFirstFileW((dir + L"\\*").c_str(), &data); + if (find == INVALID_HANDLE_VALUE) return std::wstring(); + + std::wstring fallback; + do { + if (wcscmp(data.cFileName, L".") == 0 || wcscmp(data.cFileName, L"..") == 0) continue; + const std::wstring full = dir + L"\\" + data.cFileName; + if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + const std::wstring nested = FindExeInDir(full, preferred, depth + 1); + if (!nested.empty()) { + ::FindClose(find); + return nested; + } + continue; + } + if (!preferred.empty() && _wcsicmp(data.cFileName, preferred.c_str()) == 0) { + ::FindClose(find); + return full; + } + if (fallback.empty()) { + const size_t dot = std::wstring(data.cFileName).find_last_of(L'.'); + if (dot != std::wstring::npos && _wcsicmp(data.cFileName + dot, L".exe") == 0) { + fallback = full; + } + } + } while (::FindNextFileW(find, &data)); + ::FindClose(find); + return fallback; +} + +bool IsZipFile(const std::wstring& path) { + HANDLE file = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + char magic[4]{}; + DWORD read = 0; + const bool ok = ::ReadFile(file, magic, 4, &read, nullptr) && read == 4; + ::CloseHandle(file); + return ok && magic[0] == 'P' && magic[1] == 'K'; +} + +} // namespace + +std::string Update::CurrentVersion() { + const std::wstring path = ExePath(); + DWORD dummy = 0; + const DWORD size = ::GetFileVersionInfoSizeW(path.c_str(), &dummy); + if (size == 0) return "1.1.2"; + + std::vector data(size); + if (!::GetFileVersionInfoW(path.c_str(), 0, size, data.data())) return "1.1.2"; + + VS_FIXEDFILEINFO* info = nullptr; + UINT len = 0; + if (!::VerQueryValueW(data.data(), L"\\", reinterpret_cast(&info), &len) || !info) { + return "1.1.2"; + } + const DWORD ms = info->dwFileVersionMS; + const DWORD ls = info->dwFileVersionLS; + char text[32]{}; + std::snprintf(text, sizeof(text), "%u.%u.%u", HIWORD(ms), LOWORD(ms), HIWORD(ls)); + return text; +} + +UpdateInfo Update::Check() { + UpdateInfo out; + out.currentVersion = CurrentVersion(); + + const AuthResult result = Auth::CheckUpdate(out.currentVersion); + if (!result.ok) { + out.error = result.message; + Log::Warn("版本检测失败:" + result.message); + return out; + } + + const json& data = result.data; + out.latestVersion = Str(data, "latest_version"); + out.notes = Str(data, "update_notes"); + out.fileHash = Str(data, "file_hash"); + out.entryFile = Str(data, "entry_file"); + out.fileSize = Int64(data, "file_size"); + out.forced = Str(data, "update_strategy") == "forced"; + + // 安装器模式会对未登记的版本也返回 has_update=true,这里按版本号再判一次 + const auto hasUpdate = data.find("has_update"); + if (hasUpdate == data.end() || !hasUpdate->is_boolean() || !hasUpdate->get()) { + return out; + } + if (out.latestVersion.empty() || LowerAscii(out.latestVersion) == LowerAscii(out.currentVersion)) { + return out; + } + + out.downloadUrl = Str(data, "download_url"); + if (out.downloadUrl.empty()) out.downloadUrl = Str(data, "full_package_url"); + if (out.downloadUrl.empty()) { + out.error = "服务端未提供下载地址"; + return out; + } + out.available = true; + Log::Info("发现新版本 " + out.latestVersion + "(当前 " + out.currentVersion + ")"); + return out; +} + +bool Update::Apply(const UpdateInfo& info, const std::function& progress, + std::string& error) { + if (info.downloadUrl.empty()) { + error = "缺少下载地址"; + return false; + } + + const std::wstring temp = DataDir() + L"\\update"; + if (!EnsureDir(temp)) { + error = "无法创建更新目录:" + WideToUtf8(temp); + return false; + } + // Expand-Archive 只接受 .zip 后缀,所以下载文件固定带 .zip + const std::wstring package = temp + L"\\package.zip"; + const std::wstring extractDir = temp + L"\\files"; + ::DeleteFileW(package.c_str()); + + const std::string url = Auth::ResolveUrl(info.downloadUrl); + Log::Info("开始下载更新包:" + url); + if (!DownloadFile(url, package, [&progress](int percent) { + if (progress) progress(percent * 70 / 100); + }, error)) { + Log::Error("下载更新包失败:" + error); + return false; + } + + if (!info.fileHash.empty()) { + std::string bytes; + if (!ReadWholeFile(package, bytes)) { + error = "读取更新包失败"; + return false; + } + const std::string actual = Sha256Hex(bytes); + if (LowerAscii(actual) != LowerAscii(info.fileHash)) { + error = "更新包校验失败(哈希不一致),已放弃更新"; + Log::Error(error); + return false; + } + + } + if (progress) progress(72); + + std::wstring candidate = package; + if (IsZipFile(package)) { + ::RemoveDirectoryW(extractDir.c_str()); + EnsureDir(extractDir); + if (!ExtractZip(package, extractDir, error)) { + Log::Error(error); + return false; + } + candidate = FindExeInDir(extractDir, FileNameOf(Utf8ToWide(info.entryFile))); + if (candidate.empty()) { + error = "更新包中未找到可执行文件"; + return false; + } + } + if (progress) progress(85); + + const std::wstring exe = ExePath(); + const std::wstring backup = exe + L".old"; + ::DeleteFileW(backup.c_str()); + ::SetFileAttributesW(backup.c_str(), FILE_ATTRIBUTE_NORMAL); + + if (!::MoveFileExW(exe.c_str(), backup.c_str(), MOVEFILE_REPLACE_EXISTING)) { + error = "无法替换当前程序(文件被占用),请关闭后重试"; + Log::Error(error + ",Win32=" + std::to_string(::GetLastError())); + return false; + } + + bool placed = ::MoveFileExW(candidate.c_str(), exe.c_str(), MOVEFILE_REPLACE_EXISTING) != FALSE; + if (!placed) placed = ::CopyFileW(candidate.c_str(), exe.c_str(), FALSE) != FALSE; + if (!placed) { + ::MoveFileExW(backup.c_str(), exe.c_str(), MOVEFILE_REPLACE_EXISTING); + error = "写入新版本失败,已还原旧版本"; + Log::Error(error); + return false; + } + if (progress) progress(100); + + STARTUPINFOW si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + const std::wstring dir = ExeDir(); + if (::CreateProcessW(exe.c_str(), nullptr, nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si, + &pi)) { + ::CloseHandle(pi.hThread); + ::CloseHandle(pi.hProcess); + Log::Info("新版本已就位,正在重启"); + ::Sleep(300); + ::ExitProcess(0); + } + + error = "新版本已替换,请手动重新打开程序"; + return true; +} + +} diff --git a/native/src/Update.h b/native/src/Update.h new file mode 100644 index 0000000..0fd096e --- /dev/null +++ b/native/src/Update.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include + +namespace pddai { + +// 版本检测与自动更新:走验证平台的 /check-update,下载完整包后替换自身并重启 +struct UpdateInfo { + bool available = false; + bool forced = false; + std::string currentVersion; + std::string latestVersion; + std::string notes; + std::string downloadUrl; + std::string fileHash; + std::string entryFile; + long long fileSize = 0; + std::string error; +}; + +class Update { +public: + // 当前 exe 的文件版本,格式化为 a.b.c + static std::string CurrentVersion(); + + // 查询服务端最新版本;网络错误或服务端异常时 available=false 并填 error + static UpdateInfo Check(); + + // 下载 → 校验 SHA256 → 解压(zip 包)→ 替换 exe → 启动新进程并退出。 + // progress 回调传入 0~100 的进度,可能在工作线程中被调用。 + static bool Apply(const UpdateInfo& info, const std::function& progress, + std::string& error); +}; + +} diff --git a/native/src/Util.cpp b/native/src/Util.cpp index b751df3..be61995 100644 --- a/native/src/Util.cpp +++ b/native/src/Util.cpp @@ -1,5 +1,6 @@ #include "Util.h" +#include #include #include @@ -8,6 +9,8 @@ #include #include +#include "Log.h" + namespace pddai { std::wstring Utf8ToWide(std::string_view s) { @@ -235,21 +238,17 @@ std::string Base64Encode(const std::string& bytes) { } std::string Base64Decode(const std::string& text) { - static const int table[256] = { - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,0,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,-1,-1,-1,-1,-1,-1,-1,12,13,14,15,16,17,18,19,20,21,22,23, - 24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49, - 50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 - }; int accum = 0; int bits = 0; std::string out; for (const char c : text) { - const int v = table[static_cast(c)]; + const unsigned char ch = static_cast(c); + int v = -1; + if (ch >= 'A' && ch <= 'Z') v = ch - 'A'; + else if (ch >= 'a' && ch <= 'z') v = ch - 'a' + 26; + else if (ch >= '0' && ch <= '9') v = ch - '0' + 52; + else if (ch == '+') v = 62; + else if (ch == '/') v = 63; if (v < 0) continue; accum = (accum << 6) | v; bits += 6; @@ -327,4 +326,79 @@ std::string LowerAscii(std::string_view s) { return out; } +namespace { + +// PlaySound 只认 WAV,其它格式它会「返回成功但不出声」,所以 mp3 等一律走 MCI +bool PlayViaMci(const std::wstring& file, const wchar_t* type) { + constexpr const wchar_t* kAlias = L"pddai_audio"; + ::mciSendStringW(L"close pddai_audio", nullptr, 0, nullptr); + std::wstring open = L"open \"" + file + L"\""; + if (type && *type) open += std::wstring(L" type ") + type; + open += std::wstring(L" alias ") + kAlias; + MCIERROR status = ::mciSendStringW(open.c_str(), nullptr, 0, nullptr); + if (status != 0) { + wchar_t text[256]{}; + ::mciGetErrorStringW(status, text, 256); + Log::Error("MCI open 失败: " + WideToUtf8(text)); + return false; + } + status = ::mciSendStringW(L"play pddai_audio", nullptr, 0, nullptr); + if (status != 0) { + wchar_t text[256]{}; + ::mciGetErrorStringW(status, text, 256); + Log::Error("MCI play 失败: " + WideToUtf8(text)); + ::mciSendStringW(L"close pddai_audio", nullptr, 0, nullptr); + return false; + } + return true; +} + +void PlaySystemAlert() { + // 控制面板里系统声音可能被设为「无声」,此时 PlaySound 也毫无声音,补一声蜂鸣兜底 + if (!::PlaySoundW(L"SystemExclamation", nullptr, SND_ALIAS | SND_ASYNC)) { + ::MessageBeep(MB_ICONWARNING); + } + ::Beep(880, 200); +} + +} // namespace + +void PlayAudioFile(const std::string& path) { + Log::Info("试听/播放提醒声音: " + (path.empty() ? std::string("<未选择,使用系统提示音>") : path)); + if (path.empty()) { + PlaySystemAlert(); + return; + } + const std::wstring file = Utf8ToWide(path); + if (::GetFileAttributesW(file.c_str()) == INVALID_FILE_ATTRIBUTES) { + Log::Error("音频文件不存在,回落系统提示音"); + PlaySystemAlert(); + return; + } + + // 取扩展名决定播放方式:wav 走 PlaySound,其余按 MCI 解码 + std::wstring ext; + const size_t dot = file.find_last_of(L'.'); + if (dot != std::wstring::npos) ext = file.substr(dot + 1); + for (wchar_t& c : ext) c = static_cast(towlower(c)); + + if (ext == L"wav" && + ::PlaySoundW(file.c_str(), nullptr, SND_FILENAME | SND_ASYNC | SND_NODEFAULT)) { + Log::Info("PlaySound 播放成功"); + return; + } + // mp3 必须显式指定 mpegvideo 设备;wma 等先按原样打开,再试 mpegvideo + const wchar_t* type = ext == L"mp3" ? L"mpegvideo" : L""; + if (PlayViaMci(file, type)) { + Log::Info("MCI 播放成功(" + WideToUtf8(ext) + ")"); + return; + } + if (ext != L"mp3" && PlayViaMci(file, L"mpegvideo")) { + Log::Info("MCI(mpegvideo) 播放成功(" + WideToUtf8(ext) + ")"); + return; + } + Log::Error("PlaySound/MCI 都失败,回落系统提示音"); + PlaySystemAlert(); +} + } diff --git a/native/src/Util.h b/native/src/Util.h index c07ddd1..4419291 100644 --- a/native/src/Util.h +++ b/native/src/Util.h @@ -42,6 +42,9 @@ std::string Sha256Hex(const std::string& data); std::string Rfc2822NowUtc(); std::string ComputerNameUtf8(); void SleepMs(int ms); +// 播放本地音频文件(WAV 走 PlaySound,其他格式走 MCI);路径为空或文件无效时播放系统提示音 +void PlayAudioFile(const std::string& path); + std::string LowerAscii(std::string_view s); } diff --git a/native/src/WebConsole.cpp b/native/src/WebConsole.cpp index 963fde1..83a344b 100644 --- a/native/src/WebConsole.cpp +++ b/native/src/WebConsole.cpp @@ -423,9 +423,22 @@ struct ShopConsole { ComPtr env; ComPtr controller; ComPtr webView; + // 商家后台视图:和客服台共用同一个 Environment(同一 user data folder), + // 但要独立的 Controller 才能在标签里各自保留页面状态 + HWND backendHost = nullptr; + ComPtr backendController; + ComPtr backendWebView; + bool backendCreating = false; + bool backendPending = false; // 等 Environment 就绪后再建后台视图 + // 两个视图各自的当前地址:用来判断谁停在登录页,登录后自动把另一侧刷新成登录态 + std::string chatUrl; + std::string backendUrl; + ULONGLONG chatSyncMs = 0; + ULONGLONG backendSyncMs = 0; bool creating = false; bool canceled = false; bool visible = false; + bool backendVisible = false; double zoom = 1.0; bool measuring = false; int measureRound = 0; @@ -438,6 +451,11 @@ HWND g_owner = nullptr; std::mutex g_mutex; std::map> g_consoles; std::string g_active; +// 当前显示的视图:"chat"(客服台)或 "backend"(商家后台) +std::string g_view = "chat"; + +// 前置声明:Environment 就绪后可能要立刻建后台视图 +void CreateBackendView(const std::shared_ptr& console); RECT g_layout{0, 0, 0, 0}; bool g_layoutVisible = false; @@ -628,7 +646,8 @@ void MeasureConsole(const std::shared_ptr& console) { // 所以对当前可见的店铺每 5 秒补量一次(隐藏的店铺在屏幕外,不浪费时间扫 DOM) std::shared_ptr ActiveConsole() { std::lock_guard lock(g_mutex); - if (!g_layoutVisible || g_active.empty()) return nullptr; + // 只有客服台视图需要测量分栏;后台视图是普通网页,不参与缩放校正 + if (!g_layoutVisible || g_active.empty() || g_view != "chat") return nullptr; const auto it = g_consoles.find(g_active); return it == g_consoles.end() ? nullptr : it->second; } @@ -637,27 +656,39 @@ void CALLBACK MeasureTimerProc(HWND, UINT, UINT_PTR, DWORD) { MeasureConsole(ActiveConsole()); } -// 摆放几何 + 显隐。隐藏不用 put_IsVisible(FALSE)/SW_HIDE:WebView2 被判定为不可见后 -// 会挂起渲染,CDP 的 Input 回调直接不返回,后台店铺的自动回复会全部超时。 -// 改成把宿主窗口挪到屏幕外侧,页面始终处于「可见」状态。 +// 宿主窗口的摆放:显示时贴到前端上报的内容区,隐藏时挪到屏幕外。 +// 隐藏不用 put_IsVisible(FALSE)/SW_HIDE:WebView2 被判定为不可见后会挂起渲染, +// CDP 的 Input 回调直接不返回,后台店铺的自动回复会全部超时。 +void PlaceHost(HWND host, const RECT& layout, bool show) { + if (!host || !::IsWindow(host)) return; + const int width = (std::max)(1, static_cast(layout.right - layout.left)); + const int height = (std::max)(1, static_cast(layout.bottom - layout.top)); + if (show) { + // 主界面的 WebView 会把自己的 HWND 提到最前,每次显示都重新抢一次置顶 + ::SetWindowPos(host, HWND_TOP, layout.left, layout.top, width, height, + SWP_NOACTIVATE | SWP_SHOWWINDOW); + } else { + ::SetWindowPos(host, nullptr, -20000, -20000, width, height, + SWP_NOACTIVATE | SWP_SHOWWINDOW); + } +} + +// 摆放几何 + 显隐。同一店铺的客服台与后台视图各有一个宿主窗口, +// 只有「当前店铺 + 当前视图」对应的那个显示,其余都挪到屏幕外。 void ApplyGeometry(const std::shared_ptr& console, const RECT& layout, - const std::string& active, bool visible) { + const std::string& active, const std::string& view, bool visible) { if (!console) return; const int width = layout.right - layout.left; const int height = layout.bottom - layout.top; if (width < 1 || height < 1) return; - const bool show = visible && !active.empty() && console->shopId == active; - if (console->host && ::IsWindow(console->host)) { - if (show) { - // 主界面的 WebView 会把自己的 HWND 提到最前,每次显示都重新抢一次置顶 - ::SetWindowPos(console->host, HWND_TOP, layout.left, layout.top, width, height, - SWP_NOACTIVATE | SWP_SHOWWINDOW); - } else { - ::SetWindowPos(console->host, nullptr, -20000, -20000, width, height, - SWP_NOACTIVATE | SWP_SHOWWINDOW); - } - } + const bool activeShop = visible && !active.empty() && console->shopId == active; + // 后台视图还没建好时先继续显示客服台,避免切过去先白屏 + const bool showChat = activeShop && (view != "backend" || !console->backendController); + const bool showBackend = activeShop && !showChat; + PlaceHost(console->host, layout, showChat); + PlaceHost(console->backendHost, layout, showBackend); + if (console->controller) { // 页面铺满整个宿主区域,不再在右侧留白 const int webWidth = (std::max)(1, width - kRightGutter); @@ -666,16 +697,16 @@ void ApplyGeometry(const std::shared_ptr& console, const RECT& layo console->controller->put_IsVisible(TRUE); // 客服页是「会话列表 + 聊天区 + 右侧商品抽屉」三栏,右侧抽屉固定约 460px, - // 聊天区本身也有最小宽度;内容区窄于 1200 时右侧会被挤掉一截, - // 这里按可用宽度等比缩小(窄于 1200 才生效),保证整页都留在可视区。 - // 只在尺寸真的变化时才重设缩放:否则会把测量得到的更小缩放值反复顶回去 + // 聊天区本身也有最小宽度。实测页面所需最小宽度是 1228 CSS px(不是 1200), + // 这里按 1228 + 8px 余量作为基准,开屏就把缩放算到位;否则初始值会偏大, + // 5 秒一次的测量再缩一档,表现为打开客服台几秒后整页突然「抖动」一下。 const bool resized = console->lastW != width || console->lastH != height; if (resized) { console->lastW = width; console->lastH = height; console->measureRound = 0; // 尺寸变了才重新给满校正次数 - // 基准按实际可见宽度算,留白不参与排版,页面 CSS 视口仍是 1200 - const double target = (std::min)(1.0, static_cast(webWidth) / 1200.0); + // 基准按实际可见宽度算,留白不参与排版 + const double target = (std::min)(1.0, static_cast(webWidth) / 1236.0); if (std::fabs(target - console->zoom) > 0.004) { console->zoom = target; console->controller->put_ZoomFactor(target); @@ -685,25 +716,37 @@ void ApplyGeometry(const std::shared_ptr& console, const RECT& layo } } + if (console->backendController) { + RECT bounds{0, 0, (std::max)(1, width), height}; + console->backendController->put_Bounds(bounds); + console->backendController->put_IsVisible(TRUE); + } + // 从后台切回前台时把键盘焦点交给它,否则上一次会话的焦点可能还留在被挪走的页面里 - if (show && !console->visible && console->controller) { + if (showChat && !console->visible && console->controller) { console->controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC); } - console->visible = show; + if (showBackend && !console->backendVisible && console->backendController) { + console->backendController->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC); + } + console->visible = showChat; + console->backendVisible = showBackend; } // 在 UI 线程按当前布局刷新一个店铺的几何与可见性(快照从锁里取,COM 调用不放锁) void ApplyConsoleState(const std::shared_ptr& console) { RECT layout{}; std::string active; + std::string view; bool visible = false; { std::lock_guard lock(g_mutex); layout = g_layout; active = g_active; + view = g_view; visible = g_layoutVisible; } - ApplyGeometry(console, layout, active, visible); + ApplyGeometry(console, layout, active, view, visible); } std::shared_ptr FindConsole(const std::string& shopId) { @@ -712,19 +755,90 @@ std::shared_ptr FindConsole(const std::string& shopId) { return it == g_consoles.end() ? nullptr : it->second; } +// 拼多多客服台和商家后台都在 mms.pinduoduo.com,登录后会离开 /login。 +// 两个视图共用同一配置目录,cookie 本来就是同步的;差别只是「登录前就已打开的页面」 +// 会一直停在旧的登录页,看上去像没同步。切过去时刷新一次即可复用登录态,不必再扫码。 +bool IsLoginUrl(const std::string& url) { + return url.find("/login") != std::string::npos; +} + +// 客服台里的商品卡片、广告位常用 window.open 打开链接,WebView2 默认把它丢给系统浏览器。 +// 那些是手机版商品页(mobile.yangkeduo.com),需要手机号登录,和商家后台的登录态不通用, +// 于是会频繁弹出登录页。内嵌台不需要新窗口,统一拦掉。 +void BlockNewWindows(ICoreWebView2* view) { + if (!view) return; + view->add_NewWindowRequested( + Callback( + [](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) -> HRESULT { + if (!args) return S_OK; + args->put_Handled(TRUE); + return S_OK; + }) + .Get(), + nullptr); +} + +// 记录每个视图当前地址,用于判断哪一侧还停在登录页 +void TrackViewUrl(const std::shared_ptr& console, ICoreWebView2* view, bool backend) { + if (!view) return; + BlockNewWindows(view); + view->add_NavigationStarting( + Callback( + [console, backend](ICoreWebView2*, + ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT { + if (!args) return S_OK; + LPWSTR uri = nullptr; + if (SUCCEEDED(args->get_Uri(&uri)) && uri) { + const std::string url = WideToUtf8(uri); + ::CoTaskMemFree(uri); + if (backend) console->backendUrl = url; + else console->chatUrl = url; + } + return S_OK; + }) + .Get(), + nullptr); +} + +// 切到某个视图时调用:它停在登录页、另一侧已经登录,就刷新它 +void SyncLoginState(const std::shared_ptr& console) { + if (!console) return; + const ULONGLONG now = static_cast(::GetTickCount64()); + const bool chatLogin = IsLoginUrl(console->chatUrl); + const bool backendLogin = IsLoginUrl(console->backendUrl); + if (chatLogin && !console->backendUrl.empty() && !backendLogin && console->webView) { + if (now - console->chatSyncMs < 4000) return; // 防止和页面自身跳转互相触发 + console->chatSyncMs = now; + console->webView->Reload(); + Log::Info("[内嵌台] 店铺 " + console->shopId + " 的商家后台已登录,刷新客服台同步登录态"); + } else if (backendLogin && !console->chatUrl.empty() && !chatLogin && console->backendWebView) { + if (now - console->backendSyncMs < 4000) return; + console->backendSyncMs = now; + console->backendWebView->Reload(); + Log::Info("[内嵌台] 店铺 " + console->shopId + " 的客服台已登录,刷新商家后台同步登录态"); + } +} + void MarkFailed(const std::shared_ptr& console) { HWND host = nullptr; + HWND backendHost = nullptr; { std::lock_guard lock(g_mutex); console->creating = false; const auto it = g_consoles.find(console->shopId); if (it != g_consoles.end() && it->second == console) { - if (g_active == console->shopId) g_active.clear(); + if (g_active == console->shopId) { + g_active.clear(); + g_view = "chat"; + } g_consoles.erase(it); } host = console->host; console->host = nullptr; + backendHost = console->backendHost; + console->backendHost = nullptr; } + if (backendHost && ::IsWindow(backendHost)) ::DestroyWindow(backendHost); if (host && ::IsWindow(host)) ::DestroyWindow(host); } @@ -1006,6 +1120,10 @@ void StartConsole(HWND owner, const std::shared_ptr& console) { return S_OK; } console->env = env; + if (console->backendPending) { + console->backendPending = false; + CreateBackendView(console); + } if (!console->host || !::IsWindow(console->host)) { MarkFailed(console); return S_OK; @@ -1039,6 +1157,8 @@ void StartConsole(HWND owner, const std::shared_ptr& console) { if (SUCCEEDED(console->webView->get_Settings(&settings)) && settings) { settings->put_IsStatusBarEnabled(FALSE); } + // 记录当前地址:登录后靠它判断另一侧是否还停在登录页 + TrackViewUrl(console, console->webView.Get(), false); // 通知权限一律静默拒绝:否则 WebView2 会弹「是否允许发送通知」的 // 浏览器提示框,和页面自己的「浏览器未开启通知」引导框一起挡消息区。 @@ -1089,6 +1209,83 @@ void StartConsole(HWND owner, const std::shared_ptr& console) { .Get()); } +// ---------------- 商家后台视图(与客服台共用同一 Environment) ---------------- +// 同一店铺的客服台和后台视图共用一个 ICoreWebView2Environment,也就是同一个 user data +// folder,所以 cookie、localStorage 天然共享:客服台登录过,后台标签打开就是登录态。 +// 一个 Environment 可以创建多个 Controller,所以两个视图各自保留页面状态,切回来不刷新。 + +std::string BackendUrl() { + std::string url; + try { + const json server = Config::GetJson("server.json", json::object()); + url = Trim(server.value("pddBackendUrl", std::string())); + } catch (const std::exception&) { + url.clear(); + } + return url.empty() ? std::string("https://mms.pinduoduo.com/") : url; +} + +// 懒创建:第一次切到该店铺的后台标签时才建 Controller 并加载后台页面 +void CreateBackendView(const std::shared_ptr& console) { + if (!console || !console->env || console->backendCreating) return; + if (console->backendController) { + ApplyConsoleState(console); + return; + } + + if (!console->backendHost || !::IsWindow(console->backendHost)) { + console->backendHost = CreateHost(g_owner); + } + if (!console->backendHost) { + Log::Error("[内嵌台] 店铺 " + console->shopId + " 的后台视图宿主窗口创建失败"); + return; + } + + console->backendCreating = true; + console->env->CreateCoreWebView2Controller( + console->backendHost, + Callback( + [console](HRESULT r, ICoreWebView2Controller* controller) -> HRESULT { + console->backendCreating = false; + if (FAILED(r) || !controller) { + Log::Error("[内嵌台] 店铺 " + console->shopId + " 的后台视图创建失败"); + return S_OK; + } + console->backendController = controller; + controller->get_CoreWebView2(&console->backendWebView); + + ComPtr c2; + if (SUCCEEDED(console->backendController.As(&c2)) && c2) { + COREWEBVIEW2_COLOR bg{255, 255, 255, 255}; + c2->put_DefaultBackgroundColor(bg); + } + + if (console->backendWebView) { + TrackViewUrl(console, console->backendWebView.Get(), true); + ComPtr settings; + if (SUCCEEDED(console->backendWebView->get_Settings(&settings)) && settings) { + settings->put_IsStatusBarEnabled(FALSE); + } + // 与客服台保持同一套 stealth 补丁,避免同一账号在两处露出不同的 WebView2 指纹 + std::string script = kPatchScript; + const std::string stealth = LoadTextResource(IDR_INJECT_STEALTH_JS); + if (!stealth.empty()) script = stealth + "\n" + script; + script += "\n"; + console->backendWebView->AddScriptToExecuteOnDocumentCreated( + Utf8ToWide(script).c_str(), nullptr); + + const std::wstring url = Utf8ToWide(BackendUrl()); + console->backendWebView->Navigate(url.c_str()); + } + + controller->put_IsVisible(TRUE); + ApplyConsoleState(console); + Log::Info("[内嵌台] 店铺 " + console->shopId + " 的后台视图已打开"); + return S_OK; + }) + .Get()); +} + // ---------------- 真实输入:HTTP 线程封送到 UI 线程 ---------------- int RandomInt(int min, int max) { @@ -1325,7 +1522,7 @@ void ExecuteInput(const json& payload, const std::shared_ptr& requ } // namespace -bool WebConsole::Open(HWND owner, const std::string& shopId) { +bool WebConsole::Open(HWND owner, const std::string& shopId, const std::string& view) { if (!owner || !::IsWindow(owner)) { Log::Error("[内嵌台] 主窗口无效,无法打开"); return false; @@ -1343,13 +1540,16 @@ bool WebConsole::Open(HWND owner, const std::string& shopId) { return false; } + const bool wantBackend = view == "backend"; std::shared_ptr console; bool create = false; + bool backendReady = false; std::vector> all; { std::lock_guard lock(g_mutex); g_owner = owner; g_active = id; + g_view = wantBackend ? "backend" : "chat"; const auto it = g_consoles.find(id); if (it != g_consoles.end()) { console = it->second; @@ -1360,6 +1560,11 @@ bool WebConsole::Open(HWND owner, const std::string& shopId) { g_consoles[id] = console; create = true; } + // 后台视图要等这个店铺的 Environment 就绪;已经有了就直接建 + if (wantBackend && !create && !console->backendController) { + if (console->env) backendReady = true; + else console->backendPending = true; + } for (const auto& pair : g_consoles) all.push_back(pair.second); } @@ -1374,8 +1579,14 @@ bool WebConsole::Open(HWND owner, const std::string& shopId) { ::SetTimer(nullptr, 1, 5000, MeasureTimerProc); timerStarted = true; } + if (wantBackend) { + if (backendReady) CreateBackendView(console); // 已就绪,直接建/显示后台视图 + else if (create) { /* Environment 就绪后由 StartConsole 回调接手 */ } + } // 先隐藏其它店铺,再把当前店铺的几何与可见性刷新一遍 for (const auto& item : all) ApplyConsoleState(item); + // 切过来时如果这一侧还停在登录页、另一侧已经登录,刷新一次拿到共享的登录态 + SyncLoginState(console); return true; } @@ -1419,8 +1630,10 @@ bool WebConsole::Logout(const std::string& shopId) { [console](HRESULT errorCode) -> HRESULT { if (FAILED(errorCode)) { Log::Error("[内嵌台] 清除登录数据失败"); - } else if (console->webView) { - console->webView->Reload(); + } else { + // 两个视图共用同一配置目录,清完后都回到未登录状态 + if (console->webView) console->webView->Reload(); + if (console->backendWebView) console->backendWebView->Reload(); Log::Info("[内嵌台] 已清除登录数据,页面重新加载"); } return S_OK; @@ -1437,24 +1650,35 @@ bool WebConsole::Logout(const std::string& shopId) { void WebConsole::Close(const std::string& shopId) { std::shared_ptr console; HWND host = nullptr; + HWND backendHost = nullptr; { std::lock_guard lock(g_mutex); const auto it = g_consoles.find(shopId); if (it == g_consoles.end()) return; console = it->second; g_consoles.erase(it); - if (g_active == shopId) g_active.clear(); + if (g_active == shopId) { + g_active.clear(); + g_view = "chat"; + } host = console->host; console->host = nullptr; + backendHost = console->backendHost; + console->backendHost = nullptr; } console->canceled = true; + // 后台视图和客服台共用配置目录,关店铺时一起销毁,避免留下孤立的 WebView2 + if (console->backendController) console->backendController->Close(); + console->backendController.Reset(); + console->backendWebView.Reset(); if (console->controller) { console->controller->put_IsVisible(FALSE); console->controller->Close(); } console->controller.Reset(); console->webView.Reset(); + if (backendHost && ::IsWindow(backendHost)) ::DestroyWindow(backendHost); if (host && ::IsWindow(host)) ::DestroyWindow(host); Log::Info("[内嵌台] 已关闭店铺 " + shopId); } @@ -1482,6 +1706,7 @@ std::vector WebConsole::OpenShopIds() { void WebConsole::SetLayout(const RECT& rect, bool visible) { std::vector> all; std::string active; + std::string view; bool show = false; RECT layout{}; { @@ -1496,10 +1721,11 @@ void WebConsole::SetLayout(const RECT& rect, bool visible) { } layout = g_layout; active = g_active; + view = g_view; show = g_layoutVisible && layout.right > layout.left && layout.bottom > layout.top; for (const auto& pair : g_consoles) all.push_back(pair.second); } - for (const auto& console : all) ApplyGeometry(console, layout, active, show); + for (const auto& console : all) ApplyGeometry(console, layout, active, view, show); } bool WebConsole::DispatchInput(const json& payload, std::string& error) { diff --git a/native/src/WebConsole.h b/native/src/WebConsole.h index b35792a..4c4be72 100644 --- a/native/src/WebConsole.h +++ b/native/src/WebConsole.h @@ -18,8 +18,10 @@ namespace pddai { class WebConsole { public: // 打开并切换到该店铺的内嵌台;首次调用时异步创建 Environment 与 Controller。 - // shopId 为空时取 shops.json 里的第一个店铺。 - static bool Open(HWND owner, const std::string& shopId); + // view = "chat" 显示客服台,view = "backend" 显示商家后台(共用同一 Environment, + // 因此 cookie / 登录态天然共享)。shopId 为空时取 shops.json 里的第一个店铺。 + static bool Open(HWND owner, const std::string& shopId, + const std::string& view = std::string("chat")); // 销毁某个店铺的 Controller 并释放它的配置目录占用 static void Close(const std::string& shopId); diff --git a/native/src/main.cpp b/native/src/main.cpp index 00e2a50..3fe0548 100644 --- a/native/src/main.cpp +++ b/native/src/main.cpp @@ -3,18 +3,25 @@ #include #include +#include +#include #include +#include #include #include #include +#include +#include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -29,11 +36,15 @@ #include "Log.h" #include "Server.h" #include "Http.h" +#include "Auth.h" #include "Smtp.h" #include "Stats.h" +#include "Update.h" #include "Util.h" #include "WebConsole.h" +#pragma comment(lib, "dbghelp.lib") + namespace { using Microsoft::WRL::Callback; @@ -44,7 +55,89 @@ using pddai::Utf8ToWide; using pddai::WideToUtf8; constexpr int kTitleBarHeight = 36; -constexpr const char* kVersion = "1.0.0"; +constexpr const char* kVersion = "1.1.2"; + +// ---------- 崩溃捕获 ---------- +// 闪退时没有任何痕迹就很难查,这里把异常码、模块偏移和一份 minidump 落到 data\crash。 +// 崩溃处理里只能用不分配内存的 API,所以路径预先算好,字符串用宽字符静态缓冲。 +wchar_t g_crashDir[MAX_PATH * 2] = {}; + +void AppendCrashText(const wchar_t* text) { + if (!g_crashDir[0] || !text) return; + wchar_t path[MAX_PATH * 2]; + swprintf_s(path, L"%s\\crash.log", g_crashDir); + HANDLE file = ::CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return; + DWORD written = 0; + ::WriteFile(file, text, static_cast(wcslen(text) * sizeof(wchar_t)), &written, nullptr); + ::CloseHandle(file); +} + +LONG WINAPI CrashFilter(EXCEPTION_POINTERS* info) { + const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0; + const ULONG_PTR address = info && info->ExceptionRecord + ? reinterpret_cast(info->ExceptionRecord->ExceptionAddress) : 0; + + // 找出异常地址落在哪个模块里,方便判断是 WebView2、bcrypt 还是自身代码 + wchar_t module[MAX_PATH] = L"未知"; + unsigned long long offset = static_cast(address); + HMODULE base = nullptr; + if (address && ::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(address), &base) && base) { + ::GetModuleFileNameW(base, module, MAX_PATH); + offset = static_cast(address - reinterpret_cast(base)); + } + + SYSTEMTIME st{}; + ::GetLocalTime(&st); + wchar_t line[512]; + swprintf_s(line, L"[%04d-%02d-%02d %02d:%02d:%02d] 崩溃 code=0x%08X 模块=%s 偏移=0x%llX\r\n", + st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, + static_cast(code), module, offset); + AppendCrashText(line); + + if (g_crashDir[0]) { + wchar_t dump[MAX_PATH * 2]; + swprintf_s(dump, L"%s\\crash-%04d%02d%02d-%02d%02d%02d.dmp", g_crashDir, + st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); + HANDLE file = ::CreateFileW(dump, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (file != INVALID_HANDLE_VALUE) { + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo{}; + exceptionInfo.ThreadId = ::GetCurrentThreadId(); + exceptionInfo.ExceptionPointers = info; + exceptionInfo.ClientPointers = FALSE; + ::MiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(), file, + static_cast(MiniDumpWithIndirectlyReferencedMemory | + MiniDumpWithDataSegs), + info ? &exceptionInfo : nullptr, nullptr, nullptr); + ::CloseHandle(file); + } + } + return EXCEPTION_EXECUTE_HANDLER; +} + +void TerminateHandler() { + // std::terminate 通常是工作线程里漏了 try/catch + AppendCrashText(L"std::terminate:未捕获的 C++ 异常\r\n"); + ::TerminateProcess(::GetCurrentProcess(), 3); + std::abort(); +} + +// 工作线程统一兜底:未捕获异常会让整个进程直接退出(表现为闪退), +// 这里至少记一条日志,不让后台任务把界面带走 +template +void RunThreadGuarded(const char* name, Fn&& fn) { + try { + fn(); + } catch (const std::exception& error) { + pddai::Log::Error(std::string("[线程] ") + name + " 异常:" + error.what()); + } catch (...) { + pddai::Log::Error(std::string("[线程] ") + name + " 未知异常"); + } +} HWND g_hwnd = nullptr; DWORD g_uiThreadId = 0; @@ -54,6 +147,17 @@ bool g_openConsoleOnStart = false; // 启动时先在后台把第一个店铺的客服台建起来(窗口挪到屏幕外), // 这样即使界面停在服务状态页,注入脚本与自动回复也能正常工作 bool g_consoleBootStarted = false; +// 首屏渲染完成前窗口保持全透明,避免用户看到空壳或白闪 +bool g_uiRevealed = false; +// 网络验证通过后才放行主功能,并启动本地服务与客服台 +bool g_authorized = false; +bool g_servicesStarted = false; +int g_authIntervalSeconds = 60; +// 版本更新:后台检测结果与下载状态 +std::mutex g_updateMutex; +pddai::UpdateInfo g_updateInfo; +bool g_updateChecked = false; +std::atomic g_updateDownloading{false}; // 命令行:--config 或 --config=,--console 启动即打开内嵌客服台 std::wstring ParseCliConfigDir() { @@ -96,6 +200,80 @@ void PostToast(const std::string& text, bool ok) { PostJson(payload); } +void PushUpdateState(const std::string& status, const pddai::UpdateInfo& info, int percent, + const std::string& message) { + json payload = json::object(); + payload["type"] = "updateState"; + payload["status"] = status; + payload["currentVersion"] = info.currentVersion; + payload["latestVersion"] = info.latestVersion; + payload["notes"] = info.notes; + payload["forced"] = info.forced; + payload["sizeBytes"] = info.fileSize; + payload["percent"] = percent; + payload["message"] = message; + PostJson(payload); +} + +void StartUpdateCheck() { + if (!g_authorized || g_updateDownloading) return; + std::thread([]() { + RunThreadGuarded("版本检查", [] { + const pddai::UpdateInfo info = pddai::Update::Check(); + { + std::lock_guard lock(g_updateMutex); + g_updateInfo = info; + g_updateChecked = true; + } + PushUpdateState(info.available ? "available" : "none", info, 0, info.error); + }); + }).detach(); +} + +void StartUpdateDownload() { + if (g_updateDownloading) return; + pddai::UpdateInfo info; + { + std::lock_guard lock(g_updateMutex); + info = g_updateInfo; + } + if (!info.available) return; + + g_updateDownloading = true; + std::thread([info]() { + RunThreadGuarded("下载更新", [info] { + std::string error; + int lastPercent = -1; + PushUpdateState("downloading", info, 0, "正在下载更新包…"); + const bool ok = pddai::Update::Apply(info, [&](int percent) { + if (percent - lastPercent < 2) return; + lastPercent = percent; + PushUpdateState("downloading", info, percent, "正在下载更新包…"); + }, error); + if (!ok) { + PushUpdateState("error", info, 0, error); + return; + } + // 正常流程 Apply 会重启并退出;走到这里说明需要用户手动重新打开 + PushUpdateState("ready", info, 100, error); + }); + // 无论成功还是异常都要复位,否则之后再也点不了下载 + g_updateDownloading = false; + }).detach(); +} + +// 上次自更新留下的 .old 文件,启动时清掉(旧进程可能还没完全退出,重试几次) +void CleanupOldExe() { + wchar_t path[MAX_PATH * 2]{}; + if (!::GetModuleFileNameW(nullptr, path, MAX_PATH)) return; + const std::wstring backup = std::wstring(path) + L".old"; + for (int i = 0; i < 10; ++i) { + if (::DeleteFileW(backup.c_str())) return; + if (::GetLastError() == ERROR_FILE_NOT_FOUND) return; + ::Sleep(200); + } +} + std::string MemberString(const json& obj, const char* key) { if (!obj.is_object()) return ""; const auto it = obj.find(key); @@ -171,6 +349,42 @@ void PushStatusToUi() { PostJson(payload); } +// 上次使用的店铺:重启后回到这个店铺,避免总是跳回列表第一家 +std::string ReadUiActiveShop() { + std::string id; + try { + const json ui = pddai::Config::GetJsonGlobal("ui.json", json::object()); + if (ui.is_object() && ui.contains("activeShop") && ui["activeShop"].is_string()) { + id = ui["activeShop"].get(); + } + } catch (const std::exception&) { + id.clear(); + } + if (id.empty() || !pddai::Config::IsSafeShopId(id)) return std::string(); + // 店铺可能已经被删掉,只有还存在于 shops.json 时才恢复 + for (const json& shop : pddai::Config::LoadShops()) { + if (shop.is_object() && shop.value("id", std::string()) == id) return id; + } + return std::string(); +} + +void SaveUiActiveShop(const std::string& shopId) { + if (shopId.empty() || !pddai::Config::IsSafeShopId(shopId)) return; + json ui = json::object(); + try { + const json existing = pddai::Config::GetJsonGlobal("ui.json", json::object()); + if (existing.is_object()) ui = existing; + } catch (const std::exception&) { + } + if (ui.value("activeShop", std::string()) == shopId) return; + ui["activeShop"] = shopId; + try { + pddai::Config::WriteTextGlobal("ui.json", ui.dump(2)); + } catch (const std::exception& error) { + pddai::Log::Error(std::string("保存当前店铺失败: ") + error.what()); + } +} + void PushShopsToUi() { const json shops = pddai::Config::LoadShops(); const std::map paused = pddai::Server::PausedShopIds(); @@ -193,6 +407,8 @@ void PushShopsToUi() { json payload = json::object(); payload["type"] = "shops"; payload["rows"] = rows; + // 告诉前端上次用的是哪个店铺,首屏直接打开它而不是列表第一家 + payload["activeShop"] = ReadUiActiveShop(); PostJson(payload); } @@ -461,6 +677,7 @@ void PushModelToUi() { payload["proxy"] = pick("proxyUrl"); payload["apiMode"] = pick("apiMode").empty() ? "chat" : pick("apiMode"); payload["historyLimit"] = config.value("historyLimit", 6); + payload["historyAll"] = config.value("historyAll", false); payload["imageOutputDir"] = pick("imageOutputDir"); PostJson(payload); } @@ -482,6 +699,7 @@ void PushImageSettingsToUi() { json payload = json::object(); payload["type"] = "imagesettings"; payload["enabled"] = MemberBool(config, "imageSaveEnabled", true); + payload["fileAsImage"] = MemberBool(config, "imageFileAsImage", true); payload["dir"] = MemberString(config, "imageOutputDir"); payload["groupByShop"] = MemberBool(config, "imageGroupByShop", true); payload["groupByOrder"] = MemberBool(config, "imageGroupByOrder", true); @@ -493,6 +711,7 @@ void PushImageSettingsToUi() { payload["batchSec"] = MemberInt(config, "imageBatchGapMs", 180000) / 1000; payload["historySec"] = MemberInt(config, "imageHistoryLeadMs", 600000) / 1000; payload["countCheck"] = MemberBool(config, "imageCountCheck", true); + payload["keywordFixedCount"] = MemberString(config, "imageKeywordFixedCount"); payload["countNoteEnabled"] = MemberBool(config, "imageCountNoteEnabled", true); payload["receiptReplyEnabled"] = MemberBool(config, "imageReceiptReplyEnabled", false); const std::string shortageReply = MemberString(config, "receiptShortageReply"); @@ -551,6 +770,7 @@ void SaveImageSettings(const json& msg) { if (!config.is_object()) config = json::object(); config["imageSaveEnabled"] = MemberBool(msg, "enabled", true); + config["imageFileAsImage"] = MemberBool(msg, "fileAsImage", true); config["imageGroupByShop"] = MemberBool(msg, "groupByShop", true); config["imageGroupByOrder"] = MemberBool(msg, "groupByOrder", true); config["imageOutputDir"] = pddai::Trim(MemberString(msg, "dir")); @@ -568,6 +788,7 @@ void SaveImageSettings(const json& msg) { config["imageBatchGapMs"] = batchSec * 1000; config["imageHistoryLeadMs"] = historySec * 1000; config["imageCountCheck"] = MemberBool(msg, "countCheck", true); + config["imageKeywordFixedCount"] = pddai::Trim(MemberString(msg, "keywordFixedCount")); config["imageCountNoteEnabled"] = MemberBool(msg, "countNoteEnabled", true); config["imageReceiptReplyEnabled"] = MemberBool(msg, "receiptReplyEnabled", false); const std::string shortageReply = pddai::Trim(MemberString(msg, "receiptShortageReply")); @@ -748,6 +969,86 @@ int ClampInt(int value, int lo, int hi) { return value < lo ? lo : (value > hi ? hi : value); } +// 界面配色(config/ui.json,本机偏好,不随店铺切换) +std::string ReadUiTheme() { + try { + const json ui = pddai::Config::GetJsonGlobal("ui.json", json::object()); + if (ui.is_object()) { + const std::string theme = MemberString(ui, "theme"); + if (theme == "light" || theme == "green" || theme == "blue" || theme == "dark") return theme; + } + } catch (const std::exception& error) { + pddai::Log::Error(std::string("读取界面配色失败: ") + error.what()); + } + return "dark"; +} + +void SaveUiTheme(const std::string& theme) { + if (theme != "dark" && theme != "light" && theme != "green" && theme != "blue") return; + json ui = json::object(); + try { + const json existing = pddai::Config::GetJsonGlobal("ui.json", json::object()); + if (existing.is_object()) ui = existing; + } catch (const std::exception&) { + } + ui["theme"] = theme; + try { + pddai::Config::WriteTextGlobal("ui.json", ui.dump(2)); + } catch (const std::exception& error) { + pddai::Log::Error(std::string("保存界面配色失败: ") + error.what()); + } +} + +// 导航分组折叠状态(run/config/system),跟配色一起存在 config/ui.json +bool IsNavGroupId(const std::string& id) { + return id == "run" || id == "config" || id == "system"; +} + +std::string ReadUiNavCollapsed() { + std::string out; + try { + const json ui = pddai::Config::GetJsonGlobal("ui.json", json::object()); + if (ui.is_object() && ui.contains("navCollapsed") && ui["navCollapsed"].is_array()) { + for (const auto& item : ui["navCollapsed"]) { + if (!item.is_string()) continue; + const std::string id = item.get(); + if (!IsNavGroupId(id)) continue; + if (!out.empty()) out += ","; + out += id; + } + } + } catch (const std::exception&) { + } + return out; +} + +void SaveUiNavCollapsed(const std::string& csv) { + json list = json::array(); + size_t start = 0; + while (start <= csv.size()) { + const size_t comma = csv.find(',', start); + std::string id = csv.substr(start, comma == std::string::npos ? csv.size() - start : comma - start); + const size_t first = id.find_first_not_of(" \t"); + const size_t last = id.find_last_not_of(" \t"); + id = first == std::string::npos ? std::string() : id.substr(first, last - first + 1); + if (IsNavGroupId(id)) list.push_back(id); + if (comma == std::string::npos) break; + start = comma + 1; + } + json ui = json::object(); + try { + const json existing = pddai::Config::GetJsonGlobal("ui.json", json::object()); + if (existing.is_object()) ui = existing; + } catch (const std::exception&) { + } + ui["navCollapsed"] = list; + try { + pddai::Config::WriteTextGlobal("ui.json", ui.dump(2)); + } catch (const std::exception& error) { + pddai::Log::Error(std::string("保存导航折叠状态失败: ") + error.what()); + } +} + // ---------- 服务端高级设置(server.json,保留未知键) ---------- void PushServerOptionsToUi() { json config = json::object(); @@ -784,6 +1085,7 @@ void PushServerOptionsToUi() { payload["maxReplyDelayMs"] = MemberInt(config, "maxReplyDelayMs", 8000); payload["minPageDelayMs"] = MemberInt(config, "minPageDelayMs", 150); payload["maxPageDelayMs"] = MemberInt(config, "maxPageDelayMs", 400); + payload["orderCacheMs"] = MemberInt(config, "orderCacheMs", 300000); payload["riskStopOnHit"] = MemberBool(config, "riskStopOnHit", true); payload["modelTimeoutMs"] = MemberInt(config, "modelTimeoutMs", 45000); payload["mockWhenNoApiKey"] = MemberBool(config, "mockWhenNoApiKey", true); @@ -826,6 +1128,7 @@ void SaveServerOptions(const json& msg) { config["maxReplyDelayMs"] = ClampInt(MemberInt(msg, "maxReplyDelayMs", 8000), 0, 600000); config["minPageDelayMs"] = ClampInt(MemberInt(msg, "minPageDelayMs", 150), 0, 60000); config["maxPageDelayMs"] = ClampInt(MemberInt(msg, "maxPageDelayMs", 400), 0, 60000); + config["orderCacheMs"] = ClampInt(MemberInt(msg, "orderCacheMs", 300000), 0, 3600000); config["riskStopOnHit"] = MemberBool(msg, "riskStopOnHit", true); config["modelTimeoutMs"] = ClampInt(MemberInt(msg, "modelTimeoutMs", 45000), 1000, 600000); config["mockWhenNoApiKey"] = MemberBool(msg, "mockWhenNoApiKey", true); @@ -860,6 +1163,8 @@ json MailDefaults() { mail["cc"] = json::array(); mail["subjectPrefix"] = "[PDD客服会话,需人工处理]"; mail["dedupMs"] = 600000; + mail["riskSoundEnabled"] = false; + mail["riskSoundPath"] = ""; return mail; } @@ -905,6 +1210,8 @@ void PushMailToUi() { payload["cc"] = MemberStringArray(mail, "cc"); payload["subjectPrefix"] = MemberString(mail, "subjectPrefix"); payload["dedupMs"] = MemberInt(mail, "dedupMs", 600000); + payload["riskSoundEnabled"] = MemberBool(mail, "riskSoundEnabled", false); + payload["riskSoundPath"] = MemberString(mail, "riskSoundPath"); PostJson(payload); } @@ -935,6 +1242,8 @@ void SaveMail(const json& msg) { mail["cc"] = MemberStringArray(msg, "cc"); mail["subjectPrefix"] = MemberString(msg, "subjectPrefix"); mail["dedupMs"] = ClampInt(MemberInt(msg, "dedupMs", 600000), 0, 86400000); + mail["riskSoundEnabled"] = MemberBool(msg, "riskSoundEnabled", false); + mail["riskSoundPath"] = MemberString(msg, "riskSoundPath"); pddai::Config::WriteText("mail.json", mail.dump(2) + "\n"); payload["ok"] = true; @@ -947,6 +1256,41 @@ void SaveMail(const json& msg) { PostJson(payload); } +// 提醒声音是独立配置项:选择/勾选/清除后立即写入 mail.json,不依赖「保存邮件配置」 +void SaveRiskSound(const json& msg) { + try { + json mail = pddai::Config::GetJson("mail.json", json::object()); + if (!mail.is_object()) mail = json::object(); + mail["riskSoundEnabled"] = MemberBool(msg, "enabled", false); + mail["riskSoundPath"] = MemberString(msg, "path"); + pddai::Config::WriteText("mail.json", mail.dump(2) + "\n"); + pddai::Log::Info("已保存提醒声音配置"); + PushMailToUi(); + } catch (const std::exception& error) { + pddai::Log::Error(std::string("保存提醒声音配置失败: ") + error.what()); + } +} + +// 风险意图提醒声音:试听本地音频 +void PickAudioFile() { + wchar_t path[MAX_PATH]{}; + OPENFILENAMEW ofn{}; + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = g_hwnd; + ofn.lpstrFilter = L"音频文件\0*.mp3;*.wav;*.wma;*.m4a;*.aac;*.flac\0所有文件\0*.*\0"; + ofn.lpstrFile = path; + ofn.nMaxFile = MAX_PATH; + ofn.lpstrTitle = L"选择提醒声音"; + ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR; + + json payload = json::object(); + payload["type"] = "audioPicked"; + const bool ok = ::GetOpenFileNameW(&ofn) != FALSE; + payload["ok"] = ok; + payload["path"] = ok ? WideToUtf8(path) : std::string(); + PostJson(payload); +} + void PushLogsToUi() { std::string text; for (const pddai::Log::Entry& entry : pddai::Log::Recent(500)) { @@ -1460,6 +1804,8 @@ void SaveArchive(const json& msg) { if (limit < 0) limit = 0; if (limit > 500) limit = 500; + const bool historyAll = msg.value("historyAll", false); + config["historyAll"] = historyAll; config["historyLimit"] = limit; // 图片目录已独立到「图片保存」页,仅在消息显式携带时才更新,避免被清空 if (msg.contains("imageOutputDir")) { @@ -1467,7 +1813,7 @@ void SaveArchive(const json& msg) { } pddai::Config::WriteText("server.json", config.dump(2) + "\n"); payload["ok"] = true; - pddai::Log::Info("已保存聊天记录配置:读取条数=" + std::to_string(limit)); + pddai::Log::Info("已保存聊天记录配置:读取条数=" + (historyAll ? std::string("全部") : std::to_string(limit))); PushModelToUi(); } catch (const std::exception& error) { payload["ok"] = false; @@ -1504,6 +1850,244 @@ void ResizeWebView() { RECT rc{}; ::GetClientRect(g_hwnd, &rc); g_controller->put_Bounds(rc); + // 自绘的无边框窗口在缩放/最大化时,WebView2 不会自动感知父窗口变化, + // 不通知就可能残留一块纯色,看起来像左侧菜单和标签栏消失了 + g_controller->NotifyParentWindowPositionChanged(); +} + +// 参考 QinJiang 的启动方式:WebView2 初始化期间窗口保持透明,首屏加载完再一次显形, +// 这样启动阶段既不会白闪,也不会先看到一个空窗口再突然跳出内容。 +void RevealMainWindow() { + if (g_uiRevealed || !g_hwnd) return; + g_uiRevealed = true; + if (g_controller) g_controller->put_IsVisible(TRUE); + ::SetLayeredWindowAttributes(g_hwnd, 0, 255, LWA_ALPHA); + const LONG_PTR exStyle = ::GetWindowLongPtrW(g_hwnd, GWL_EXSTYLE); + ::SetWindowLongPtrW(g_hwnd, GWL_EXSTYLE, (exStyle & ~WS_EX_LAYERED) | WS_EX_APPWINDOW); + ::SetWindowPos(g_hwnd, nullptr, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); +} + +// ---------- 网络验证:启动校验 / 注册 / 登录 / 卡密充值 / 心跳 ---------- +constexpr UINT_PTR kAuthTimerId = 0xA17F; + +// 工作线程把结果封送回 UI 线程,保证授权状态、服务启停与消息推送都在主线程完成 +struct AuthOutcome { + bool ok = false; // 当前是否处于已授权状态 + bool actionOk = false; // 本次操作本身是否成功(用于 toast) + std::string action; // ""/login/register/recharge/logout/retry/heartbeat + std::string message; + std::string reason; + std::string username; + std::string summary; + json data; + int intervalSeconds = 0; +}; + +void PostAuthOutcome(const AuthOutcome& out) { + json payload = json::object(); + payload["ok"] = out.ok; + payload["actionOk"] = out.actionOk; + payload["action"] = out.action; + payload["message"] = out.message; + payload["reason"] = out.reason; + payload["username"] = out.username; + payload["summary"] = out.summary; + payload["intervalSeconds"] = out.intervalSeconds; + // 记住的账号密码回填给验证页 + payload["remember"] = pddai::Auth::Remembered(); + payload["savedUsername"] = pddai::Auth::SavedUsername(); + payload["savedPassword"] = pddai::Auth::SavedPassword(); + if (g_hwnd) { + ::PostMessageW(g_hwnd, WM_APP_AUTH, 0, + reinterpret_cast(new std::string(payload.dump()))); + } +} + +std::string BuildAuthSummary(const std::string& username, const json& data) { + std::string text = "账号:" + (username.empty() ? std::string("-") : username); + if (data.is_object()) { + if (data.value("is_permanent", false)) { + text += " · 永久授权"; + } else { + const auto balance = data.find("balance"); + const auto expiry = data.find("expiry_at"); + if (balance != data.end() && balance->is_number()) { + char buf[64]{}; + std::snprintf(buf, sizeof(buf), "%.2f", balance->get()); + text += " · 余额 " + std::string(buf); + } else if (expiry != data.end() && expiry->is_string()) { + text += " · 到期 " + expiry->get(); + } + } + } + return text; +} + +// 校验登录态:服务端把 JWT 里的用户/设备作为心跳依据,因此 heartbeat 是唯一可靠的校验方式 +void RunVerifyAsync(const std::string& action, bool withInfo) { + std::thread([action, withInfo]() { + RunThreadGuarded("网络验证", [action, withInfo] { + AuthOutcome out; + out.action = action; + if (withInfo) { + const pddai::AuthResult info = pddai::Auth::Info(); + if (info.ok && info.data.is_object()) { + out.intervalSeconds = ClampInt(info.data.value("heartbeat_interval", 60), 10, 3600); + } + } + + const json state = pddai::Auth::State(); + out.username = MemberString(state, "username"); + if (MemberString(state, "token").empty()) { + out.reason = "no-session"; + out.message = "请先登录或注册账号,未授权时无法使用客服功能"; + out.summary = BuildAuthSummary(out.username, json()); + } else { + const pddai::AuthResult hb = pddai::Auth::Heartbeat(); + out.ok = hb.ok; + out.actionOk = hb.ok; + out.data = hb.data; + out.message = hb.ok ? "验证通过" : hb.message; + out.summary = BuildAuthSummary(out.username, hb.data); + if (!hb.ok) { + out.reason = (hb.status == 401 || hb.status == 403) ? "expired" : "offline"; + } + } + PostAuthOutcome(out); + }); + }).detach(); +} + +void HandleAuthMessage(const std::string& type, const json& parsed) { + const std::string username = MemberString(parsed, "username"); + const std::string password = MemberString(parsed, "password"); + const std::string cardKey = MemberString(parsed, "cardKey"); + const bool remember = parsed.is_object() && parsed.value("remember", false); + + std::string action; + if (type == "authLogin") action = "login"; + else if (type == "authRegister") action = "register"; + else if (type == "authRecharge") action = "recharge"; + else if (type == "authLogout") action = "logout"; + else if (type == "authRetry") action = "retry"; + + if (action == "retry") { + RunVerifyAsync("retry", true); + return; + } + if (action == "logout") { + pddai::Auth::ClearSession(); + AuthOutcome out; + out.action = "logout"; + out.actionOk = true; + out.reason = "logout"; + out.message = "已退出登录,请重新登录"; + const json state = pddai::Auth::State(); + out.username = MemberString(state, "username"); + out.summary = BuildAuthSummary(out.username, json()); + PostAuthOutcome(out); + return; + } + + std::thread([action, username, password, cardKey, remember]() { + RunThreadGuarded("账号操作", [action, username, password, cardKey, remember] { + AuthOutcome out; + out.action = action; + out.username = username; + if (action == "login") { + const pddai::AuthResult result = pddai::Auth::Login(username, password); + out.ok = result.ok; + out.actionOk = result.ok; + out.message = result.message; + out.data = result.data; + if (result.ok) { + // 勾选「记住账号密码」才落盘,取消勾选则清除旧记录 + if (remember) pddai::Auth::RememberCredentials(username, password); + else pddai::Auth::ForgetCredentials(); + } else { + out.reason = (result.status == 401 || result.status == 403) ? "expired" : "offline"; + } + } else if (action == "register") { + const pddai::AuthResult result = pddai::Auth::Register(username, password); + out.actionOk = result.ok; + out.message = result.ok ? "注册成功,请切换到「登录」页签登录" : result.message; + out.reason = "no-session"; + } else if (action == "recharge") { + const pddai::AuthResult result = pddai::Auth::Recharge(username, cardKey); + out.actionOk = result.ok; + out.message = result.message; + out.data = result.data; + if (!result.ok) out.reason = "no-session"; + } + // 注册 / 充值不改变已有登录态:以心跳结果为准,避免把已授权用户误判为未授权 + if (action == "register" || action == "recharge") { + const json state = pddai::Auth::State(); + const std::string signedIn = MemberString(state, "username"); + if (!MemberString(state, "token").empty()) { + const pddai::AuthResult hb = pddai::Auth::Heartbeat(); + out.ok = hb.ok; + out.username = signedIn; + out.data = hb.data; + if (!hb.ok) { + out.message = hb.message; + out.reason = "expired"; + } else if (action == "register") { + out.message = "注册成功"; + } + out.summary = BuildAuthSummary(signedIn, hb.data); + } else { + out.ok = false; + if (out.reason.empty()) out.reason = "no-session"; + if (out.actionOk && action == "recharge") out.message = "充值成功,请登录后使用"; + out.summary = BuildAuthSummary(username, json()); + } + } else { + out.summary = BuildAuthSummary(out.username, out.data); + } + PostAuthOutcome(out); + }); + }).detach(); +} + +bool IsAuthMessage(const std::string& type) { + return type == "authLogin" || type == "authRegister" || type == "authRecharge" || + type == "authLogout" || type == "authRetry"; +} + +// 未授权时仍允许最小化 / 最大化 / 关闭 / 拖窗,避免窗口卡死关不掉 +bool IsWindowMessage(const std::string& type) { + return type == "minimize" || type == "maximize" || type == "close" || + type == "dragmove" || type == "resize"; +} + +void OnAuthorized() { + if (!g_servicesStarted) { + g_servicesStarted = true; + if (!pddai::Server::Start(pddai::Config::Host(), pddai::Config::Port())) { + pddai::Log::Error("本地服务未启动,可在日志中查看原因"); + } + if (!g_consoleBootStarted) { + g_consoleBootStarted = true; + // 启动时打开上次使用的店铺(没有记录才退回第一家),避免重启后跳回店铺一 + pddai::WebConsole::Open(g_hwnd, ReadUiActiveShop()); + } + } + ::SetTimer(g_hwnd, kAuthTimerId, + static_cast(ClampInt(g_authIntervalSeconds, 10, 3600) * 1000), nullptr); +} + +void StartAuthCheck() { + json busy = json::object(); + busy["type"] = "authState"; + busy["ok"] = false; + busy["actionOk"] = false; + busy["busy"] = true; + busy["reason"] = "checking"; + busy["message"] = "正在连接验证服务器…"; + busy["summary"] = "网络验证中"; + PostJson(busy); + RunVerifyAsync(std::string(), true); } // 前端通过 window.chrome.webview.postMessage 发来的指令 @@ -1513,6 +2097,22 @@ void HandleWebMessage(std::wstring_view msg) { if (parsed.is_discarded() || !parsed.is_object()) return; const std::string type = MemberString(parsed, "type"); + // 未通过验证时,除验证指令和窗口控制外一律不处理,主功能保持不可用 + if (IsAuthMessage(type)) { + HandleAuthMessage(type, parsed); + return; + } + if (!g_authorized && !IsWindowMessage(type)) return; + + if (type == "checkUpdate") { + StartUpdateCheck(); + return; + } + if (type == "updateDownload") { + StartUpdateDownload(); + return; + } + // 设置类消息按前端传的 shopId 落到该店铺目录;不带 shopId 的消息走全局配置 const pddai::Config::ShopScope shopScope(MemberString(parsed, "shopId")); @@ -1536,6 +2136,13 @@ void HandleWebMessage(std::wstring_view msg) { } else if (type == "setTextConfig") { const std::string name = MemberString(parsed, "name"); if (IsSafeTextConfigName(name)) SaveTextConfig(name, MemberString(parsed, "text")); + } else if (type == "saveTheme") { + SaveUiTheme(MemberString(parsed, "theme")); + } else if (type == "saveNavCollapsed") { + SaveUiNavCollapsed(MemberString(parsed, "value")); + } else if (type == "setActiveShop") { + // 记住当前店铺,下次启动直接打开它 + SaveUiActiveShop(MemberString(parsed, "shopId")); } else if (type == "getServerOptions") { PushServerOptionsToUi(); } else if (type == "saveServerOptions") { @@ -1544,6 +2151,12 @@ void HandleWebMessage(std::wstring_view msg) { PushMailToUi(); } else if (type == "saveMail") { SaveMail(parsed); + } else if (type == "pickAudioFile") { + PickAudioFile(); + } else if (type == "playAudio") { + pddai::PlayAudioFile(MemberString(parsed, "path")); + } else if (type == "saveRiskSound") { + SaveRiskSound(parsed); } else if (type == "getPresets") { PushPresetsToUi(); } else if (type == "saveModel") { @@ -1579,7 +2192,9 @@ void HandleWebMessage(std::wstring_view msg) { } else if (type == "launchBrowser") { LaunchBrowserAsync(); } else if (type == "openConsole") { - if (!pddai::WebConsole::Open(g_hwnd, MemberString(parsed, "shopId"))) { + const std::string view = MemberString(parsed, "view"); + if (!pddai::WebConsole::Open(g_hwnd, MemberString(parsed, "shopId"), + view.empty() ? std::string("chat") : view)) { PostToast("内嵌客服台打开失败,请查看日志", false); } } else if (type == "closeConsole") { @@ -1595,12 +2210,25 @@ void HandleWebMessage(std::wstring_view msg) { PostToast("该店铺尚未打开,无法退出登录", false); } } else if (type == "consoleLayout") { - // 前端上报内容区矩形(客户区 CSS 像素),visible=false 时隐藏当前店铺 + // 前端上报内容区矩形(CSS 像素),visible=false 时隐藏当前店铺。 + // 主界面被 Ctrl+滚轮缩放后,视口 CSS 尺寸和元素位置都会变,而原生子窗口 + // 是按窗口像素摆放的,必须按缩放比换算,否则放大后会偏到左上, + // 把左侧菜单和标签栏盖成一块纯色。 + double zoom = 1.0; + if (g_controller) { + double current = 1.0; + if (SUCCEEDED(g_controller->get_ZoomFactor(¤t)) && current > 0.1 && current < 10.0) { + zoom = current; + } + } + const auto scaled = [zoom](double value) { + return static_cast(std::lround(value * zoom)); + }; RECT rc{}; - rc.left = parsed.value("x", 0); - rc.top = parsed.value("y", 0); - rc.right = rc.left + parsed.value("w", 0); - rc.bottom = rc.top + parsed.value("h", 0); + rc.left = scaled(parsed.value("x", 0)); + rc.top = scaled(parsed.value("y", 0)); + rc.right = rc.left + scaled(parsed.value("w", 0)); + rc.bottom = rc.top + scaled(parsed.value("h", 0)); pddai::WebConsole::SetLayout(rc, parsed.value("visible", false)); } else if (type == "stopBrowser") { pddai::Browser::Stop(); @@ -1683,10 +2311,11 @@ void InitWebView(HWND hwnd) { [hwnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT { if (FAILED(result) || !env) { pddai::Log::Error("WebView2 环境创建失败,请确认已安装 WebView2 Runtime"); + RevealMainWindow(); const int answer = ::MessageBoxW( hwnd, L"界面需要 WebView2 Runtime。\n\n点击“是”前往微软下载页安装,安装完成后重新启动本程序。", - L"PddAI 客服助手", MB_YESNO | MB_ICONWARNING | MB_TOPMOST); + L"拼多多客服助手", MB_YESNO | MB_ICONWARNING | MB_TOPMOST); if (answer == IDYES) { ::ShellExecuteW(nullptr, L"open", L"https://developer.microsoft.com/microsoft-edge/webview2/", @@ -1708,6 +2337,7 @@ void InitWebView(HWND hwnd) { COREWEBVIEW2_COLOR bg{0, 0x14, 0x14, 0x14}; c2->put_DefaultBackgroundColor(bg); } + controller->put_IsVisible(FALSE); // 配图预览的虚拟域名由 PushImagesToUi 按当前店铺图片库目录动态映射 @@ -1736,6 +2366,8 @@ void InitWebView(HWND hwnd) { g_webView->add_NavigationCompleted( Callback( [](ICoreWebView2*, ICoreWebView2NavigationCompletedEventArgs*) -> HRESULT { + RevealMainWindow(); + StartAuthCheck(); if (g_openConsoleOnStart) { g_openConsoleOnStart = false; json payload = json::object(); @@ -1750,17 +2382,23 @@ void InitWebView(HWND hwnd) { ResizeWebView(); - // 后台预开第一个店铺的客服台:停在服务状态页时自动回复照样运行 - if (!g_consoleBootStarted) { - g_consoleBootStarted = true; - pddai::WebConsole::Open(g_hwnd, std::string()); - } - - const std::string html = pddai::LoadTextResource(IDR_UI_HTML); + std::string html = pddai::LoadTextResource(IDR_UI_HTML); if (html.empty()) { pddai::Log::Error("嵌入的 UI 资源为空"); return S_OK; } + // 文档渲染前注入主题与导航折叠状态,避免开屏先闪一下默认值 + const std::string theme = ReadUiTheme(); + const std::string navCollapsed = ReadUiNavCollapsed(); + const std::string headTag = ""; + const size_t headPos = html.find(headTag); + if (headPos != std::string::npos) { + html.insert(headPos + headTag.size(), + ""); + } g_webView->NavigateToString(Utf8ToWide(html).c_str()); return S_OK; }) @@ -1776,8 +2414,23 @@ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { return 0; // 去掉系统非客户区,标题栏由前端自绘 case WM_NCPAINT: return 0; + case WM_MOVE: + // 拖动窗口后 WebView2 的合成层不会自己跟着走,不通知会停在旧位置 + if (g_controller) g_controller->NotifyParentWindowPositionChanged(); + return 0; + case WM_EXITSIZEMOVE: + // 拖动边框调整大小结束后再对齐一次,避免 WebView2 停在中间态 + ResizeWebView(); + return 0; case WM_SIZE: ResizeWebView(); + // 最大化 / 还原时通知前端切换窗口按钮图标 + if (g_webView && (wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED)) { + g_webView->PostWebMessageAsJson( + wParam == SIZE_MAXIMIZED + ? L"{\"type\":\"windowState\",\"maximized\":true}" + : L"{\"type\":\"windowState\",\"maximized\":false}"); + } return 0; case WM_ERASEBKGND: return 1; @@ -1786,6 +2439,60 @@ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (text) SendJsonString(*text); return 0; } + case WM_APP_AUTH: { + std::unique_ptr text(reinterpret_cast(lParam)); + if (!text) return 0; + const json r = json::parse(*text, nullptr, false); + if (r.is_discarded() || !r.is_object()) return 0; + + const bool ok = r.value("ok", false); + const std::string action = r.value("action", std::string()); + const int interval = r.value("intervalSeconds", 0); + if (interval > 0) g_authIntervalSeconds = ClampInt(interval, 10, 3600); + + g_authorized = ok; + if (ok) { + OnAuthorized(); + // 验证通过后台检查一次版本,有更新再弹窗询问 + if (!g_updateChecked) StartUpdateCheck(); + } else { + ::KillTimer(hwnd, kAuthTimerId); + } + + json state = json::object(); + state["type"] = "authState"; + state["ok"] = ok; + state["actionOk"] = r.value("actionOk", false); + state["action"] = action; + state["message"] = r.value("message", std::string()); + state["reason"] = r.value("reason", std::string()); + state["username"] = r.value("username", std::string()); + state["summary"] = r.value("summary", std::string()); + state["remember"] = r.value("remember", false); + state["savedUsername"] = r.value("savedUsername", std::string()); + state["savedPassword"] = r.value("savedPassword", std::string()); + state["busy"] = false; + state["appVersion"] = pddai::Update::CurrentVersion(); + SendJsonString(state.dump()); + + // 心跳成功只刷新状态,不弹 toast;失败时提示续费 / 重新登录 + if (!action.empty() && (action != "heartbeat" || !ok)) { + json result = json::object(); + result["type"] = "authResult"; + result["action"] = action; + result["ok"] = r.value("actionOk", false); + result["message"] = r.value("message", std::string()); + result["username"] = r.value("username", std::string()); + SendJsonString(result.dump()); + } + return 0; + } + case WM_TIMER: + if (wParam == kAuthTimerId && g_authorized) { + RunVerifyAsync("heartbeat", false); + return 0; + } + return ::DefWindowProcW(hwnd, msg, wParam, lParam); case WM_APP_CONSOLE_INPUT: pddai::WebConsole::HandleUiInputMessage(lParam); return 0; @@ -1814,6 +2521,10 @@ bool RegisterWindowClass(HINSTANCE hInst) { wc.lpfnWndProc = WndProc; wc.hInstance = hInst; wc.hCursor = ::LoadCursorW(nullptr, IDC_ARROW); + wc.hIcon = static_cast(::LoadImageW(hInst, MAKEINTRESOURCEW(IDI_APP_ICON), + IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED)); + wc.hIconSm = static_cast(::LoadImageW(hInst, MAKEINTRESOURCEW(IDI_APP_ICON), + IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR | LR_SHARED)); wc.hbrBackground = CreateSolidBrush(RGB(0x14, 0x14, 0x14)); wc.lpszClassName = L"PddAI_MainWindow"; return ::RegisterClassExW(&wc) != 0; @@ -1828,6 +2539,19 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow) { pddai::Log::Init(); pddai::Log::Info("PddAI 启动:CoInitialize 完成"); + // 闪退留证据:异常写入 data\crash\crash.log,同时生成 minidump + { + const std::wstring crashDir = pddai::DataDir() + L"\\crash"; + if (crashDir.size() < MAX_PATH * 2) { + ::lstrcpyW(g_crashDir, crashDir.c_str()); + ::CreateDirectoryW(crashDir.c_str(), nullptr); + } + ::SetUnhandledExceptionFilter(CrashFilter); + std::set_terminate(TerminateHandler); + } + + CleanupOldExe(); + const pddai::Config::InitResult configResult = pddai::Config::Init(ParseCliConfigDir()); pddai::Log::Info("配置目录:" + pddai::WideToUtf8(configResult.dir) + (configResult.seeded ? "(已生成默认配置)" : "")); @@ -1835,11 +2559,7 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow) { // 已有店铺首次启动时把全局模板复制成各自的配置目录 pddai::Config::MigrateShops(); - const std::string host = pddai::Config::Host(); - const int port = pddai::Config::Port(); - if (!pddai::Server::Start(host, port)) { - pddai::Log::Error("本地服务未启动,可在日志中查看原因"); - } + // 本地服务与客服台预加载延后到网络验证通过之后(OnAuthorized),未授权时主功能不可用 // 手机控制页或客服台面板切换监听状态时,通知桌面端刷新店铺列表 pddai::Server::SetStateListener([]() { @@ -1855,7 +2575,7 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow) { pddai::Log::Info("窗口类已注册"); g_hwnd = ::CreateWindowExW( - 0, L"PddAI_MainWindow", L"PddAI 客服助手", + WS_EX_LAYERED, L"PddAI_MainWindow", L"拼多多客服助手", WS_POPUP | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 1180, 760, nullptr, nullptr, hInst, nullptr); @@ -1864,10 +2584,27 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow) { return 1; } - pddai::Log::Info("窗口已创建,准备初始化 WebView2"); - InitWebView(g_hwnd); + // CW_USEDEFAULT 会交给系统摆到左上角层叠位置,这里按工作区居中, + // 避免每次启动窗口都贴在屏幕左上角 + { + RECT work{}; + if (::SystemParametersInfoW(SPI_GETWORKAREA, 0, &work, 0)) { + constexpr int kWinW = 1180, kWinH = 760; + int x = work.left + ((work.right - work.left) - kWinW) / 2; + int y = work.top + ((work.bottom - work.top) - kWinH) / 2; + if (x < work.left) x = work.left; + if (y < work.top) y = work.top; + ::SetWindowPos(g_hwnd, nullptr, x, y, 0, 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + } + } + + // WebView2 需要窗口可见才能初始化;先全透明显示,首屏渲染完再由 RevealMainWindow 显形 + ::SetLayeredWindowAttributes(g_hwnd, 0, 0, LWA_ALPHA); ::ShowWindow(g_hwnd, nCmdShow); ::UpdateWindow(g_hwnd); + pddai::Log::Info("窗口已创建,准备初始化 WebView2"); + InitWebView(g_hwnd); pddai::Log::Info("进入消息循环"); MSG msg{}; diff --git a/native/src/resource.h b/native/src/resource.h index cda0b4c..52c157a 100644 --- a/native/src/resource.h +++ b/native/src/resource.h @@ -13,6 +13,7 @@ #define WM_APP_LOG (WM_APP + 3) #define WM_APP_POSTJSON (WM_APP + 4) #define WM_APP_CONSOLE_INPUT (WM_APP + 5) +#define WM_APP_AUTH (WM_APP + 6) #define IDC_TRAY_OPEN 2001 #define IDC_TRAY_PAUSE 2002 diff --git a/native/ui/index.html b/native/ui/index.html index 97185a3..9d8813d 100644 --- a/native/ui/index.html +++ b/native/ui/index.html @@ -2,11 +2,49 @@ -PddAI 客服助手 +拼多多客服助手
- PddAI 客服助手 + 拼多多客服助手 当前店铺:未打开 +
- - - + + + +
+ +
+
账号—
+
授权—
+
+ +
+
+ + +
+
+ +
+
+

发现新版本

+
+
+
+
+
+ + +
+
@@ -277,23 +485,35 @@
- 运行 - 服务状态 - 客服工作台 - 店铺配置 - 商品信息 - 知识库 - 客服人格 - 快捷回复 - 图片库 - 风险意图 - 转人工与话术 - 图片保存 - 模型配置 - 系统 - 系统设置 - 日志 - 关于 + + +
@@ -334,6 +554,18 @@
+ +
+
+
退出登录
+
+
+ + +
+
+
@@ -349,7 +581,7 @@

客服人格

-

设定客服的自称、语气与话术风格,保存后立即应用到自动回复。配置保存在 persona.json。

+

设定客服的自称、语气与话术风格,保存后立即应用到自动回复。人格设置保存在 persona.json,提示词保存在 system-prompt.md 与 reply-guidelines.md,统一由底部「保存设置」写入。

自称
称呼买家 @@ -371,10 +603,6 @@
禁用词
-
- - -

提示词文件

system-prompt.md 是发给模型的系统提示词;reply-guidelines.md 是通用回复要求,会截断后附在参考信息里。留空表示不使用,人格设定会追加在系统提示词后面。

@@ -382,9 +610,9 @@
回复要求
-
- - +
+ +
@@ -402,7 +630,7 @@

快捷回复

-

买家整句与关键词完全一致(或包含关键词)时,直接发送这里的回复,不再调用模型。改动保存后立即生效。

+

买家消息命中关键词就直接发送这里的回复,不再调用模型。每张卡片分「触发条件」和「命中后发送」两块:填了「随机回复」就从里面随机挑一条发,留空则发「固定回复」。

开场说明

命中条件时,在正式回复前先单独发送一次这段说明。同一会话、同一订单只发一次。

@@ -492,6 +720,9 @@

保存开关与位置

+
+

买家有时不发聊天图片,而是以文件(如 001.jpg)发送。勾选后会在文件名气泡里找缩略图或下载链接,按普通买家图片一起归档、校验张数。

保存根目录 @@ -540,6 +771,14 @@
+

商品关键词固定张数

+

有些商品规格里写的「12张」是制作数量,买家实际只需要发 1 张原图。给这类商品配一条规则后,命中就按固定张数校验,不再解析规格里的「N张」,也不按件数累加。

+
+ 固定规则 + +
+

每行一条,用等号分隔,张数填买家实际需要发的图片张数(1~9999)。关键词会与订单里的商品名、规格比对,包含即命中;命中多条时以写在最上面的为准。留空表示不启用,仍按规格里的「N张」计算。

+
@@ -633,6 +872,30 @@

系统设置

操作节奏与检索参数保存在 server.json,邮件配置保存在 mail.json;模型接口请到「模型配置」页单独设置。监听端口、监听地址、访问密码与每日暂停时间属于本机,改动后需要重启程序;其余配置按左侧「当前店铺」独立保存,保存后立即生效。

+

界面外观

+

配色只影响本机界面,不随店铺切换,选择后立即生效并记住。

+
+ + + + +

本地服务

监听端口 @@ -655,6 +918,9 @@ ~ 毫秒;切换页签/页面时在区间内随机等待,避免操作过快
+
个人订单缓存 + + 秒;同一会话内复用订单数据的时长,避免右侧订单面板反复切换闪动。切换会话、买家提到下单/付款时仍会立即重读;填 0 表示每轮都重读
@@ -721,10 +987,24 @@
+

提醒声音

+

命中风险意图(转人工)时在本机播放提示音,与是否启用邮件无关。选择音频、勾选启用、清除都会立即保存,不需要再点其它保存按钮。

+
+ + + + + +

聊天记录

读取记录条数 - - 填 0 表示读取全部(会向上滚动加载历史);默认 6 条
+ + + 「部分」读取最近 N 条(默认 6),「全部」会向上滚动加载完整历史

图片保存的路径与目录规则已独立到「图片保存」页。

@@ -772,7 +1052,7 @@

关于

-

PddAI 客服助手 · 原生 Windows 客户端
+

拼多多客服助手 · 原生 Windows 客户端
界面 WebView2 · 本地服务内置 · 客服台内嵌 WebView2

@@ -781,7 +1061,9 @@
版本—
+
+
@@ -796,6 +1078,38 @@
+
+
+
拼多多客服助手
+
首次使用需联网验证,登录后才能使用客服功能
+
+ + + +
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
正在连接验证服务器…
+
+ + +
+
网络验证中
+
+
+
@@ -849,11 +1163,26 @@ diff --git a/res/黑色.ico b/res/黑色.ico new file mode 100644 index 0000000..6403319 Binary files /dev/null and b/res/黑色.ico differ