Files

1517 lines
50 KiB
JavaScript
Raw Permalink Normal View History

(() => {
"use strict";
const DEFAULT_SERVER_BASE = "http://127.0.0.1:3456";
const STORE_KEY = "pddReplyAssistantState";
const CONTROL_POLL_MS = 1500;
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,
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,
trustedContextWarningShown: false,
position: { right: 18, bottom: 18 },
manualConversationKeys: new Set(),
cardOnlyConversationKeys: new Set(),
logLines: []
};
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();
async function init() {
loadState();
resetConfigDraftFromState();
buildWidget();
renderWidget();
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.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,
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 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" ? "调试模式" : "自动模式"}。`);
});
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.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.saveConfigBtn
);
ui.meta = document.createElement("div");
ui.meta.className = "pdd-ra-meta";
ui.log = document.createElement("div");
ui.log.className = "pdd-ra-log";
body.append(controls, ui.configPanel, ui.meta, 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})。`);
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.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 statusName = state.processing ? "is-busy" : state.paused ? "is-idle" : "is-listening";
ui.status.className = `pdd-ra-status ${statusName}`;
const controlState = state.remoteControlReady ? "手机控制已连接" : "手机控制未连接";
ui.meta.textContent = `店铺:${state.shopName || state.shopId}|服务:${state.serverBase}|${controlState}|商品来源:聊天卡片|人工介入:${state.manualConversationKeys.size}个|${state.processing ? "处理中" : state.paused ? "已暂停" : "监听中"}`;
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);
}
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,
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 row = findFirstUrgentConversation();
if (!row) return;
state.processing = true;
const runId = ++state.runId;
const abortController = new AbortController();
state.activeAbortController = abortController;
renderWidget();
try {
log("发现待回复用户,正在打开首个可自动处理的会话。");
const beforeChatSignature = getChatSignature();
await clickConversation(row);
ensureTaskActive(runId);
await waitForStableChat(beforeChatSignature, row);
ensureTaskActive(runId);
const payload = buildConversationPayload();
if (payload?.skip) {
markCardOnlyConversation(row);
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
log("最新一条是商品卡片,暂不回复,等待客户继续发送文字消息。");
renderWidget();
scheduleCheck(500);
return;
}
log(`已提取历史消息${payload.msgList.length}条。`);
printPayloadToDebugConsole(payload);
const result = await requestReply(payload, abortController.signal);
ensureTaskActive(runId);
if (isManualRequired(result)) {
markManualConversation(row);
const names = Array.isArray(result.riskIntents) ? result.riskIntents.join("、") : "未知";
const emailState = result.email?.sent ? "邮件已发送" : result.email?.deduped ? "邮件已去重" : "邮件未发送";
log(`命中高危意图:${names}。不回复此用户,${emailState},继续监听其他新消息。`);
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
renderWidget();
scheduleCheck(300);
return;
}
const reply = normalizeText(result.reply || result.message || result.text || "");
if (!reply) throw new Error("服务返回内容为空");
ensureTaskActive(runId);
await fillReply(reply);
ensureTaskActive(runId);
if (state.mode === "auto") {
const sent = await sendReplyAndVerify(reply);
ensureTaskActive(runId);
if (sent) {
log("已确认自动发送成功,恢复监听。");
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
renderWidget();
scheduleCheck(500);
} else {
state.processing = false;
setErrorStatus();
setPausedState(true, "自动发送未确认成功,已暂停监听。请人工检查当前会话,避免重复生成。", {
sync: true,
source: "auto-send-failed"
});
}
} else {
log("已回填回复。当前为调试模式,请人工确认后点击发送。");
waitForManualSend();
}
} catch (error) {
if (isTaskCanceled(error)) {
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
log("当前回复任务已取消,不会回填或发送。");
renderWidget();
return;
}
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
setErrorStatus();
log(`处理失败:${error.message}`);
renderWidget();
scheduleCheck(1200);
}
}
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;
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));
if (rows.length) return rows[0];
const fallbackItems = Array.from(list.children)
.filter((item) => isVisible(item) && !isManualConversation(item) && !isCardOnlyConversation(item));
if (fallbackItems.length) return fallbackItems[0];
}
return null;
}
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 = getConversationKey(row);
return key ? state.manualConversationKeys.has(key) : false;
}
function markManualConversation(row) {
if (!row) return;
if (row.dataset) row.dataset.pddRaManual = "1";
const key = getConversationKey(row);
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}` : "";
}
async function clickConversation(row) {
log(`准备点击会话:${normalizeText(row.innerText || row.textContent || "").slice(0, 40)}`);
row.scrollIntoView({ block: "center", inline: "nearest" });
await sleep(80);
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();
});
}
function buildConversationPayload() {
const messageItems = collectMessageItems();
const latestItem = getLatestConversationItem(messageItems);
const hasPendingCustomerText = hasPendingCustomerMessage(messageItems);
if (latestItem?.type === "product-card" && !hasPendingCustomerText) {
return {
skip: true,
reason: "latest-product-card",
latestProductCard: latestItem.product
};
}
if (latestItem?.type === "product-card" && hasPendingCustomerText) {
log("检测到客户文字后有平台商品卡提醒,继续按客户文字处理。");
}
const latestProductCard = extractLatestProductCardInfo();
const msgList = extractMessages(4, messageItems);
if (latestProductCard?.message) {
msgList.unshift({
usertype: "cus",
msg: latestProductCard.message
});
}
return {
msgList
};
}
function hasPendingCustomerMessage(messageItems) {
const lastSysIndex = findLastIndex(messageItems, (item) => item.usertype === "sys");
return messageItems.slice(lastSysIndex + 1).some((item) => item.usertype === "cus" && item.msg);
}
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 [];
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,
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 lines = normalizeText(element.innerText || element.textContent || "")
.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}`;
return {
name: title,
model,
message
};
}
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();
}
function collectMessageItems() {
const root = document.querySelector(selectors.messageList);
if (!root) return [];
const rootRect = root.getBoundingClientRect();
const all = Array.from(root.querySelectorAll("*"));
const raw = [];
for (const element of all) {
if (!isVisible(element)) continue;
if (isInsideSpecificProductCard(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,
usertype: centerX > rootCenterX ? "sys" : "cus",
msg: text
});
}
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()) {
return messageItems.slice(-limit).map(({ usertype, msg }) => ({ usertype, msg }));
}
function isInsideSpecificProductCard(element) {
return Boolean(element.closest?.(selectors.productCards));
}
function isLikelyChatText(text) {
if (!text) return false;
if (text.length > 600) 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 (/邀请关注|邀请下单|小额打款|小额收款|邀请开票/.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);
textarea.focus();
await sleep(80);
setTextareaValue(textarea, "");
dispatchTextInputEvents(textarea, "");
const trustedInput = await requestTrustedTextInput(reply);
await sleep(180);
if (trustedInput && normalizeText(textarea.value || "").includes(normalizeText(reply).slice(0, 20))) {
log("已使用真实输入事件写入回复。");
return;
}
if (trustedInput) {
log("真实输入事件未写入到输入框,改用页面脚本回填。");
}
setTextareaValue(textarea, reply);
dispatchTextInputEvents(textarea, reply);
await sleep(180);
}
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;
}
await clickSendButton();
const buttonSent = await waitForSendSuccess({
reply,
textarea,
beforeChatSignature,
beforeMessageCount,
timeout: 2800
});
if (buttonSent) return true;
log("按钮发送未确认成功,尝试使用回车发送。");
await pressEnterToSend(textarea);
return waitForSendSuccess({
reply,
textarea,
beforeChatSignature,
beforeMessageCount,
timeout: 4200
});
}
async function clickSendButton() {
const button = await waitForElement(selectors.sendButton, 5000);
if (isDisabledSendButton(button)) {
log("发送按钮看起来处于不可用状态,仍会尝试真实点击和回车兜底。");
}
button.scrollIntoView({ block: "center", inline: "center" });
await sleep(80);
const trusted = await requestTrustedClick(button);
if (!trusted) {
log("真实点击不可用,改用页面脚本点击。");
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 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();
return requestTrustedAction({
action: "trusted-click",
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
});
}
async function requestTrustedEnter() {
return requestTrustedAction({ action: "trusted-enter" });
}
function requestTrustedAction(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);
}
});
}
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;
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();
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 });
state.logLines.push(`[${time}] ${message}`);
if (state.logLines.length > 80) state.logLines.shift();
renderWidget();
}
function setErrorStatus() {
if (ui.status) ui.status.className = "pdd-ra-status is-error";
}
})();