(() => { "use strict"; const DEFAULT_SERVER_BASE = "http://127.0.0.1:3456"; const STORE_KEY = "pddReplyAssistantState"; const IMAGE_INDEX_KEY = "pddReplyAssistantImageIndex"; const CONTROL_POLL_MS = 1500; // 买家连续发图:末尾连续图片达到该数量就先等静默,避免每来一张回一次 const IMAGE_BURST_MIN = 3; const IMAGE_BURST_SETTLE_MS = 4000; 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"], answeredList: "ul.already-unreply", messageList: "#msgListContainer", productCards: ".commonCard, .msg-content.good-card.clearfix", replyTextarea: "#replyTextarea", sendButton: ".send-btn" }; const state = { mode: "debug", 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", shopName: "默认店铺", shopToken: "", configDraft: { serverBase: DEFAULT_SERVER_BASE, shopId: "default", shopName: "默认店铺", shopToken: "" }, observer: null, checkTimer: null, controlTimer: null, controlSyncBlockedUntil: 0, remoteControlReady: false, remoteControlWarningShown: false, runId: 0, activeAbortController: null, manualSendCleanup: null, // 调试模式回填后等人工发送,此时不算「处理中」 awaitingManualSend: false, trustedContextWarningShown: false, 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", imageConcurrentMs: 60000, imageBatchGapMs: 180000, imageHistoryLeadMs: 600000, imageCountCheck: true, // 商品关键词固定张数:每行「关键词 = 张数」,命中后整单按固定值校验 imageKeywordFixedCount: "", // 买家以文件形式(如 001.jpg)发送的图片也按聊天图片识别 imageFileAsImage: true, imageReviewEnabled: true, imageKeepOrderTab: true, // 数量不符时是否给买家回复差值(文案可配置) imageReceiptReplyEnabled: false, receiptShortageReply: "", receiptOverflowReply: "", // 买家说「第2张替换掉 / 第3张删掉」时自动调整已保存的图片 imageAdjustEnabled: true, imageAdjustReplyEnabled: true, adjustReplaceReply: "", adjustDeleteReply: "", // 指令识别词(逗号分隔),由图片保存页下发 imageAdjustReplaceWords: "替换,换成,换掉,换一张,换一下,换下,更换,改成,改为,换个", imageAdjustDeleteWords: "删掉,删除,去掉,不要,不想要,不需要,不用,取消,移除,删了", imageAdjustResendWords: "重新发,重发,再发一张,补发", imageAdjustPointWords: "这个,这张,那张,这幅,那幅,这张图,这个图,它", imageAdjustNegativeWords: "不要,不用,不需要,无需,别,勿", // 图片指纹(dHash)汉明距离阈值,越小越严格 imageAdjustMatchThreshold: 8, // 指令识别方式:rules 只用固定词;hybrid 固定词没命中时问模型;ai 优先问模型 imageAdjustMode: "rules", imageAdjustAiConfidence: 0.75, // 切换页签/页面时的随机等待区间(毫秒) minPageDelayMs: 150, maxPageDelayMs: 400, // 个人订单缓存时长(毫秒),0 表示每轮都重读 orderCacheMs: 300000, // 参与归属与模型上下文的订单状态(正常/已完成/退款售后) orderStatusNormal: true, orderStatusDone: true, orderStatusRefund: true, // 开场说明:命中条件时先单独发一段规则说明(可带配图) greeting: { enabled: false, onFirst: true, onOrder: true, text: "", images: [] }, // 命中高危意图后是否把该会话标记为转人工(后续消息不再自动回复) riskStopOnHit: true }, greetedConversations: new Set(), greetedOrders: new Set(), // 仅图片会话最近一次确认回复的时间,避免连发图片时反复回复 imageAckAt: new Map(), // 人工回复检测:会话标识 -> 本软件成功发出去的文字 ownTexts: new Map(), // 会话标识 -> 上次看到的客服侧消息,用来判断有没有新的人工回复 lastSysSeen: new Map(), currentConversationIdentity: "", imageAckLogAt: 0, // 图片数量不符时待回复买家的差值通知 receiptNotes: [], currentConversationKey: "", // 已处理过的图片调整指令(会话 + 消息时间 + 原文),防止轮询时重复替换/删除 adjustHandled: new Set(), // 模型识别结果缓存(同一句指令只问一次模型) aiAdjustCache: new Map(), // 本轮刚完成图片调整,用于跳过模型回复(key 匹配当前会话) lastAdjustReply: null, // 当前这一轮处理的日志与对话,结束后按「日期/店铺/用户」落盘 activeRunLog: null, // 订单面板缓存:避免每轮都切换右侧页签造成闪动 orderCache: null, archivedImageUrls: new Set() }; const ui = { root: null, panel: null, bubble: null, status: null, modeBtn: null, pauseBtn: null, configBtn: null, configPanel: null, serverInput: null, shopIdInput: null, shopNameInput: null, shopTokenInput: null, saveConfigBtn: null, meta: null, log: null }; const dragState = { active: false, dragged: false, startX: 0, startY: 0, startRight: 0, startBottom: 0 }; // 日志批量落盘队列(必须早于 init 声明,初始化时就会写第一条日志) let logQueue = []; let logFlushTimer = 0; init(); async function init() { loadState(); loadArchivedImageIndex(); resetConfigDraftFromState(); buildWidget(); renderWidget(); attachHumanInputWatch(); startWatching(); startRemoteControlPolling(); log("助手已启动,正在监听新会话。"); } function loadState() { try { const raw = localStorage.getItem(STORE_KEY); 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; if (saved.position && Number.isFinite(saved.position.right) && Number.isFinite(saved.position.bottom)) { state.position = saved.position; } if (typeof saved.serverBase === "string" && saved.serverBase) { state.serverBase = saved.serverBase.replace(/\/+$/, ""); } if (typeof saved.shopId === "string" && saved.shopId) state.shopId = saved.shopId.trim(); if (typeof saved.shopName === "string" && saved.shopName) state.shopName = saved.shopName.trim(); if (typeof saved.shopToken === "string") state.shopToken = saved.shopToken; } catch (error) { console.warn("[PDD Reply Assistant] failed to load state", error); } } function saveState() { localStorage.setItem( STORE_KEY, JSON.stringify({ mode: state.mode, humanFallback: state.humanFallback, humanFallbackTrigger: state.humanFallbackTrigger, paused: state.paused, minimized: state.minimized, configOpen: state.configOpen, position: state.position, serverBase: state.serverBase, shopId: state.shopId, shopName: state.shopName, shopToken: state.shopToken }) ); } // 已归档图片索引落盘:页面刷新/软件重启后不再重复下载、重复编号 function loadArchivedImageIndex() { try { const raw = localStorage.getItem(IMAGE_INDEX_KEY); if (!raw) return; const list = JSON.parse(raw); if (Array.isArray(list)) state.archivedImageUrls = new Set(list.slice(-3000)); } catch (error) { console.warn("[PDD Reply Assistant] failed to load image index", error); } } function persistArchivedImageIndex() { try { const list = Array.from(state.archivedImageUrls).slice(-3000); localStorage.setItem(IMAGE_INDEX_KEY, JSON.stringify(list)); } catch (error) { // 配额满时丢弃索引,下一次重新扫一遍,不影响归档 console.warn("[PDD Reply Assistant] failed to save image index", error); } } function buildWidget() { if (document.getElementById("pdd-reply-assistant-root")) return; ui.root = document.createElement("div"); ui.root.id = "pdd-reply-assistant-root"; ui.panel = document.createElement("div"); ui.panel.className = "pdd-ra-panel"; const header = document.createElement("div"); header.className = "pdd-ra-header"; ui.status = document.createElement("span"); ui.status.className = "pdd-ra-status is-idle"; const title = document.createElement("div"); title.className = "pdd-ra-title"; title.textContent = "PDD客服回复助手"; const minBtn = document.createElement("button"); minBtn.className = "pdd-ra-icon-btn"; minBtn.type = "button"; minBtn.title = "最小化"; minBtn.textContent = "-"; minBtn.addEventListener("click", (event) => { event.stopPropagation(); state.minimized = true; saveState(); renderWidget(); }); header.append(ui.status, title, minBtn); const body = document.createElement("div"); body.className = "pdd-ra-body"; const controls = document.createElement("div"); controls.className = "pdd-ra-controls"; ui.modeBtn = document.createElement("button"); ui.modeBtn.className = "pdd-ra-button is-primary"; ui.modeBtn.type = "button"; ui.modeBtn.addEventListener("click", () => { state.mode = state.mode === "debug" ? "auto" : "debug"; saveState(); renderWidget(); log(`已切换为${state.mode === "debug" ? "调试模式" : "自动模式"}。`); // mode 一起上报,桌面 UI 的选项卡圆点才能区分自动/调试 syncPauseStateToServer("browser-panel"); }); ui.pauseBtn = document.createElement("button"); ui.pauseBtn.className = "pdd-ra-button"; ui.pauseBtn.type = "button"; ui.pauseBtn.addEventListener("click", () => { const nextPaused = !state.paused; setPausedState( nextPaused, nextPaused ? "已暂停监听,当前未完成的回复任务已取消。" : "已恢复监听。", { sync: true, source: "browser-panel" } ); }); ui.configBtn = document.createElement("button"); ui.configBtn.className = "pdd-ra-button"; ui.configBtn.type = "button"; ui.configBtn.addEventListener("click", () => { const nextOpen = !state.configOpen; if (nextOpen) resetConfigDraftFromState(); state.configOpen = nextOpen; saveState(); renderWidget(); }); controls.append(ui.modeBtn, ui.pauseBtn, ui.configBtn); ui.configPanel = document.createElement("div"); ui.configPanel.className = "pdd-ra-config"; ui.serverInput = createConfigInput("服务地址", "http://127.0.0.1:3456", "text", "serverBase"); ui.shopIdInput = createConfigInput("店铺ID", "handing-main", "text", "shopId"); 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"; ui.saveConfigBtn.textContent = "保存配置"; ui.saveConfigBtn.addEventListener("click", saveShopConfigFromInputs); ui.configPanel.append( ui.serverInput.wrapper, ui.shopIdInput.wrapper, ui.shopNameInput.wrapper, ui.shopTokenInput.wrapper, ui.humanFallbackRow, ui.humanTriggerRow, ui.saveConfigBtn ); ui.meta = document.createElement("div"); ui.meta.className = "pdd-ra-meta"; ui.log = document.createElement("div"); ui.log.className = "pdd-ra-log"; // 日志面板本身不好选中,提供一键复制,并在后台按日期落盘 ui.logTools = document.createElement("div"); ui.logTools.className = "pdd-ra-logtools"; ui.copyLogBtn = document.createElement("button"); ui.copyLogBtn.className = "pdd-ra-button"; ui.copyLogBtn.type = "button"; ui.copyLogBtn.textContent = "复制日志"; ui.copyLogBtn.addEventListener("click", copyLogs); ui.logHint = document.createElement("span"); ui.logHint.className = "pdd-ra-loghint"; ui.logHint.textContent = "同时保存到 data\\logs\\plugin-日期.txt"; ui.logTools.append(ui.copyLogBtn, ui.logHint); body.append(controls, ui.configPanel, ui.meta, ui.logTools, ui.log); ui.panel.append(header, body); ui.bubble = document.createElement("div"); ui.bubble.className = "pdd-ra-bubble"; ui.bubble.title = "点击恢复"; ui.bubble.textContent = "PDD"; ui.bubble.addEventListener("click", () => { if (dragState.dragged) return; state.minimized = false; saveState(); renderWidget(); }); ui.root.append(ui.panel, ui.bubble); document.documentElement.appendChild(ui.root); makeDraggable(header); makeDraggable(ui.bubble); } function createConfigInput(labelText, placeholder, type = "text", draftKey = "") { const wrapper = document.createElement("label"); wrapper.className = "pdd-ra-field"; const label = document.createElement("span"); label.textContent = labelText; const input = document.createElement("input"); input.type = type; input.placeholder = placeholder; input.autocomplete = "off"; input.addEventListener("input", () => { if (draftKey) state.configDraft[draftKey] = input.value; }); wrapper.append(label, input); return { wrapper, input }; } function saveShopConfigFromInputs() { updateConfigDraftFromInputs(); const serverBase = normalizeServerBase(state.configDraft.serverBase); const shopId = normalizeConfigValue(state.configDraft.shopId); const shopName = normalizeConfigValue(state.configDraft.shopName) || shopId || "默认店铺"; const shopToken = String(state.configDraft.shopToken || "").trim(); if (!serverBase) { log("配置未保存:服务地址不能为空。"); return; } if (!shopId) { log("配置未保存:店铺ID不能为空。"); return; } state.serverBase = serverBase; state.shopId = shopId; state.shopName = shopName; state.shopToken = shopToken; resetConfigDraftFromState(); state.remoteControlReady = false; state.remoteControlWarningShown = false; saveState(); renderWidget(); log(`已保存店铺配置:${state.shopName}(${state.shopId})。`); // 回写 shops.json,避免只在本地 localStorage 生效、重启被主界面配置覆盖 fetch(`${state.serverBase}/api/shop-config`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ shopId: state.shopId, shopName: state.shopName, pluginToken: state.shopToken }) }).catch(() => {}); syncPauseStateToServer("plugin-config-save"); } function normalizeServerBase(value) { return String(value || "").trim().replace(/\/+$/, ""); } function normalizeConfigValue(value) { return String(value || "").trim(); } function resetConfigDraftFromState() { state.configDraft = { serverBase: state.serverBase, shopId: state.shopId, shopName: state.shopName, shopToken: state.shopToken }; } function updateConfigDraftFromInputs() { state.configDraft.serverBase = ui.serverInput.input.value; state.configDraft.shopId = ui.shopIdInput.input.value; state.configDraft.shopName = ui.shopNameInput.input.value; state.configDraft.shopToken = ui.shopTokenInput.input.value; } function renderWidget() { if (!ui.root) return; ui.root.classList.toggle("is-minimized", state.minimized); ui.root.style.right = `${state.position.right}px`; ui.root.style.bottom = `${state.position.bottom}px`; // 模式按钮用颜色区分,不只靠文字变化:自动=绿、调试=蓝 ui.modeBtn.textContent = state.mode === "debug" ? "调试模式" : "自动模式"; ui.modeBtn.classList.toggle("is-auto", state.mode !== "debug"); ui.modeBtn.classList.toggle("is-debug", state.mode === "debug"); ui.modeBtn.title = state.mode === "debug" ? "调试模式:只回填内容,需人工确认发送" : "自动模式:生成后直接发送"; ui.pauseBtn.textContent = state.paused ? "恢复监听" : "暂停监听"; ui.pauseBtn.classList.toggle("is-paused", state.paused); ui.configBtn.textContent = state.configOpen ? "收起配置" : "配置"; ui.configPanel.classList.toggle("is-open", state.configOpen); syncConfigInputs(); // 调试模式等待人工发送时不算「处理中」,否则圆点会一直停在黄色 const busy = state.processing && !state.awaitingManualSend; const statusName = busy ? "is-busy" : state.paused ? "is-idle" : state.mode === "debug" ? "is-debug" : "is-listening"; ui.status.className = `pdd-ra-status ${statusName}`; const statusText = busy ? "处理中" : state.awaitingManualSend ? "待人工发送" : state.paused ? "已暂停" : state.mode === "debug" ? "调试监听中" : "自动监听中"; const controlState = state.remoteControlReady ? "手机控制已连接" : "手机控制未连接"; ui.meta.textContent = `店铺:${state.shopName || state.shopId}|服务:${state.serverBase}|${controlState}|商品来源:聊天卡片|人工介入:${state.manualConversationKeys.size}个|${statusText}`; ui.log.textContent = state.logLines.join("\n"); ui.log.scrollTop = ui.log.scrollHeight; } function syncConfigInputs() { if (!state.configOpen) return; syncInputValue(ui.serverInput.input, state.configDraft.serverBase); 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) { if (document.activeElement === input) return; input.value = value || ""; } function makeDraggable(handle) { handle.addEventListener("mousedown", (event) => { if (event.button !== 0) return; const target = event.target; if (target && target.closest && target.closest("button")) return; dragState.active = true; dragState.dragged = false; dragState.startX = event.clientX; dragState.startY = event.clientY; dragState.startRight = state.position.right; dragState.startBottom = state.position.bottom; event.preventDefault(); }); } document.addEventListener("mousemove", (event) => { if (!dragState.active) return; const dx = event.clientX - dragState.startX; const dy = event.clientY - dragState.startY; if (Math.abs(dx) + Math.abs(dy) > 4) dragState.dragged = true; const rootRect = ui.root.getBoundingClientRect(); const maxRight = Math.max(8, window.innerWidth - rootRect.width - 8); const maxBottom = Math.max(8, window.innerHeight - rootRect.height - 8); state.position.right = clamp(dragState.startRight - dx, 8, maxRight); state.position.bottom = clamp(dragState.startBottom - dy, 8, maxBottom); renderWidget(); }); document.addEventListener("mouseup", () => { if (!dragState.active) return; dragState.active = false; saveState(); setTimeout(() => { dragState.dragged = false; }, 0); }); function clamp(value, min, max) { return Math.min(max, Math.max(min, value)); } function startWatching() { if (state.observer) state.observer.disconnect(); state.observer = new MutationObserver(() => scheduleCheck(250)); state.observer.observe(document.body, { childList: true, subtree: true, characterData: true }); scheduleCheck(300); } function startRemoteControlPolling() { if (state.controlTimer) window.clearTimeout(state.controlTimer); const poll = async () => { await pollRemoteControlState(); state.controlTimer = window.setTimeout(poll, CONTROL_POLL_MS); }; poll(); } async function pollRemoteControlState() { try { const response = await fetch(`${state.serverBase}/api/control-state?shopId=${encodeURIComponent(state.shopId || "default")}`, { cache: "no-store", headers: getShopAuthHeaders() }); const data = await response.json(); if (!response.ok || !data?.ok) { throw new Error(data?.error || `HTTP ${response.status}`); } state.remoteControlReady = true; state.remoteControlWarningShown = false; renderWidget(); if (data.updatedBy === "server-start") { syncPauseStateToServer("plugin-start"); return; } if (Date.now() < state.controlSyncBlockedUntil) return; if (typeof data.paused === "boolean" && data.paused !== state.paused) { setPausedState( data.paused, data.paused ? "手机端已暂停监听,当前未完成的回复任务已取消。" : "手机端已恢复监听。", { sync: false, source: "remote-control" } ); } } catch (error) { state.remoteControlReady = false; renderWidget(); if (!state.remoteControlWarningShown) { state.remoteControlWarningShown = true; console.warn("[PDD Reply Assistant] remote control unavailable", error); log("手机控制暂不可用,本地面板仍可正常操作。"); } } } async function syncPauseStateToServer(source) { state.controlSyncBlockedUntil = Date.now() + 2500; try { const response = await fetch(`${state.serverBase}/api/control-state`, { method: "POST", headers: { "Content-Type": "application/json", ...getShopAuthHeaders() }, body: JSON.stringify({ shopId: state.shopId || "default", paused: state.paused, mode: state.mode, source }) }); const data = await response.json(); if (!response.ok || !data?.ok) { throw new Error(data?.error || `HTTP ${response.status}`); } state.remoteControlReady = true; state.remoteControlWarningShown = false; renderWidget(); } catch (error) { state.remoteControlReady = false; renderWidget(); if (!state.remoteControlWarningShown) { state.remoteControlWarningShown = true; console.warn("[PDD Reply Assistant] failed to sync control state", error); log("监听状态未同步到手机控制页,本地操作已生效。"); } } } function setPausedState(paused, message, options = {}) { const shouldSync = options.sync !== false; const source = options.source || "browser-panel"; if (state.paused === paused) { if (shouldSync) syncPauseStateToServer(source); return; } state.paused = paused; saveState(); if (paused) { cancelCurrentTask(message || "已暂停监听,当前未完成的回复任务已取消。"); } else { log(message || "已恢复监听。"); renderWidget(); scheduleCheck(100); } if (shouldSync) syncPauseStateToServer(source); } function scheduleCheck(delay) { if (state.paused) return; if (state.checkTimer) window.clearTimeout(state.checkTimer); state.checkTimer = window.setTimeout(checkForNewConversation, delay); } async function checkForNewConversation() { if (state.paused || state.processing) return; const candidate = findFirstUrgentConversation(); if (!candidate) return; const row = candidate.row; state.processing = true; const runId = ++state.runId; const abortController = new AbortController(); state.activeAbortController = abortController; // 每轮处理单独记录,结束后写入「日期/店铺/用户」目录,方便按用户复盘 state.currentConversationKey = getConversationKey(row); state.currentConversationIdentity = getConversationIdentity(row); state.activeRunLog = { key: state.currentConversationKey, user: conversationDisplayName(row, state.currentConversationKey), runId, startedAt: Date.now(), mode: state.mode, outcome: "", reply: "", imageCount: 0, orderCount: 0, messages: [], lines: [] }; renderWidget(); try { log("发现待回复用户,正在打开首个可自动处理的会话。"); const beforeChatSignature = getChatSignature(); await clickConversation(row); ensureTaskActive(runId); await waitForStableChat(beforeChatSignature, row); ensureTaskActive(runId); let payload = await buildConversationPayload(); if (state.activeRunLog && Array.isArray(payload?.msgList)) { state.activeRunLog.messages = payload.msgList.map((item) => ({ usertype: item.usertype, msg: item.msg, t: item.t || 0 })); 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); state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; if (state.activeRunLog) { state.activeRunLog.outcome = waitingImage ? "等待买家发送替换用的新图" : "最新是商品卡片,跳过本轮"; } log(waitingImage ? "买家已发出图片替换指令,等待新图到达后再处理。" : "最新一条是商品卡片,暂不回复,等待客户继续发送文字消息。"); renderWidget(); scheduleCheck(waitingImage ? 1200 : 500); return; } log(`已提取历史消息${payload.msgList.length}条。`); printPayloadToDebugConsole(payload); // 买家连发图片/视频时,同一会话在冷却期内只确认一次,避免上百张刷出上百条回复 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) : null; // 图片调整成功的确认文案:即使带着文字指令,也不该再让模型补一段回复 const adjustNote = state.receiptNotes.find( (note) => note.key === conversationKey && note.kind === "adjust" ); const adjustHandledNow = Boolean(state.lastAdjustReply && state.lastAdjustReply.key === conversationKey && Date.now() - state.lastAdjustReply.at < 60000); if (adjustHandledNow) state.lastAdjustReply = null; // 差值文案为空时不能吞掉本轮回复,交回模型处理 const pendingReceipt = Boolean(pendingNote && buildReceiptText(pendingNote)); const adjustReceipt = Boolean(adjustNote && buildReceiptText(adjustNote)); // 有数量差值要回复时不受连发冷却限制,保证买家能看到最新数量 if (!pendingReceipt && !adjustReceipt && onlyMedia && Date.now() - (state.imageAckAt.get(conversationIdentity) || 0) < IMAGE_ACK_COOLDOWN_MS) { if (Date.now() - state.imageAckLogAt > 20000) { state.imageAckLogAt = Date.now(); log("买家还在连续发送图片/视频,冷却期内本轮不重复回复。"); } state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; if (state.activeRunLog) state.activeRunLog.outcome = "买家连续发图冷却中,跳过本轮"; renderWidget(); scheduleCheck(8000); return; } // 自动模式下纯图片且数量与规格不符,或刚完成图片调整:直接回复对应文案,不调用模型 if ((pendingReceipt || adjustReceipt) && state.mode === "auto") { const noteText = adjustReceipt ? buildReceiptText(adjustNote) : buildReceiptText(pendingNote); if (state.activeRunLog) state.activeRunLog.reply = noteText; await sendReceiptNotes(runId); ensureTaskActive(runId); state.imageAckAt.set(conversationIdentity, Date.now()); if (conversationIdentity && buyerFingerprint) { state.repliedBuyerFingerprint.set(conversationIdentity, buyerFingerprint); } log(adjustReceipt ? "图片替换已生效,已直接回复确认,不再发送其他文字。" : "图片数量与规格不符,已直接回复差值,不再发送其他文字。"); if (state.activeRunLog) { state.activeRunLog.outcome = adjustReceipt ? "仅回复图片替换确认" : "仅回复图片数量差值"; } state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; renderWidget(); scheduleCheck(500); return; } // 调整完成但没配置确认文案时也不调模型,避免对「把这个换成这个」再生成一段解释 if (adjustHandledNow && state.mode === "auto") { log("图片替换已完成,本轮不再调用模型回复。"); if (state.activeRunLog) state.activeRunLog.outcome = "图片替换完成,未调用模型"; state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; renderWidget(); scheduleCheck(500); 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; if (!hitRisk || state.runtime.riskStopOnHit !== false) markManualConversation(row); const names = Array.isArray(result.riskIntents) ? result.riskIntents.join("、") : "未知"; const emailState = result.email?.sent ? "邮件已发送" : result.email?.deduped ? "邮件已去重" : "邮件未发送"; log(`命中高危意图:${names}。不回复此用户,${emailState},${hitRisk && state.runtime.riskStopOnHit === false ? "后续消息继续自动回复" : "该会话后续不再自动回复"}。`); if (state.activeRunLog) { state.activeRunLog.outcome = hitRisk ? `命中高危意图,转人工(${names})` : "模型判定转人工"; } state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; renderWidget(); scheduleCheck(300); return; } const reply = normalizeText(result.reply || result.message || result.text || ""); const images = Array.isArray(result.images) ? result.images.filter((image) => image && (image.file || image.name)).slice(0, 9) : []; if (!reply && !images.length) throw new Error("服务返回内容为空"); if (state.activeRunLog) { state.activeRunLog.reply = reply; state.activeRunLog.imageCount = images.length; } ensureTaskActive(runId); // 开场说明:命中条件时先单独发文字/配图,再发正式回复(仅自动模式会真正发送) const greeting = state.mode === "auto" ? pickGreeting(payload, row) : null; if (greeting) { if (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); } if (greeting.images.length) { if (!(await sendImageMessages(greeting.images))) throw new Error("开场说明配图发送失败"); log("已先发送开场说明配图。"); await sleep(pageDelayMs() + 200); ensureTaskActive(runId); } } 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; if (reply) sent = await sendReplyAndVerify(reply); if (sent && images.length) { ensureTaskActive(runId); sent = await sendImageMessages(images); } ensureTaskActive(runId); if (sent) { if (conversationIdentity && buyerFingerprint) { state.repliedBuyerFingerprint.set(conversationIdentity, buyerFingerprint); } rememberOwnText(reply, conversationIdentity); // 纯媒体批次记一次确认时间,后续连发的图片/视频不再逐条回复 if (onlyMedia) state.imageAckAt.set(conversationIdentity, Date.now()); await sendReceiptNotes(runId); log("已确认自动发送成功,恢复监听。"); if (state.activeRunLog) state.activeRunLog.outcome = "已自动回复并确认发送"; state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; renderWidget(); scheduleCheck(500); } else { if (state.activeRunLog) state.activeRunLog.outcome = "自动发送未确认,已暂停监听"; state.processing = false; setErrorStatus(); setPausedState(true, "自动发送未确认成功,已暂停监听。请人工检查当前会话,避免重复生成。", { sync: true, source: "auto-send-failed" }); } } else { if (state.activeRunLog) state.activeRunLog.outcome = "调试模式,已回填待人工发送"; log("已回填回复。当前为调试模式,请人工确认后点击发送。"); if (images.length) log(`本次回复附带 ${images.length} 张配图,调试模式下请手动上传发送。`); // 调试模式不自动发差值通知,把当前会话的文案打到日志里方便人工发送 const receiptKey = state.currentConversationKey || ""; const pendingReceipts = state.receiptNotes.filter((note) => note.key === receiptKey); if (pendingReceipts.length) { state.receiptNotes = state.receiptNotes.filter((note) => note.key !== receiptKey); pendingReceipts.forEach((note) => { const text = buildReceiptText(note); if (text) log(`[调试] 订单 ${note.orderNo} 待回复:${text}`); }); } // 等人工发送期间不算「处理中」,状态圆点改为调试色而不是一直黄色 state.awaitingManualSend = true; renderWidget(); waitForManualSend(); } } catch (error) { if (isTaskCanceled(error)) { state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; if (state.activeRunLog) state.activeRunLog.outcome = "任务已取消"; log("当前回复任务已取消,不会回填或发送。"); renderWidget(); return; } state.processing = false; if (state.activeAbortController === abortController) state.activeAbortController = null; setErrorStatus(); if (state.activeRunLog) state.activeRunLog.outcome = `处理失败:${error.message}`; log(`处理失败:${error.message}`); renderWidget(); scheduleCheck(1200); } finally { finishRunLog(runId); } } function cancelCurrentTask(message) { state.runId += 1; if (state.checkTimer) { window.clearTimeout(state.checkTimer); state.checkTimer = null; } if (state.activeAbortController) { state.activeAbortController.abort(); state.activeAbortController = null; } if (state.manualSendCleanup) { state.manualSendCleanup(); state.manualSendCleanup = null; } state.processing = false; state.awaitingManualSend = false; log(message); renderWidget(); } function ensureTaskActive(runId) { if (state.paused || runId !== state.runId) { const error = new Error("task-canceled"); error.name = "AbortError"; throw error; } } function isTaskCanceled(error) { return error && (error.name === "AbortError" || error.message === "task-canceled"); } function isManualRequired(result) { return Boolean(result && (result.manualRequired || result.action === "manual")); } function findFirstUrgentConversation() { for (const list of getUrgentConversationLists()) { 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) && !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))) .filter((list) => list && isVisible(list)); } function getConversationRows(list) { const candidates = [ ...Array.from(list.children), ...Array.from(list.querySelectorAll("li, [role='listitem'], [class*='user'], [class*='item'], [class*='session'], [class*='conversation']")) ]; return Array.from(new Set(candidates)).filter(isConversationRow); } function isConversationRow(element) { if (!element || !isVisible(element)) return false; const rect = element.getBoundingClientRect(); if (rect.width < 120 || rect.height < 36) return false; const text = normalizeText(element.innerText || element.textContent || ""); if (!text || /^请\s*\d+\s*分钟内回复$/.test(text)) return false; const hasAvatar = Boolean(element.querySelector("img, [class*='avatar'], [class*='head']")); const hasMessageLikeText = /[\u4e00-\u9fa5A-Za-z0-9]/.test(text); return hasAvatar && hasMessageLikeText; } function isManualConversation(row) { if (!row) return false; if (row.dataset && row.dataset.pddRaManual === "1") return true; 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 = getConversationStateKey(row); if (key) state.manualConversationKeys.add(key); } function isCardOnlyConversation(row) { if (!row) return false; const key = getCardOnlyConversationKey(row); return key ? state.cardOnlyConversationKeys.has(key) : false; } function markCardOnlyConversation(row) { if (!row) return; const key = getCardOnlyConversationKey(row); if (key) state.cardOnlyConversationKeys.add(key); } function getCardOnlyConversationKey(row) { const base = getConversationKey(row); const preview = normalizeConversationPreview(row); return base || preview ? `${base}|preview:${preview}` : ""; } function normalizeConversationPreview(row) { return normalizeText(row.innerText || row.textContent || "") .replace(/\d{1,2}:\d{2}(:\d{2})?/g, "") .replace(/\d+\s*秒后超时/g, "") .replace(/请\s*\d+\s*分钟内回复/g, "") .replace(/夜间待回复/g, "") .replace(/超时/g, "") .replace(/\s+/g, "") .slice(0, 160); } function getConversationKey(row) { const attrs = ["data-id", "data-uid", "data-user-id", "data-conversation-id", "data-session-id"]; for (const attr of attrs) { const value = row.getAttribute?.(attr); if (value) return `${attr}:${value}`; } const imgSrc = row.querySelector?.("img")?.getAttribute("src") || ""; const text = normalizeText(row.innerText || row.textContent || "") .replace(/\d{1,2}:\d{2}(:\d{2})?/g, "") .replace(/\d+\s*秒后超时/g, "") .replace(/请\s*\d+\s*分钟内回复/g, "") .replace(/超时/g, "") .replace(/\s+/g, ""); const stableText = text.slice(0, 120); return stableText || imgSrc ? `${imgSrc}|${stableText}` : ""; } function shortHash(value) { let hash = 0; const text = String(value || ""); for (let index = 0; index < text.length; index += 1) { hash = ((hash << 5) - hash + text.charCodeAt(index)) | 0; } return (hash >>> 0).toString(16).padStart(8, "0").slice(0, 6); } // 日志目录用「可读昵称 + 会话短哈希」,既方便找人又不会因重名串目录 function conversationDisplayName(row, conversationKey) { const lines = 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)) .filter((line) => !/(请\s*\d+\s*分钟内回复|夜间待回复|超时)/.test(line)); const name = (lines[0] || "") .replace(/[\\/:*?"<>|\s]+/g, "") .slice(0, 20); return `${name || "用户"}_${shortHash(conversationKey || lines.join("|"))}`; } // 把本轮处理记录(含对话上下文与每步日志)写到「日期/店铺/用户」目录 function finishRunLog(runId) { const run = state.activeRunLog; if (!run || run.runId !== runId) return; state.activeRunLog = null; const payload = { shopId: state.shopId || "default", user: run.user, conversationKey: run.key, runId: run.runId, mode: run.mode, startedAt: formatClock(run.startedAt), finishedAt: formatClock(Date.now()), outcome: run.outcome || "处理结束", reply: run.reply || "", imageCount: run.imageCount || 0, orderCount: run.orderCount || 0, messages: run.messages, lines: run.lines }; try { fetch(`${state.serverBase}/api/conversation-log`, { method: "POST", headers: { "Content-Type": "application/json", ...getShopAuthHeaders() }, body: JSON.stringify(payload) }).catch(() => {}); } catch (_) { // 服务没起时忽略,面板里仍保留本轮日志 } } async function clickConversation(row) { log(`准备点击会话:${normalizeText(row.innerText || row.textContent || "").slice(0, 40)}`); row.scrollIntoView({ block: "center", inline: "nearest" }); await sleep(80); // 真实点击优先:CDP Input 派发的事件 isTrusted 天然为真,还会带上 user activation const pointTarget = elementFromCenter(row) || row; if (await requestTrustedClick(pointTarget)) { await sleep(80); return; } const targets = getClickTargets(row); for (const target of targets) { dispatchClickSequence(target); await sleep(80); } } function getClickTargets(row) { const rect = row.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const centerY = rect.top + rect.height / 2; const pointTarget = document.elementFromPoint(centerX, centerY); const candidates = [ row, pointTarget, row.querySelector("[class*='item']"), row.querySelector("[class*='avatar']"), row.querySelector("img"), row.firstElementChild ].filter(Boolean); return Array.from(new Set(candidates)).filter((target) => target instanceof Element); } function dispatchClickSequence(element) { const rect = element.getBoundingClientRect(); const clientX = Math.max(rect.left + 4, rect.left + rect.width / 2); const clientY = Math.max(rect.top + 4, rect.top + rect.height / 2); const eventInit = { bubbles: true, cancelable: true, composed: true, view: window, clientX, clientY, button: 0, buttons: 1 }; if (typeof PointerEvent === "function") { element.dispatchEvent(new PointerEvent("pointerdown", { ...eventInit, pointerId: 1, pointerType: "mouse" })); } element.dispatchEvent(new MouseEvent("mousedown", eventInit)); if (typeof PointerEvent === "function") { element.dispatchEvent(new PointerEvent("pointerup", { ...eventInit, pointerId: 1, pointerType: "mouse", buttons: 0 })); } element.dispatchEvent(new MouseEvent("mouseup", { ...eventInit, buttons: 0 })); element.dispatchEvent(new MouseEvent("click", { ...eventInit, buttons: 0 })); if (typeof element.click === "function") element.click(); } async function waitForStableChat(beforeChatSignature, row) { await waitForElement(selectors.messageList, 10000); await waitForElement(selectors.replyTextarea, 10000); await waitForChatSwitch(beforeChatSignature, row, 2500); await sleep(700); } async function waitForChatSwitch(beforeChatSignature, row, timeout) { const started = Date.now(); while (Date.now() - started < timeout) { const currentSignature = getChatSignature(); if (!beforeChatSignature || currentSignature !== beforeChatSignature || isSelectedConversation(row)) { return; } await sleep(120); } log("点击后未检测到聊天区明显变化,仍继续尝试提取当前聊天内容。"); } function getChatSignature() { const root = document.querySelector(selectors.messageList); const textarea = document.querySelector(selectors.replyTextarea); return [ normalizeText(root ? root.innerText || root.textContent || "" : "").slice(-1200), normalizeText(textarea ? textarea.value || "" : "") ].join("|"); } function isSelectedConversation(row) { if (!row) return false; const selectedSelector = ".active, .selected, .current, [aria-selected='true'], [class*='active'], [class*='selected'], [class*='current']"; return Boolean(row.matches?.(selectedSelector) || row.querySelector?.(selectedSelector)); } function waitForElement(selector, timeout) { const started = Date.now(); return new Promise((resolve, reject) => { const tick = () => { const element = document.querySelector(selector); if (element && isVisible(element)) { resolve(element); return; } if (Date.now() - started > timeout) { reject(new Error(`未找到页面元素:${selector}`)); return; } window.setTimeout(tick, 120); }; tick(); }); } async function buildConversationPayload() { await ensureRuntimeConfig(); // 买家连发图片时先等一小段静默,避免刚收到几张就抢先回复 await waitForImageBurstSettle(); // 0 表示读取全部:向上滚动把历史消息加载进 DOM 后再一次性收集 if (state.runtime.historyLimit === 0) await expandMessageHistory(); // 订单面板数据同时给「图片归属」和「模型上下文」,只读一次 const messageItems = collectMessageItems(); const orders = await readOrdersCached(hasOrderHint(messageItems)).catch(() => []); log(orders.length ? `订单面板:读取到 ${orders.length} 个订单。` : "订单面板:未读取到订单。"); // 纯图片/视频批次先把归档做完,数量差值回复才能在本轮直接发出去,避免先冒出一段无关文字; // 带图片调整指令的会话也要等归档完成再决定怎么回复。 const adjustIntent = await resolveImageAdjustment(messageItems); if (isMediaOnlyBatch(messageItems) || adjustIntent) { try { const outcome = await archiveChatImages(orders, messageItems); if (outcome === "wait") { return { skip: true, reason: "waiting-adjust-image", msgList: [] }; } } catch (error) { log(`图片归档失败:${error?.message || error}`); } } else { // 含文字的会话不阻塞模型回复,归档失败只记日志 archiveChatImages(orders, messageItems).catch((error) => log(`图片归档失败:${error?.message || error}`)); } const latestItem = getLatestConversationItem(messageItems); const hasPendingCustomerText = hasPendingCustomerMessage(messageItems); const buyerSentCard = latestItem?.type === "product-card" && latestItem.usertype === "cus"; 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("检测到客户文字后有平台商品卡提醒,继续按客户文字处理。"); } const latestProductCard = extractLatestProductCardInfo(); const limit = state.runtime.historyLimit; const msgList = extractMessages(limit, messageItems); if (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); return { msgList, orders: compactOrdersForPayload(orders) }; } // 只带模型需要的字段,避免把整个订单对象塞进提示词 function compactOrdersForPayload(orders) { if (!Array.isArray(orders) || !orders.length) return []; return orders.slice(-10).map((order) => ({ orderSn: order.orderSn, orderTime: order.orderTime ? formatClock(order.orderTime) : "", status: order.status || "", afterSale: order.afterSale ? "有售后" : "无售后", goods: (order.goods || []).slice(0, 5).map((item) => ({ name: String(item.name || "").slice(0, 60), spec: String(item.spec || "").slice(0, 60), num: item.num || 1 })) })); } function formatClock(epochMs) { const d = new Date(epochMs); const pad = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; } function hasPendingCustomerMessage(messageItems) { const lastSysIndex = findLastIndex(messageItems, (item) => item.usertype === "sys"); return messageItems.slice(lastSysIndex + 1).some((item) => item.usertype === "cus" && item.msg); } // 末尾连续发送的图片张数(遇到文字或客服消息就停) function trailingCustomerImageCount(messageItems) { let count = 0; for (let i = messageItems.length - 1; i >= 0; i -= 1) { const item = messageItems[i]; if (item.usertype !== "cus" || item.msg !== "[图片]") break; count += 1; } return count; } // 买家一次发很多照片时,等发完再回复;最多等 IMAGE_BURST_MAX_ROUNDS 轮 async function waitForImageBurstSettle() { for (let round = 0; round < IMAGE_BURST_MAX_ROUNDS; round += 1) { const items = collectMessageItems(); const images = trailingCustomerImageCount(items); if (images < IMAGE_BURST_MIN) return; log(`买家已连续发送 ${images} 张图片,等待 ${IMAGE_BURST_SETTLE_MS / 1000} 秒确认发完再回复。`); await sleep(IMAGE_BURST_SETTLE_MS); if (collectMessageItems().length <= items.length) return; } } // 最近一条客服消息之后的买家消息是否只有图片/视频(没有文字),用于避免连发时反复回复 function isMediaOnlyBatch(msgList) { const list = Array.isArray(msgList) ? msgList : []; let lastSysIndex = -1; list.forEach((item, index) => { if (item && item.usertype === "sys") lastSysIndex = index; }); const pending = list.slice(lastSysIndex + 1).filter((item) => item && item.usertype === "cus"); if (!pending.length) return false; return pending.every((item) => /^\[(图片|视频)\](x\d+)?$/.test(item.msg)); } // 开场说明:会话里还没有客服消息(首次咨询)或出现没发过的订单号时,先发一次 function pickGreeting(payload, row) { const cfg = state.runtime.greeting; if (!cfg || !cfg.enabled) return null; const text = normalizeText(cfg.text || ""); const images = Array.isArray(cfg.images) ? cfg.images : []; if (!text && !images.length) return null; const key = row ? getConversationKey(row) : ""; const messages = Array.isArray(payload?.msgList) ? payload.msgList : []; const noSysMessage = !messages.some((item) => item && item.usertype === "sys"); const firstNeeded = cfg.onFirst && noSysMessage && !(key && state.greetedConversations.has(key)); const orderSns = (Array.isArray(payload?.orders) ? payload.orders : []) .map((order) => String((order && order.orderSn) || "")) .filter(Boolean); const newOrders = cfg.onOrder ? orderSns.filter((sn) => !state.greetedOrders.has(sn)) : []; if (!firstNeeded && !newOrders.length) return null; if (key) state.greetedConversations.add(key); newOrders.forEach((sn) => state.greetedOrders.add(sn)); log(`触发开场说明(${firstNeeded ? "首次咨询" : "新订单"})。`); return { text, images }; } function findLastIndex(items, predicate) { for (let index = items.length - 1; index >= 0; index -= 1) { if (predicate(items[index], index, items)) return index; } return -1; } function getLatestConversationItem(messageItems = collectMessageItems()) { const candidates = [ ...getProductCardItems(), ...messageItems.map((item) => ({ type: "message", top: item.top, bottom: item.bottom, left: item.left, usertype: item.usertype, msg: item.msg })) ]; if (!candidates.length) return null; candidates.sort((a, b) => a.bottom - b.bottom || a.top - b.top || a.left - b.left); return candidates[candidates.length - 1]; } function getProductCardItems() { 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) => { const rect = element.getBoundingClientRect(); const product = parseProductCardInfo(element); return { type: "product-card", element, top: rect.top, bottom: rect.bottom, left: rect.left, usertype: rect.left + rect.width / 2 < rootCenterX ? "cus" : "sys", product }; }) .filter((item) => item.product?.message); } function printPayloadToDebugConsole(payload) { const json = JSON.stringify(payload, null, 2); console.groupCollapsed("[PDD客服回复助手] 发送给本地服务的聊天结构"); console.log(payload); console.log(json); console.groupEnd(); log(`调试台已打印聊天结构:msgList=${payload.msgList.length}条。`); } function extractLatestProductCardInfo() { const candidates = getProductCardItems(); if (!candidates.length) return null; candidates.sort((a, b) => a.top - b.top); const latest = candidates[candidates.length - 1].product; log(`读取到最后一个商品卡片:${latest.message}`); return latest; } function isProductCardContainer(element, rootRect) { if (!isVisible(element)) return false; if (!element.querySelector?.("img")) return false; const rect = element.getBoundingClientRect(); if (rect.width < 180 || rect.width > Math.min(620, rootRect.width * 0.75)) return false; if (rect.height < 56 || rect.height > 260) return false; const text = normalizeText(element.innerText || element.textContent || ""); if (!text || text.length < 8 || text.length > 900) return false; if (!/商品ID|查看商品规格|咨询商品规格|¥\s*\d+|¥\s*\d+/.test(text)) return false; if (!/[\u4e00-\u9fa5A-Za-z0-9]/.test(text)) return false; return true; } function parseProductCardInfo(element) { const rawText = normalizeText(element.innerText || element.textContent || ""); const lines = rawText .split(/\n+/) .map((line) => cleanupProductCardLine(line)) .filter(Boolean) .filter((line) => !isProductCardNoiseLine(line)); const uniqueLines = []; for (const line of lines) { if (!uniqueLines.includes(line)) uniqueLines.push(line); } const title = uniqueLines.find((line) => isLikelyProductTitle(line)); if (!title) return null; const modelLine = uniqueLines.find((line) => line !== title && isLikelyProductModel(line, title)); const model = modelLine ? cleanupProductModel(modelLine) : ""; const message = model && !title.includes(model) ? `这款${title}的${model}` : `这款${title}`; // 价格和商品ID 会被当成噪声过滤掉,但它们对回答价格/规格问题有用,单独抓出来 const priceMatch = rawText.match(/[¥¥]\s*\d+(?:\.\d+)?/); const idMatch = rawText.match(/商品ID[::]?\s*(\d+)/i); return { name: title, model, message, price: priceMatch ? priceMatch[0].replace(/¥/, "¥") : "", productId: idMatch ? idMatch[1] : "" }; } function parseProductCardText(element) { const info = parseProductCardInfo(element); if (!info) return ""; return info.model && !info.name.includes(info.model) ? `${info.name} ${info.model}` : info.name; } function cleanupProductCardLine(line) { return normalizeText(line) .replace(/^商品ID[::]?\s*\d+\s*复制?$/i, "") .replace(/^商品ID[::]?\s*/i, "") .replace(/\s+/g, " ") .trim(); } function isProductCardNoiseLine(line) { if (!line) return true; if (/^复制$/.test(line)) return true; if (/^查看商品规格$/.test(line)) return true; if (/^咨询商品规格$/.test(line)) return true; if (/^当前用户来自/.test(line)) return true; if (/^¥|^¥/.test(line)) return true; if (/^\d+\s*\/\s*\d+人团$/.test(line)) return true; if (/商品ID|下单时间|订单编号|实收|复制|备注/.test(line)) return true; return false; } function isLikelyProductTitle(line) { if (line.length < 6) return false; if (/^¥|^¥/.test(line)) return false; if (/^\d/.test(line) && line.length < 12) return false; return /[\u4e00-\u9fa5]/.test(line); } function isLikelyProductModel(line, title) { if (!line || line === title) return false; if (line.length > 80) return false; if (/^\(|^(/.test(line)) return false; if (/^\d+\s*\/\s*\d+人团$/.test(line)) return false; if (/¥|¥/.test(line)) return false; if (title.includes(line)) return false; return /\d+(\.\d+)?\s*(米|m|M|号|斤|克|g|G)|规格|型号|颜色|尺码|套餐|单竿|套装/.test(line); } function cleanupProductModel(line) { return normalizeText(line) .split(/[((,,]/)[0] .replace(/规格[::]?/g, "") .replace(/型号[::]?/g, "") .trim(); } // 只认视频/播放器相关类名,避免 display、replay 这类同形子串误判 function isVideoClass(cls) { if (/video|player/i.test(cls)) return true; return /(^|[-_ ])play([-_ ]|$)/i.test(cls) || /play[-_]?(btn|icon|mask|overlay|button|circle)/i.test(cls); } // 只缓存「命中视频」的行:负结果不缓存,避免封面图稍后才加载时被判成图片 const VIDEO_ROW_CACHE = new WeakMap(); const VIDEO_ROW_LOGGED = new WeakSet(); // 视频消息在拼多多聊天里常是「大封面图 + 播放按钮/时长提示」,类名随构建经常变, // 所以按整条消息行判断;命中后整行按视频处理,封面图也不计入照片数量和归档 function isVideoMessageRow(row) { if (!row || row.nodeType !== 1) return false; if (VIDEO_ROW_CACHE.get(row) === true) return true; let result = Boolean(row.querySelector("video")); if (!result) { result = Array.from(row.querySelectorAll('[class*="video"], [class*="Video"], [class*="player"], [class*="Player"], [class*="play"], [class*="Play"]')) .some((item) => { const cls = String(item.className || ""); if (!isVideoClass(cls)) return false; if (/avatar|icon|emoji|face|logo|qrcode|banner|audio|voice|display/i.test(cls)) return false; const r = item.getBoundingClientRect(); return r.width >= 24 && r.height >= 24; }); } if (!result) { result = Boolean(row.querySelector('[title*="视频"], [aria-label*="视频"]')); } if (!result) { // 有「视频/点击播放/时长」提示且同一行里挂着封面大图,才是视频气泡; // 只有文字没有图的消息不按视频处理,避免把买家说的“视频”当视频消息 const hasCover = Array.from(row.querySelectorAll("img")).some((img) => { const r = img.getBoundingClientRect(); return isVisible(img) && r.width >= 60 && r.height >= 48; }); if (hasCover) { const text = normalizeText(row.innerText || row.textContent || ""); result = /视频|点击播放|正在播放/.test(text) || /^\d{1,2}:\d{2}(:\d{2})?$/.test(text); } } if (result) VIDEO_ROW_CACHE.set(row, true); return result; } // 视频消息在 DOM 里常带时长/封面文本,不能当买家文字处理,统一用 [视频] 占位 function collectChatVideos(root) { const out = []; const seen = new Set(); const push = (element) => { if (!element || seen.has(element) || !isVisible(element)) return; if (element.closest(selectors.productCards)) return; const rect = element.getBoundingClientRect(); if (rect.width < 80 || rect.height < 60) return; seen.add(element); out.push({ element, top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right }); }; root.querySelectorAll("video").forEach(push); // 先按整条消息行判定(类名不可靠时靠行内提示文字 + 封面图兜底) root.querySelectorAll('li.onemsg, [id^="middlePanel_list_"]').forEach((row) => { if (!isVideoMessageRow(row)) return; if (!VIDEO_ROW_LOGGED.has(row)) { VIDEO_ROW_LOGGED.add(row); log("识别到视频消息,已忽略它的封面图和提示文字。"); } push(row); }); // 视频气泡不一定是