- dedupe by buyer message fingerprint and pending-message detection - stop treating platform auto-reply and order/product cards as chat messages - reply to buyer-sent product cards, inject card price and goods id - add optional human-intervention fallback to debug mode - configurable personal-order cache, block WebView2 new windows - capture crash dumps, bump version to 1.1.2
4121 lines
168 KiB
JavaScript
4121 lines
168 KiB
JavaScript
(() => {
|
||
"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);
|
||
});
|
||
// 视频气泡不一定是 <video>:拼多多的视频消息常是「封面图 + 播放按钮」,
|
||
// 类名可能只有 player/play,按类名 + 尺寸 + 大封面图一起判断,避免把时长文字当买家消息
|
||
root.querySelectorAll('[class*="video"], [class*="Video"], [class*="player"], [class*="Player"], [class*="play"], [class*="Play"]').forEach((element) => {
|
||
if (!isVisible(element)) return;
|
||
const cls = String(element.className || "");
|
||
if (!isVideoClass(cls)) return;
|
||
if (/avatar|icon|emoji|face|logo|qrcode|banner|audio|voice|display/i.test(cls)) return;
|
||
const rect = element.getBoundingClientRect();
|
||
if (rect.width < 24 || rect.height < 24) return;
|
||
// 小尺寸的播放按钮:只有同一消息行里存在大封面图时才认定为视频
|
||
const row = element.closest('li.onemsg, [id^="middlePanel_list_"]');
|
||
if (element.tagName !== "VIDEO" && !element.querySelector("video") && rect.width < 80) {
|
||
const cover = row && Array.from(row.querySelectorAll("img")).find((img) => {
|
||
const r = img.getBoundingClientRect();
|
||
return isVisible(img) && r.width >= 80 && r.height >= 60;
|
||
});
|
||
if (cover) push(row || cover);
|
||
return;
|
||
}
|
||
push(element);
|
||
// 整行都算视频气泡,行内的时长/「视频」提示文字一并排除
|
||
if (row && row !== element) push(row);
|
||
});
|
||
return out;
|
||
}
|
||
|
||
function collectVideoScopes(videos, root) {
|
||
const scopes = new Set();
|
||
for (const video of videos) {
|
||
// 只把视频所在的那条消息行圈进来,不能往上爬到消息列表容器,
|
||
// 否则会把整屏所有消息的文字都当成视频内容丢掉
|
||
const row = video.element.closest('li.onemsg, [id^="middlePanel_list_"]');
|
||
if (row && row !== root) scopes.add(row);
|
||
let node = video.element;
|
||
for (let depth = 0; node && node !== root && depth < 6; depth += 1) {
|
||
scopes.add(node);
|
||
if (node === row) break;
|
||
node = node.parentElement;
|
||
}
|
||
}
|
||
return scopes;
|
||
}
|
||
|
||
function isInsideVideoScope(element, scopes, root) {
|
||
if (!scopes.size) return false;
|
||
let node = element;
|
||
while (node && node !== root) {
|
||
if (scopes.has(node)) return true;
|
||
node = node.parentElement;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
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];
|
||
if (last && last.usertype === usertype && Math.abs(last.top - video.top) < 40) continue;
|
||
out.push({ top: video.top, bottom: video.bottom, left: video.left,
|
||
t: messageTimeOf(video.element), usertype, msg: "[视频]" });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function collectMessageItems() {
|
||
const root = document.querySelector(selectors.messageList);
|
||
if (!root) return [];
|
||
|
||
const rootRect = root.getBoundingClientRect();
|
||
const all = Array.from(root.querySelectorAll("*"));
|
||
const videos = collectChatVideos(root);
|
||
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;
|
||
if (looksLikeProductCard(element, text)) continue;
|
||
|
||
const rect = element.getBoundingClientRect();
|
||
if (rect.width < 24 || rect.height < 12) continue;
|
||
|
||
const centerX = rect.left + rect.width / 2;
|
||
const rootCenterX = rootRect.left + rootRect.width / 2;
|
||
const distanceFromCenter = Math.abs(centerX - rootCenterX);
|
||
if (distanceFromCenter < rootRect.width * 0.08 && text.length < 24) continue;
|
||
|
||
raw.push({
|
||
top: rect.top,
|
||
bottom: rect.bottom,
|
||
left: rect.left,
|
||
t: messageTimeOf(element),
|
||
usertype: centerX > rootCenterX ? "sys" : "cus",
|
||
msg: text
|
||
});
|
||
}
|
||
|
||
// 图片和视频都没有文字,补占位让模型知道对方发过媒体
|
||
raw.push(...collectImagePlaceholders(root, rootRect, isAutoNode));
|
||
raw.push(...collectVideoPlaceholders(videos, rootRect, isAutoNode));
|
||
|
||
raw.sort((a, b) => a.top - b.top || a.left - b.left);
|
||
|
||
const deduped = [];
|
||
for (const item of raw) {
|
||
const last = deduped[deduped.length - 1];
|
||
if (last && last.usertype === item.usertype && last.msg === item.msg && Math.abs(last.top - item.top) < 12) {
|
||
continue;
|
||
}
|
||
if (deduped.some((old) => old.usertype === item.usertype && old.msg === item.msg && Math.abs(old.top - item.top) < 24)) {
|
||
continue;
|
||
}
|
||
deduped.push(item);
|
||
}
|
||
|
||
return deduped;
|
||
}
|
||
|
||
function extractMessages(limit = 6, messageItems = collectMessageItems()) {
|
||
// 先合并连续图片/视频再按条数截取:否则上百张图会把历史窗口塞满,模型看不到文字
|
||
const merged = [];
|
||
for (const item of messageItems) {
|
||
const last = merged[merged.length - 1];
|
||
const media = /^\[(图片|视频)\]$/.test(item.msg) ? item.msg : "";
|
||
if (media && last && last.usertype === item.usertype) {
|
||
if (last.msg === media) {
|
||
last.msg = `${media}x2`;
|
||
continue;
|
||
}
|
||
const prefix = `${media}x`;
|
||
if (last.msg.startsWith(prefix)) {
|
||
const count = Number(last.msg.slice(prefix.length));
|
||
if (Number.isFinite(count)) {
|
||
last.msg = `${media}x${count + 1}`;
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
merged.push({ usertype: item.usertype, msg: item.msg });
|
||
}
|
||
// limit 为 0 时表示「全部」,不能用 slice(-0)
|
||
return limit > 0 ? merged.slice(-limit) : merged;
|
||
}
|
||
|
||
// ---------- 聊天记录条数与图片归档 ----------
|
||
function sleep(ms) {
|
||
return new Promise((resolve) => window.setTimeout(resolve, ms));
|
||
}
|
||
|
||
// 页面操作(切换页签/切换页面)的随机等待,区间可在软件「高级设置」里配置
|
||
function pageDelayMs() {
|
||
const min = Math.max(0, Number(state.runtime.minPageDelayMs) || 0);
|
||
const max = Math.max(min, Number(state.runtime.maxPageDelayMs) || min);
|
||
return min + Math.floor(Math.random() * (max - min + 1));
|
||
}
|
||
|
||
async function ensureRuntimeConfig() {
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
const controller = typeof AbortController === "function" ? new AbortController() : null;
|
||
const timer = controller ? window.setTimeout(() => controller.abort(), 1500) : 0;
|
||
try {
|
||
const query = state.shopId ? `?shopId=${encodeURIComponent(state.shopId)}` : "";
|
||
const response = await fetch(`${base}/api/runtime-config${query}`, {
|
||
signal: controller ? controller.signal : undefined
|
||
});
|
||
if (!response.ok) return;
|
||
const d = await response.json();
|
||
const n = Number(d.historyLimit);
|
||
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 || "");
|
||
if (mode === "time" || mode === "sequence" || mode === "sequence-reverse" || mode === "hybrid") {
|
||
state.runtime.imageAssignMode = mode;
|
||
}
|
||
const concurrent = Number(d.imageConcurrentMs);
|
||
if (Number.isFinite(concurrent) && concurrent >= 1000 && concurrent <= 3600000) {
|
||
state.runtime.imageConcurrentMs = concurrent;
|
||
}
|
||
const batchGap = Number(d.imageBatchGapMs);
|
||
if (Number.isFinite(batchGap) && batchGap >= 30000 && batchGap <= 3600000) {
|
||
state.runtime.imageBatchGapMs = batchGap;
|
||
}
|
||
const historyLead = Number(d.imageHistoryLeadMs);
|
||
if (Number.isFinite(historyLead) && historyLead >= 60000 && historyLead <= 86400000) {
|
||
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;
|
||
state.runtime.receiptShortageReply = String(d.receiptShortageReply || "");
|
||
state.runtime.receiptOverflowReply = String(d.receiptOverflowReply || "");
|
||
state.runtime.imageAdjustEnabled = d.imageAdjustEnabled !== false;
|
||
state.runtime.imageAdjustReplyEnabled = d.imageAdjustReplyEnabled !== false;
|
||
state.runtime.adjustReplaceReply = String(d.adjustReplaceReply || "");
|
||
state.runtime.adjustDeleteReply = String(d.adjustDeleteReply || "");
|
||
["imageAdjustReplaceWords", "imageAdjustDeleteWords", "imageAdjustResendWords",
|
||
"imageAdjustPointWords", "imageAdjustNegativeWords"].forEach((key) => {
|
||
if (typeof d[key] === "string" && d[key].trim()) state.runtime[key] = d[key];
|
||
});
|
||
const matchThreshold = Number(d.imageAdjustMatchThreshold);
|
||
if (Number.isFinite(matchThreshold) && matchThreshold >= 0 && matchThreshold <= 16) {
|
||
state.runtime.imageAdjustMatchThreshold = matchThreshold;
|
||
}
|
||
const adjustMode = String(d.imageAdjustMode || "rules");
|
||
state.runtime.imageAdjustMode =
|
||
(adjustMode === "hybrid" || adjustMode === "ai") ? adjustMode : "rules";
|
||
const adjustConfidence = Number(d.imageAdjustAiConfidence);
|
||
if (Number.isFinite(adjustConfidence) && adjustConfidence >= 0 && adjustConfidence <= 1) {
|
||
state.runtime.imageAdjustAiConfidence = adjustConfidence;
|
||
}
|
||
const pageMin = Number(d.minPageDelayMs);
|
||
if (Number.isFinite(pageMin) && pageMin >= 0 && pageMin <= 60000) {
|
||
state.runtime.minPageDelayMs = pageMin;
|
||
}
|
||
const pageMax = Number(d.maxPageDelayMs);
|
||
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;
|
||
state.runtime.riskStopOnHit = d.riskStopOnHit !== false;
|
||
const greeting = d.greeting;
|
||
if (greeting && typeof greeting === "object") {
|
||
state.runtime.greeting = {
|
||
enabled: greeting.enabled === true,
|
||
onFirst: greeting.onFirst !== false,
|
||
onOrder: greeting.onOrder !== false,
|
||
text: String(greeting.text || ""),
|
||
images: Array.isArray(greeting.images)
|
||
? greeting.images
|
||
.filter((item) => item && item.file)
|
||
.map((item) => ({
|
||
file: String(item.file),
|
||
name: String(item.name || ""),
|
||
withText: item.withText !== false
|
||
}))
|
||
: []
|
||
};
|
||
}
|
||
} catch (error) {
|
||
// 本地服务没起来就沿用默认 6 条,不影响自动回复
|
||
} finally {
|
||
if (timer) window.clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
function findScrollParent(el) {
|
||
let cur = el;
|
||
for (let i = 0; i < 6 && cur; i++) {
|
||
const st = window.getComputedStyle(cur);
|
||
if (/(auto|scroll)/.test(st.overflowY || "") && cur.scrollHeight > cur.clientHeight + 8) return cur;
|
||
cur = cur.parentElement;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// 「全部」模式:把消息容器滚到顶,等平台把更早的历史追加进 DOM,
|
||
// 连续几轮消息数不再增长就认为到底了,最后把滚动位置还给用户
|
||
async function expandMessageHistory() {
|
||
const root = document.querySelector(selectors.messageList);
|
||
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++) {
|
||
if (scroller) scroller.scrollTop = 0;
|
||
await sleep(280);
|
||
const count = collectMessageItems().length + collectChatImages(root).length;
|
||
if (count === last) stable += 1;
|
||
else stable = 0;
|
||
last = count;
|
||
if (stable >= 3) break;
|
||
}
|
||
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;
|
||
|
||
function isDecorativeImage(element, url) {
|
||
const cls = String(element.className || "") + " " + String(element.id || "");
|
||
if (/avatar|head|icon|emoji|face|logo|qrcode/i.test(cls)) return true;
|
||
if (/avatar|icon|emoji|face|logo|qrcode/i.test(url)) return true;
|
||
return false;
|
||
}
|
||
|
||
// 视频封面不是聊天图片,不能计入照片数量和图片归档
|
||
function isVideoCover(element) {
|
||
let node = element;
|
||
for (let depth = 0; node && depth < 3; depth += 1) {
|
||
if (node.tagName === "VIDEO") return true;
|
||
const cls = `${node.className || ""} ${node.id || ""}`;
|
||
if (/video|player/i.test(cls) && !/avatar|icon|emoji|face|logo|qrcode|banner|audio|voice|display/i.test(cls)) return true;
|
||
node = node.parentElement;
|
||
}
|
||
// 兜底:整条消息行被判定为视频时,这张图只是视频封面
|
||
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();
|
||
const push = (url, rect, element) => {
|
||
if (!/^https?:/i.test(url) || seen.has(url)) return;
|
||
if (isDecorativeImage(element, url)) return;
|
||
seen.add(url);
|
||
out.push({ url, top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right, element });
|
||
};
|
||
|
||
root.querySelectorAll("img").forEach((img) => {
|
||
if (!isVisible(img)) return;
|
||
const r = img.getBoundingClientRect();
|
||
if (r.width < IMAGE_MIN_SIZE || r.height < IMAGE_MIN_SIZE) return;
|
||
if (img.closest(selectors.productCards)) return;
|
||
if (isVideoCover(img)) return;
|
||
const url = img.currentSrc || img.src || img.getAttribute("data-src") ||
|
||
img.getAttribute("data-original") || "";
|
||
push(url, r, img);
|
||
});
|
||
|
||
// 有些聊天图片是 background-image 而不是 <img>
|
||
root.querySelectorAll("*").forEach((el) => {
|
||
if (!isVisible(el) || el.closest(selectors.productCards)) return;
|
||
if (isVideoCover(el)) return;
|
||
const bg = window.getComputedStyle(el).backgroundImage || "";
|
||
if (bg === "none" || bg.indexOf("url(") < 0) return;
|
||
const r = el.getBoundingClientRect();
|
||
if (r.width < IMAGE_MIN_SIZE || r.height < IMAGE_MIN_SIZE) return;
|
||
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, 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];
|
||
// 同一气泡里的多张图(九宫格)合并成一个占位
|
||
if (last && last.usertype === usertype && Math.abs(last.top - img.top) < 40) continue;
|
||
out.push({ top: img.top, bottom: img.bottom, left: img.left,
|
||
t: messageTimeOf(img.element), usertype, msg: "[图片]" });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// ---------- 订单面板(右侧「个人订单」,当前会话买家维度) ----------
|
||
// 订单号、下单时间、规格、件数都由商家后台面板给出,买家不需要在聊天里发订单号。
|
||
// 优先读 Vue 组件里的结构化订单对象(下单时间精确到秒),读不到再解析面板文本(只到分钟)。
|
||
function normalizeOrderGoods(list) {
|
||
if (!list) return [];
|
||
const raw = Array.isArray(list) ? list : [list];
|
||
return raw
|
||
.filter((item) => item && typeof item === "object")
|
||
.map((item) => ({
|
||
name: String(item.goodsName || ""),
|
||
spec: String(item.spec || ""),
|
||
num: Number(item.goodsNumber) > 0 ? Number(item.goodsNumber) : 1
|
||
}));
|
||
}
|
||
|
||
// 「50张」「100张/份」「6寸50张」这类规格里能直接读到张数,件数另算
|
||
function parseSheetCount(text) {
|
||
const m = String(text || "").match(/(\d{1,4})\s*张/);
|
||
if (!m) return 0;
|
||
const n = Number(m[1]);
|
||
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) {
|
||
const per = parseSheetCount(item.spec) || parseSheetCount(item.name);
|
||
if (!per) continue;
|
||
matched = true;
|
||
total += per * (item.num || 1);
|
||
}
|
||
return matched ? total : 0;
|
||
}
|
||
|
||
function readOrderItemFromVue(element) {
|
||
const vm = element.__vue__;
|
||
const order = vm && vm.$props ? vm.$props.order : null;
|
||
if (!order || !order.orderSn) return null;
|
||
const goods = normalizeOrderGoods(order.orderGoodsList);
|
||
return {
|
||
orderSn: String(order.orderSn),
|
||
orderTime: Number(order.orderTime) * 1000,
|
||
payStatus: Number(order.payStatus) || 0,
|
||
status: String(order.orderStatusStr || ""),
|
||
afterSale: Boolean(order.afterSalesInfo && order.afterSalesInfo.afterSalesStatus),
|
||
goods,
|
||
expected: expectedSheetCount(goods)
|
||
};
|
||
}
|
||
|
||
// 面板文本兜底:订单号在 .order-sn,「下单时间:」后面就是时间文本
|
||
function parseOrderTimeFromText(element) {
|
||
const text = String(element.innerText || "");
|
||
const m = text.match(/下单时间[::]?\s*(\d{4})[-/](\d{1,2})[-/](\d{1,2})[\sT]*(\d{1,2})[::](\d{2})/);
|
||
if (!m) return 0;
|
||
return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5])).getTime();
|
||
}
|
||
|
||
function readOrderItemFromDom(element) {
|
||
const snNode = element.querySelector(".order-sn");
|
||
const orderSn = snNode ? String(snNode.innerText || "").trim() : "";
|
||
if (!orderSn) return null;
|
||
|
||
const orderTime = parseOrderTimeFromText(element);
|
||
|
||
const goods = [];
|
||
element.querySelectorAll(".goods-content").forEach((node) => {
|
||
const name = node.querySelector(".goods-name");
|
||
const spec = node.querySelector(".goods-spec");
|
||
const num = node.querySelector(".goods-num");
|
||
const count = num ? Number(String(num.innerText || "").replace(/[^\d]/g, "")) : 1;
|
||
goods.push({
|
||
name: name ? String(name.innerText || "").trim() : "",
|
||
spec: spec ? String(spec.innerText || "").trim() : "",
|
||
num: count > 0 ? count : 1
|
||
});
|
||
});
|
||
|
||
return {
|
||
orderSn,
|
||
orderTime,
|
||
payStatus: 0,
|
||
status: String((element.querySelector(".title-status") || {}).innerText || "").trim(),
|
||
afterSale: Boolean(element.querySelector(".base-info-item-aftersale-status")),
|
||
goods,
|
||
expected: expectedSheetCount(goods)
|
||
};
|
||
}
|
||
|
||
// 每轮读订单都要点开「个人订单」页签再点回去,轮询时就表现为右侧一直闪。
|
||
// 缓存时长可在「高级设置 → 个人订单缓存」里配(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"));
|
||
if (!containers.length) return [];
|
||
const out = [];
|
||
const seen = new Set();
|
||
// Vue 常用 v-show 保留隐藏页签的 DOM,「最新订单」是店铺维度待支付列表,
|
||
// 隐藏时残留的 .order-item 会被一起读到,把别的买家的订单串进当前会话,所以只取可见项
|
||
for (const list of containers) {
|
||
const items = Array.from(list.querySelectorAll(".order-item")).filter((el) =>
|
||
el.offsetParent !== null || el.getClientRects().length > 0
|
||
);
|
||
for (const element of items) {
|
||
const order = readOrderItemFromVue(element) || readOrderItemFromDom(element);
|
||
if (!order) continue;
|
||
// Vue 里可能没有 orderTime,用面板文本补一次时间,不能因为缺时间把订单丢掉
|
||
if (!order.orderTime) order.orderTime = parseOrderTimeFromText(element);
|
||
if (seen.has(order.orderSn)) continue;
|
||
seen.add(order.orderSn);
|
||
out.push(order);
|
||
}
|
||
}
|
||
out.sort((a, b) => (a.orderTime || Number.MAX_SAFE_INTEGER) - (b.orderTime || Number.MAX_SAFE_INTEGER) ||
|
||
a.orderSn.localeCompare(b.orderSn));
|
||
return out;
|
||
}
|
||
|
||
// 三分类:正常订单(待支付/待发货/已发货)、已完成、退款售后
|
||
function orderStatusCategory(order) {
|
||
const text = String(order.status || "");
|
||
if (/退款|退货|换货|售后|纠纷/.test(text) || order.afterSale) return "refund";
|
||
if (/已完成|交易成功|已收货|已完成订单/.test(text)) return "done";
|
||
return "normal";
|
||
}
|
||
|
||
function orderStatusEnabled(order) {
|
||
switch (orderStatusCategory(order)) {
|
||
case "refund": return state.runtime.orderStatusRefund !== false;
|
||
case "done": return state.runtime.orderStatusDone !== false;
|
||
default: return state.runtime.orderStatusNormal !== false;
|
||
}
|
||
}
|
||
|
||
function filterOrders(orders) {
|
||
if (!Array.isArray(orders)) return [];
|
||
return orders.filter((order) => order && orderStatusEnabled(order));
|
||
}
|
||
|
||
// 订单面板可能停在别的页签,也可能刚切会话还在异步加载,两种都要等
|
||
function orderPanelSaysEmpty() {
|
||
const panel = document.querySelector(".right-panel") || document.querySelector(".order-panel");
|
||
const text = String(panel ? panel.innerText : "");
|
||
// 注意「近90天没有更多订单了」是列表结尾文案,列表里已读到订单时也会出现,不能当空列表
|
||
return /暂无订单|没有相关订单|无订单信息|该用户暂无/.test(text);
|
||
}
|
||
|
||
// 只认「个人订单」:latitude/order/userAllOrder 返回当前会话买家近 90 天订单。
|
||
// 「最新订单」是店铺维度待支付订单(chats/unpaidOrders),属于整个店铺,
|
||
// 不能当作当前买家的订单,也不作为兜底数据源。
|
||
function findPersonalOrderTab() {
|
||
const nodes = Array.from(document.querySelectorAll(
|
||
".bar-box .bar-item, .order-panel-second-bar, .order-panel-tab, .tab-item"));
|
||
return nodes.find((el) => /个人订单/.test(el.innerText || "")) || null;
|
||
}
|
||
|
||
function isPersonalTabActive(tab) {
|
||
if (!tab) return false;
|
||
const cls = String(tab.className || "");
|
||
return /active|selected|current|is-active/.test(cls);
|
||
}
|
||
|
||
async function readOrderPanelWithAutoSwitch() {
|
||
let tab = findPersonalOrderTab();
|
||
|
||
// 右侧停在别的面板时「个人订单」页签还没渲染,先点回订单主面板
|
||
if (!tab) {
|
||
const mainTab = Array.from(document.querySelectorAll(".bar-box .bar-item"))
|
||
.find((el) => /订单/.test(el.innerText || ""));
|
||
if (mainTab) {
|
||
mainTab.click();
|
||
await sleep(pageDelayMs());
|
||
for (let i = 0; i < 8 && !tab; i++) {
|
||
await sleep(150);
|
||
tab = findPersonalOrderTab();
|
||
}
|
||
}
|
||
}
|
||
|
||
const previous = Array.from(document.querySelectorAll(".bar-box .bar-item"))
|
||
.find((el) => el.classList.contains("active")) || null;
|
||
const restore = () => {
|
||
if (previous && !state.runtime.imageKeepOrderTab) previous.click();
|
||
};
|
||
|
||
// 已经停在个人订单且列表渲染好了,可以直接读;否则必须切过去再等异步加载
|
||
if (tab && isPersonalTabActive(tab)) {
|
||
const direct = readOrderPanel();
|
||
if (direct.length) return filterOrders(direct);
|
||
}
|
||
|
||
if (!tab) return [];
|
||
tab.click();
|
||
await sleep(pageDelayMs());
|
||
for (let i = 0; i < 14; i++) {
|
||
await sleep(150);
|
||
const found = readOrderPanel();
|
||
if (found.length) {
|
||
restore();
|
||
return filterOrders(found);
|
||
}
|
||
if (orderPanelSaysEmpty()) break;
|
||
}
|
||
restore();
|
||
return [];
|
||
}
|
||
|
||
// ---------- 图片时间线 ----------
|
||
// 每条消息行 id 是 middlePanel_list_<毫秒时间戳>,比 .message-time 稳定,所有消息类型都有
|
||
function messageTimeOf(element) {
|
||
let current = element;
|
||
for (let i = 0; i < 8 && current; i++) {
|
||
const m = String(current.id || "").match(/middlePanel_list_(\d{10,15})/);
|
||
if (m) return Number(m[1]);
|
||
current = current.parentElement;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
function collectImageEvents(root) {
|
||
const rootRect = root.getBoundingClientRect();
|
||
const rootCenterX = rootRect.left + rootRect.width / 2;
|
||
const events = [];
|
||
for (const img of collectChatImages(root)) {
|
||
const centerX = (img.left + img.right) / 2;
|
||
events.push({
|
||
url: img.url,
|
||
t: messageTimeOf(img.element),
|
||
top: img.top,
|
||
usertype: centerX > rootCenterX ? "sys" : "cus"
|
||
});
|
||
}
|
||
events.sort((a, b) => {
|
||
if (a.t > 0 && b.t > 0) return a.t - b.t || a.top - b.top;
|
||
if (a.t > 0) return -1;
|
||
if (b.t > 0) return 1;
|
||
return a.top - b.top;
|
||
});
|
||
return events;
|
||
}
|
||
|
||
// ---------- 归属引擎(多方案融合) ----------
|
||
// time :只按时间区间归属(先图后单靠历史缓冲,先单后图靠区间)
|
||
// sequence :全部订单视为一组,图片按批次顺序一一对应
|
||
// sequence-reverse :同 sequence,但图片批次从最新的订单开始倒着分配
|
||
// hybrid :默认;下单时间相近的订单成组走顺序拆分,其余按时间归属
|
||
function clusterByGap(items, timeOf, gapMs) {
|
||
const clusters = [];
|
||
for (const item of items) {
|
||
const last = clusters[clusters.length - 1];
|
||
if (last && timeOf(item) - timeOf(last[last.length - 1]) <= gapMs) last.push(item);
|
||
else clusters.push([item]);
|
||
}
|
||
return clusters;
|
||
}
|
||
|
||
function assignImagesToOrders(images, orders, opts) {
|
||
if (!orders.length) {
|
||
const urls = images.map((item) => item.url);
|
||
return urls.length
|
||
? { groups: [{ orderNo: "未归档订单", urls, reason: "no-order", confidence: "low", review: false }] }
|
||
: { groups: [] };
|
||
}
|
||
|
||
const bestOrderTime = orders[0].orderTime;
|
||
const history = images.filter((item) => item.t > 0 && item.t < bestOrderTime - opts.historyLeadMs);
|
||
const usable = images.filter((item) => item.t > 0 && item.t >= bestOrderTime - opts.historyLeadMs);
|
||
const untimed = images.filter((item) => !(item.t > 0));
|
||
|
||
// time 模式不合并订单(每单独立区间);顺序/倒序拆分把全部订单视为一组
|
||
const reverse = opts.mode === "sequence-reverse";
|
||
const effectiveConcurrent = opts.mode === "time"
|
||
? 0
|
||
: (opts.mode === "sequence" || reverse ? Number.MAX_SAFE_INTEGER : opts.concurrentMs);
|
||
const orderClusters = clusterByGap(orders, (order) => order.orderTime, effectiveConcurrent);
|
||
|
||
const buckets = new Map();
|
||
const addUrls = (order, urls, reason, confidence) => {
|
||
if (!urls.length) return;
|
||
const bucket = buckets.get(order.orderSn) || { urls: [], reason, confidence };
|
||
for (const url of urls) if (!bucket.urls.includes(url)) bucket.urls.push(url);
|
||
buckets.set(order.orderSn, bucket);
|
||
};
|
||
|
||
const clusterStart = (index) => orderClusters[index][0].orderTime;
|
||
const clusterEnd = (index) =>
|
||
index + 1 < orderClusters.length ? clusterStart(index + 1) : Number.POSITIVE_INFINITY;
|
||
const windowStart = (index) => (index === 0 ? clusterStart(0) - opts.historyLeadMs : clusterStart(index));
|
||
|
||
const reviewUrls = [];
|
||
for (let i = 0; i < orderClusters.length; i++) {
|
||
const cluster = orderClusters[i];
|
||
const start = windowStart(i);
|
||
const end = clusterEnd(i);
|
||
const inWindow = usable.filter((item) => item.t >= start && item.t < end);
|
||
if (!inWindow.length) continue;
|
||
|
||
if (cluster.length === 1) {
|
||
addUrls(cluster[0], inWindow.map((item) => item.url), "time", "high");
|
||
continue;
|
||
}
|
||
|
||
// 组内拆分:图片按发送间隔切成批次;顺序方案第 j 批交给第 j 张单,
|
||
// 倒序方案反过来,第 j 批交给倒数第 j 张单(最新下的单先分配)
|
||
const batches = clusterByGap(inWindow, (item) => item.t, opts.batchGapMs);
|
||
const reason = reverse ? "sequence-reverse" : "sequence";
|
||
for (let j = 0; j < batches.length; j++) {
|
||
const urls = batches[j].map((item) => item.url);
|
||
if (j >= cluster.length) {
|
||
reviewUrls.push(...urls);
|
||
continue;
|
||
}
|
||
const orderIndex = reverse ? cluster.length - 1 - j : j;
|
||
const order = cluster[orderIndex];
|
||
const restIndex = reverse ? orderIndex - 1 : orderIndex + 1;
|
||
// 规格里能读到张数时按张数截断,超出的部分顺延给组内下一张单
|
||
if (opts.countCheck && order.expected > 0 && urls.length > order.expected) {
|
||
addUrls(order, urls.slice(0, order.expected), reason, "medium");
|
||
const rest = urls.slice(order.expected);
|
||
if (restIndex >= 0 && restIndex < cluster.length) addUrls(cluster[restIndex], rest, reason, "medium");
|
||
else reviewUrls.push(...rest);
|
||
} else {
|
||
addUrls(order, urls, reason, "medium");
|
||
}
|
||
}
|
||
}
|
||
|
||
const groups = [];
|
||
for (const order of orders) {
|
||
const bucket = buckets.get(order.orderSn);
|
||
if (!bucket || !bucket.urls.length) continue;
|
||
const expected = opts.countCheck ? order.expected : 0;
|
||
groups.push({
|
||
orderNo: order.orderSn,
|
||
urls: bucket.urls,
|
||
reason: bucket.reason,
|
||
confidence: bucket.confidence,
|
||
expected,
|
||
shortage: expected > 0 && bucket.urls.length < expected,
|
||
overflow: expected > 0 && bucket.urls.length > expected,
|
||
review: false
|
||
});
|
||
}
|
||
|
||
if (history.length) {
|
||
groups.push({
|
||
orderNo: "历史未归属",
|
||
urls: history.map((item) => item.url),
|
||
reason: "history",
|
||
confidence: "low",
|
||
review: false
|
||
});
|
||
}
|
||
|
||
const leftovers = [...reviewUrls, ...untimed.map((item) => item.url)];
|
||
if (leftovers.length) {
|
||
groups.push({
|
||
orderNo: opts.reviewEnabled ? "待确认" : "未归档订单",
|
||
urls: leftovers,
|
||
reason: "review",
|
||
confidence: "low",
|
||
review: opts.reviewEnabled
|
||
});
|
||
}
|
||
return { groups };
|
||
}
|
||
|
||
async function archiveChatImages(prefetchedOrders, messageItems) {
|
||
if (!state.runtime.imageSaveEnabled) return;
|
||
const root = document.querySelector(selectors.messageList);
|
||
if (!root) return;
|
||
const images = collectImageEvents(root);
|
||
|
||
const orders = Array.isArray(prefetchedOrders)
|
||
? prefetchedOrders
|
||
: await readOrdersCached();
|
||
|
||
// 买家说「第2张替换掉 / 第3张删掉」时调整已保存的图片;删除不需要新图
|
||
const adjust = await resolveImageAdjustment(messageItems);
|
||
// 「把这个换成这个 / 换」没有序号:先用图片指纹定位买家重发的旧图
|
||
if (adjust && adjust.reference) {
|
||
const outcome = await applyReferenceAdjustment(adjust, images, orders);
|
||
if (outcome !== "skip") return outcome;
|
||
}
|
||
if (adjust && adjust.action === "delete" && !adjust.reference) {
|
||
const timedOrders = orders.filter((order) => order.orderTime > 0);
|
||
const target = timedOrders[timedOrders.length - 1] || orders[orders.length - 1];
|
||
if (!target) log("图片调整:未读取到订单,已跳过删除指令。");
|
||
else await applyImageAdjustment(adjust, target.orderSn, target.expected || 0, []);
|
||
}
|
||
|
||
if (!images.length) return;
|
||
// 时间匹配必须有下单时间,缺时间的订单只给模型用,不参与图片归属
|
||
const timedOrders = orders.filter((order) => order.orderTime > 0);
|
||
const groups = assignImagesToOrders(images, timedOrders, {
|
||
mode: state.runtime.imageAssignMode,
|
||
concurrentMs: state.runtime.imageConcurrentMs,
|
||
batchGapMs: state.runtime.imageBatchGapMs,
|
||
historyLeadMs: state.runtime.imageHistoryLeadMs,
|
||
countCheck: state.runtime.imageCountCheck,
|
||
reviewEnabled: state.runtime.imageReviewEnabled
|
||
}).groups;
|
||
if (!groups.length) return;
|
||
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
for (const group of groups) {
|
||
const fresh = group.urls.filter((url) => !state.archivedImageUrls.has(url));
|
||
if (!fresh.length) continue;
|
||
if (state.archivedImageUrls.size > 3000) {
|
||
state.archivedImageUrls = new Set();
|
||
}
|
||
// 先占位再发,避免同一批图在下一次轮询里重复上报;失败要释放,留到下次重试
|
||
fresh.forEach((url) => state.archivedImageUrls.add(url));
|
||
persistArchivedImageIndex();
|
||
const release = () => {
|
||
fresh.forEach((url) => state.archivedImageUrls.delete(url));
|
||
persistArchivedImageIndex();
|
||
};
|
||
try {
|
||
// 「未归档订单 / 历史未归属 / 待确认」里的图片不参与替换,避免改错订单
|
||
const realOrder = group.reason !== "review" && group.reason !== "history"
|
||
&& group.reason !== "no-order";
|
||
// 替换指令配合本次新图:本批刚好一张新图时,用它替换指定的第 N 张
|
||
if (adjust && !adjust.reference && adjust.action === "replace" && realOrder && fresh.length === 1) {
|
||
const ok = await applyImageAdjustment(adjust, group.orderNo, group.expected || 0, fresh);
|
||
if (!ok) release();
|
||
continue;
|
||
}
|
||
if (adjust && !adjust.reference && adjust.action === "replace" && realOrder) {
|
||
log(`图片调整:本批有 ${fresh.length} 张新图,无法确定替换哪一张,按普通归档处理。`);
|
||
}
|
||
const response = await fetch(`${base}/api/save-images`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
shopId: state.shopId || "default",
|
||
orderNo: group.orderNo,
|
||
review: group.review === true,
|
||
reason: group.reason,
|
||
expected: group.expected || 0,
|
||
images: fresh.map((url) => ({ url }))
|
||
})
|
||
});
|
||
const result = await response.json();
|
||
if (!response.ok || !result.ok) {
|
||
release();
|
||
log(`图片归档失败(${group.orderNo}):${result.error || response.status}`);
|
||
continue;
|
||
}
|
||
const countNote = group.expected > 0
|
||
? `(期望 ${group.expected} 张${group.shortage ? ",偏少" : ""}${group.overflow ? ",偏多" : ""})`
|
||
: "";
|
||
log(`图片归档:订单 ${group.orderNo} [${group.reason}] 保存 ${result.saved || 0} 张,跳过 ${result.skipped || 0} 张${countNote} → ${result.dir || ""}`);
|
||
// 数量与规格不符时排队一条回复,由回复流程统一发送,避免和主回复抢输入框
|
||
if (!group.review && state.runtime.imageReceiptReplyEnabled
|
||
&& Number(result.expected) > 0 && Number(result.diff) !== 0) {
|
||
queueReceiptNote({
|
||
key: state.currentConversationKey || "",
|
||
orderNo: group.orderNo,
|
||
expected: Number(result.expected),
|
||
total: Number(result.total),
|
||
gap: Math.abs(Number(result.diff)),
|
||
overflow: Number(result.diff) > 0
|
||
});
|
||
log(`订单 ${group.orderNo} 数量${Number(result.diff) > 0 ? "超出" : "不足"} ${Math.abs(Number(result.diff))} 张,已排队回复买家。`);
|
||
}
|
||
} catch (error) {
|
||
release();
|
||
log(`图片归档请求失败(${group.orderNo}):${error?.message || error}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 最近一条客服消息之后的最后一条买家文字(调整指令只认当前待回复的这一段)
|
||
function latestPendingBuyerText(messageItems) {
|
||
const items = Array.isArray(messageItems) ? messageItems : collectMessageItems();
|
||
let lastSys = -1;
|
||
items.forEach((item, index) => {
|
||
if (item && item.usertype === "sys") lastSys = index;
|
||
});
|
||
for (let index = items.length - 1; index > lastSys; index -= 1) {
|
||
const item = items[index];
|
||
if (item && item.usertype === "cus" && item.msg
|
||
&& item.msg !== "[图片]" && item.msg !== "[视频]") {
|
||
return { text: item.msg, t: Number(item.t) || 0 };
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function chineseNumberToInt(value) {
|
||
const text = String(value || "").trim();
|
||
if (!text) return 0;
|
||
if (/^\d+$/.test(text)) return Number(text);
|
||
const digits = { 零: 0, 〇: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };
|
||
let total = 0;
|
||
let current = 0;
|
||
for (const ch of text) {
|
||
if (ch === "十") {
|
||
total += (current || 1) * 10;
|
||
current = 0;
|
||
} else if (ch === "百") {
|
||
total += (current || 1) * 100;
|
||
current = 0;
|
||
} else if (digits[ch] !== undefined) {
|
||
current = digits[ch];
|
||
} else {
|
||
return 0;
|
||
}
|
||
}
|
||
return total + current;
|
||
}
|
||
|
||
// 指令识别词可在图片保存页配置(逗号分隔),这里按当前配置拆成数组
|
||
function adjustWords(key) {
|
||
const value = state.runtime[key];
|
||
return String(value || "")
|
||
.split(/[,,\s]+/)
|
||
.map((word) => word.trim())
|
||
.filter(Boolean);
|
||
}
|
||
|
||
function hasAdjustWord(text, words) {
|
||
return words.some((word) => text.includes(word));
|
||
}
|
||
|
||
function startsWithAdjustWord(text, words) {
|
||
return words.some((word) => text.startsWith(word));
|
||
}
|
||
|
||
// 只做规则解析,保证「第2张替换掉 / 把这个换成这个 / 这张不要了」这类指令的确定性,
|
||
// 避免模型误判后乱改文件。没有序号的指令(reference=true)交给图片指纹定位。
|
||
function parseImageAdjustInstruction(text) {
|
||
const raw = normalizeText(text || "");
|
||
if (!raw) return null;
|
||
|
||
const replaceWords = adjustWords("imageAdjustReplaceWords");
|
||
const deleteWords = adjustWords("imageAdjustDeleteWords");
|
||
const resendWords = adjustWords("imageAdjustResendWords");
|
||
const pointWords = adjustWords("imageAdjustPointWords");
|
||
const negativeWords = adjustWords("imageAdjustNegativeWords");
|
||
// 「不用换 / 别删 / 不需要重新发」这类否定句不处理(裸「换/删/改」也算动作词)
|
||
const actionWords = replaceWords.concat(deleteWords, resendWords, ["换", "删", "改"]);
|
||
if (negativeWords.some((neg) => actionWords.some((word) => raw.includes(neg + word)))) {
|
||
return null;
|
||
}
|
||
|
||
let index = 0;
|
||
const match = raw.match(/第\s*([0-9零〇一二两三四五六七八九十百]+)\s*(?:张|幅|个)/);
|
||
if (match) index = chineseNumberToInt(match[1]);
|
||
else if (/最后(?:一|1)?张/.test(raw)) index = -1;
|
||
|
||
if (index) {
|
||
// 「第5张不要了,我重新发」用随后发来的新图顶替第5张
|
||
if (hasAdjustWord(raw, resendWords)) return { action: "replace", index, reference: false };
|
||
if (hasAdjustWord(raw, replaceWords) || raw.includes("换")) {
|
||
return { action: "replace", index, reference: false };
|
||
}
|
||
if (hasAdjustWord(raw, deleteWords)) return { action: "delete", index, reference: false };
|
||
return null;
|
||
}
|
||
|
||
// 没有序号:只接受明确指向图片的说法,避免把普通聊天当成调整指令。
|
||
// 删除额外要求「这张/那张/图/照片」这类明确指向图片的说法,
|
||
// 防止「不需要了,谢谢」「删除这个订单」这种正常对话误删图片。
|
||
const shortReplace = raw.length <= 4 && raw.includes("换");
|
||
const pointsToImage = hasAdjustWord(raw, pointWords)
|
||
|| startsWithAdjustWord(raw, replaceWords)
|
||
|| shortReplace;
|
||
const pointsToDelete = /(这张|那张|这幅|那幅|图|照片)/.test(raw);
|
||
if (!pointsToImage && !(pointsToDelete && hasAdjustWord(raw, deleteWords))) return null;
|
||
if (hasAdjustWord(raw, replaceWords) || shortReplace || hasAdjustWord(raw, resendWords)) {
|
||
return { action: "replace", index: 0, reference: true };
|
||
}
|
||
if (pointsToDelete && hasAdjustWord(raw, deleteWords)) {
|
||
return { action: "delete", index: 0, reference: true };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// 固定词优先;hybrid/ai 模式下固定词没命中时再问模型。
|
||
// 模型只给意图,真正的目标仍由序号/图片指纹确认,绝不直接改文件。
|
||
async function resolveImageAdjustment(messageItems) {
|
||
if (state.runtime.imageAdjustEnabled === false) return null;
|
||
const latest = latestPendingBuyerText(messageItems);
|
||
if (!latest) return null;
|
||
const key = `${state.currentConversationKey || ""}|${latest.t}|${latest.text}`;
|
||
if (state.adjustHandled.has(key)) return null;
|
||
|
||
const rules = parseImageAdjustInstruction(latest.text);
|
||
if (rules) return { ...rules, key, text: latest.text };
|
||
const mode = state.runtime.imageAdjustMode;
|
||
if (mode !== "hybrid" && mode !== "ai") return null;
|
||
// 混合模式先粗筛,避免每句闲聊都调一次模型
|
||
if (mode === "hybrid" && !looksLikeImageAdjust(latest.text)) return null;
|
||
|
||
let prediction = state.aiAdjustCache.get(key);
|
||
if (!prediction) {
|
||
prediction = await requestImageAdjustIntent(latest.text);
|
||
if (prediction) {
|
||
if (state.aiAdjustCache.size > 200) state.aiAdjustCache.clear();
|
||
state.aiAdjustCache.set(key, prediction);
|
||
}
|
||
}
|
||
const adjust = buildAiAdjustment(prediction);
|
||
if (!adjust) return null;
|
||
log(`图片指令识别(模型):${latest.text} → ${adjust.action}${adjust.reference ? "(按图定位)" : ` 第 ${adjust.index} 张`}`);
|
||
return { ...adjust, key, text: latest.text, source: "ai" };
|
||
}
|
||
|
||
function looksLikeImageAdjust(text) {
|
||
return /(图|照片|相片|张|换|替换|删|去掉|不要|不用|重发|重新发|改成|改一下)/.test(text || "");
|
||
}
|
||
|
||
async function requestImageAdjustIntent(text) {
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
const items = collectMessageItems();
|
||
const recent = items
|
||
.filter((item) => item && item.usertype === "cus" && item.text)
|
||
.slice(-5)
|
||
.map((item) => String(item.text).slice(0, 200));
|
||
let buyerImageCount = 0;
|
||
const root = document.querySelector(selectors.messageList);
|
||
if (root) buyerImageCount = collectImageEvents(root).filter((item) => item.usertype === "cus").length;
|
||
try {
|
||
const response = await fetch(`${base}/api/parse-adjust`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
shopId: state.shopId || "default",
|
||
text,
|
||
recent,
|
||
buyerImageCount
|
||
})
|
||
});
|
||
const result = await response.json();
|
||
if (!response.ok || !result.ok) {
|
||
log(`图片指令识别失败:${result.error || response.status}`);
|
||
return null;
|
||
}
|
||
return result;
|
||
} catch (error) {
|
||
log(`图片指令识别请求失败:${error?.message || error}`);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 模型结果必须给出明确目标且置信度达标,否则宁可不改
|
||
function buildAiAdjustment(prediction) {
|
||
if (!prediction) return null;
|
||
const intent = String(prediction.intent || "none");
|
||
if (intent !== "replace" && intent !== "delete") return null;
|
||
const threshold = Number(state.runtime.imageAdjustAiConfidence);
|
||
const confidence = Number(prediction.confidence);
|
||
if (!Number.isFinite(confidence)
|
||
|| confidence < (Number.isFinite(threshold) ? threshold : 0.75)) {
|
||
log(`图片指令识别:置信度 ${Number.isFinite(confidence) ? confidence : 0} 低于阈值,已忽略。`);
|
||
return null;
|
||
}
|
||
const rawIndex = Number(prediction.index);
|
||
const target = String(prediction.target || "");
|
||
if (target === "resent_photo") return { action: intent, index: 0, reference: true };
|
||
if (Number.isFinite(rawIndex) && rawIndex !== 0) {
|
||
return { action: intent, index: Math.trunc(rawIndex), reference: false };
|
||
}
|
||
log("图片指令识别:模型未给出明确目标,本次不调整。");
|
||
return null;
|
||
}
|
||
|
||
async function applyImageAdjustment(adjust, orderNo, expected, urls, dropIndexes) {
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
try {
|
||
const response = await fetch(`${base}/api/adjust-images`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
shopId: state.shopId || "default",
|
||
orderNo,
|
||
action: adjust.action,
|
||
index: adjust.index,
|
||
expected: Number(expected) || 0,
|
||
images: (urls || []).map((url) => ({ url })),
|
||
dropIndexes: Array.isArray(dropIndexes) ? dropIndexes : []
|
||
})
|
||
});
|
||
const result = await response.json();
|
||
if (!response.ok || !result.ok) {
|
||
log(`图片调整失败(${orderNo}):${result.error || response.status}`);
|
||
return false;
|
||
}
|
||
state.adjustHandled.add(adjust.key);
|
||
state.lastAdjustReply = { key: state.currentConversationKey || "", at: Date.now() };
|
||
const verb = adjust.action === "delete" ? "删除" : "替换";
|
||
log(`图片调整:订单 ${orderNo} 第 ${result.index} 张已${verb},当前共 ${result.total} 张${result.note ? "(文件夹已标注)" : ""}。`);
|
||
if (state.runtime.imageAdjustReplyEnabled !== false) {
|
||
const text = buildAdjustText(adjust, result);
|
||
if (text) {
|
||
queueReceiptNote({ key: state.currentConversationKey || "", orderNo, text, kind: "adjust" });
|
||
log(`订单 ${orderNo} 的图片调整确认已排队回复买家。`);
|
||
}
|
||
}
|
||
return true;
|
||
} catch (error) {
|
||
log(`图片调整请求失败(${orderNo}):${error?.message || error}`);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// 按图片内容定位:把买家重发的旧图与订单目录里已保存的图片做指纹比对
|
||
async function locateReferenceImage(url, orderNos) {
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
const threshold = Number(state.runtime.imageAdjustMatchThreshold);
|
||
try {
|
||
const response = await fetch(`${base}/api/locate-image`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
shopId: state.shopId || "default",
|
||
url,
|
||
orderNos,
|
||
maxDistance: Number.isFinite(threshold) ? threshold : 8
|
||
})
|
||
});
|
||
const result = await response.json();
|
||
if (!response.ok || !result.ok) {
|
||
log(`图片定位失败:${result.error || response.status}`);
|
||
return null;
|
||
}
|
||
return result;
|
||
} catch (error) {
|
||
log(`图片定位请求失败:${error?.message || error}`);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 「把这个换成这个」:指令前重发的旧图当参考图定位目标,指令后发的新图当替换图。
|
||
// 返回 skip(按普通归档继续处理)/ wait(还没收到新图)/ handled(已完成调整)
|
||
async function applyReferenceAdjustment(adjust, images, orders) {
|
||
const candidates = (Array.isArray(orders) ? orders : [])
|
||
.filter((order) => order && order.orderSn)
|
||
.slice()
|
||
.sort((a, b) => (Number(b.orderTime) || 0) - (Number(a.orderTime) || 0))
|
||
.map((order) => String(order.orderSn));
|
||
if (!candidates.length) {
|
||
log("图片调整:未读取到订单,无法按图定位,已跳过。");
|
||
return "skip";
|
||
}
|
||
if (!(adjust.t > 0)) {
|
||
log("图片调整:指令消息没有时间戳,无法区分参考图和新图,按普通归档处理。");
|
||
return "skip";
|
||
}
|
||
|
||
const buyerImages = images
|
||
.filter((item) => item && item.usertype === "cus" && item.t > 0)
|
||
.sort((a, b) => a.t - b.t || a.top - b.top);
|
||
const refs = buyerImages.filter((item) => item.t <= adjust.t).slice(-3).reverse();
|
||
const news = buyerImages.filter((item) => item.t > adjust.t);
|
||
if (!refs.length) {
|
||
log("图片调整:没有找到指令前发送的参考图,按普通归档处理。");
|
||
return "skip";
|
||
}
|
||
if (adjust.action === "replace" && !news.length) {
|
||
log("图片调整:已收到「换成新图」的指令,正在等待买家发送新图。");
|
||
return "wait";
|
||
}
|
||
|
||
let located = null;
|
||
let reference = null;
|
||
let probed = false;
|
||
for (const item of refs) {
|
||
const result = await locateReferenceImage(item.url, candidates);
|
||
if (!result) continue;
|
||
probed = true;
|
||
if (Array.isArray(result.matches) && result.matches.length) {
|
||
located = result;
|
||
reference = item;
|
||
break;
|
||
}
|
||
}
|
||
if (!located) {
|
||
// 「这张不要了」:如果指向的是刚发来还没归档的新图,直接不保存即可
|
||
const latest = refs[0];
|
||
if (adjust.action === "delete" && latest && !state.archivedImageUrls.has(latest.url)) {
|
||
state.archivedImageUrls.add(latest.url);
|
||
persistArchivedImageIndex();
|
||
state.adjustHandled.add(adjust.key);
|
||
log("图片调整:买家表示这张不要了,已跳过保存这张新图。");
|
||
return "skip";
|
||
}
|
||
// 服务端正常返回但没有命中时不再反复探测,避免每轮都重新下载比对
|
||
if (probed) state.adjustHandled.add(adjust.key);
|
||
log("图片调整:已保存的图片里没有找到买家重发的这张旧图,按普通归档处理。");
|
||
return "skip";
|
||
}
|
||
|
||
const match = located.matches[0];
|
||
const dropIndexes = [];
|
||
if (located.duplicate && located.duplicate.orderNo === match.orderNo
|
||
&& Number(located.duplicate.index) !== Number(match.index)
|
||
&& state.archivedImageUrls.has(reference.url)) {
|
||
dropIndexes.push(Number(located.duplicate.index));
|
||
}
|
||
// 参考图只用于指认目标,不再重复归档;替换图由调整接口直接写入
|
||
const touched = adjust.action === "replace" ? [reference.url, news[0].url] : [reference.url];
|
||
touched.forEach((url) => state.archivedImageUrls.add(url));
|
||
persistArchivedImageIndex();
|
||
|
||
const targetOrder = (Array.isArray(orders) ? orders : [])
|
||
.find((order) => order && String(order.orderSn) === match.orderNo);
|
||
const urls = adjust.action === "replace" ? [news[0].url] : [];
|
||
log(`图片调整:参考图定位到订单 ${match.orderNo} 第 ${match.index} 张(差异 ${match.distance})。`);
|
||
const ok = await applyImageAdjustment(
|
||
{ ...adjust, index: Number(match.index) },
|
||
match.orderNo,
|
||
targetOrder ? Number(targetOrder.expected) || 0 : 0,
|
||
urls,
|
||
dropIndexes
|
||
);
|
||
if (!ok) {
|
||
touched.forEach((url) => state.archivedImageUrls.delete(url));
|
||
persistArchivedImageIndex();
|
||
return "skip";
|
||
}
|
||
return "handled";
|
||
}
|
||
|
||
function isInsideSpecificProductCard(element) {
|
||
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;
|
||
// 视频消息自带的提示文字(视频/点击播放/时长)不是买家说的话
|
||
if (/^(视频|视频消息|视频通话|查看视频|点击播放(视频)?|播放视频|正在播放|加载中)$/.test(text)) return false;
|
||
if (text.length <= 12 && /点击播放|播放视频|视频加载中/.test(text)) return false;
|
||
if (text.length <= 12 && /^\d{1,2}:\d{2}(:\d{2})?\s*(视频)?$/.test(text)) return false;
|
||
if (/当前用户来自/.test(text)) return false;
|
||
if (/邀请关注|邀请下单|小额打款|小额收款|邀请开票/.test(text)) return false;
|
||
if (/订单编号|下单时间|实收|复制|备注|催支付/.test(text)) return false;
|
||
return /[\u4e00-\u9fa5A-Za-z0-9]/.test(text);
|
||
}
|
||
|
||
function looksLikeProductCard(element, text) {
|
||
if (/¥\s*\d+/.test(text)) return true;
|
||
if (/商品详情页|购买力|下单数/.test(text)) return true;
|
||
const imgCount = element.querySelectorAll ? element.querySelectorAll("img").length : 0;
|
||
return imgCount > 0 && text.length > 12;
|
||
}
|
||
|
||
function hasChildWithSameText(element, text) {
|
||
return Array.from(element.children || []).some((child) => normalizeText(child.innerText || child.textContent || "") === text);
|
||
}
|
||
|
||
async function requestReply(payload, signal) {
|
||
const response = await fetch(`${state.serverBase}/api/reply`, {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
...getShopAuthHeaders()
|
||
},
|
||
signal,
|
||
body: JSON.stringify({
|
||
...payload,
|
||
shopId: state.shopId || "default",
|
||
shopName: state.shopName || state.shopId || "默认店铺"
|
||
})
|
||
});
|
||
if (!response.ok) {
|
||
const detail = await safeReadText(response);
|
||
throw new Error(`本地服务返回 ${response.status}${detail ? `:${detail}` : ""}`);
|
||
}
|
||
return response.json();
|
||
}
|
||
|
||
function getShopAuthHeaders() {
|
||
const headers = {
|
||
"X-Shop-Id": state.shopId || "default"
|
||
};
|
||
if (state.shopToken) headers["X-Shop-Token"] = state.shopToken;
|
||
return headers;
|
||
}
|
||
|
||
async function safeReadText(response) {
|
||
try {
|
||
return (await response.text()).slice(0, 200);
|
||
} catch (_) {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
async function fillReply(reply) {
|
||
const textarea = await waitForElement(selectors.replyTextarea, 5000);
|
||
// 输入框里有人工写的内容、又不是本软件上次回填的,就不要覆盖
|
||
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, "");
|
||
|
||
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;
|
||
}
|
||
}
|
||
|
||
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) {
|
||
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
|
||
if (setter) {
|
||
setter.call(textarea, value);
|
||
} else {
|
||
textarea.value = value;
|
||
}
|
||
}
|
||
|
||
function dispatchTextInputEvents(textarea, value) {
|
||
textarea.focus();
|
||
textarea.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "" }));
|
||
textarea.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: value }));
|
||
if (typeof InputEvent === "function") {
|
||
textarea.dispatchEvent(new InputEvent("beforeinput", {
|
||
bubbles: true,
|
||
cancelable: true,
|
||
inputType: value ? "insertText" : "deleteContentBackward",
|
||
data: value
|
||
}));
|
||
textarea.dispatchEvent(new InputEvent("input", {
|
||
bubbles: true,
|
||
inputType: value ? "insertText" : "deleteContentBackward",
|
||
data: value
|
||
}));
|
||
} else {
|
||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||
}
|
||
textarea.dispatchEvent(new Event("change", { bubbles: true }));
|
||
textarea.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true, key: value ? "Process" : "Backspace" }));
|
||
}
|
||
|
||
async function sendReplyAndVerify(reply) {
|
||
const textarea = await waitForElement(selectors.replyTextarea, 5000);
|
||
const beforeChatSignature = getChatSignature();
|
||
const beforeMessageCount = getMessageNodeCount();
|
||
const beforeValue = normalizeText(textarea.value || "");
|
||
|
||
if (!beforeValue) {
|
||
log("发送前输入框为空,已取消自动发送。");
|
||
return false;
|
||
}
|
||
|
||
// 输入框内容必须就是本次要发的回复;不一致说明写入失败、里面还是上一次的内容
|
||
if (!composerHasReply(textarea, reply)) {
|
||
log("输入框内容与本次回复不一致,已取消自动发送,避免重复发送上一条回复。");
|
||
return false;
|
||
}
|
||
|
||
await clickSendButton();
|
||
const buttonSent = await waitForSendSuccess({
|
||
reply,
|
||
textarea,
|
||
beforeChatSignature,
|
||
beforeMessageCount,
|
||
timeout: 2800
|
||
});
|
||
if (buttonSent) return true;
|
||
|
||
// 输入框已被清空通常说明按钮点击其实已经发出去了,只是校验没及时命中;
|
||
// 这时再按一次回车,就会把同一条消息重复发出去
|
||
if (!normalizeText(textarea.value || "")) {
|
||
log("输入框已清空,判定已经发送成功,不再回车重发。");
|
||
return true;
|
||
}
|
||
|
||
log("按钮发送未确认成功,尝试使用回车发送。");
|
||
await pressEnterToSend(textarea);
|
||
return waitForSendSuccess({
|
||
reply,
|
||
textarea,
|
||
beforeChatSignature,
|
||
beforeMessageCount,
|
||
timeout: 4200
|
||
});
|
||
}
|
||
|
||
async function clickSendButton(target) {
|
||
const button = target || await waitForElement(selectors.sendButton, 5000);
|
||
if (!target && isDisabledSendButton(button)) {
|
||
log("发送按钮看起来处于不可用状态,仍会尝试真实点击和回车兜底。");
|
||
}
|
||
button.scrollIntoView({ block: "center", inline: "center" });
|
||
await sleep(80);
|
||
const trusted = await requestTrustedClick(button);
|
||
if (!trusted) {
|
||
// 非扩展环境(例如通过 CDP 注入)没有 chrome.runtime,本就无法走真实点击
|
||
const hasRuntime = Boolean(globalThis.chrome && globalThis.chrome.runtime &&
|
||
typeof globalThis.chrome.runtime.sendMessage === "function");
|
||
log(hasRuntime ? "真实点击不可用,改用页面脚本点击。" : "当前为非扩展注入环境,直接使用页面脚本点击。");
|
||
dispatchClickSequence(button);
|
||
const pointTarget = elementFromCenter(button);
|
||
if (pointTarget && pointTarget !== button) dispatchClickSequence(pointTarget);
|
||
}
|
||
await sleep(500);
|
||
return true;
|
||
}
|
||
|
||
async function pressEnterToSend(textarea) {
|
||
textarea.focus();
|
||
await sleep(80);
|
||
const trusted = await requestTrustedEnter();
|
||
if (!trusted) {
|
||
textarea.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 }));
|
||
textarea.dispatchEvent(new KeyboardEvent("keypress", { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 }));
|
||
textarea.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 }));
|
||
}
|
||
await sleep(500);
|
||
}
|
||
|
||
async function waitForSendSuccess({ reply, textarea, beforeChatSignature, beforeMessageCount, timeout = 5000 }) {
|
||
const started = Date.now();
|
||
const expected = normalizeForMatch(reply).slice(0, 80);
|
||
|
||
while (Date.now() - started < timeout) {
|
||
await sleep(160);
|
||
|
||
const currentValue = normalizeText(textarea.value || "");
|
||
const currentSignature = getChatSignature();
|
||
const currentMessageCount = getMessageNodeCount();
|
||
const chatText = normalizeForMatch(getChatText());
|
||
|
||
const inputCleared = !currentValue;
|
||
const chatChanged = currentSignature !== beforeChatSignature;
|
||
const messageAdded = currentMessageCount > beforeMessageCount;
|
||
const replyAppeared = expected && chatText.includes(expected);
|
||
|
||
if (inputCleared && (chatChanged || messageAdded || replyAppeared)) {
|
||
return true;
|
||
}
|
||
if (replyAppeared && (chatChanged || messageAdded)) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
log("自动发送校验失败:输入框未清空或聊天区未出现新发送消息。");
|
||
return false;
|
||
}
|
||
|
||
// ---------- 配图发送 ----------
|
||
|
||
// 聊天区的图片数量用于校验图片消息是否真的发出(图片消息没有文字可比对)
|
||
function getChatImageCount() {
|
||
const root = document.querySelector(selectors.messageList);
|
||
if (!root) return 0;
|
||
let count = 0;
|
||
root.querySelectorAll("img").forEach((img) => {
|
||
if (img.currentSrc || img.src) count += 1;
|
||
});
|
||
return count;
|
||
}
|
||
|
||
function findChatFileInput() {
|
||
const inputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
||
const imageInputs = inputs.filter((input) => /image/i.test(input.accept || "") || !input.accept);
|
||
if (!imageInputs.length) return null;
|
||
|
||
// 优先使用聊天编辑区同一容器里的上传控件,避免误触页面其它上传入口
|
||
const textarea = document.querySelector(selectors.replyTextarea);
|
||
if (textarea) {
|
||
const root = textarea.closest("form") || textarea.closest('[class*="editor"]') ||
|
||
textarea.parentElement?.parentElement?.parentElement;
|
||
if (root) {
|
||
const scoped = imageInputs.find((input) => root.contains(input));
|
||
if (scoped) return scoped;
|
||
}
|
||
}
|
||
return imageInputs[0];
|
||
}
|
||
|
||
async function uploadImageToEditor(image) {
|
||
const fileInput = findChatFileInput();
|
||
if (!fileInput) return false;
|
||
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
const url = `${base}/api/image?shopId=${encodeURIComponent(state.shopId || "default")}&file=${encodeURIComponent(image.file || image.name)}`;
|
||
const response = await fetch(url);
|
||
if (!response.ok) throw new Error(`读取配图失败:${response.status}`);
|
||
const blob = await response.blob();
|
||
|
||
const ext = (blob.type.split("/")[1] || "png").replace("jpeg", "jpg");
|
||
const fileName = `${image.name || image.file || "image"}.${ext}`.replace(/[\\/:*?"<>|]/g, "_");
|
||
const dataTransfer = new DataTransfer();
|
||
dataTransfer.items.add(new File([blob], fileName, { type: blob.type || "image/png" }));
|
||
fileInput.files = dataTransfer.files;
|
||
fileInput.dispatchEvent(new Event("change", { bubbles: true }));
|
||
return true;
|
||
}
|
||
|
||
// 页面在收到图片后会弹出「是否发送图片」确认框,发送按钮是 .btn-ok
|
||
function findImageConfirmButton() {
|
||
const boxes = Array.from(document.querySelectorAll(".modal-box"));
|
||
for (const box of boxes) {
|
||
if (!normalizeText(box.innerText || "").includes("是否发送图片")) continue;
|
||
const button = box.querySelector(".btn-ok");
|
||
if (button) return button;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function waitForImageConfirmButton(timeout) {
|
||
const started = Date.now();
|
||
while (Date.now() - started < timeout) {
|
||
const button = findImageConfirmButton();
|
||
if (button) return button;
|
||
await sleep(160);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function waitForChatImageSent(beforeImages, beforeMessages, timeout) {
|
||
const started = Date.now();
|
||
while (Date.now() - started < timeout) {
|
||
await sleep(160);
|
||
if (getChatImageCount() > beforeImages) return true;
|
||
if (getMessageNodeCount() > beforeMessages) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// 同一会话同一订单只保留一条待回复说明,避免多轮归档排入重复文案
|
||
function queueReceiptNote(note) {
|
||
const key = note.key || "";
|
||
state.receiptNotes = state.receiptNotes.filter(
|
||
(item) => !(item.key === key && item.orderNo === note.orderNo)
|
||
);
|
||
state.receiptNotes.push(note);
|
||
}
|
||
|
||
// 图片数量与规格不符时,按配置文案回复买家差值(放在主回复之后发送,避免抢占输入框)
|
||
function buildReceiptText(note) {
|
||
if (note && note.text) return String(note.text);
|
||
const template = note.overflow ? state.runtime.receiptOverflowReply : state.runtime.receiptShortageReply;
|
||
if (!template) return "";
|
||
return template
|
||
.split("{total}").join(String(note.total))
|
||
.split("{expected}").join(String(note.expected))
|
||
.split("{gap}").join(String(note.gap));
|
||
}
|
||
|
||
function buildAdjustText(adjust, result) {
|
||
const template = adjust.action === "delete"
|
||
? state.runtime.adjustDeleteReply
|
||
: state.runtime.adjustReplaceReply;
|
||
if (!template) return "";
|
||
const total = Number(result.total) || 0;
|
||
const expected = Number(result.expected) || 0;
|
||
return template
|
||
.split("{index}").join(String(Number(result.index) || adjust.index))
|
||
.split("{total}").join(String(total))
|
||
.split("{expected}").join(String(expected))
|
||
.split("{gap}").join(String(expected > 0 ? Math.abs(total - expected) : 0));
|
||
}
|
||
|
||
async function sendReceiptNotes(runId) {
|
||
const key = state.currentConversationKey || "";
|
||
// 只发当前会话的待回复说明,别的会话留到下次打开再发,避免发错人
|
||
const notes = state.receiptNotes.filter((note) => note.key === key);
|
||
if (!notes.length) return;
|
||
state.receiptNotes = state.receiptNotes.filter((note) => note.key !== key);
|
||
for (const note of notes) {
|
||
const text = buildReceiptText(note);
|
||
if (!text) continue;
|
||
await fillReply(text);
|
||
ensureTaskActive(runId);
|
||
if (!(await sendReplyAndVerify(text))) {
|
||
log(`订单 ${note.orderNo} 的图片说明回复未确认成功,已跳过。`);
|
||
continue;
|
||
}
|
||
rememberOwnText(text, state.currentConversationIdentity);
|
||
log(`已回复买家订单 ${note.orderNo} 的图片相关说明。`);
|
||
await sleep(pageDelayMs() + 200);
|
||
ensureTaskActive(runId);
|
||
}
|
||
}
|
||
|
||
async function sendImageMessages(images) {
|
||
for (let index = 0; index < images.length; index += 1) {
|
||
const image = images[index];
|
||
const label = image.name || image.file;
|
||
const beforeImages = getChatImageCount();
|
||
const beforeMessages = getMessageNodeCount();
|
||
|
||
let uploaded = false;
|
||
try {
|
||
uploaded = await uploadImageToEditor(image);
|
||
} catch (error) {
|
||
log(`配图读取失败:${error.message}`);
|
||
return false;
|
||
}
|
||
if (!uploaded) {
|
||
log("未找到聊天区的图片上传控件,无法自动发送配图。");
|
||
return false;
|
||
}
|
||
log(`已提交配图 ${label},等待上传。`);
|
||
|
||
const confirmButton = await waitForImageConfirmButton(6000);
|
||
if (confirmButton) {
|
||
log("图片上传完成,点击确认框的「发送」。");
|
||
await clickSendButton(confirmButton);
|
||
} else {
|
||
log("未出现图片发送确认框,尝试点击普通发送按钮。");
|
||
await clickSendButton();
|
||
}
|
||
let sent = await waitForChatImageSent(beforeImages, beforeMessages, 4000);
|
||
if (!sent && !confirmButton) {
|
||
const textarea = await waitForElement(selectors.replyTextarea, 5000);
|
||
await pressEnterToSend(textarea);
|
||
sent = await waitForChatImageSent(beforeImages, beforeMessages, 3500);
|
||
}
|
||
if (!sent) {
|
||
log(`配图 ${label} 发送未确认成功。`);
|
||
return false;
|
||
}
|
||
log(`配图 ${label} 已发送。`);
|
||
await sleep(300);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
async function clearReplyInput() {
|
||
const textarea = await waitForElement(selectors.replyTextarea, 5000);
|
||
if (!normalizeText(textarea.value || "")) return;
|
||
setTextareaValue(textarea, "");
|
||
dispatchTextInputEvents(textarea, "");
|
||
await sleep(120);
|
||
}
|
||
|
||
function elementFromCenter(element) {
|
||
const rect = element.getBoundingClientRect();
|
||
return document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
|
||
}
|
||
|
||
async function requestTrustedTextInput(text) {
|
||
return requestTrustedAction({
|
||
action: "trusted-insert-text",
|
||
text
|
||
});
|
||
}
|
||
|
||
async function requestTrustedClick(element) {
|
||
const rect = element.getBoundingClientRect();
|
||
const x = rect.left + rect.width / 2;
|
||
const y = rect.top + rect.height / 2;
|
||
if (rect.width < 1 || rect.height < 1) return false;
|
||
// 视口外的坐标落到页面上也是空的,直接放弃让调用方走合成事件
|
||
if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) return false;
|
||
return requestTrustedAction({
|
||
action: "trusted-click",
|
||
x,
|
||
y,
|
||
// 宿主用 SendInput 打物理点击,只认比例:像素坐标会被 DPI 和窗口边框带偏
|
||
ratioX: x / window.innerWidth,
|
||
ratioY: y / window.innerHeight,
|
||
// 宿主用 客户区宽/视口宽 现场标定 CSS 到客户区的换算比例,
|
||
// 这样无论宿主进程声明哪种 DPI 感知,坐标都对得上
|
||
innerWidth: window.innerWidth,
|
||
innerHeight: window.innerHeight,
|
||
// 客户区里除视口外还有标签栏和地址栏,宿主按这个高度把视口抠出来
|
||
uiHeight: Math.max(0, window.outerHeight - window.innerHeight),
|
||
devicePixelRatio: window.devicePixelRatio || 1
|
||
});
|
||
}
|
||
|
||
async function requestTrustedEnter() {
|
||
return requestTrustedAction({ action: "trusted-enter" });
|
||
}
|
||
|
||
async function requestTrustedAction(payload) {
|
||
// 宿主 SendInput 优先:没有 CDP 会话、没有“正在调试此浏览器”横幅,最干净
|
||
if (await requestTrustedViaBridge(payload)) return true;
|
||
// 客户端没开或浏览器不在前台时,退回扩展的 debugger 通道
|
||
return requestTrustedViaExtension(payload);
|
||
}
|
||
|
||
function requestTrustedViaExtension(payload) {
|
||
return new Promise((resolve) => {
|
||
let runtime = null;
|
||
try {
|
||
runtime = globalThis.chrome?.runtime || null;
|
||
} catch (error) {
|
||
reportTrustedActionUnavailable(error);
|
||
resolve(false);
|
||
return;
|
||
}
|
||
|
||
if (!runtime || typeof runtime.sendMessage !== "function") {
|
||
resolve(false);
|
||
return;
|
||
}
|
||
|
||
let done = false;
|
||
let timer = 0;
|
||
const finish = (value) => {
|
||
if (done) return;
|
||
done = true;
|
||
window.clearTimeout(timer);
|
||
resolve(value);
|
||
};
|
||
|
||
timer = window.setTimeout(() => {
|
||
finish(false);
|
||
}, 2500);
|
||
|
||
try {
|
||
runtime.sendMessage({ source: "pdd-reply-assistant", ...payload }, (response) => {
|
||
let error = null;
|
||
try {
|
||
error = runtime.lastError || null;
|
||
} catch (lastError) {
|
||
error = lastError;
|
||
}
|
||
|
||
if (done) return;
|
||
if (error || !response?.ok) {
|
||
reportTrustedActionUnavailable(error || response?.error);
|
||
finish(false);
|
||
return;
|
||
}
|
||
|
||
finish(true);
|
||
});
|
||
} catch (error) {
|
||
reportTrustedActionUnavailable(error);
|
||
finish(false);
|
||
}
|
||
});
|
||
}
|
||
|
||
// 宿主先尝试 SendInput 物理输入,失败再退回 CDP Input.*:
|
||
// 两条路的事件都由浏览器/系统自己产生,isTrusted 为 true,还会带 user activation。
|
||
async function requestTrustedViaBridge(payload) {
|
||
const base = String(state.serverBase || DEFAULT_SERVER_BASE).replace(/\/+$/, "");
|
||
if (!base) return false;
|
||
|
||
const controller = typeof AbortController === "function" ? new AbortController() : null;
|
||
const timer = controller ? window.setTimeout(() => controller.abort(), 1500) : 0;
|
||
try {
|
||
const response = await fetch(`${base}/api/trusted`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ ...payload, shopId: state.shopId || "" }),
|
||
signal: controller ? controller.signal : undefined
|
||
});
|
||
if (!response.ok) return false;
|
||
const result = await response.json();
|
||
return Boolean(result && result.ok);
|
||
} catch (error) {
|
||
return false;
|
||
} finally {
|
||
if (timer) window.clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
function reportTrustedActionUnavailable(error) {
|
||
const message = typeof error === "string" ? error : error?.message || "";
|
||
if (!message) return;
|
||
|
||
if (/Extension context invalidated/i.test(message)) {
|
||
if (!state.trustedContextWarningShown) {
|
||
state.trustedContextWarningShown = true;
|
||
log("插件上下文已更新,已降级为普通输入/点击;刷新客服页面可恢复真实操作。");
|
||
}
|
||
return;
|
||
}
|
||
|
||
log(`真实操作不可用:${message}`);
|
||
}
|
||
|
||
function isDisabledSendButton(button) {
|
||
if (!button) return true;
|
||
const classText = String(button.className || "").toLowerCase();
|
||
const ariaDisabled = button.getAttribute("aria-disabled") === "true";
|
||
const disabledAttr = button.hasAttribute("disabled");
|
||
const style = window.getComputedStyle(button);
|
||
return ariaDisabled || disabledAttr || /disabled|disable/.test(classText) || style.pointerEvents === "none";
|
||
}
|
||
|
||
function getMessageNodeCount() {
|
||
const root = document.querySelector(selectors.messageList);
|
||
if (!root) return 0;
|
||
return Array.from(root.querySelectorAll("*")).filter((element) => {
|
||
const text = normalizeText(element.innerText || element.textContent || "");
|
||
if (!text) return false;
|
||
if (hasChildWithSameText(element, text)) return false;
|
||
return isLikelyChatText(text) || looksLikeProductCard(element, text);
|
||
}).length;
|
||
}
|
||
|
||
function getChatText() {
|
||
const root = document.querySelector(selectors.messageList);
|
||
return normalizeText(root ? root.innerText || root.textContent || "" : "");
|
||
}
|
||
|
||
function waitForManualSend() {
|
||
const button = document.querySelector(selectors.sendButton);
|
||
const textarea = document.querySelector(selectors.replyTextarea);
|
||
if (!button && !textarea) {
|
||
state.processing = false;
|
||
state.awaitingManualSend = false;
|
||
log("未找到发送按钮和输入框,已恢复监听。");
|
||
renderWidget();
|
||
scheduleCheck(500);
|
||
return;
|
||
}
|
||
|
||
let finished = false;
|
||
if (state.manualSendCleanup) state.manualSendCleanup();
|
||
const cleanup = () => {
|
||
button?.removeEventListener("click", onClick, true);
|
||
textarea?.removeEventListener("keydown", onKeyDown, true);
|
||
};
|
||
state.manualSendCleanup = cleanup;
|
||
|
||
const finish = (reason) => {
|
||
if (finished) return;
|
||
finished = true;
|
||
cleanup();
|
||
state.awaitingManualSend = false;
|
||
if (state.manualSendCleanup === cleanup) state.manualSendCleanup = null;
|
||
if (state.paused) {
|
||
state.processing = false;
|
||
renderWidget();
|
||
return;
|
||
}
|
||
state.processing = false;
|
||
log(`检测到人工${reason}发送,恢复监听。`);
|
||
renderWidget();
|
||
scheduleCheck(500);
|
||
};
|
||
|
||
const onClick = () => finish("点击");
|
||
const onKeyDown = (event) => {
|
||
if (event.key !== "Enter") return;
|
||
if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey || event.isComposing) return;
|
||
window.setTimeout(() => finish("回车"), 80);
|
||
};
|
||
|
||
button?.addEventListener("click", onClick, true);
|
||
textarea?.addEventListener("keydown", onKeyDown, true);
|
||
}
|
||
|
||
function isVisible(element) {
|
||
if (!element || !(element instanceof Element)) return false;
|
||
const rect = element.getBoundingClientRect();
|
||
const style = window.getComputedStyle(element);
|
||
return rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
|
||
}
|
||
|
||
function normalizeText(value) {
|
||
return String(value || "")
|
||
.replace(/\u00a0/g, " ")
|
||
.replace(/[ \t]+/g, " ")
|
||
.replace(/\n{3,}/g, "\n\n")
|
||
.trim();
|
||
}
|
||
|
||
function normalizeForMatch(value) {
|
||
return normalizeText(value).replace(/\s+/g, "").toLowerCase();
|
||
}
|
||
|
||
function sleep(ms) {
|
||
return new Promise((resolve) => window.setTimeout(resolve, ms));
|
||
}
|
||
|
||
function log(message) {
|
||
const time = new Date().toLocaleTimeString("zh-CN", { hour12: false });
|
||
const line = `[${time}] ${message}`;
|
||
state.logLines.push(line);
|
||
if (state.logLines.length > 80) state.logLines.shift();
|
||
if (state.activeRunLog) {
|
||
state.activeRunLog.lines.push(line);
|
||
if (state.activeRunLog.lines.length > 400) state.activeRunLog.lines.shift();
|
||
}
|
||
queueLogLine(line);
|
||
renderWidget();
|
||
}
|
||
|
||
// ---------- 日志:复制与落盘 ----------
|
||
function queueLogLine(line) {
|
||
logQueue.push(line);
|
||
if (logFlushTimer) return;
|
||
logFlushTimer = window.setTimeout(flushLogLines, 1200);
|
||
}
|
||
|
||
function flushLogLines() {
|
||
logFlushTimer = 0;
|
||
if (!logQueue.length) return;
|
||
const lines = logQueue;
|
||
logQueue = [];
|
||
try {
|
||
fetch(`${state.serverBase}/api/plugin-log`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json", ...getShopAuthHeaders() },
|
||
body: JSON.stringify({ shopId: state.shopId || "default", lines })
|
||
}).catch(() => {});
|
||
} catch (_) {
|
||
// 服务没起或跨域失败时忽略,面板里仍能看到日志
|
||
}
|
||
}
|
||
|
||
async function copyLogs() {
|
||
const text = state.logLines.join("\n");
|
||
if (!text) {
|
||
log("暂无日志可复制。");
|
||
return;
|
||
}
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
log("日志已复制到剪贴板。");
|
||
return;
|
||
} catch (_) {
|
||
// 剪贴板权限不可用时退回 execCommand
|
||
}
|
||
const area = document.createElement("textarea");
|
||
area.value = text;
|
||
area.style.position = "fixed";
|
||
area.style.opacity = "0";
|
||
document.body.appendChild(area);
|
||
area.select();
|
||
let ok = false;
|
||
try { ok = document.execCommand("copy"); } catch (_) { ok = false; }
|
||
area.remove();
|
||
log(ok ? "日志已复制到剪贴板。" : "复制失败,请打开 data\\logs 下当天的日志文件。");
|
||
}
|
||
|
||
function setErrorStatus() {
|
||
if (ui.status) ui.status.className = "pdd-ra-status is-error";
|
||
}
|
||
})();
|