Files
zhangyu db5cc03fd2 Fix auto-reply duplication, message parsing and console stability
- 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
2026-11-18 23:00:57 +08:00

3268 lines
170 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>拼多多客服助手</title>
<style>
/* 四套配色:黑(默认)/ 白 / 护眼绿 / 清新蓝,由「系统设置 → 界面外观」切换 */
:root { --bg:#141414; --panel:#1c1c1c; --panel2:#222; --line:#2e2e2e;
--text:#e6e6e6; --dim:#8a8a8a; --accent:#4a9eff; --accent-hover:#3d8ce6;
--on-accent:#fff; --on-danger:#fff; --ok:#3fb950; --warn:#d29922; --err:#f85149;
--input:#111; --hover:#202020; --hover2:#2a2a2a; --hover3:#333;
--line-hover:#3d3d3d; --line-hover-strong:#4a4a4a;
--chip:#242424; --chip-warn:#2b2416; --item-on:#1c2733;
--dialog:#252525; --nav-mute:#6b6b6b; --icon-mute:#5a5a5a; --mute:#666;
--scroll:#3a3a3a; --thumb:#0d0d0d;
--overlay:rgba(0,0,0,.55); --shadow:rgba(0,0,0,.5);
color-scheme:dark; }
:root[data-theme="light"] { --bg:#f4f5f7; --panel:#ffffff; --panel2:#eef0f3; --line:#d8dce3;
--text:#1f2329; --dim:#6b7280; --accent:#2563eb; --accent-hover:#1d4ed8;
--on-accent:#fff; --on-danger:#fff; --ok:#1a7f37; --warn:#9a6700; --err:#cf222e;
--input:#ffffff; --hover:#f0f2f5; --hover2:#e8ebef; --hover3:#dde1e7;
--line-hover:#c3c9d4; --line-hover-strong:#aab2bf;
--chip:#eef0f3; --chip-warn:#fff4d6; --item-on:#e8f0ff;
--dialog:#ffffff; --nav-mute:#7a8290; --icon-mute:#8a92a0; --mute:#8a92a0;
--scroll:#c6ccd6; --thumb:#e9ebef;
--overlay:rgba(15,23,42,.35); --shadow:rgba(15,23,42,.18);
color-scheme:light; }
:root[data-theme="green"] { --bg:#c7edcc; --panel:#e6f8e9; --panel2:#d3efd8; --line:#a8d8b4;
--text:#1d3a27; --dim:#547a60; --accent:#2e8b57; --accent-hover:#257247;
--on-accent:#fff; --on-danger:#fff; --ok:#1a7f37; --warn:#8a6100; --err:#c62828;
--input:#f3fcf4; --hover:#cdecd3; --hover2:#c3e7ca; --hover3:#b6dfbe;
--line-hover:#8fc9a0; --line-hover-strong:#77b98b;
--chip:#cdecd3; --chip-warn:#fdf3d0; --item-on:#b6dfc2;
--dialog:#f0fbf2; --nav-mute:#5f8469; --icon-mute:#6d9478; --mute:#6d9478;
--scroll:#a8d8b4; --thumb:#d9f2de;
--overlay:rgba(20,60,35,.3); --shadow:rgba(20,60,35,.16);
color-scheme:light; }
:root[data-theme="blue"] { --bg:#f0f7ff; --panel:#ffffff; --panel2:#e6f2ff; --line:#d2e5fa;
--text:#10233f; --dim:#61758f; --accent:#2e90fa; --accent-hover:#1c7ed6;
--on-accent:#fff; --on-danger:#fff; --ok:#1a7f37; --warn:#9a6700; --err:#d92d20;
--input:#ffffff; --hover:#e8f3ff; --hover2:#dcedff; --hover3:#cfe4ff;
--line-hover:#b6d4f0; --line-hover-strong:#96bde6;
--chip:#e6f2ff; --chip-warn:#fff4d6; --item-on:#d8eaff;
--dialog:#ffffff; --nav-mute:#7086a3; --icon-mute:#8095b3; --mute:#8095b3;
--scroll:#c4dbf2; --thumb:#eef6ff;
--overlay:rgba(10,40,90,.32); --shadow:rgba(10,40,90,.14);
color-scheme:light; }
* { box-sizing:border-box; margin:0; padding:0; }
html,body { height:100%; overflow:hidden; }
body { background:var(--bg); color:var(--text);
font:14px/1.5 "Microsoft YaHei","Segoe UI",system-ui,sans-serif; user-select:none; }
::-webkit-scrollbar { width:8px; height:8px; }
::-webkit-scrollbar-track { background:var(--bg); }
::-webkit-scrollbar-thumb { background:var(--scroll); border-radius:4px; }
::-webkit-scrollbar-thumb:hover { background:var(--line-hover-strong); }
::-webkit-scrollbar-corner { background:var(--bg); }
.titlebar { height:36px; display:flex; align-items:center; background:var(--panel);
border-bottom:1px solid var(--line); -webkit-app-region:no-drag; }
.titlebar .brand { padding:0 14px; font-size:13px; color:var(--dim); letter-spacing:.5px; }
.scope-chip { flex:none; margin-left:4px; padding:3px 9px; border-radius:10px;
background:var(--chip); color:var(--dim); font-size:11px; max-width:220px;
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.scope-chip.none { color:var(--warn); background:var(--chip-warn); }
.titlebar .drag { flex:1; height:100%; }
.titlebar button { width:44px; height:36px; border:0; background:transparent; color:var(--dim);
font-size:13px; cursor:pointer; display:inline-flex; align-items:center;
justify-content:center; }
.titlebar button svg { display:block; }
.titlebar button:hover { background:var(--hover2); color:var(--text); }
.titlebar button.close:hover { background:var(--err); color:var(--on-danger); }
.app { display:flex; height:calc(100% - 36px); }
.nav { width:180px; background:var(--panel); border-right:1px solid var(--line);
padding:10px 0; flex:none; overflow-y:auto; }
.shop-switch { padding:0 10px 10px; margin-bottom:8px; border-bottom:1px solid var(--line); }
.shop-switch .nav-label { padding:2px 8px 6px; }
.shop-combo { position:relative; }
.shop-combo-trigger { width:100%; box-sizing:border-box; display:flex; align-items:center; gap:6px;
background:var(--input); border:1px solid var(--line); color:var(--text);
border-radius:4px; padding:7px 9px; font:13px/1.3 inherit; font-family:inherit;
cursor:pointer; text-align:left; }
.shop-combo-trigger:hover { border-color:var(--line-hover); }
.shop-combo-trigger.open { border-color:var(--accent); }
.shop-combo-caret { flex:none; color:var(--dim); font-size:10px; }
.shop-combo-panel { display:none; position:fixed; z-index:600; box-sizing:border-box;
background:var(--panel2); border:1px solid var(--line); border-radius:6px; padding:6px;
box-shadow:0 10px 28px var(--shadow); }
.shop-combo-panel.show { display:block; }
.shop-combo-list { display:flex; flex-direction:column; gap:2px; max-height:240px;
overflow-y:auto; margin-bottom:6px; }
.shop-item { display:flex; align-items:center; gap:6px; padding:6px 8px; border-radius:4px;
border:1px solid transparent; cursor:pointer; color:var(--dim); font-size:13px; }
.shop-item:hover { background:var(--chip); color:var(--text); }
.shop-item.on { background:var(--item-on); border-color:var(--accent); color:var(--text); }
.shop-item-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.shop-item-del, .shop-item-edit { flex:none; background:none; border:none; color:var(--icon-mute);
cursor:pointer; font-size:12px; line-height:1; padding:2px 3px; }
.shop-item-edit:hover { color:var(--accent); }
.shop-item-del:hover { color:var(--err); }
.shop-add { width:100%; }
.nav-label { display:block; padding:12px 18px 4px; font-size:11px; letter-spacing:.06em;
color:var(--nav-mute); }
.nav-group-head { width:100%; display:flex; align-items:center; justify-content:space-between;
padding:9px 18px; background:none; border:0; color:var(--dim);
font-family:inherit; font-size:13px; text-align:left; cursor:pointer; }
.nav-group-head:hover { color:var(--text); background:var(--hover); }
.nav-caret { display:inline-flex; align-items:center; justify-content:center;
color:var(--nav-mute); transition:transform .15s ease; }
.nav-group-head:hover .nav-caret { color:var(--text); }
.nav-group.collapsed .nav-caret { transform:rotate(-90deg); }
.nav-group.collapsed .nav-group-body { display:none; }
.nav a { display:block; padding:9px 18px; color:var(--dim); font-size:13px;
cursor:pointer; border-left:2px solid transparent; }
.nav a:hover { color:var(--text); background:var(--hover); }
.nav a.active { color:var(--text); background:var(--hover); border-left-color:var(--accent); }
.main { flex:1; overflow:auto; padding:22px 26px; position:relative; }
h1 { font-size:18px; margin-bottom:6px; font-weight:600; }
h2 { font-size:14px; margin:20px 0 10px; color:var(--dim); font-weight:600;
border-bottom:1px solid var(--line); padding-bottom:6px; }
p.desc { color:var(--dim); font-size:13px; margin-bottom:14px; }
/* 客服工作台:标签页栏留在前端,内容区由原生 WebView2 覆盖 */
#page-console { position:absolute; inset:0; }
#page-console.active { display:flex; flex-direction:column; }
/* 浮层打开时客服台被原生挪走,这块空占位文字会露出来,先藏掉 */
body.console-hidden #consoleEmpty { display:none; }
.console-tabs { height:44px; flex:none; display:flex; align-items:center; gap:6px;
background:var(--panel); border-bottom:1px solid var(--line); padding:0 10px; }
.console-tablist { flex:1; min-width:0; height:100%; display:flex; align-items:center;
gap:2px; overflow-x:auto; overflow-y:hidden; }
.console-tablist::-webkit-scrollbar { height:0; }
.console-tab { flex:none; display:flex; align-items:center; height:32px; background:transparent;
border:1px solid transparent; border-radius:4px; }
.console-tab:hover { background:var(--hover); }
.console-tab.active { background:var(--hover); border-color:var(--scroll); }
/* 拖动排序:拖起时半透明,落点前后用强调色竖线提示 */
.console-tab.dragging { opacity:.45; }
.console-tab.drop-before { box-shadow: inset 2px 0 0 var(--accent); }
.console-tab.drop-after { box-shadow: inset -2px 0 0 var(--accent); }
/* 选项卡前的状态圆点:绿=自动模式服务中,蓝=调试模式服务中,黄=已暂停,灰=未知 */
.tab-dot { display:inline-block; width:7px; height:7px; border-radius:50%;
vertical-align:middle; margin-right:6px; margin-top:-1px;
background:#555; box-shadow:0 0 0 1px rgba(0,0,0,.35); }
.tab-dot.ok { background:var(--ok); }
.tab-dot.info { background:#3b82f6; }
.tab-dot.warn { background:var(--warn); }
.tab-dot.off { background:#555; }
/* 商家后台标签:同一个店铺的第二个标签,用小徽标和客服台标签区分 */
.tab-view { display:inline-block; margin-left:6px; padding:1px 5px; border-radius:3px;
font-size:10px; line-height:1.5; background:var(--chip); color:var(--dim); }
.console-tab.active .tab-view { background:var(--item-on); color:var(--accent); }
.console-tab-open, .console-tab-x { background:transparent; border:none; color:var(--dim);
font-family:inherit; cursor:pointer; }
.console-tab-open { padding:6px 4px 6px 10px; font-size:13px; white-space:nowrap; }
.console-tab.active .console-tab-open { color:var(--text); }
.console-tab-x { padding:6px 10px 6px 4px; font-size:13px; line-height:1; }
.console-tab-x:hover { color:var(--err); }
.console-add { margin-left:8px; flex:none; width:28px; height:28px; border-radius:4px;
border:1px solid var(--line); background:transparent; color:var(--dim);
cursor:pointer; font-size:15px; line-height:1; font-family:inherit; }
.console-add:hover { color:var(--text); border-color:var(--line-hover-strong); background:var(--hover); }
.console-logout { margin-left:8px; flex:none; height:28px; padding:0 10px; border-radius:4px;
border:1px solid var(--line); background:transparent; color:var(--dim);
cursor:pointer; font-size:12px; font-family:inherit; }
.console-logout:hover { color:var(--text); border-color:var(--line-hover-strong); background:var(--hover); }
.console-host { flex:1; position:relative; background:var(--bg); overflow:hidden; }
.console-host .empty { position:absolute; inset:0; display:flex; align-items:center;
justify-content:center; color:var(--dim); font-size:13px; }
.console-mask { position:absolute; inset:0; background:var(--overlay); display:none;
align-items:center; justify-content:center; z-index:5; }
.console-mask.show { display:flex; }
.console-dialog { width:330px; max-height:72%; display:flex; flex-direction:column;
background:var(--dialog); border:1px solid var(--line); border-radius:6px;
padding:16px; box-shadow:0 12px 32px var(--shadow); }
.console-dialog-title { font-size:14px; font-weight:600; margin-bottom:12px; }
.console-dialog-body { flex:1; overflow:auto; display:flex; flex-direction:column;
gap:6px; margin-bottom:12px; }
.picker-item { text-align:left; padding:9px 11px; font-size:13px; background:var(--hover2);
border:1px solid var(--line); border-radius:4px; color:var(--text);
cursor:pointer; font-family:inherit; }
.picker-item:hover { border-color:var(--accent); background:var(--hover3); }
.console-dialog-foot { display:flex; justify-content:flex-end; gap:8px; }
.grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(220px,1fr)); gap:12px; }
.card { background:var(--panel); border:1px solid var(--line); border-radius:6px; padding:14px 16px; }
.card .k { color:var(--dim); font-size:12px; margin-bottom:6px; }
.card .v { font-size:20px; font-weight:600; }
.card .v.ok { color:var(--ok); } .card .v.warn { color:var(--warn); }
.card .v.err { color:var(--err); } .card .v.idle { color:var(--dim); }
table { width:100%; border-collapse:collapse; font-size:13px; }
th,td { padding:8px 10px; border-bottom:1px solid var(--line); text-align:left; }
th { color:var(--dim); font-weight:500; }
.page { display:none; } .page.active { display:block; }
.row { display:flex; gap:10px; align-items:center; margin-bottom:10px; }
input,textarea { background:var(--input); border:1px solid var(--line); color:var(--text);
border-radius:4px; padding:7px 9px; font-size:13px; font-family:inherit; }
/* 下拉框:自绘外观 + base-select 自定义弹出层,避免深色背景上使用系统浅色菜单 */
select { background-color:var(--input); border:1px solid var(--line); color:var(--text);
border-radius:4px; padding:7px 26px 7px 9px;
font-size:13px; font-family:inherit; cursor:pointer;
-webkit-appearance:none; appearance:none;
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6'><path d='M1 1l4 4 4-4' fill='none' stroke='%238a8a8a' stroke-width='1.3'/></svg>");
background-repeat:no-repeat; background-position:right 10px center; }
/* 支持 base-select 的浏览器:弹出层完全按下面的深色样式绘制,并隐藏默认图标 */
select, select::picker(select) { appearance:base-select; }
select::picker-icon { display:none; }
select::picker(select) { background:var(--bg); border:1px solid var(--line); border-radius:4px;
margin-top:4px; padding:4px; color:var(--text);
max-height:260px; overflow:auto;
box-shadow:0 8px 24px var(--shadow); }
select option { background:var(--panel); color:var(--text); padding:6px 9px;
border-radius:3px; font-size:13px; }
select option:hover, select option:focus { background:var(--hover2); }
select option:checked { background:var(--hover2); color:var(--text); }
/* 数字输入框:隐藏系统上下调节器,改为纯输入,避免浅色箭头与深色边框不协调 */
input[type=number] { -moz-appearance:textfield; }
input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button { -webkit-appearance:none; margin:0; }
input { min-width:0; user-select:text; }
/* 复选框:系统默认在深色主题下是近乎不可见的黑块,改为自绘 + 主题强调色 */
input[type=checkbox] { appearance:none; -webkit-appearance:none;
width:15px; height:15px; min-width:15px;
border:1px solid var(--line-hover); border-radius:3px;
background:var(--input); cursor:pointer; position:relative;
padding:0; flex:0 0 auto; user-select:none; vertical-align:middle; }
input[type=checkbox]:hover { border-color:var(--line-hover-strong); }
input[type=checkbox]:checked { background:var(--accent); border-color:var(--accent); }
input[type=checkbox]:checked::after { content:''; position:absolute; left:4px; top:1px;
width:4px; height:8px; border:solid var(--on-accent);
border-width:0 2px 2px 0; transform:rotate(45deg); }
input[type=checkbox]:focus-visible { outline:2px solid var(--accent); outline-offset:1px; }
textarea { width:100%; min-height:220px; font-family:Consolas,monospace; font-size:12px;
line-height:1.6; user-select:text; }
button.act { background:var(--accent); border:0; color:var(--on-accent); border-radius:4px;
padding:8px 18px; font-size:13px; cursor:pointer; }
button.act:hover { background:var(--accent-hover); }
button.act.ghost { background:transparent; border:1px solid var(--line); color:var(--text); }
button.act.ghost:hover { border-color:var(--line-hover-strong); background:var(--hover); }
button.act:disabled { background:var(--hover2); color:var(--mute); cursor:not-allowed; }
button.mini { background:transparent; border:1px solid var(--line); color:var(--dim);
border-radius:4px; padding:4px 9px; font-size:12px; cursor:pointer; }
button.mini:hover { color:var(--text); border-color:var(--line-hover-strong); }
button.mini.del:hover { color:var(--err); border-color:var(--err); }
.hint { color:var(--dim); font-size:12px; line-height:1.7; }
.hint code { background:var(--input); border:1px solid var(--line); border-radius:3px; padding:1px 5px; }
.lan { background:var(--panel); border:1px solid var(--line);
border-radius:6px; padding:12px 14px; }
.lan a { color:var(--accent); text-decoration:none; display:block; font-size:13px;
font-family:Consolas,monospace; padding:3px 0; user-select:text; }
.lan a:hover { text-decoration:underline; }
.prod-list,.know-list { display:flex; flex-direction:column; gap:12px; }
.prod-card,.know-card { background:var(--panel);
border:1px solid var(--line); border-radius:6px; padding:14px 16px; }
.prod-card .head,.know-card .head { display:flex; gap:8px; align-items:center; margin-bottom:10px; }
.prod-card .lbl,.know-card .lbl { width:58px; flex:none; color:var(--dim); font-size:12px; }
/* 规则卡片内的分组标题与字段说明:把「触发条件」和「命中后发送」分开,避免一行行糊在一起 */
.rule-section { margin:16px 0 10px; padding-top:10px; border-top:1px dashed var(--line);
font-size:12px; color:var(--text); opacity:.75; letter-spacing:.04em; }
.rule-section:first-child { margin-top:0; padding-top:0; border-top:0; }
.rule-hint { margin:-4px 0 12px 76px; font-size:12px; color:var(--mute); line-height:1.6; }
.thumb.bad::after { content:'无法预览'; display:flex; align-items:center; justify-content:center;
height:100%; color:var(--dim); font-size:11px; }
.img-pick { display:flex; flex-wrap:wrap; gap:8px; align-items:flex-start; flex:1; }
.img-pick-item { display:flex; flex-direction:column; gap:4px; width:72px; }
.img-pick-item img { width:72px; height:72px; object-fit:cover; border-radius:4px;
border:1px solid var(--line); display:block; background:var(--input); }
.img-pick-name { font-size:11px; color:var(--dim); text-align:center;
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.img-pick .mini { align-self:center; }
.img-modal { position:fixed; inset:0; z-index:10001; background:var(--overlay);
display:none; align-items:center; justify-content:center; }
.img-modal-box { width:min(760px, 80vw); max-height:76vh; display:flex; flex-direction:column;
background:var(--panel); border:1px solid var(--line); border-radius:8px; padding:16px; }
.img-modal-head { display:flex; align-items:center; justify-content:space-between; margin-bottom:12px; }
.img-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(112px, 1fr)); gap:10px;
overflow-y:auto; flex:1; }
.img-cell { border:1px solid var(--line); border-radius:6px; padding:6px; cursor:pointer;
background:var(--input); user-select:none; }
.img-cell.on { border-color:var(--accent); background:var(--item-on); }
.img-cell .thumb { width:100%; height:96px; overflow:hidden; border-radius:4px; background:var(--thumb); }
.img-cell .thumb img { width:100%; height:100%; object-fit:cover; display:block; }
.img-cell-name { display:block; margin-top:6px; font-size:12px; color:var(--text);
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; text-align:center; }
.img-gallery { display:grid; grid-template-columns:repeat(auto-fill, minmax(112px, 1fr)); gap:10px;
margin-top:12px; }
.img-gallery .img-cell { cursor:default; }
/* 网格为空时的提示要占满整行,否则会被挤进单个格子 */
.gallery-empty { grid-column:1 / -1; padding:28px 0; color:var(--dim); font-size:13px; text-align:center; }
.img-picker-settings { max-height:150px; overflow-y:auto; margin-top:10px;
padding-top:10px; border-top:1px solid var(--line); }
.model-list { display:flex; flex-direction:column; gap:10px; margin:12px 0; }
.model-item { display:flex; gap:10px; background:var(--panel); border:1px solid var(--line);
border-radius:6px; padding:10px 12px; }
.model-item.dragging { opacity:.5; }
.model-item.drop-target { border-color:var(--accent); }
.model-drag { cursor:grab; color:var(--mute); font-size:14px; line-height:1; padding-top:8px; user-select:none; }
.model-main { flex:1; min-width:0; }
.model-no { width:20px; flex:none; color:var(--dim); font-size:12px; }
.img-picker-settings .row { margin:6px 0; }
textarea.attr { min-height:86px; }
textarea.know-content { min-height:96px; }
.greet-thumbs { display:flex; gap:8px; flex-wrap:wrap; margin-top:8px; }
.greet-thumbs .thumb { width:56px; height:56px; }
.greet-thumbs .thumb img { width:100%; height:100%; object-fit:cover; border-radius:4px; }
.toast { position:fixed; left:50%; bottom:26px; transform:translateX(-50%);
background:var(--dialog); border:1px solid var(--line); color:var(--text);
padding:9px 18px; border-radius:6px; font-size:13px; z-index:10000;
opacity:0; transition:opacity .18s ease; pointer-events:none; max-width:80%; }
.toast.show { opacity:1; }
.toast.ok { border-color:var(--ok); } .toast.err { border-color:var(--err); }
.handles { position:fixed; inset:0; pointer-events:none; z-index:9999; }
.handles div { position:absolute; pointer-events:none; }
.h-l,.h-r { top:0; bottom:0; width:6px; cursor:ew-resize; }
.h-t,.h-b { left:0; right:0; height:6px; cursor:ns-resize; }
.h-l { left:0 } .h-r { right:0 } .h-t { top:0 } .h-b { bottom:0 }
.h-tl,.h-tr,.h-bl,.h-br { width:10px; height:10px; z-index:1; }
.h-tl { top:0; left:0; cursor:nwse-resize } .h-tr { top:0; right:0; cursor:nesw-resize }
.h-bl { bottom:0; left:0; cursor:nesw-resize } .h-br { bottom:0; right:0; cursor:nwse-resize }
/* 界面外观:三套配色的选择卡片 */
.theme-picker { display:flex; gap:12px; flex-wrap:wrap; margin:8px 0 4px; }
.theme-card { width:186px; display:flex; flex-direction:column; align-items:flex-start; gap:8px;
padding:12px; border:1px solid var(--line); border-radius:8px; cursor:pointer;
background:var(--panel); color:var(--text); font-family:inherit; text-align:left; }
.theme-card:hover { border-color:var(--line-hover-strong); }
.theme-card.on { border-color:var(--accent); box-shadow:0 0 0 1px var(--accent); }
.theme-swatch { display:flex; gap:5px; width:100%; }
.theme-swatch i { flex:1; height:36px; border-radius:5px; border:1px solid var(--line); }
.theme-swatch.dark i:nth-child(1) { background:#141414; }
.theme-swatch.dark i:nth-child(2) { background:#1c1c1c; }
.theme-swatch.dark i:nth-child(3) { background:#4a9eff; }
.theme-swatch.light i:nth-child(1) { background:#f4f5f7; }
.theme-swatch.light i:nth-child(2) { background:#ffffff; }
.theme-swatch.light i:nth-child(3) { background:#2563eb; }
.theme-swatch.green i:nth-child(1) { background:#c7edcc; }
.theme-swatch.green i:nth-child(2) { background:#e6f8e9; }
.theme-swatch.green i:nth-child(3) { background:#2e8b57; }
.theme-swatch.blue i:nth-child(1) { background:#f0f7ff; }
.theme-swatch.blue i:nth-child(2) { background:#ffffff; }
.theme-swatch.blue i:nth-child(3) { background:#2e90fa; }
.theme-name { font-size:13px; font-weight:600; }
.theme-card.on .theme-name::after { content:" ✓"; color:var(--accent); }
.theme-desc { font-size:12px; color:var(--dim); line-height:1.5; }
/* 网络验证:未授权时盖住主界面,保留自绘标题栏以便最小化 / 关闭窗口 */
.auth-overlay { position:fixed; inset:36px 0 0 0; z-index:100000; display:flex;
align-items:center; justify-content:center; background:var(--bg); }
.auth-box { width:min(430px, 88vw); background:var(--panel); border:1px solid var(--line);
border-radius:10px; padding:24px 26px; box-shadow:0 18px 50px var(--shadow); }
.auth-title { font-size:18px; font-weight:600; }
.auth-sub { color:var(--dim); font-size:12px; margin:4px 0 18px; line-height:1.6; }
.auth-tabs { display:flex; gap:6px; margin-bottom:18px; border-bottom:1px solid var(--line); }
.auth-tabs button { background:transparent; border:0; border-bottom:2px solid transparent;
color:var(--dim); padding:8px 14px; font-size:13px; cursor:pointer;
font-family:inherit; }
.auth-tabs button:hover { color:var(--text); }
.auth-tabs button.on { color:var(--accent); border-bottom-color:var(--accent); }
.auth-pane { display:none; } .auth-pane.on { display:block; }
.auth-field { display:flex; flex-direction:column; gap:6px; margin-bottom:12px; }
.auth-field label { font-size:12px; color:var(--dim); }
.auth-field input { width:100%; }
.auth-actions { display:flex; gap:8px; margin-top:16px; }
.auth-remember { display:flex; align-items:center; gap:6px; margin-top:4px;
font-size:12px; color:var(--dim); cursor:pointer; user-select:none; }
.auth-remember input { width:15px; height:15px; margin:0; cursor:pointer; }
.auth-remember:hover { color:var(--text); }
.auth-actions button.act { flex:1; }
.auth-msg { min-height:20px; margin-top:12px; font-size:12px; color:var(--err);
line-height:1.6; word-break:break-all; }
.auth-msg.ok { color:var(--ok); }
.auth-state { margin-top:14px; padding-top:12px; border-top:1px solid var(--line);
color:var(--dim); font-size:12px; line-height:1.8; word-break:break-all; }
.auth-foot { display:flex; justify-content:space-between; gap:8px; margin-top:12px; }
.titlebar button.auth-badge { flex:none; width:auto; height:auto; margin-left:4px;
padding:3px 9px; border-radius:10px; font-family:inherit;
background:var(--chip); color:var(--dim); font-size:11px;
border:1px solid transparent; max-width:260px; overflow:hidden;
text-overflow:ellipsis; white-space:nowrap; }
.titlebar button.auth-badge:hover { background:var(--chip); color:var(--text);
border-color:var(--line-hover-strong); }
.titlebar button.auth-badge.on { color:var(--ok); }
.titlebar button.auth-badge:focus { outline:none; }
.titlebar button.auth-badge:focus-visible { outline:1px solid var(--line-hover-strong); outline-offset:1px; }
/* 标题栏账号弹窗 */
.acc-pop { position:fixed; z-index:100002; width:268px; padding:14px;
background:var(--panel); border:1px solid var(--line);
border-radius:10px; box-shadow:0 12px 32px rgba(0,0,0,.45); display:none; }
.acc-pop.on { display:block; }
.acc-pop .acc-row { display:flex; justify-content:space-between; gap:10px;
font-size:12px; color:var(--dim); line-height:1.9; }
.acc-pop .acc-row b { color:var(--text); font-weight:500; text-align:right;
word-break:break-all; }
.acc-pop .acc-msg { min-height:16px; margin-top:6px; font-size:11px;
color:var(--err); line-height:1.6; }
.acc-pop .acc-msg.ok { color:var(--ok); }
.acc-pop .acc-line { height:1px; background:var(--line); margin:10px 0; }
.acc-pop input { width:100%; height:30px; margin-bottom:8px; }
.acc-pop .acc-actions { display:flex; gap:8px; }
.acc-pop .acc-actions button { flex:1; height:30px; padding:0 8px; font-size:12px;
display:inline-flex; align-items:center; justify-content:center; }
/* 版本更新弹窗 */
.upd-mask { position:fixed; inset:0; z-index:100004; display:none;
align-items:center; justify-content:center; background:rgba(0,0,0,.45); }
.upd-mask.on { display:flex; }
.upd-box { width:420px; max-width:86vw; padding:20px 22px;
background:var(--panel); border:1px solid var(--line); border-radius:12px;
box-shadow:0 20px 50px rgba(0,0,0,.5); }
.upd-box h3 { margin:0 0 6px; font-size:15px; color:var(--text); font-weight:600; }
.upd-ver { font-size:12px; color:var(--dim); margin-bottom:10px; }
.upd-notes { max-height:180px; overflow:auto; padding:10px 12px; margin-bottom:12px;
background:var(--chip); border-radius:8px; font-size:12px; line-height:1.7;
color:var(--text); white-space:pre-wrap; word-break:break-word; }
.upd-bar { height:6px; border-radius:3px; background:var(--chip); overflow:hidden;
margin-bottom:8px; display:none; }
.upd-bar.on { display:block; }
.upd-bar i { display:block; height:100%; width:0; background:var(--accent);
border-radius:3px; transition:width .2s linear; }
.upd-msg { min-height:16px; font-size:11px; color:var(--err); line-height:1.6; }
.upd-msg.ok { color:var(--ok); }
.upd-actions { display:flex; gap:8px; justify-content:flex-end; margin-top:14px; }
.upd-actions button { height:32px; padding:0 16px; font-size:12px;
display:inline-flex; align-items:center; justify-content:center; }
/* 验证页也要能看到操作结果 toast */
.toast { z-index:100001; }
</style>
</head>
<body>
<div class="titlebar">
<span class="brand">拼多多客服助手</span>
<span class="scope-chip" id="scopeChip" title="设置类页面只作用于这个店铺">当前店铺:未打开</span>
<button class="auth-badge" id="authBadge" title="点击查看账号信息、充值与退出登录">未验证</button>
<div class="drag" id="drag"></div>
<button id="btnMin" title="最小化"><svg width="12" height="12" viewBox="0 0 10 10" aria-hidden="true"><path d="M1.8 5h6.4" stroke="currentColor" stroke-width="1.1" stroke-linecap="round"/></svg></button>
<button id="btnMax" title="最大化"><svg width="12" height="12" viewBox="0 0 10 10" aria-hidden="true"><rect x="1.9" y="1.9" width="6.2" height="6.2" rx="0.8" fill="none" stroke="currentColor" stroke-width="1.1"/></svg></button>
<button id="btnClose" class="close" title="关闭"><svg width="12" height="12" viewBox="0 0 10 10" aria-hidden="true"><path d="M2.2 2.2l5.6 5.6M7.8 2.2L2.2 7.8" stroke="currentColor" stroke-width="1.1" stroke-linecap="round"/></svg></button>
</div>
<div class="acc-pop" id="accPop">
<div class="acc-row"><span>账号</span><b id="accPopName">—</b></div>
<div class="acc-row"><span>授权</span><b id="accPopState">—</b></div>
<div class="acc-line"></div>
<input id="accPopCard" placeholder="输入卡密,充值到当前账号">
<div class="acc-msg" id="accPopMsg"></div>
<div class="acc-actions">
<button class="act" id="accPopRecharge">卡密充值</button>
<button class="act ghost" id="accPopLogout">退出登录</button>
</div>
</div>
<div class="upd-mask" id="updMask">
<div class="upd-box">
<h3 id="updTitle">发现新版本</h3>
<div class="upd-ver" id="updVer"></div>
<div class="upd-notes" id="updNotes"></div>
<div class="upd-bar" id="updBarWrap"><i id="updBar"></i></div>
<div class="upd-msg" id="updMsg"></div>
<div class="upd-actions">
<button class="act" id="updNow">立即更新</button>
<button class="act ghost" id="updLater">稍后再说</button>
</div>
</div>
</div>
<div class="app">
<div class="nav">
<div class="shop-switch">
<span class="nav-label">当前店铺</span>
<div class="shop-combo" id="shopCombo">
<button class="shop-combo-trigger" id="shopComboTrigger">
<span class="shop-item-name" id="shopComboText">未配置店铺</span>
<span class="shop-combo-caret">▾</span>
</button>
<div class="shop-combo-panel" id="shopComboPanel">
<div class="shop-combo-list" id="shopList"></div>
<button class="mini shop-add" id="btnNavAddShop">+ 新增店铺</button>
</div>
</div>
</div>
<div class="nav-group" data-group="run">
<button class="nav-group-head">运行<span class="nav-caret"><svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 4.5L6 8l3.5-3.5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></span></button>
<div class="nav-group-body">
<a class="active" data-page="status">服务状态</a>
<a data-page="console">工作台</a>
</div>
</div>
<div class="nav-group" data-group="config">
<button class="nav-group-head">店铺配置<span class="nav-caret"><svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 4.5L6 8l3.5-3.5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></span></button>
<div class="nav-group-body">
<a data-page="products">商品信息</a>
<a data-page="knowledge">知识库</a>
<a data-page="persona">客服人格</a>
<a data-page="quick">快捷回复</a>
<a data-page="replyimg">图片库</a>
<a data-page="risk">风险意图</a>
<a data-page="rules">转人工与话术</a>
<a data-page="images">图片保存</a>
<a data-page="model">模型配置</a>
</div>
</div>
<div class="nav-group" data-group="system">
<button class="nav-group-head">系统<span class="nav-caret"><svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 4.5L6 8l3.5-3.5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></span></button>
<div class="nav-group-body">
<a data-page="system">系统设置</a>
<a data-page="logs">日志</a>
<a data-page="about">关于</a>
</div>
</div>
</div>
<div class="main">
<section class="page active" id="page-status">
<h1>服务状态</h1>
<p class="desc">本地服务为内嵌客服台与手机控制页提供接口,配置改动保存后立即生效,无需重启。</p>
<div class="grid">
<div class="card"><div class="k">本地服务</div><div class="v idle" id="stServer">未启动</div></div>
<div class="card"><div class="k">监听地址</div><div class="v" style="font-size:15px" id="stAddr">—</div></div>
<div class="card"><div class="k">已配置店铺</div><div class="v" id="stShops">0</div></div>
</div>
<h2>今日统计</h2>
<div class="grid">
<div class="card"><div class="k">自动回复</div><div class="v" id="stReply">0</div></div>
<div class="card"><div class="k">转人工拦截</div><div class="v warn" id="stManual">0</div></div>
<div class="card"><div class="k">邮件告警</div><div class="v" id="stMail">0</div></div>
<div class="card"><div class="k">模型调用失败</div><div class="v err" id="stFail">0</div></div>
</div>
<h2>手机控制页</h2>
<div class="lan" id="lanBox"><span class="hint">读取中…</span></div>
</section>
<section class="page" id="page-console">
<div class="console-tabs">
<div class="console-tablist" id="consoleTabList"></div>
<button type="button" class="console-add" id="consoleAdd" aria-label="打开店铺">+</button>
<button type="button" class="console-logout" id="consoleLogout">退出登录</button>
</div>
<div class="console-host" id="consoleHost">
<div class="empty" id="consoleEmpty">正在打开客服台…</div>
</div>
<div class="console-mask" id="consoleMask">
<div class="console-dialog">
<div class="console-dialog-title">打开店铺</div>
<div class="console-dialog-body" id="consolePickerBody"></div>
<div class="console-dialog-foot">
<button type="button" class="act" id="consolePickerCancel">取消</button>
</div>
</div>
</div>
<!-- 退出登录确认:自绘弹窗,避免 WebView2 的 confirm() 被置顶的客服台盖住后卡死 -->
<div class="console-mask" id="consoleConfirmMask">
<div class="console-dialog">
<div class="console-dialog-title" id="consoleConfirmTitle">退出登录</div>
<div class="console-dialog-body" id="consoleConfirmText"
style="display:block;color:var(--dim);font-size:13px;line-height:1.7"></div>
<div class="console-dialog-foot">
<button type="button" class="act ghost" id="consoleConfirmCancel">取消</button>
<button type="button" class="act" id="consoleConfirmOk">确定</button>
</div>
</div>
</div>
</section>
<section class="page" id="page-products">
<h1>商品信息</h1>
<p class="desc">每个商品一张卡片,改动保存后立即生效。属性按「名称:内容」每行一条填写,长文本(如售后说明)直接写在内容里。</p>
<div id="productCards" class="prod-list"></div>
<div class="row" style="margin-top:12px">
<button class="act" id="btnAddProduct">新增商品</button>
<button class="act" id="btnSaveProducts">保存商品</button>
<button class="act ghost" id="btnReloadProducts">重新加载</button>
</div>
</section>
<section class="page" id="page-persona">
<h1>客服人格</h1>
<p class="desc">设定客服的自称、语气与话术风格,保存后立即应用到自动回复。人格设置保存在 persona.json,提示词保存在 system-prompt.md 与 reply-guidelines.md,统一由底部「保存设置」写入。</p>
<div class="row"><span style="width:110px;color:#8a8a8a">自称</span>
<input id="peSelfName" style="flex:1" placeholder="例如:小鱼"></div>
<div class="row"><span style="width:110px;color:#8a8a8a">称呼买家</span>
<input id="peCustomerTitle" style="flex:1" placeholder="例如:您 / 亲"></div>
<div class="row"><span style="width:110px;color:#8a8a8a">语气风格</span>
<input id="peTone" style="flex:1" placeholder="例如:亲切、专业、干脆,不用敬语套话"></div>
<div class="row"><span style="width:110px;color:#8a8a8a">回复长度</span>
<select id="peReplyLength" style="width:200px">
<option value="short">简短(1-2 句)</option>
<option value="medium">适中(3-4 句)</option>
<option value="long">详细(按需展开)</option>
</select>
<label class="hint" style="display:flex;align-items:center;gap:6px;margin-left:16px;cursor:pointer">
<input id="peUseEmoji" type="checkbox" style="width:16px;height:16px;min-width:0"> 允许使用表情符号</label>
</div>
<div class="row"><span style="width:110px;color:#8a8a8a">开场白</span>
<input id="peGreeting" style="flex:1" placeholder="一般对话不需要,留空即可"></div>
<div class="row"><span style="width:110px;color:#8a8a8a">结束语</span>
<input id="peClosing" style="flex:1" placeholder="留空即可"></div>
<div class="row" style="align-items:flex-start"><span style="width:110px;color:#8a8a8a">禁用词</span>
<textarea id="peBannedWords" spellcheck="false" style="min-height:92px" placeholder="每行一个,例如:绝对、保证、全网最低"></textarea></div>
<h2>提示词文件</h2>
<p class="hint">system-prompt.md 是发给模型的系统提示词;reply-guidelines.md 是通用回复要求,会截断后附在参考信息里。留空表示不使用,人格设定会追加在系统提示词后面。</p>
<div class="row" style="align-items:flex-start"><span style="width:110px;color:#8a8a8a">系统提示词</span>
<textarea id="taSystemPrompt" spellcheck="false" style="min-height:200px" placeholder="留空表示不使用自定义系统提示词"></textarea></div>
<div class="row" style="align-items:flex-start"><span style="width:110px;color:#8a8a8a">回复要求</span>
<textarea id="taReplyGuidelines" spellcheck="false" style="min-height:150px" placeholder="例如:先回答问题再补充说明;不确定的时效不要承诺"></textarea></div>
<div class="row" style="margin-top:12px">
<button class="act" id="btnSavePersona">保存设置</button>
<button class="act ghost" id="btnReloadPersona">重新加载</button>
</div>
</section>
<section class="page" id="page-knowledge">
<h1>知识库</h1>
<p class="desc">问答、售后、发货等知识统一放在这里。买家消息命中触发词时会作为参考资料传给模型。配置保存在 knowledge.json。</p>
<div class="row">
<input id="inKnowSearch" style="flex:1" placeholder="搜索标题 / 触发词 / 内容">
<button class="act" id="btnAddKnowledge">新增条目</button>
<button class="act ghost" id="btnSaveKnowledge">保存知识库</button>
<button class="act ghost" id="btnReloadKnowledge">重新加载</button>
</div>
<div id="knowledgeList" class="know-list"></div>
</section>
<section class="page" id="page-quick">
<h1>快捷回复</h1>
<p class="desc">买家消息命中关键词就直接发送这里的回复,不再调用模型。每张卡片分「触发条件」和「命中后发送」两块:填了「随机回复」就从里面随机挑一条发,留空则发「固定回复」。</p>
<h2>开场说明</h2>
<p class="hint">命中条件时,在正式回复前先单独发送一次这段说明。同一会话、同一订单只发一次。</p>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center;cursor:pointer">
<input id="greetEnabled" type="checkbox" style="width:16px;min-width:16px"> 启用开场说明</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px;cursor:pointer">
<input id="greetOnFirst" type="checkbox" style="width:16px;min-width:16px"> 买家咨询第一句时发送</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px;cursor:pointer">
<input id="greetOnOrder" type="checkbox" style="width:16px;min-width:16px"> 有新订单时发送</label>
</div>
<div class="row" style="align-items:flex-start">
<textarea id="greetText" class="know-content" spellcheck="false" style="min-height:110px"
placeholder="例如:默认按付款顺序处理,加急请直接留言;如需改尺寸请在发货前告知,发出后无法修改。"></textarea>
</div>
<div class="row" style="align-items:center">
<span style="width:72px;color:#8a8a8a">配图</span>
<button class="act ghost" id="btnGreetImages">选择配图</button>
<span class="hint" id="greetImageCount">未选择</span>
</div>
<div id="greetImagePreview" class="greet-thumbs"></div>
<div class="row" style="margin:8px 0 22px">
<button class="act" id="btnSaveGreeting">保存开场说明</button>
<button class="act ghost" id="btnReloadGreeting">重新加载</button>
</div>
<div id="ruleQuick" class="know-list"></div>
<div class="row" style="margin:12px 0 4px">
<button class="act" id="btnAddQuick">新增快捷回复</button>
<button class="act ghost" id="btnSaveQuick">保存快捷回复</button>
<button class="act ghost" id="btnReloadQuick">重新加载</button>
</div>
</section>
<section class="page" id="page-replyimg">
<h1>图片库</h1>
<p class="desc">图片库直接读取目录里的图片:默认是程序目录下的 images,也可以为当前店铺选择其他目录。把图片放进目录后点「重新扫描」即可,无需上传。配图的名称、AI 触发词与发送方式在「快捷回复」选择配图时设置。</p>
<div class="row">
<button class="act ghost" id="btnPickImageDir">选择目录</button>
<button class="act ghost" id="btnOpenImageDir">打开目录</button>
<button class="act" id="btnReloadReplyImage">重新扫描</button>
</div>
<p class="hint" id="picDir">当前目录:-</p>
<div id="replyImageList" class="img-gallery"></div>
</section>
<section class="page" id="page-risk">
<h1>风险意图</h1>
<p class="desc">命中关键词后:不自动回复买家,会话直接标记为人工处理,并按 mail.json 的配置给店主发告警邮件(需先在「系统设置」里启用邮件)。命中后不再调用模型,也不走转人工白名单。</p>
<p class="hint">界面里的「回复」和「默认回复」只作话术留档,当前引擎不会自动发送;需要自动发的固定话术请放到「快捷回复」。</p>
<div id="ruleRisk" class="know-list"></div>
<div class="row" style="margin:12px 0 4px">
<button class="act" id="btnAddRisk">新增风险意图</button>
<button class="act ghost" id="btnSaveRisk">保存风险意图</button>
<button class="act ghost" id="btnReloadRisk">重新加载</button>
</div>
<p class="hint">name 写 default 的条目表示默认风险意图,用于兜底提示;目前仍以关键词命中为准。</p>
</section>
<section class="page" id="page-rules">
<h1>转人工与话术</h1>
<p class="desc">转人工白名单决定哪些问题交给人工处理;语气示例作为模型参考话术。改动保存后立即生效。</p>
<h2>转人工白名单 manual-handoff-whitelist.json</h2>
<p class="hint">命中触发词(且未命中排除词)时,该会话交给人工处理,不再自动回复。语义说明用于分类模型判断,示例与反例可帮助模型区分边界情况。</p>
<div id="ruleHandoff" class="know-list"></div>
<div class="row" style="margin:12px 0 4px">
<button class="act" id="btnAddHandoff">新增转人工规则</button>
<button class="act ghost" id="btnSaveHandoff">保存转人工规则</button>
<button class="act ghost" id="btnReloadHandoff">重新加载</button>
</div>
<h2>语气示例 tone-examples.json</h2>
<p class="hint">给模型看的优秀回复范例,按与买家问题的相似度挑选若干条作为参考。notes 用来写这类情况的处理要点。</p>
<div id="ruleTone" class="know-list"></div>
<div class="row" style="margin:12px 0 4px">
<button class="act" id="btnAddTone">新增语气示例</button>
<button class="act ghost" id="btnSaveTone">保存语气示例</button>
<button class="act ghost" id="btnReloadTone">重新加载</button>
</div>
</section>
<section class="page" id="page-images">
<h1>图片保存</h1>
<p class="desc">买家在聊天里发送的图片会自动下载到本地,按下面的规则归档。改动保存后立即生效,已保存的文件不会被移动或删除。</p>
<h2>保存开关与位置</h2>
<div class="row"><label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgEnabled" type="checkbox" style="width:16px;min-width:16px"> 启用自动保存买家图片</label></div>
<div class="row"><label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgFileAsImage" type="checkbox" style="width:16px;min-width:16px"> 买家以文件形式发送的图片也保存并计数</label></div>
<p class="hint">买家有时不发聊天图片,而是以文件(如 001.jpg)发送。勾选后会在文件名气泡里找缩略图或下载链接,按普通买家图片一起归档、校验张数。</p>
<div class="row"><span style="width:120px;color:#8a8a8a">保存根目录</span>
<input id="imgDir" style="flex:1" placeholder="留空则保存到程序目录下的 output">
<button class="mini" id="btnPickImgDir">选择文件夹</button>
<button class="mini" id="btnOpenImgDir">打开目录</button></div>
<h2>目录规则</h2>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgGroupShop" type="checkbox" style="width:16px;min-width:16px"> 按店铺 ID 分目录</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px">
<input id="imgGroupOrder" type="checkbox" style="width:16px;min-width:16px"> 按订单号分目录</label></div>
<p class="hint" id="imgRulePreview"></p>
<h2>订单图片归属</h2>
<p class="hint">订单号与下单时间自动取自右侧「个人订单」面板(当前买家近 90 天订单),买家不需要在聊天里发订单号;店铺维度的「最新订单」不参与。</p>
<div class="row"><span style="width:120px;color:#8a8a8a">归属方案</span>
<select id="imgAssignMode" style="flex:1">
<option value="hybrid">融合(默认):下单时间相近的订单按顺序拆分,其余按时间匹配</option>
<option value="time">时间匹配:只按图片时间与下单时间归档</option>
<option value="sequence">顺序拆分:图片批次按订单先后一一对应</option>
<option value="sequence-reverse">倒序拆分:图片批次按订单从最新往前一一对应</option>
</select></div>
<div class="row">
<span style="width:120px;color:#8a8a8a">同时段阈值</span>
<input id="imgConcurrentSec" type="number" min="1" max="3600" style="width:110px"> 秒
<span style="width:90px;color:#8a8a8a;margin-left:18px">批次间隔</span>
<input id="imgBatchSec" type="number" min="30" max="3600" style="width:110px"> 秒
<span style="width:110px;color:#8a8a8a;margin-left:18px">先图后单缓冲</span>
<input id="imgHistorySec" type="number" min="60" max="86400" style="width:110px"> 秒</div>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgCountCheck" type="checkbox" style="width:16px;min-width:16px"> 按规格张数校验数量</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px">
<input id="imgReview" type="checkbox" style="width:16px;min-width:16px"> 归属不确定的图片放入「待确认」目录</label></div>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgCountNote" type="checkbox" style="width:16px;min-width:16px"> 数量不符时在订单文件夹名后加备注(如 订单号【少2张】)</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px">
<input id="imgReceiptReply" type="checkbox" style="width:16px;min-width:16px"> 数量不符时自动回复买家差值</label></div>
<div class="row">
<span style="width:110px;color:#8a8a8a">数量不足回复</span>
<input id="imgReceiptShortage" type="text" style="flex:1" placeholder="可用 {total} {expected} {gap} 占位符">
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">数量超出回复</span>
<input id="imgReceiptOverflow" type="text" style="flex:1" placeholder="可用 {total} {expected} {gap} 占位符">
</div>
<h2>商品关键词固定张数</h2>
<p class="hint">有些商品规格里写的「12张」是制作数量,买家实际只需要发 1 张原图。给这类商品配一条规则后,命中就按固定张数校验,不再解析规格里的「N张」,也不按件数累加。</p>
<div class="row" style="align-items:flex-start">
<span style="width:110px;color:#8a8a8a;padding-top:6px">固定规则</span>
<textarea id="imgKeywordFixedCount" spellcheck="false" style="flex:1;min-height:80px" placeholder="每行一条,格式:关键词 = 张数&#10;证件照 = 1&#10;签证照 = 1"></textarea>
</div>
<p class="hint">每行一条,用等号分隔,张数填买家实际需要发的图片张数(1~9999)。关键词会与订单里的商品名、规格比对,包含即命中;命中多条时以写在最上面的为准。留空表示不启用,仍按规格里的「N张」计算。</p>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgKeepOrderTab" type="checkbox" style="width:16px;min-width:16px"> 自动切到「个人订单」页签并保持(关闭则每次读完切回原页签)</label></div>
<h2>参与的订单状态</h2>
<p class="hint">勾选的订单类型会进入图片归属与模型上下文(用于回答订单号、下单时间、状态等);取消勾选的订单不会参与。</p>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="stNormal" type="checkbox" style="width:16px;min-width:16px"> 正常订单(待支付/待发货/已发货)</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px">
<input id="stDone" type="checkbox" style="width:16px;min-width:16px"> 已完成订单</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px">
<input id="stRefund" type="checkbox" style="width:16px;min-width:16px"> 退款/售后订单</label></div>
<p class="hint">同时段阈值:两张单下单时间相差在此范围内时改用顺序拆分;批次间隔:图片间隔超过此值算新的一批;先图后单缓冲:图片早于下单时间但未超过此值时仍归该单,超出则视为历史图,归入「历史未归属」。</p>
<h2>命名与去重</h2>
<p class="hint">文件名按 001.jpg、002.png… 顺序编号,顺序与买家发图顺序一致;目录里已存在的序号会自动跳过,不覆盖原文件。</p>
<p class="hint">订单号来自右侧订单面板;面板里读不到订单时图片归入「未归档订单」,归属不确定的归入「待确认」,早于所有订单的历史图归入「历史未归属」。同一订单后续补发的图片会接着已有编号继续排。</p>
<h2>买家图片调整</h2>
<p class="hint">买家发来新图并说「第2张替换掉」「第3张删掉」,或重发旧图后说「把这个换成这个」时,自动调整订单文件夹里已保存的图片;原图会移动到订单文件夹内的备份子目录,可随时找回。</p>
<div class="row">
<label class="hint" style="display:flex;gap:8px;align-items:center">
<input id="imgAdjust" type="checkbox" style="width:16px;min-width:16px"> 识别替换/删除第 N 张的调整指令</label>
<label class="hint" style="display:flex;gap:8px;align-items:center;margin-left:24px">
<input id="imgAdjustReply" type="checkbox" style="width:16px;min-width:16px"> 调整成功后回复买家确认</label></div>
<div class="row">
<span style="width:110px;color:#8a8a8a">替换回复</span>
<input id="imgAdjustReplace" type="text" style="flex:1" placeholder="可用 {index} {total} {expected} {gap} 占位符">
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">删除回复</span>
<input id="imgAdjustDelete" type="text" style="flex:1" placeholder="可用 {index} {total} {expected} {gap} 占位符">
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">原图备份目录</span>
<input id="imgReplacedDir" style="width:200px" placeholder="已替换">
<span class="hint" style="margin-left:12px">被替换/删除的原图会移到这里,目录位于订单文件夹内</span>
</div>
<h3>指令识别方式</h3>
<p class="hint">固定词:只用下面的识别词,不调用模型;固定词 + AI 兜底:识别词没命中、且消息提到图片时才问一次模型;AI 优先:固定词没命中也会问模型。模型只判断意图,实际替换/删除仍按序号或图片指纹确认,置信度低于阈值的识别结果不会执行。</p>
<div class="row">
<span style="width:110px;color:#8a8a8a">识别方式</span>
<select id="imgAdjustMode" style="width:220px">
<option value="rules">固定词</option>
<option value="hybrid">固定词 + AI 兜底</option>
<option value="ai">AI 优先</option>
</select>
<span style="width:80px;color:#8a8a8a;margin-left:16px">AI 置信度</span>
<input id="imgAdjustAiConfidence" type="number" min="0" max="1" step="0.05" style="width:100px" placeholder="0.75">
<span class="hint" style="margin-left:12px">0~1,默认 0.75,越高越保守</span>
</div>
<h3>指令识别词</h3>
<p class="hint">逗号分隔,可自行增删。只有出现这些词才按调整指令处理;「重新发」类词必须同时带序号或图片指向(如「这张重新发」)才生效,单独说「我重新发」只当作普通对话。删除类指令必须明确指向图片(「这张」「图」「照片」或「第N张」),「不需要了,谢谢」这类正常对话不会触发。</p>
<div class="row">
<span style="width:110px;color:#8a8a8a">替换词</span>
<input id="imgAdjustReplaceWords" type="text" style="flex:1" placeholder="替换,换成,换掉">
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">删除词</span>
<input id="imgAdjustDeleteWords" type="text" style="flex:1" placeholder="删掉,删除,不要">
<span class="hint" style="margin-left:12px">需配合「这张/图/照片」或第N张才删除</span>
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">重新发词</span>
<input id="imgAdjustResendWords" type="text" style="flex:1" placeholder="重新发,重发,补发">
<span class="hint" style="margin-left:12px">配合序号或指向词才按替换处理</span>
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">图片指向词</span>
<input id="imgAdjustPointWords" type="text" style="flex:1" placeholder="这个,这张,那张">
<span class="hint" style="margin-left:12px">用于「这个/这张」这类没有序号的指令</span>
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">否定词</span>
<input id="imgAdjustNegativeWords" type="text" style="flex:1" placeholder="不要,不用,别">
<span class="hint" style="margin-left:12px">否定词紧邻指令词时整句忽略,如「不用换」</span>
</div>
<div class="row">
<span style="width:110px;color:#8a8a8a">指纹匹配阈值</span>
<input id="imgAdjustThreshold" type="number" min="0" max="16" style="width:100px" placeholder="8">
<span class="hint" style="margin-left:12px">0~16,越小越严格;用于「重发旧图后换成新图」时定位是哪一张</span>
</div>
<div class="row" style="margin-top:12px">
<button class="act" id="btnSaveImageSettings">保存图片设置</button>
<button class="act ghost" id="btnReloadImageSettings">重新加载</button>
</div>
</section>
<section class="page" id="page-system">
<h1>系统设置</h1>
<p class="desc">操作节奏与检索参数保存在 server.json,邮件配置保存在 mail.json;模型接口请到「模型配置」页单独设置。监听端口、监听地址、访问密码与每日暂停时间属于本机,改动后需要重启程序;其余配置按左侧「当前店铺」独立保存,保存后立即生效。</p>
<h2>界面外观</h2>
<p class="desc">配色只影响本机界面,不随店铺切换,选择后立即生效并记住。</p>
<div class="theme-picker" id="themePicker">
<button class="theme-card" data-theme="dark">
<span class="theme-swatch dark"><i></i><i></i><i></i></span>
<span class="theme-name">黑色</span>
<span class="theme-desc">默认深色,长时间值守不刺眼</span>
</button>
<button class="theme-card" data-theme="light">
<span class="theme-swatch light"><i></i><i></i><i></i></span>
<span class="theme-name">白色</span>
<span class="theme-desc">明亮清爽,适合白天或投屏演示</span>
</button>
<button class="theme-card" data-theme="green">
<span class="theme-swatch green"><i></i><i></i><i></i></span>
<span class="theme-name">护眼绿</span>
<span class="theme-desc">浅豆沙绿底,长时间值守更护眼</span>
</button>
<button class="theme-card" data-theme="blue">
<span class="theme-swatch blue"><i></i><i></i><i></i></span>
<span class="theme-name">清新蓝</span>
<span class="theme-desc">浅蓝底色,强调色为清爽天蓝</span>
</button>
</div>
<h2>本地服务</h2>
<div class="row"><span style="width:120px;color:#8a8a8a">监听端口</span>
<input id="svPort" type="number" min="1" max="65535" style="width:120px" placeholder="3456">
<span style="width:100px;color:#8a8a8a;margin-left:16px">监听地址</span>
<input id="svHost" style="width:180px" placeholder="127.0.0.1">
<span class="hint" style="flex:1">填 0.0.0.0 允许手机在同一 WiFi 下访问控制页</span></div>
<div class="row"><span style="width:120px;color:#8a8a8a">访问密码</span>
<input id="svControlToken" style="flex:1" placeholder="留空表示不校验;填了之后手机控制页需带 ?token=密码"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">每日暂停时间</span>
<input id="svDailyPauseTime" style="width:120px" placeholder="07:50">
<span class="hint" style="flex:1">HH:MM,到点后暂停自动回复,第二天恢复;留空表示不暂停</span></div>
<h2>操作节奏</h2>
<div class="row"><span style="width:120px;color:#8a8a8a">回复随机延迟</span>
<input id="svMinDelay" type="number" min="0" style="width:100px" placeholder="3000">
<span style="color:#8a8a8a">~</span>
<input id="svMaxDelay" type="number" min="0" style="width:100px" placeholder="8000">
<span class="hint">毫秒;每次回复在区间内随机等待,避免固定节奏</span></div>
<div class="row"><span style="width:120px;color:#8a8a8a">页面操作延迟</span>
<input id="svPageMinDelay" type="number" min="0" style="width:100px" placeholder="150">
<span style="color:#8a8a8a">~</span>
<input id="svPageMaxDelay" type="number" min="0" style="width:100px" placeholder="400">
<span class="hint">毫秒;切换页签/页面时在区间内随机等待,避免操作过快</span></div>
<div class="row"><span style="width:120px;color:#8a8a8a">个人订单缓存</span>
<input id="svOrderCacheSec" type="number" min="0" style="width:100px" placeholder="300">
<span class="hint">秒;同一会话内复用订单数据的时长,避免右侧订单面板反复切换闪动。切换会话、买家提到下单/付款时仍会立即重读;填 0 表示每轮都重读</span></div>
<div class="row">
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer">
<input id="svRiskStopOnHit" type="checkbox" style="width:16px;height:16px;min-width:0"> 命中高危意图后停止该会话的自动回复</label>
<span class="hint" style="flex:1">勾选后命中风险意图即转人工,该会话后续消息都不再自动回复;取消勾选则只跳过当前这条,后续正常聊天继续回复(两种情况下都会发告警邮件)</span></div>
<h2>模型与检索</h2>
<div class="row"><span style="width:120px;color:#8a8a8a">分类模型</span>
<input id="svClassifierModel" style="flex:1" placeholder="留空则沿用回复模型">
<span style="width:100px;color:#8a8a8a;margin-left:16px">转人工分类</span>
<select id="svHandoffMode" style="width:190px">
<option value="ambiguous">仅模糊时调用模型</option>
<option value="always">总是调用模型</option>
<option value="off">关闭分类模型</option>
</select></div>
<div class="row"><span style="width:120px;color:#8a8a8a">商品候选数</span>
<input id="svMaxProducts" type="number" min="1" max="20" style="width:100px" placeholder="3">
<span style="width:100px;color:#8a8a8a;margin-left:16px">知识条目数</span>
<input id="svMaxFaq" type="number" min="1" max="20" style="width:100px" placeholder="5">
<span style="width:100px;color:#8a8a8a;margin-left:16px">语气示例数</span>
<input id="svMaxTone" type="number" min="0" max="20" style="width:100px" placeholder="3"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">回复要求字数</span>
<input id="svMaxGuidelines" type="number" min="0" style="width:110px" placeholder="1200">
<span style="width:120px;color:#8a8a8a;margin-left:16px">模型超时</span>
<input id="svModelTimeout" type="number" min="1000" style="width:120px" placeholder="45000">
<span class="hint">毫秒</span></div>
<div class="row">
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer">
<input id="svMock" type="checkbox" style="width:16px;height:16px;min-width:0"> 未配置 API Key 时使用本地兜底回复</label></div>
<h2>邮件告警 mail.json</h2>
<p class="hint">需要人工接手或命中风险意图时给店主发提醒邮件。QQ / 163 邮箱请先在邮箱设置里开启 SMTP 并生成授权码,授权码填在下面,或写到环境变量里。</p>
<div class="row">
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer;width:120px">
<input id="mailEnabled" type="checkbox" style="width:16px;height:16px;min-width:0"> 启用邮件</label>
<span style="width:70px;color:#8a8a8a">服务商</span><input id="mailProvider" style="width:110px" placeholder="qq / 163">
<span style="width:46px;color:#8a8a8a;margin-left:10px">服务器</span><input id="mailHost" style="flex:1" placeholder="smtp.qq.com">
<span style="width:40px;color:#8a8a8a;margin-left:10px">端口</span><input id="mailPort" type="number" min="1" max="65535" style="width:100px" placeholder="465"></div>
<div class="row">
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer;margin-right:18px">
<input id="mailSecure" type="checkbox" style="width:16px;height:16px;min-width:0"> 隐式 TLS(465 端口)</label>
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer;margin-right:18px">
<input id="mailStartTls" type="checkbox" style="width:16px;height:16px;min-width:0"> STARTTLS(587 端口)</label>
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer">
<input id="mailRejectUnauthorized" type="checkbox" style="width:16px;height:16px;min-width:0"> 校验服务器证书</label></div>
<div class="row"><span style="width:120px;color:#8a8a8a">登录账号</span>
<input id="mailUser" style="flex:1" placeholder="your-email@qq.com"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">授权码变量名</span>
<input id="mailAuthCodeEnv" style="width:240px" placeholder="PDD_MAIL_AUTH_CODE">
<span style="width:64px;color:#8a8a8a;margin-left:12px">授权码</span>
<input id="mailAuthCode" style="flex:1" placeholder="直接填授权码,或留空改用上面的环境变量"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">发件人</span>
<input id="mailFrom" style="flex:1" placeholder="一般与登录账号相同">
<span style="width:64px;color:#8a8a8a;margin-left:12px">显示名</span>
<input id="mailSenderName" style="width:180px" placeholder="PDD客服助手"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">收件人</span>
<input id="mailTo" style="flex:1" placeholder="多个邮箱用逗号分隔"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">抄送</span>
<input id="mailCc" style="flex:1" placeholder="多个邮箱用逗号分隔,留空即可"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">主题前缀</span>
<input id="mailSubjectPrefix" style="flex:1" placeholder="[PDD客服会话,需人工处理]"></div>
<div class="row"><span style="width:120px;color:#8a8a8a">告警去重</span>
<input id="mailDedupMs" type="number" min="0" style="width:160px" placeholder="600000">
<span class="hint" style="flex:1">毫秒;同一会话在此时长内只发一次,默认 600000(10 分钟)</span></div>
<div class="row" style="margin-top:12px">
<button class="act" id="btnSaveMail">保存邮件配置</button>
<button class="act ghost" id="btnTestMail">发送测试邮件</button>
</div>
<div class="row"><span class="hint" id="stMailTest" style="flex:1"></span></div>
<h2>提醒声音</h2>
<p class="hint">命中风险意图(转人工)时在本机播放提示音,与是否启用邮件无关。选择音频、勾选启用、清除都会立即保存,不需要再点其它保存按钮。</p>
<div class="row">
<label class="hint" style="display:flex;align-items:center;gap:6px;cursor:pointer;width:150px">
<input id="riskSoundEnabled" type="checkbox" style="width:16px;height:16px;min-width:0"> 启用提醒声音</label>
<input id="riskSoundPath" readonly style="flex:1" placeholder="未选择时使用系统默认提示音">
<button class="act ghost" id="btnPickRiskSound">选择音频</button>
<button class="act ghost" id="btnTestRiskSound">试听</button>
<button class="act ghost" id="btnClearRiskSound">清除</button>
</div>
<h2>聊天记录</h2>
<div class="row"><span style="width:120px;color:#8a8a8a">读取记录条数</span>
<select id="selHistoryMode" style="width:140px">
<option value="partial">部分</option>
<option value="all">全部</option>
</select>
<input id="inHistoryLimit" type="number" min="1" max="500" step="1" style="width:120px;margin-left:12px" placeholder="6">
<span class="hint" style="flex:1">「部分」读取最近 N 条(默认 6),「全部」会向上滚动加载完整历史</span></div>
<p class="hint" style="margin-top:8px">图片保存的路径与目录规则已独立到「图片保存」页。</p>
<div class="row" style="margin-top:10px">
<button class="act" id="btnSaveArchive">保存聊天记录设置</button>
</div>
<div class="row" style="margin-top:24px">
<button class="act" id="btnSaveServerOptions">保存系统设置</button>
<button class="act ghost" id="btnReloadServerOptions">重新加载</button>
</div>
<h2>配置备份</h2>
<p class="hint">导出为单个 JSON 备份包(含全局配置与所有店铺配置);导入会覆盖同名文件,并先把当前配置备份到 config/.backup-时间戳。</p>
<div class="row">
<button class="act" id="btnExportConfig">导出配置</button>
<button class="act ghost" id="btnImportConfig">导入配置</button>
<button class="act ghost" id="btnOpenConfigDir">打开配置目录</button>
</div>
</section>
<section class="page" id="page-model">
<h1>模型配置</h1>
<p class="desc">按列表顺序尝试:当前一个出现网络不通、429、5xx、超时或返回为空时,自动切换到下一个。配置保存在 server.json,按左侧「当前店铺」独立保存。</p>
<div id="modelList" class="model-list"></div>
<div class="row" style="margin-top:6px">
<button class="act ghost" id="btnAddModel">+ 添加模型</button>
<span style="width:64px;color:#8a8a8a;margin-left:12px">全局代理</span>
<input id="inProxy" style="flex:1" placeholder="留空则直连,例如 http://127.0.0.1:7890"></div>
<p class="hint" id="stModelState" style="margin-top:8px"></p>
<div class="row" style="margin-top:10px">
<button class="act" id="btnSaveModel">保存模型设置</button>
<button class="act ghost" id="btnTestModel">测试全部模型</button>
</div>
<div class="row"><span class="hint" id="stModelTest" style="flex:1"></span></div>
</section>
<section class="page" id="page-logs">
<h1>日志</h1>
<div class="row">
<button class="act ghost" id="btnRefreshLogs">刷新</button>
<input id="inLogFilter" placeholder="关键字过滤" style="width:220px">
<label class="hint" style="display:flex;gap:6px;align-items:center">
<input type="checkbox" id="chkLogAuto" style="width:auto"> 每 3 秒自动刷新
</label>
</div>
<textarea id="taLogs" spellcheck="false" readonly></textarea>
</section>
<section class="page" id="page-about">
<h1>关于</h1>
<p class="desc">拼多多客服助手 · 原生 Windows 客户端<br>
界面 WebView2 · 本地服务内置 · 客服台内嵌 WebView2</p>
<table>
<tr><th style="width:140px">版本</th><td id="abVer">—</td></tr>
<tr><th>监听端口</th><td id="abPort">3456</td></tr>
<tr><th>配置目录</th><td id="abCfg">—</td></tr>
</table>
<div class="row" style="margin-top:16px">
<button class="act ghost" id="btnOpenCfg">打开配置目录</button>
<button class="act" id="btnCheckUpdate">检查更新</button>
</div>
<div class="row" style="margin-top:10px"><span class="hint" id="updStatus"></span></div>
</section>
</div>
</div>
<div class="handles">
<div class="h-t" data-e="n"></div><div class="h-b" data-e="s"></div>
<div class="h-l" data-e="w"></div><div class="h-r" data-e="e"></div>
<div class="h-tl" data-e="nw"></div><div class="h-tr" data-e="ne"></div>
<div class="h-bl" data-e="sw"></div><div class="h-br" data-e="se"></div>
</div>
<div class="toast" id="toast"></div>
<div class="auth-overlay" id="authOverlay">
<div class="auth-box">
<div class="auth-title">拼多多客服助手</div>
<div class="auth-sub">首次使用需联网验证,登录后才能使用客服功能</div>
<div class="auth-tabs">
<button class="on" data-tab="login">登录</button>
<button data-tab="register">注册</button>
<button data-tab="recharge">卡密充值</button>
</div>
<div class="auth-pane on" data-pane="login">
<div class="auth-field"><label>账号</label><input data-k="username" autocomplete="username" placeholder="请输入账号"></div>
<div class="auth-field"><label>密码</label><input data-k="password" type="password" autocomplete="current-password" placeholder="请输入密码"></div>
<label class="auth-remember"><input type="checkbox" id="authRemember"> 记住账号密码</label>
</div>
<div class="auth-pane" data-pane="register">
<div class="auth-field"><label>账号</label><input data-k="username" autocomplete="username" placeholder="请设置账号"></div>
<div class="auth-field"><label>密码</label><input data-k="password" type="password" autocomplete="new-password" placeholder="至少 6 位"></div>
<div class="auth-field"><label>确认密码</label><input data-k="confirm" type="password" autocomplete="new-password" placeholder="再次输入密码"></div>
</div>
<div class="auth-pane" data-pane="recharge">
<div class="auth-field"><label>账号</label><input data-k="username" autocomplete="username" placeholder="要充值的账号"></div>
<div class="auth-field"><label>卡密</label><input data-k="card" placeholder="请输入卡密"></div>
</div>
<div class="auth-msg" id="authMsg">正在连接验证服务器…</div>
<div class="auth-actions">
<button class="act" id="authSubmit">登录</button>
<button class="act ghost" id="authRetry">重试验证</button>
</div>
<div class="auth-state" id="authStateLine">网络验证中</div>
</div>
</div>
<div class="img-modal" id="imgPicker">
<div class="img-modal-box">
<div class="img-modal-head">
<span>选择配图</span>
<button class="mini" id="imgPickerClose">关闭</button>
</div>
<div class="img-grid" id="imgPickerGrid"></div>
<div class="img-picker-settings" id="imgPickerSettings"></div>
<div class="row" style="margin-top:12px;justify-content:flex-end">
<button class="act ghost" id="imgPickerCancel">取消</button>
<button class="act" id="imgPickerOk">确定</button>
</div>
</div>
</div>
<div class="img-modal" id="shopDelModal">
<div class="img-modal-box" style="width:min(440px, 70vw)">
<div class="img-modal-head">
<span>删除店铺</span>
<button class="mini" id="shopDelClose">关闭</button>
</div>
<p class="hint" id="shopDelText" style="line-height:1.8"></p>
<div class="row" style="margin-top:16px;justify-content:flex-end">
<button class="act ghost" id="shopDelCancel">取消</button>
<button class="act" id="shopDelOk" style="background:var(--err);border-color:var(--err)">删除</button>
</div>
</div>
</div>
<div class="img-modal" id="shopAddModal">
<div class="img-modal-box" style="width:min(460px, 70vw)">
<div class="img-modal-head">
<span id="shopFormTitle">新增店铺</span>
<button class="mini" id="shopAddClose">关闭</button>
</div>
<div class="row"><span style="width:72px;color:#8a8a8a">店铺 ID</span>
<input id="shopAddId" style="flex:1" placeholder="例如 shop2"></div>
<div class="row"><span style="width:72px;color:#8a8a8a">店铺名</span>
<input id="shopAddName" style="flex:1" placeholder="留空则与 ID 相同"></div>
<div class="row"><span style="width:72px;color:#8a8a8a">Token</span>
<input id="shopAddToken" style="flex:1" placeholder="手机控制页访问本地服务用">
<button class="mini" id="shopTokenRegen" style="margin-left:8px">重新生成</button></div>
<p class="hint" id="shopAddTip" style="margin-top:8px">保存后会自动建立 config/shops/&lt;店铺ID&gt; 配置目录。</p>
<div class="row" style="margin-top:12px;justify-content:flex-end">
<button class="act ghost" id="shopAddCancel">取消</button>
<button class="act" id="shopAddOk">创建</button>
</div>
</div>
</div>
<script>
const $ = (s) => document.querySelector(s);
// ---------- 界面配色:本机偏好,保存到 config/ui.json ----------
const THEMES = ['dark', 'light', 'green', 'blue'];
function applyTheme(theme, persist) {
const next = THEMES.includes(theme) ? theme : 'dark';
document.documentElement.dataset.theme = next;
document.querySelectorAll('#themePicker .theme-card').forEach((card) => {
card.classList.toggle('on', card.dataset.theme === next);
});
if (persist) post({ type: 'saveTheme', theme: next });
}
applyTheme(window.__PDDAI_THEME__ || 'dark');
document.querySelectorAll('#themePicker .theme-card').forEach((card) => {
card.onclick = () => applyTheme(card.dataset.theme, true);
});
// 设置类消息必须带 shopId,读写的都是该店铺自己的配置目录
const SHOP_SCOPED_TYPES = new Set([
'getConfig', 'setConfig', 'getTextConfig', 'setTextConfig',
'getModel', 'saveModel', 'getServerOptions', 'saveServerOptions',
'getMail', 'saveMail', 'saveRiskSound', 'getImageSettings', 'saveImageSettings',
'saveArchive', 'testMail', 'testModel',
'getImageLibrary', 'saveImageLibrary', 'pickImageLibraryDir'
]);
const post = (obj) => {
if (obj && SHOP_SCOPED_TYPES.has(obj.type)) {
if (!consoleShopId) {
toast('请先在左侧「当前店铺」里选择一个店铺', false);
return;
}
obj = Object.assign({}, obj, { shopId: consoleShopId });
}
window.chrome.webview.postMessage(obj);
};
const handlers = {};
let toastTimer = null;
function toast(text, ok) {
const el = $('#toast');
el.textContent = text;
el.className = 'toast show ' + (ok ? 'ok' : 'err');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.className = 'toast ' + (ok ? 'ok' : 'err'); }, 2600);
}
window.chrome.webview.addEventListener('message', (e) => {
const d = e.data;
if (!d || !d.type) return;
const h = handlers[d.type];
if (h) h(d);
});
// ---------- 导航 ----------
const loaded = {};
let currentPage = 'status';
function switchPage(name) {
currentPage = name;
document.querySelectorAll('.nav a').forEach(x => x.classList.toggle('active', x.dataset.page === name));
// 目标页所在分组如果是折叠的,先展开,避免选中项看不见
const target = document.querySelector('.nav a[data-page="' + name + '"]');
const group = target && target.closest('.nav-group');
if (group && group.classList.contains('collapsed')) {
group.classList.remove('collapsed');
persistNavCollapsed();
}
document.querySelectorAll('.page').forEach(x => x.classList.toggle('active', x.id === 'page-' + name));
if (!loaded[name]) { loaded[name] = true; refreshPage(name); }
reportConsoleLayout();
}
document.querySelectorAll('.nav a').forEach(a => a.onclick = () => switchPage(a.dataset.page));
// ---------- 导航分组折叠 ----------
function persistNavCollapsed() {
const collapsed = [...document.querySelectorAll('.nav-group.collapsed')].map(g => g.dataset.group);
post({ type: 'saveNavCollapsed', value: collapsed.join(',') });
}
document.querySelectorAll('.nav-group').forEach((group) => {
group.querySelector('.nav-group-head').onclick = () => {
group.classList.toggle('collapsed');
persistNavCollapsed();
};
});
String(window.__PDDAI_NAV_COLLAPSED__ || '').split(',').forEach((id) => {
if (!id) return;
const group = document.querySelector('.nav-group[data-group="' + id + '"]');
if (group) group.classList.add('collapsed');
});
function refreshPage(name) {
if (name === 'console') post({ type: 'getShops' });
if (name === 'products') post({ type: 'getConfig', name: 'products.json' });
if (name === 'persona') {
post({ type: 'getConfig', name: 'persona.json' });
post({ type: 'getTextConfig', name: 'system-prompt.md' });
post({ type: 'getTextConfig', name: 'reply-guidelines.md' });
}
if (name === 'knowledge') post({ type: 'getConfig', name: 'knowledge.json' });
if (name === 'quick') {
post({ type: 'getConfig', name: 'quick-replies.json' });
post({ type: 'getConfig', name: 'greeting.json' });
post({ type: 'getImageLibrary' });
}
if (name === 'replyimg') post({ type: 'getImageLibrary' });
if (name === 'risk') post({ type: 'getConfig', name: 'risk-intents.json' });
if (name === 'rules') {
post({ type: 'getConfig', name: 'manual-handoff-whitelist.json' });
post({ type: 'getConfig', name: 'tone-examples.json' });
}
if (name === 'images') post({ type: 'getImageSettings' });
if (name === 'system') {
// 系统设置只负责本机服务、操作节奏与邮件
post({ type: 'getMail' });
post({ type: 'getServerOptions' });
}
if (name === 'model') {
// 先取服务商列表,再取当前模型配置
if (loaded.modelDone) post({ type: 'getModel' }); else post({ type: 'getPresets' });
}
if (name === 'logs') post({ type: 'getLogs' });
if (name === 'browser') post({ type: 'getBrowser' });
}
// 这些页面的数据都属于单个店铺,切店铺时要重新加载
const SHOP_PAGES = new Set(['products', 'persona', 'knowledge', 'quick', 'replyimg', 'risk', 'rules', 'images', 'model', 'system']);
function updateScopeChip() {
const chip = $('#scopeChip');
if (!chip) return;
const id = typeof consoleShopId === 'string' ? consoleShopId : null;
chip.textContent = '当前店铺:' + (id ? shopLabel(id) : '未打开');
chip.classList.toggle('none', !id);
}
function refreshShopScopedPage() {
if (currentPage && SHOP_PAGES.has(currentPage) && loaded[currentPage]) refreshPage(currentPage);
}
function setShopScope(id) {
const changed = consoleShopId !== id;
consoleShopId = id || null;
if (changed) closeImagePicker();
updateScopeChip();
document.querySelectorAll('#shopList .shop-item').forEach(el => {
el.classList.toggle('on', el.dataset.id === (consoleShopId || ''));
});
updateShopComboText();
if (changed) refreshShopScopedPage();
}
// 统一入口:切店铺一律走这里,把「当前店铺」「工作台标签」「原生 WebView2 画面」
// 三者一次对齐。以前在其它页面只改作用域、等进工作台再补标签,启动或跨页切换时
// 就会出现左侧显示 A、标签却是空的或另一个店铺。
function switchShop(id) {
if (!id) {
setShopScope(null);
renderTabs();
return;
}
activateTab(id, 'chat');
}
// 左侧「当前店铺」组合框:点条目切换,点 ✕ 弹窗确认删除,底部可新增
let navShopRows = [];
function shopLabelOf(id) {
const row = navShopRows.find(r => r.id === id);
return row ? (row.name || row.id) : id;
}
function updateShopComboText() {
$('#shopComboText').textContent = consoleShopId ? shopLabelOf(consoleShopId) : '未配置店铺';
}
function openShopCombo() {
// 用组合框自身的矩形定位,宽度与按钮完全一致;fixed 可越过导航的滚动裁剪
const trigger = $('#shopComboTrigger');
const panel = $('#shopComboPanel');
const rect = trigger.getBoundingClientRect();
panel.style.left = rect.left + 'px';
panel.style.top = (rect.bottom + 4) + 'px';
panel.style.width = rect.width + 'px';
panel.classList.add('show');
trigger.classList.add('open');
}
function closeShopCombo() {
$('#shopComboPanel').classList.remove('show');
$('#shopComboTrigger').classList.remove('open');
}
function toggleShopCombo() {
if ($('#shopComboPanel').classList.contains('show')) closeShopCombo();
else openShopCombo();
}
$('#shopComboTrigger').onclick = toggleShopCombo;
document.addEventListener('mousedown', (e) => {
if (!e.target.closest('#shopCombo')) closeShopCombo();
});
// 面板 fixed 定位,外层滚动时收起,避免与按钮错位
document.addEventListener('scroll', (e) => {
if (e.target && e.target.closest && e.target.closest('#shopCombo')) return;
closeShopCombo();
}, true);
function renderShopList(rows) {
navShopRows = rows || [];
const box = $('#shopList');
if (!box) return;
if (!navShopRows.length) {
box.innerHTML = '<div class="hint" style="padding:4px 8px 6px">还没有店铺,点下方新增</div>';
updateShopComboText();
return;
}
box.innerHTML = navShopRows.map(r =>
'<div class="shop-item' + (r.id === consoleShopId ? ' on' : '') + '" data-id="' + esc(r.id) +
'" title="' + esc(r.name || r.id) + '">' +
'<span class="shop-item-name">' + esc(r.name || r.id) + '</span>' +
'<button class="shop-item-edit" data-edit="' + esc(r.id) + '" title="编辑店铺">✎</button>' +
'<button class="shop-item-del" data-del="' + esc(r.id) + '" title="删除店铺">✕</button>' +
'</div>').join('');
box.querySelectorAll('.shop-item').forEach(el => {
el.onclick = () => { switchShop(el.dataset.id); closeShopCombo(); };
});
box.querySelectorAll('.shop-item-edit').forEach(btn => {
btn.onclick = (e) => { e.stopPropagation(); openShopEditModal(btn.dataset.edit); };
});
box.querySelectorAll('.shop-item-del').forEach(btn => {
btn.onclick = (e) => {
e.stopPropagation();
closeShopCombo();
openShopDelModal(btn.dataset.del);
};
});
updateShopComboText();
}
// ---------- 左侧店铺的新增 / 编辑 / 删除 ----------
let shopDelId = null;
let shopFormMode = 'add';
let shopFormId = null;
function openShopDelModal(id) {
const row = navShopRows.find(r => r.id === id);
shopDelId = id;
closeShopCombo();
$('#shopDelText').textContent = '确定删除店铺「' + ((row && (row.name || row.id)) || id) +
'」吗?删除后它会从店铺列表和客服台标签中移除,但配置文件目录 config/shops/' + id + ' 会保留,重新添加同 ID 店铺即可继续使用。';
$('#shopDelModal').style.display = 'flex';
}
function closeShopDelModal() {
$('#shopDelModal').style.display = 'none';
shopDelId = null;
}
$('#shopDelClose').onclick = closeShopDelModal;
$('#shopDelCancel').onclick = closeShopDelModal;
$('#shopDelOk').onclick = () => {
const id = shopDelId;
if (!id) return;
const rows = navShopRows.filter(r => r.id !== id);
closeShopDelModal();
persistShops(rows);
// 删掉的正好是当前店铺时,切到剩下的第一个
if (consoleShopId === id) switchShop(rows.length ? rows[0].id : null);
renderShopList(rows);
toast('已删除店铺 ' + id, true);
};
function openShopAddModal() {
closeShopCombo();
let n = navShopRows.length + 1;
const used = new Set(navShopRows.map(r => r.id));
while (used.has('shop' + n)) n++;
shopFormMode = 'add';
shopFormId = null;
$('#shopFormTitle').textContent = '新增店铺';
$('#shopAddId').value = 'shop' + n;
$('#shopAddId').disabled = false;
$('#shopAddName').value = '';
$('#shopAddToken').value = '';
$('#shopAddOk').textContent = '创建';
$('#shopAddTip').textContent = '保存后会自动建立 config/shops/<店铺ID> 配置目录。Token 留空则不校验。';
$('#shopAddModal').style.display = 'flex';
$('#shopAddId').focus();
}
function openShopEditModal(id) {
const row = navShopRows.find(r => r.id === id);
if (!row) return;
closeShopCombo();
shopFormMode = 'edit';
shopFormId = id;
$('#shopFormTitle').textContent = '编辑店铺';
$('#shopAddId').value = row.id;
$('#shopAddId').disabled = true;
$('#shopAddName').value = row.name || row.id;
$('#shopAddToken').value = row.token || '';
$('#shopAddOk').textContent = '保存';
$('#shopAddTip').textContent = 'Token 用于手机控制页访问本地服务,留空则不校验。';
$('#shopAddModal').style.display = 'flex';
$('#shopAddName').focus();
}
function closeShopAddModal() {
$('#shopAddModal').style.display = 'none';
shopFormMode = 'add';
shopFormId = null;
}
$('#btnNavAddShop').onclick = openShopAddModal;
$('#shopAddClose').onclick = closeShopAddModal;
$('#shopAddCancel').onclick = closeShopAddModal;
$('#shopTokenRegen').onclick = () => { $('#shopAddToken').value = randomToken(); };
$('#shopAddOk').onclick = () => {
const id = $('#shopAddId').value.trim();
const name = $('#shopAddName').value.trim() || id;
const token = $('#shopAddToken').value.trim();
if (!id) { $('#shopAddTip').textContent = '店铺 ID 不能为空'; return; }
if (!/^[A-Za-z0-9_-]+$/.test(id)) { $('#shopAddTip').textContent = '店铺 ID 只能包含字母、数字、下划线和短横线'; return; }
if (shopFormMode === 'edit') {
const rows = navShopRows.map(r => r.id === shopFormId ? { ...r, name: name, token: token } : r);
closeShopAddModal();
persistShops(rows);
renderShopList(rows);
toast('已保存店铺 ' + id, true);
return;
}
if (navShopRows.some(r => r.id === id)) { $('#shopAddTip').textContent = '店铺 ID 已存在,请换一个'; return; }
const rows = navShopRows.concat([{ id: id, name: name, token: token, paused: false }]);
closeShopAddModal();
persistShops(rows);
renderShopList(rows);
switchShop(id);
toast('已新增店铺 ' + id, true);
};
// 保存店铺列表(左侧组合框共用同一份 shops.json)
function persistShops(rows) {
const payload = rows.map(r => ({
id: String(r.id || '').trim(),
name: String(r.name || r.id || '').trim(),
pluginToken: String(r.token || '').trim()
}));
post({ type: 'saveShops', text: JSON.stringify(payload, null, 2) });
}
// ---------- 状态页 ----------
handlers.status = (d) => {
$('#stServer').textContent = d.running ? '运行中' : '未启动';
$('#stServer').className = 'v ' + (d.running ? 'ok' : 'err');
$('#stAddr').textContent = d.addr || '—';
$('#stShops').textContent = d.shops ?? 0;
$('#abPort').textContent = d.port || (d.addr || '').split(':').pop() || '3456';
$('#abCfg').textContent = d.configDir || '—';
$('#abVer').textContent = 'v' + (d.version || '0.0.0');
const s = d.stats || {};
$('#stReply').textContent = s.reply ?? 0;
$('#stManual').textContent = s.manual ?? 0;
$('#stMail').textContent = s.mail ?? 0;
$('#stFail').textContent = s.fail ?? 0;
const urls = d.lanUrls || [];
const box = $('#lanBox');
if (!urls.length) {
box.innerHTML = '<span class="hint">当前监听 ' + (d.host || '127.0.0.1') +
',只能本机访问。把 server.json 的 <code>host</code> 改为 <code>0.0.0.0</code> 并重启,手机即可在同一 WiFi 下打开控制页。</span>';
return;
}
const tokenTip = d.hasControlToken
? '<span class="hint">已设置 controlToken,访问时需在链接后加 <code>?token=你的密码</code>。</span>'
: '';
box.innerHTML = urls.map(u => '<a href="' + u + '/control" target="_blank">' + u + '/control</a>').join('') + tokenTip;
};
// ---------- 客服工作台:每个店铺一个标签页 ----------
// 标签栏由前端绘制,内容区交给原生 WebView2 覆盖(每个店铺独立 cookie,互不串台)。
// 标签可手动开关:右上角 + 打开已配置的店铺,标签上的 × 关闭并销毁它的 WebView2。
let consoleRows = []; // shops.json 里的全部店铺
let openTabs = []; // 当前打开的标签(按顺序)
let consoleShopId = null; // 当前激活的店铺
let consoleView = 'chat'; // 当前激活的视图:'chat' 客服台 / 'backend' 商家后台
let activeShop = ''; // 上次使用的店铺(后端从 ui.json 恢复),首屏优先打开它
let consoleAutoOpened = false;
let dragTabId = null; // 正在拖动的标签(拖动排序用)
function shopLabel(id) {
const s = consoleRows.find(x => x.id === id);
return s ? (s.name || s.id) : id;
}
function renderTabs() {
const list = $('#consoleTabList');
list.innerHTML = openTabs.map(id => {
const row = consoleRows.find(x => x.id === id);
// 圆点颜色:暂停=黄,自动模式=绿,调试模式=蓝,未上报=灰
const mode = row && row.mode;
const dot = !row ? 'off' : row.paused ? 'warn' : mode === 'auto' ? 'ok' : mode === 'debug' ? 'info' : 'off';
const dotTitle = !row ? '状态未知'
: row.paused ? '服务已暂停'
: mode === 'auto' ? '自动模式 · 服务中'
: mode === 'debug' ? '调试模式 · 服务中'
: '插件未上报模式';
const chatActive = id === consoleShopId && consoleView === 'chat';
const backendActive = id === consoleShopId && consoleView === 'backend';
return '<div class="console-tab' + (chatActive ? ' active' : '') + '">' +
'<button type="button" class="console-tab-open" data-id="' + esc(id) + '" data-view="chat">' +
'<span class="tab-dot ' + dot + '" title="' + dotTitle + '"></span>' +
esc(shopLabel(id)) + '</button>' +
'<button type="button" class="console-tab-x" data-close="' + esc(id) +
'" aria-label="关闭 ' + esc(shopLabel(id)) + '">×</button>' +
'</div>' +
// 商家后台:和客服台共用同一配置目录,登录态直接共享
'<div class="console-tab view-backend' + (backendActive ? ' active' : '') + '">' +
'<button type="button" class="console-tab-open" data-id="' + esc(id) +
'" data-view="backend" title="拼多多商家后台,与客服台共享登录态">' +
esc(shopLabel(id)) + '<span class="tab-view">后台</span></button>' +
'</div>';
}).join('');
list.querySelectorAll('.console-tab').forEach(tab => {
const open = tab.querySelector('.console-tab-open');
const id = open.dataset.id;
const view = open.dataset.view;
open.onclick = () => activateTab(id, view);
const close = tab.querySelector('.console-tab-x');
if (close) close.onclick = (e) => {
e.stopPropagation();
closeTab(id);
};
tab.draggable = true;
tab.ondragstart = (e) => {
dragTabId = id;
tab.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
try { e.dataTransfer.setData('text/plain', id); } catch (_) {}
};
tab.ondragend = () => {
dragTabId = null;
tab.classList.remove('dragging');
list.querySelectorAll('.console-tab').forEach(t => t.classList.remove('drop-before', 'drop-after'));
};
tab.ondragover = (e) => {
if (!dragTabId) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const rect = tab.getBoundingClientRect();
const after = e.clientX > rect.left + rect.width / 2;
list.querySelectorAll('.console-tab').forEach(t => {
if (t !== tab) t.classList.remove('drop-before', 'drop-after');
});
tab.classList.toggle('drop-before', !after);
tab.classList.toggle('drop-after', after);
};
tab.ondragleave = () => tab.classList.remove('drop-before', 'drop-after');
tab.ondrop = (e) => {
e.preventDefault();
const from = dragTabId || e.dataTransfer.getData('text/plain');
const rect = tab.getBoundingClientRect();
const after = e.clientX > rect.left + rect.width / 2;
moveTab(from, id, after);
};
});
}
// 拖动排序:把 fromId 移动到 toId 前/后,只影响标签顺序,不影响原生客服台
function moveTab(fromId, toId, after) {
if (!fromId || !toId || fromId === toId) return;
const from = openTabs.indexOf(fromId);
const to = openTabs.indexOf(toId);
if (from < 0 || to < 0) return;
openTabs.splice(from, 1);
let idx = openTabs.indexOf(toId);
if (after) idx += 1;
openTabs.splice(idx, 0, fromId);
renderTabs();
}
function renderConsoleTabs(rows) {
consoleRows = rows;
// 配置里删掉的店铺,顺手关掉它的页面和标签
openTabs = openTabs.filter(id => {
if (rows.some(s => s.id === id)) return true;
post({ type: 'closeConsole', shopId: id });
return false;
});
if (consoleShopId && !rows.some(s => s.id === consoleShopId)) consoleShopId = null;
// 首次拿到店铺列表就对齐三者,不依赖当前是不是工作台页:启动默认停在服务状态页,
// 若等到进入工作台才补标签,就会出现「当前店铺」和标签对不上的空窗期。
// activeShop 是上次使用的店铺,优先恢复它,避免重启后总是跳回列表第一家。
if (!consoleAutoOpened && rows.length) {
consoleAutoOpened = true;
const preferred = [consoleShopId, activeShop, rows[0].id]
.find(id => id && rows.some(r => r.id === id));
activateTab(preferred, 'chat');
return; // activateTab 已完成 renderTabs / updateScopeChip / 上报布局
}
// 后续同步(店铺列表会定时刷新):当前作用域店铺一定要有对应标签
if (consoleShopId && !openTabs.includes(consoleShopId)) openTabs.push(consoleShopId);
if ($('#page-console').classList.contains('active') && !openTabs.length) {
$('#consoleEmpty').textContent = rows.length
? '没有打开的店铺,点右上角 + 打开'
: '还没有店铺,请先在左侧「当前店铺」里新增';
}
renderTabs();
updateScopeChip();
}
function activateTab(id, view) {
consoleAutoOpened = true;
if (!openTabs.includes(id)) openTabs.push(id);
consoleView = view === 'backend' ? 'backend' : 'chat';
setShopScope(id);
// 记住当前店铺,下次启动直接打开它
activeShop = id;
post({ type: 'setActiveShop', shopId: id });
renderTabs();
$('#consoleEmpty').textContent = consoleView === 'backend' ? '正在打开商家后台…' : '正在打开客服台…';
post({ type: 'openConsole', shopId: id, view: consoleView });
reportConsoleLayout();
}
function closeTab(id) {
const idx = openTabs.indexOf(id);
if (idx < 0) return;
openTabs.splice(idx, 1);
post({ type: 'closeConsole', shopId: id });
if (consoleShopId === id) {
consoleView = 'chat';
setShopScope(openTabs[idx] || openTabs[idx - 1] || null);
if (consoleShopId) {
$('#consoleEmpty').textContent = '正在打开客服台…';
post({ type: 'openConsole', shopId: consoleShopId, view: 'chat' });
} else {
$('#consoleEmpty').textContent = consoleRows.length
? '没有打开的店铺,点右上角 + 打开'
: '还没有店铺,请先到「店铺配置」添加';
}
}
renderTabs();
reportConsoleLayout();
}
// 打开店铺选择框:只列配置里还没开的店铺
function openConsolePicker() {
const body = $('#consolePickerBody');
const candidates = consoleRows.filter(s => !openTabs.includes(s.id));
if (!consoleRows.length) {
body.innerHTML = '<p class="hint">还没有配置店铺。先到「店铺配置」里新增并保存,这里就能打开。</p>';
} else if (!candidates.length) {
body.innerHTML = '<p class="hint">配置里的店铺都已经打开了。</p>';
} else {
body.innerHTML = candidates.map(s =>
'<button type="button" class="picker-item" data-id="' + esc(s.id) + '">打开 ' +
esc(s.name || s.id) + '</button>').join('');
body.querySelectorAll('.picker-item').forEach(el => el.onclick = () => {
closeConsolePicker();
activateTab(el.dataset.id);
});
}
$('#consoleMask').classList.add('show');
// 遮罩要盖在内容区上,先把原生 WebView2 收起来,否则它会盖在弹窗上面
reportConsoleLayout();
}
function closeConsolePicker() {
$('#consoleMask').classList.remove('show');
reportConsoleLayout();
}
$('#consoleAdd').onclick = openConsolePicker;
// 不能用 alert/confirm:它们是 WebView2 的原生模态对话框,会被置顶的客服台子窗口
// 盖住,用户点不到,界面就一直卡在等待输入的状态。改成自绘弹窗,弹出时顺带把
// 客服台挪走(见 overlayCoversConsole)。
let consoleConfirmAction = null;
function askConsoleConfirm(title, text, onOk) {
$('#consoleConfirmTitle').textContent = title;
$('#consoleConfirmText').textContent = text;
consoleConfirmAction = onOk;
$('#consoleConfirmMask').classList.add('show');
reportConsoleLayout();
}
function closeConsoleConfirm() {
$('#consoleConfirmMask').classList.remove('show');
consoleConfirmAction = null;
reportConsoleLayout();
}
$('#consoleConfirmCancel').onclick = closeConsoleConfirm;
$('#consoleConfirmOk').onclick = () => {
const action = consoleConfirmAction;
closeConsoleConfirm();
if (action) action();
};
$('#consoleConfirmMask').onclick = (e) => {
if (e.target === $('#consoleConfirmMask')) closeConsoleConfirm();
};
$('#consoleLogout').onclick = () => {
if (!consoleShopId) { toast('请先打开一个店铺标签', false); return; }
const id = consoleShopId;
askConsoleConfirm('退出登录',
'退出「' + shopLabel(id) + '」的拼多多登录?页面会回到登录页,需要重新扫码登录。',
() => post({ type: 'logoutConsole', shopId: id }));
};
$('#consolePickerCancel').onclick = closeConsolePicker;
$('#consoleMask').onclick = (e) => {
if (e.target === $('#consoleMask')) closeConsolePicker();
};
addEventListener('keydown', (e) => {
if (e.key !== 'Escape') return;
if ($('#shopComboPanel').classList.contains('show')) { closeShopCombo(); return; }
if ($('#consoleMask').classList.contains('show')) { closeConsolePicker(); return; }
if ($('#consoleConfirmMask').classList.contains('show')) { closeConsoleConfirm(); return; }
if ($('#shopDelModal').style.display === 'flex') { closeShopDelModal(); return; }
if ($('#shopAddModal').style.display === 'flex') closeShopAddModal();
});
// 这些浮层盖在客服工作台区域上方,但原生 WebView2 是独立子窗口,永远画在 HTML 之上,
// 所以只要它们出现,就让原生把客服台挪走,避免充值弹窗被挡住
function overlayCoversConsole() {
if ($('#consoleMask').classList.contains('show')) return true;
if ($('#consoleConfirmMask').classList.contains('show')) return true; // 退出登录确认
if ($('#accPop').classList.contains('on')) return true; // 标题栏账号/充值弹窗
const overlay = $('#authOverlay');
if (overlay && getComputedStyle(overlay).display !== 'none') return true; // 验证/充值全屏页
if ($('#shopAddModal').style.display === 'flex' || $('#shopDelModal').style.display === 'flex') return true;
return false;
}
// 内容区矩形上报给原生;原生按这个矩形摆放并显示当前店铺的 WebView2
function reportConsoleLayout() {
// 不在客服工作台、或浮层开着时,让原生把客服台收起来
const blocked = !$('#page-console').classList.contains('active') || overlayCoversConsole();
document.body.classList.toggle('console-hidden', blocked);
if (blocked) {
post({ type: 'consoleLayout', visible: false });
return;
}
const r = $('#consoleHost').getBoundingClientRect();
if (r.width < 1 || r.height < 1) return;
post({ type: 'consoleLayout', visible: true,
x: Math.round(r.left), y: Math.round(r.top),
w: Math.round(r.width), h: Math.round(r.height) });
}
addEventListener('resize', () => reportConsoleLayout());
new ResizeObserver(() => reportConsoleLayout()).observe($('#consoleHost'));
// 账号弹窗与验证页显隐时同步收起/恢复内嵌客服台
new MutationObserver(() => reportConsoleLayout())
.observe($('#accPop'), { attributes: true, attributeFilter: ['class'] });
new MutationObserver(() => reportConsoleLayout())
.observe($('#authOverlay'), { attributes: true, attributeFilter: ['style', 'class'] });
// ---------- 店铺(左侧组合框管理) ----------
handlers.shops = (d) => {
const rows = d.rows || [];
// 只在首屏采纳后端记录的上次店铺,之后以界面上的实际选择为准
if (!consoleAutoOpened && typeof d.activeShop === 'string' && d.activeShop) {
activeShop = d.activeShop;
}
renderConsoleTabs(rows);
renderShopList(rows);
if (!consoleShopId && rows.length) switchShop(activeShop || rows[0].id);
else updateScopeChip();
};
$('#btnExportConfig').onclick = () => post({ type: 'exportConfig' });
$('#btnImportConfig').onclick = () => {
if (confirm('导入配置会覆盖同名的现有配置(原配置会先自动备份),继续吗?')) {
post({ type: 'importConfig' });
}
};
$('#btnOpenConfigDir').onclick = () => post({ type: 'openConfigDir' });
handlers.configImported = () => {
post({ type: 'getShops' });
refreshPage(currentPage);
};
// 客服台面板 / 手机控制页切换监听状态后,刷新店铺列表
handlers.shopStateChanged = () => post({ type: 'getShops' });
function esc(v) { return String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;'); }
function randomToken() {
const a = new Uint8Array(12);
crypto.getRandomValues(a);
return Array.from(a).map(b => b.toString(16).padStart(2, '0')).join('');
}
// ---------- 配置读取分发 ----------
handlers.config = (d) => {
if (!d.ok) { toast('读取 ' + d.name + ' 失败:' + (d.error || ''), false); return; }
if (d.name === 'products.json') { loadProducts(d.text); return; }
if (d.name === 'persona.json') { loadPersona(d.text); return; }
if (d.name === 'knowledge.json') { loadKnowledge(d.text); return; }
if (d.name === 'quick-replies.json') { loadRuleSection('quick', d.text); return; }
if (d.name === 'greeting.json') { loadGreeting(d.text); return; }
if (d.name === 'risk-intents.json') { loadRuleSection('risk', d.text); return; }
if (d.name === 'manual-handoff-whitelist.json') { loadRuleSection('handoff', d.text); return; }
if (d.name === 'tone-examples.json') { loadRuleSection('tone', d.text); return; }
};
handlers.textconfig = (d) => {
if (!d.ok) { toast('读取 ' + d.name + ' 失败:' + (d.error || ''), false); return; }
if (d.name === 'system-prompt.md') $('#taSystemPrompt').value = d.text || '';
if (d.name === 'reply-guidelines.md') $('#taReplyGuidelines').value = d.text || '';
};
// ---------- 商品信息 ----------
let products = [];
let productsDirty = false;
function splitList(text) {
return String(text || '').split(/[、,,;;\s]+/).map(s => s.trim()).filter(Boolean);
}
function attrsToText(attrs) {
return (attrs || []).map(a => a.k + ':' + a.v).join('\n');
}
function parseAttrsText(text) {
return String(text || '').split(/\r?\n/).map(line => {
const t = line.trim();
if (!t) return null;
const idx = t.search(/[::]/);
if (idx < 0) return { k: t, v: '' };
return { k: t.slice(0, idx).trim(), v: t.slice(idx + 1).trim() };
}).filter(Boolean);
}
function normalizeProduct(p) {
const raw = (p && typeof p.attributes === 'object' && p.attributes) ? p.attributes : {};
return {
id: p && p.id != null ? p.id : null,
name: String((p && p.name) || ''),
aliases: Array.isArray(p && p.aliases) ? p.aliases.slice() : [],
attributes: Object.keys(raw).map(k => ({ k, v: String(raw[k] == null ? '' : raw[k]) }))
};
}
function loadProducts(text) {
if (productsDirty) return; // 有未保存改动时不覆盖
let arr = [];
try { arr = JSON.parse(text || '[]'); } catch (e) { toast('products.json 解析失败:' + e.message, false); return; }
if (!Array.isArray(arr)) arr = [];
products = arr.map(normalizeProduct);
productsDirty = false;
renderProducts();
}
function renderProducts() {
const box = $('#productCards');
if (!products.length) {
box.innerHTML = '<p class="hint">还没有商品,点「新增商品」开始添加。</p>';
return;
}
box.innerHTML = products.map((p, i) =>
'<div class="prod-card">' +
'<div class="head">' +
'<span class="lbl">商品 ' + (i + 1) + '</span>' +
'<input data-i="' + i + '" data-k="name" style="flex:1" placeholder="商品名称" value="' + esc(p.name) + '">' +
'<button class="mini del" data-del="' + i + '">删除</button>' +
'</div>' +
'<div class="row" style="margin-bottom:8px"><span class="lbl">别名</span>' +
'<input data-i="' + i + '" data-k="aliases" style="flex:1" placeholder="多个别名用逗号或顿号分隔" value="' +
esc(p.aliases.join('、')) + '"></div>' +
'<div class="row" style="margin:0;align-items:flex-start"><span class="lbl">属性</span>' +
'<textarea class="attr" data-i="' + i + '" data-k="attributes" spellcheck="false" ' +
'placeholder="每行一条,格式:属性名:内容">' + esc(attrsToText(p.attributes)) + '</textarea></div>' +
'</div>').join('');
box.querySelectorAll('input[data-k],textarea[data-k]').forEach(el => el.oninput = () => {
const i = +el.dataset.i, k = el.dataset.k;
if (k === 'name') products[i].name = el.value;
else if (k === 'aliases') products[i].aliases = splitList(el.value);
else if (k === 'attributes') products[i].attributes = parseAttrsText(el.value);
productsDirty = true;
});
box.querySelectorAll('button[data-del]').forEach(b => b.onclick = () => {
products.splice(+b.dataset.del, 1);
productsDirty = true;
renderProducts();
});
}
$('#btnAddProduct').onclick = () => {
const used = new Set(products.map(p => p.id));
let id = 1;
while (used.has(id)) id++;
products.push(normalizeProduct({ id, name: '', aliases: [], attributes: {} }));
productsDirty = true;
renderProducts();
};
$('#btnSaveProducts').onclick = () => {
const rows = products.map((p, i) => {
const attributes = {};
(p.attributes || []).forEach(a => { if (a.k) attributes[a.k] = a.v; });
return {
id: p.id != null ? p.id : i + 1,
name: p.name.trim(),
aliases: p.aliases.map(s => String(s).trim()).filter(Boolean),
attributes
};
});
if (rows.some(r => !r.name)) { toast('商品名称不能为空', false); return; }
// 原文件里可能有重复 id,保存时顺延成唯一值,避免检索时串商品
const used = new Set();
rows.forEach(r => { while (used.has(r.id)) r.id++; used.add(r.id); });
productsDirty = false;
post({ type: 'setConfig', name: 'products.json', text: JSON.stringify(rows, null, 2) });
};
$('#btnReloadProducts').onclick = () => { productsDirty = false; post({ type: 'getConfig', name: 'products.json' }); };
// ---------- 客服人格 ----------
function loadPersona(text) {
let p = {};
try { p = JSON.parse(text || '{}'); } catch (e) { p = {}; }
if (!p || typeof p !== 'object' || Array.isArray(p)) p = {};
$('#peSelfName').value = p.selfName || '';
$('#peCustomerTitle').value = p.customerTitle || '';
$('#peTone').value = p.tone || '';
$('#peReplyLength').value = p.replyLength || 'short';
$('#peUseEmoji').checked = !!p.useEmoji;
$('#peGreeting').value = p.greeting || '';
$('#peClosing').value = p.closing || '';
$('#peBannedWords').value = Array.isArray(p.bannedWords) ? p.bannedWords.join('\n') : '';
}
$('#btnSavePersona').onclick = () => {
const data = {
selfName: $('#peSelfName').value.trim(),
customerTitle: $('#peCustomerTitle').value.trim(),
tone: $('#peTone').value.trim(),
replyLength: $('#peReplyLength').value,
useEmoji: $('#peUseEmoji').checked,
greeting: $('#peGreeting').value.trim(),
closing: $('#peClosing').value.trim(),
bannedWords: $('#peBannedWords').value.split(/\r?\n/).map(s => s.trim()).filter(Boolean)
};
post({ type: 'setConfig', name: 'persona.json', text: JSON.stringify(data, null, 2) });
post({ type: 'setTextConfig', name: 'system-prompt.md', text: $('#taSystemPrompt').value });
post({ type: 'setTextConfig', name: 'reply-guidelines.md', text: $('#taReplyGuidelines').value });
toast('客服人格与提示词已保存', true);
};
$('#btnReloadPersona').onclick = () => {
post({ type: 'getConfig', name: 'persona.json' });
post({ type: 'getTextConfig', name: 'system-prompt.md' });
post({ type: 'getTextConfig', name: 'reply-guidelines.md' });
};
// ---------- 知识库 ----------
let knowledge = [];
let knowledgeDirty = false;
function normalizeKnowledge(item) {
return {
id: item && item.id != null ? item.id : null,
title: String((item && item.title) || (item && item.question) || ''),
category: String((item && item.category) || '通用'),
keywords: Array.isArray(item && item.keywords) ? item.keywords.slice() : [],
priority: Number.isFinite(Number(item && item.priority)) ? Number(item.priority) : 3,
content: String((item && item.content) || (item && item.answer) || '')
};
}
function loadKnowledge(text) {
if (knowledgeDirty) return;
let arr = [];
try { arr = JSON.parse(text || '[]'); } catch (e) { toast('knowledge.json 解析失败:' + e.message, false); return; }
if (!Array.isArray(arr)) arr = [];
knowledge = arr.map(normalizeKnowledge);
knowledgeDirty = false;
renderKnowledge();
}
function renderKnowledge() {
const box = $('#knowledgeList');
const kw = $('#inKnowSearch').value.trim();
if (!knowledge.length) {
box.innerHTML = '<p class="hint">知识库还是空的,点「新增条目」添加;原来的 faq.json 会在首次启动时自动迁移进来。</p>';
return;
}
const hits = knowledge.map((k, i) => ({ k, i })).filter(({ k }) =>
!kw || (k.title + ' ' + k.category + ' ' + k.keywords.join(' ') + ' ' + k.content).indexOf(kw) >= 0);
if (!hits.length) {
box.innerHTML = '<p class="hint">没有匹配「' + esc(kw) + '」的条目。</p>';
return;
}
box.innerHTML = hits.map(({ k, i }) =>
'<div class="know-card">' +
'<div class="head">' +
'<input data-i="' + i + '" data-k="title" style="flex:1" placeholder="标题,例如:配节售后政策" value="' + esc(k.title) + '">' +
'<input data-i="' + i + '" data-k="category" style="width:110px" placeholder="分类" value="' + esc(k.category) + '">' +
'<input data-i="' + i + '" data-k="priority" type="number" min="1" max="10" step="1" style="width:76px" title="优先级 1-10" value="' + esc(k.priority) + '">' +
'<button class="mini del" data-del="' + i + '">删除</button>' +
'</div>' +
'<div class="row" style="margin-bottom:8px"><span class="lbl">触发词</span>' +
'<input data-i="' + i + '" data-k="keywords" style="flex:1" placeholder="多个触发词用逗号或顿号分隔" value="' +
esc(k.keywords.join('、')) + '"></div>' +
'<div class="row" style="margin:0;align-items:flex-start"><span class="lbl">内容</span>' +
'<textarea class="know-content" data-i="' + i + '" data-k="content" spellcheck="false" ' +
'placeholder="知识正文,会原样作为参考资料">' + esc(k.content) + '</textarea></div>' +
'</div>').join('');
box.querySelectorAll('input[data-k],textarea[data-k]').forEach(el => el.oninput = () => {
const i = +el.dataset.i, k = el.dataset.k;
if (k === 'keywords') knowledge[i].keywords = splitList(el.value);
else if (k === 'priority') knowledge[i].priority = Number(el.value) || 1;
else knowledge[i][k] = el.value;
knowledgeDirty = true;
});
box.querySelectorAll('button[data-del]').forEach(b => b.onclick = () => {
knowledge.splice(+b.dataset.del, 1);
knowledgeDirty = true;
renderKnowledge();
});
}
$('#inKnowSearch').oninput = () => renderKnowledge();
$('#btnAddKnowledge').onclick = () => {
const used = new Set(knowledge.map(k => k.id));
let id = 1;
while (used.has(id)) id++;
knowledge.unshift(normalizeKnowledge({ id, title: '', category: '通用', keywords: [], priority: 3, content: '' }));
knowledgeDirty = true;
renderKnowledge();
};
$('#btnSaveKnowledge').onclick = () => {
const rows = knowledge.map((k, i) => ({
id: k.id != null ? k.id : i + 1,
title: k.title.trim(),
category: k.category.trim() || '通用',
keywords: k.keywords.map(s => String(s).trim()).filter(Boolean),
content: k.content.trim(),
priority: Number(k.priority) || 3
}));
if (rows.some(r => !r.title)) { toast('知识条目标题不能为空', false); return; }
const used = new Set();
rows.forEach(r => { while (used.has(r.id)) r.id++; used.add(r.id); });
knowledgeDirty = false;
post({ type: 'setConfig', name: 'knowledge.json', text: JSON.stringify(rows, null, 2) });
};
$('#btnReloadKnowledge').onclick = () => { knowledgeDirty = false; post({ type: 'getConfig', name: 'knowledge.json' }); };
// ---------- 开场说明(先单独发一段规则说明,可带配图) ----------
let greetDraft = { imageIds: [] };
function renderGreetingImages() {
const box = $('#greetImagePreview');
if (!box) return;
const ids = Array.isArray(greetDraft.imageIds) ? greetDraft.imageIds : [];
const picked = ids.map(file => picState.find(img => img.file === file)).filter(Boolean);
$('#greetImageCount').textContent = picked.length ? ('已选择 ' + picked.length + ' 张') : '未选择';
box.innerHTML = picked.map(img =>
'<div class="thumb" title="' + esc(img.name || img.file) + '">' +
(img.url ? '<img src="' + esc(img.url) + '" alt="" onerror="this.style.display=\'none\';this.parentNode.classList.add(\'bad\')">' : '') +
'</div>').join('');
}
function loadGreeting(text) {
let cfg = {};
try { cfg = JSON.parse(text || '{}') || {}; } catch (_) { cfg = {}; }
$('#greetEnabled').checked = cfg.enabled === true;
$('#greetOnFirst').checked = cfg.onFirst !== false;
$('#greetOnOrder').checked = cfg.onOrder !== false;
$('#greetText').value = String(cfg.text || '');
greetDraft = {
imageIds: Array.isArray(cfg.imageIds) ? cfg.imageIds.filter(file => typeof file === 'string') : []
};
renderGreetingImages();
}
$('#btnGreetImages').onclick = () => openImagePicker('greeting', -1);
$('#btnSaveGreeting').onclick = () => {
const text = $('#greetText').value.trim();
// 只保留图片库里还存在的文件,避免保存后发送时找不到图
const imageIds = greetDraft.imageIds.filter(file => picState.some(img => img.file === file));
const cfg = {
enabled: $('#greetEnabled').checked,
onFirst: $('#greetOnFirst').checked,
onOrder: $('#greetOnOrder').checked,
text: text,
imageIds: imageIds
};
if (cfg.enabled && !text && !imageIds.length) { toast('启用开场说明时,至少要填写文案或选择配图', false); return; }
if (cfg.enabled && !cfg.onFirst && !cfg.onOrder) { toast('至少选择一个触发时机', false); return; }
post({ type: 'setConfig', name: 'greeting.json', text: JSON.stringify(cfg, null, 2) });
toast('开场说明已保存', true);
};
$('#btnReloadGreeting').onclick = () => post({ type: 'getConfig', name: 'greeting.json' });
// ---------- 规则与话术 ----------
// 四份配置结构不同,统一用「字段描述 + 通用卡片」渲染;保存时先按字段归一化,再原样保留未知字段
const ruleDefs = {
quick: {
file: 'quick-replies.json',
list: '#ruleQuick',
empty: '还没有快捷回复,点「新增快捷回复」添加。',
draft: () => ({ name: '', match: 'includes', keywords: [], reply: '', replies: [], imageIds: [] }),
fields: [
{ k: 'name', label: '名称', type: 'text', inHead: true, flex: true, placeholder: '例如:问候' },
{ k: 'match', label: '匹配', type: 'select', inHead: true, width: '150px',
options: [['includes', '包含关键词(推荐)'], ['exact', '整句完全一致']] },
{ k: 'keywords', label: '关键词', type: 'list', section: '触发条件',
placeholder: '例如:你好、您好、在吗',
hint: '多个关键词用「、」分隔;买家这句话里出现任意一个就算命中' },
{ k: 'replies', label: '随机回复', type: 'lines', section: '命中后发送', cls: 'know-content', omitEmpty: true,
placeholder: '一行一条,按回车换行分隔,例如:您好,请问有什么需要帮忙的?',
hint: '一行一条回复,按回车换行分隔,不要用逗号或斜杠。命中后随机抽一条发送;留空则发送下面的「固定回复」。' },
{ k: 'reply', label: '固定回复', type: 'area', cls: 'know-content',
placeholder: '不配置随机回复时发送这条;只发图片时可留空',
hint: '单条固定话术,适合不需要变化的场景' },
{ k: 'imageIds', label: '配图', type: 'images', omitEmpty: true }
],
validate: (rows) => {
if (rows.some(r => !r.name)) return '快捷回复的名称不能为空';
if (rows.some(r => !r.keywords.length)) return '每条快捷回复至少要有一个关键词';
if (rows.some(r => !r.reply && !(r.replies || []).length && !(r.imageIds || []).length)) {
return '快捷回复至少要有回复内容、随机回复或配图';
}
return '';
}
},
risk: {
file: 'risk-intents.json',
list: '#ruleRisk',
empty: '还没有风险意图,点「新增风险意图」添加。',
draft: () => ({ name: '', keywords: [], reply: '', defaultReply: '' }),
fields: [
{ k: 'name', label: '名称', type: 'text', inHead: true, flex: true, placeholder: '例如:平台外交易(默认条目写 default)' },
{ k: 'keywords', label: '关键词', type: 'list', placeholder: '例如:微信、支付宝、私下转账' },
{ k: 'reply', label: '预设话术', type: 'area', cls: 'know-content', placeholder: '仅作留档,命中后不会自动发送', omitEmpty: true },
{ k: 'defaultReply', label: '默认话术', type: 'area', cls: 'attr', placeholder: '仅 default 条目使用,仅作留档', omitEmpty: true }
],
validate: (rows) => {
if (rows.some(r => !r.name)) return '风险意图的名称不能为空';
if (rows.some(r => r.name !== 'default' && !r.keywords.length)) return '非 default 的风险意图至少要有 1 个关键词';
return '';
}
},
handoff: {
file: 'manual-handoff-whitelist.json',
list: '#ruleHandoff',
empty: '还没有转人工规则,点「新增转人工规则」添加。',
draft: () => ({ name: '', semantics: '', keywords: [], excludeKeywords: [], examples: [], negativeExamples: [] }),
fields: [
{ k: 'name', label: '名称', type: 'text', inHead: true, flex: true, placeholder: '例如:退款退货' },
{ k: 'semantics', label: '语义说明', type: 'area', cls: 'attr', placeholder: '买家表达什么诉求时要转人工', omitEmpty: true },
{ k: 'keywords', label: '触发词', type: 'list', placeholder: '例如:退款、退货、仅退款' },
{ k: 'excludeKeywords', label: '排除词', type: 'list', placeholder: '例如:退货规则怎么写(这些属于咨询不转人工)', omitEmpty: true },
{ k: 'examples', label: '示例', type: 'lines', placeholder: '每行一条,例如:收到货坏了想换', omitEmpty: true },
{ k: 'negativeExamples', label: '反例', type: 'lines', placeholder: '每行一条,例如:请问容易坏吗', omitEmpty: true }
],
validate: (rows) => {
if (rows.some(r => !r.name)) return '转人工规则的名称不能为空';
if (rows.some(r => !r.keywords.length)) return '转人工规则至少要有一个触发词';
return '';
}
},
tone: {
file: 'tone-examples.json',
list: '#ruleTone',
empty: '还没有语气示例,点「新增语气示例」添加。',
draft: () => ({ id: '', scene: '', customer: '', goodReply: '', notes: '' }),
fields: [
{ k: 'id', label: '编号', type: 'text', inHead: true, width: '150px', placeholder: '可留空' },
{ k: 'scene', label: '场景', type: 'text', inHead: true, flex: true, placeholder: '例如:买家问售后' },
{ k: 'customer', label: '买家原话', type: 'area', cls: 'attr', placeholder: '买家当时的提问', omitEmpty: true },
{ k: 'goodReply', label: '优秀回复', type: 'area', cls: 'know-content', placeholder: '希望模型模仿的回复' },
{ k: 'notes', label: '备注', type: 'text', placeholder: '这类情况的处理要点,可留空', omitEmpty: true }
],
validate: (rows) => {
if (rows.some(r => !r.scene)) return '语气示例的场景不能为空';
if (rows.some(r => !r.goodReply)) return '语气示例的优秀回复不能为空';
return '';
}
}
};
const ruleState = { quick: [], risk: [], handoff: [], tone: [] };
const ruleDirty = { quick: false, risk: false, handoff: false, tone: false };
function ruleFieldHtml(f, i, raw) {
const v = raw[f.k];
const attrs = ' data-i="' + i + '" data-k="' + f.k + '"';
const ph = ' placeholder="' + esc(f.placeholder || '') + '"';
if (f.type === 'select') {
const opts = f.options.map(([val, label]) =>
'<option value="' + val + '"' + (String(v || '') === val ? ' selected' : '') + '>' + esc(label) + '</option>');
return '<select' + attrs + ' style="width:' + (f.width || '160px') + '">' + opts.join('') + '</select>';
}
if (f.type === 'list') {
return '<input' + attrs + ' style="flex:1"' + ph + ' value="' +
esc((Array.isArray(v) ? v : []).join('、')) + '">';
}
if (f.type === 'lines') {
return '<textarea' + attrs + ' spellcheck="false"' + (f.cls ? ' class="' + f.cls + '"' : '') +
' style="min-height:86px"' + ph + '>' + esc((Array.isArray(v) ? v : []).join('\n')) + '</textarea>';
}
if (f.type === 'area') {
return '<textarea' + attrs + ' spellcheck="false" class="' + (f.cls || 'attr') + '"' + ph + '>' +
esc(v == null ? '' : String(v)) + '</textarea>';
}
if (f.type === 'images') {
const selected = Array.isArray(v) ? v : [];
const chosen = selected.map(key => {
const img = picState.find(x => x.file === key);
return { file: key, name: img ? img.name : key, url: img ? img.url : '' };
});
const thumbs = chosen.map(img =>
'<span class="img-pick-item">' + (img.url ? '<img src="' + esc(img.url) + '" alt="">' : '') +
'<span class="img-pick-name">' + esc(img.name || img.file) + '</span></span>').join('');
return '<div class="img-pick" data-k="' + f.k + '" data-i="' + i + '">' +
(thumbs || '<span class="hint">未选择配图</span>') +
'<button class="mini" data-pick="' + i + '">选择配图</button></div>';
}
return '<input' + attrs + ' style="' + (f.flex ? 'flex:1' : 'width:' + (f.width || '160px')) + '"' + ph +
' value="' + esc(v == null ? '' : String(v)) + '">';
}
function renderRuleSection(key) {
const def = ruleDefs[key];
const box = $(def.list);
const items = ruleState[key];
if (!items.length) { box.innerHTML = '<p class="hint">' + def.empty + '</p>'; return; }
box.innerHTML = items.map((raw, i) => {
const head = def.fields.filter(f => f.inHead).map(f => ruleFieldHtml(f, i, raw)).join('');
let lastSection = '';
const body = def.fields.filter(f => !f.inHead).map(f => {
let html = '';
if (f.section && f.section !== lastSection) {
lastSection = f.section;
html += '<div class="rule-section">' + esc(f.section) + '</div>';
}
html += '<div class="row" style="margin:0 0 8px;align-items:flex-start">' +
'<span class="lbl" style="width:66px">' + esc(f.label) + '</span>' +
ruleFieldHtml(f, i, raw) + '</div>';
if (f.hint) html += '<div class="rule-hint">' + esc(f.hint) + '</div>';
return html;
}).join('');
return '<div class="know-card">' +
'<div class="head"><span class="lbl">#' + (i + 1) + '</span>' + head +
'<button class="mini del" data-del="' + i + '">删除</button></div>' + body + '</div>';
}).join('');
box.querySelectorAll('input[data-k],select[data-k],textarea[data-k]').forEach(el => {
const onChange = () => {
const raw = ruleState[key][+el.dataset.i];
const f = def.fields.find(x => x.k === el.dataset.k);
if (!raw || !f) return;
if (f.type === 'list') raw[f.k] = splitList(el.value);
else if (f.type === 'lines') raw[f.k] = el.value.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
else raw[f.k] = el.value;
ruleDirty[key] = true;
};
el.oninput = onChange;
el.onchange = onChange;
});
box.querySelectorAll('[data-pick]').forEach(btn => {
btn.onclick = () => openImagePicker(key, +btn.dataset.pick);
});
box.querySelectorAll('button[data-del]').forEach(b => b.onclick = () => {
ruleState[key].splice(+b.dataset.del, 1);
ruleDirty[key] = true;
renderRuleSection(key);
});
}
function loadRuleSection(key, text) {
if (ruleDirty[key]) return; // 有未保存改动时不覆盖
let arr = [];
try { arr = JSON.parse(text || '[]'); } catch (e) {
toast(ruleDefs[key].file + ' 解析失败:' + e.message, false);
return;
}
if (!Array.isArray(arr)) arr = [];
ruleState[key] = arr.filter(x => x && typeof x === 'object' && !Array.isArray(x));
renderRuleSection(key);
}
function addRuleItem(key) {
ruleState[key].push(ruleDefs[key].draft());
ruleDirty[key] = true;
renderRuleSection(key);
}
function saveRuleSection(key) {
const def = ruleDefs[key];
const handled = new Set(def.fields.map(f => f.k));
const rows = ruleState[key].map(raw => {
const out = {};
for (const f of def.fields) {
let v = raw[f.k];
v = (f.type === 'list' || f.type === 'lines' || f.type === 'images')
? (Array.isArray(v) ? v.map(s => String(s).trim()).filter(Boolean) : [])
: (v == null ? '' : String(v).trim());
if (f.omitEmpty && !v.length) continue;
out[f.k] = v;
}
// 保留文件里原本存在、界面上没有的字段(例如自定义扩展字段)
for (const k of Object.keys(raw)) if (!handled.has(k)) out[k] = raw[k];
return out;
});
const err = def.validate(rows);
if (err) { toast(err, false); return; }
ruleDirty[key] = false;
post({ type: 'setConfig', name: def.file, text: JSON.stringify(rows, null, 2) });
}
function reloadRuleSection(key) {
ruleDirty[key] = false;
post({ type: 'getConfig', name: ruleDefs[key].file });
}
$('#btnAddQuick').onclick = () => addRuleItem('quick');
$('#btnSaveQuick').onclick = () => saveRuleSection('quick');
$('#btnReloadQuick').onclick = () => reloadRuleSection('quick');
$('#btnAddRisk').onclick = () => addRuleItem('risk');
$('#btnSaveRisk').onclick = () => saveRuleSection('risk');
$('#btnReloadRisk').onclick = () => reloadRuleSection('risk');
$('#btnAddHandoff').onclick = () => addRuleItem('handoff');
$('#btnSaveHandoff').onclick = () => saveRuleSection('handoff');
$('#btnReloadHandoff').onclick = () => reloadRuleSection('handoff');
$('#btnAddTone').onclick = () => addRuleItem('tone');
$('#btnSaveTone').onclick = () => saveRuleSection('tone');
$('#btnReloadTone').onclick = () => reloadRuleSection('tone');
// ---------- 图片库 ----------
let picState = [];
let picDir = '';
function renderImageLibrary() {
const box = $('#replyImageList');
if (!box) return;
if (!picState.length) {
box.innerHTML = '<p class="gallery-empty">图片库里还没有图片。把图片放进「当前目录」后点「重新扫描」。</p>';
return;
}
box.innerHTML = picState.map(img =>
'<div class="img-cell">' +
'<div class="thumb">' + (img.url ? '<img src="' + esc(img.url) + '" alt="" onerror="this.style.display=\'none\';this.parentNode.classList.add(\'bad\')">' : '') + '</div>' +
'<span class="img-cell-name">' + esc(img.name || img.file) + '</span>' +
'</div>'
).join('');
}
handlers.imageLibrary = (d) => {
if (d.shopId && consoleShopId && d.shopId !== consoleShopId) return;
picDir = d.dir || '';
const dirEl = $('#picDir');
if (dirEl) dirEl.textContent = '当前目录:' + (picDir || '-');
if (d.ok === false) toast(d.error || '读取图片库失败', false);
picState = (d.items || []).map(item => ({
file: item.file || '', name: item.name || '',
keywords: Array.isArray(item.keywords) ? item.keywords : [],
withText: item.withText !== false, url: item.url || ''
}));
renderImageLibrary();
if (!ruleDirty.quick) renderRuleSection('quick');
renderGreetingImages();
};
// 快捷回复里的配图选择:缩略图多选弹窗,选中后可设置名称/触发词/发送方式
const imgPicker = { key: '', index: -1, selected: [], meta: {} };
function renderImagePicker() {
const grid = $('#imgPickerGrid');
if (!grid) return;
if (!picState.length) {
grid.innerHTML = '<p class="gallery-empty">图片库里还没有图片,请把图片放进图片库目录后点「重新扫描」。</p>';
renderPickerSettings();
return;
}
grid.innerHTML = picState.map(img => {
const on = imgPicker.selected.includes(img.file);
return '<div class="img-cell' + (on ? ' on' : '') + '" data-file="' + esc(img.file) + '">' +
'<div class="thumb">' + (img.url ? '<img src="' + esc(img.url) + '" alt="" onerror="this.style.display=\'none\';this.parentNode.classList.add(\'bad\')">' : '') + '</div>' +
'<span class="img-cell-name">' + esc(img.name || img.file) + '</span></div>';
}).join('');
grid.querySelectorAll('[data-file]').forEach(cell => cell.onclick = () => {
const file = cell.dataset.file;
const at = imgPicker.selected.indexOf(file);
if (at >= 0) imgPicker.selected.splice(at, 1); else imgPicker.selected.push(file);
renderImagePicker();
renderPickerSettings();
});
}
function renderPickerSettings() {
const box = $('#imgPickerSettings');
if (!box) return;
if (!imgPicker.selected.length) {
box.innerHTML = '<p class="hint">勾选图片后可设置名称、AI 触发词与发送方式。</p>';
return;
}
box.innerHTML = imgPicker.selected.map(file => {
const meta = imgPicker.meta[file] || {};
return '<div class="row" data-sfile="' + esc(file) + '">' +
'<input data-sk="name" style="width:140px" placeholder="名称" value="' + esc(meta.name || '') + '">' +
'<input data-sk="keywords" style="flex:1" placeholder="AI 触发词,多个用、分隔" value="' + esc((meta.keywords || []).join('、')) + '">' +
'<select data-sk="withText" style="width:120px">' +
'<option value="1"' + (meta.withText !== false ? ' selected' : '') + '>文字 + 图片</option>' +
'<option value="0"' + (meta.withText === false ? ' selected' : '') + '>仅图片</option>' +
'</select></div>';
}).join('');
box.querySelectorAll('[data-sk]').forEach(el => {
const apply = () => {
const file = el.parentNode.dataset.sfile;
const meta = imgPicker.meta[file];
if (!meta) return;
if (el.dataset.sk === 'keywords') meta.keywords = splitList(el.value);
else if (el.dataset.sk === 'withText') meta.withText = el.value === '1';
else meta.name = el.value;
};
el.oninput = apply;
el.onchange = apply;
});
}
function openImagePicker(key, index) {
// 开场说明没有规则列表,配图直接存在 greetDraft 上
const raw = key === 'greeting' ? greetDraft : (ruleState[key] && ruleState[key][index]);
if (!raw) return;
imgPicker.key = key;
imgPicker.index = index;
imgPicker.selected = Array.isArray(raw.imageIds) ? raw.imageIds.slice() : [];
imgPicker.meta = {};
picState.forEach(img => {
imgPicker.meta[img.file] = {
name: img.name || '', keywords: (img.keywords || []).slice(), withText: img.withText !== false
};
});
renderImagePicker();
renderPickerSettings();
$('#imgPicker').style.display = 'flex';
}
function closeImagePicker() {
$('#imgPicker').style.display = 'none';
}
$('#btnPickImageDir').onclick = () => post({ type: 'pickImageLibraryDir' });
$('#btnOpenImageDir').onclick = () => {
if (!picDir) { toast('图片库目录尚未就绪', false); return; }
post({ type: 'openImageDir', path: picDir });
};
$('#btnReloadReplyImage').onclick = () => post({ type: 'getImageLibrary' });
$('#imgPickerClose').onclick = closeImagePicker;
$('#imgPickerCancel').onclick = closeImagePicker;
$('#imgPickerOk').onclick = () => {
const key = imgPicker.key;
// 按图片库里的顺序保存,展示与发送顺序保持一致
const ordered = picState.map(img => img.file).filter(file => imgPicker.selected.includes(file));
if (key === 'greeting') {
greetDraft.imageIds = ordered;
renderGreetingImages();
} else {
const raw = ruleState[key] && ruleState[key][imgPicker.index];
if (raw) {
raw.imageIds = ordered;
ruleDirty[key] = true;
}
}
// 同步本弹窗里改过的名称/触发词/发送方式到图片库
const rows = picState.map(img => {
const meta = imgPicker.meta[img.file] || {};
let name = String(meta.name || '').trim();
if (!name) name = img.file.replace(/\.[^.]+$/, '');
return {
file: img.file, name,
keywords: Array.isArray(meta.keywords) ? meta.keywords : [],
withText: meta.withText !== false
};
});
post({ type: 'saveImageLibrary', text: JSON.stringify(rows, null, 2) });
closeImagePicker();
if (key && key !== 'greeting') renderRuleSection(key);
};
// ---------- 模型接口与邮件 ----------
let presets = [];
let modelDraft = [];
let modelDragIndex = null;
function newModelId() { return 'm' + Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36); }
function providerOptionsHtml(selected) {
const list = presets.slice();
if (selected && !list.some(p => p.id === selected)) list.unshift({ id: selected, name: selected });
return list.map(p => '<option value="' + esc(p.id) + '"' + (p.id === selected ? ' selected' : '') + '>' +
esc(p.name) + '</option>').join('');
}
function presetOf(id) { return presets.find(x => x.id === id); }
function applyPresetToDraft(item, fillUrl) {
const p = presetOf(item.provider);
if (!p) return;
if (fillUrl || !item.apiUrl) item.apiUrl = p.apiUrl || item.apiUrl;
if (!item.model && p.defaultModel) item.model = p.defaultModel;
if (p.apiMode) item.apiMode = p.apiMode;
}
function renderModelList() {
const box = $('#modelList');
if (!modelDraft.length) {
box.innerHTML = '<div class="hint" style="padding:6px 2px">还没有模型,点下方「添加模型」。</div>';
return;
}
box.innerHTML = modelDraft.map((m, i) => {
const p = presetOf(m.provider);
const modeText = m.apiMode ? ('接口类型 ' + m.apiMode) : '';
return '<div class="model-item" draggable="true" data-index="' + i + '" data-id="' + esc(m.id) + '">' +
'<span class="model-drag" title="拖动调整顺序">⋮⋮</span>' +
'<div class="model-main">' +
'<div class="row" style="margin-bottom:6px">' +
'<span class="model-no">' + (i + 1) + '</span>' +
'<select class="m-provider" data-field="provider" style="width:200px">' + providerOptionsHtml(m.provider) + '</select>' +
'<span class="hint m-mode" style="white-space:nowrap">' + esc(modeText) + '</span>' +
'<button class="act ghost m-del" style="margin-left:auto;padding:5px 12px">删除</button>' +
'</div>' +
'<div class="row" style="margin-bottom:6px">' +
'<span style="width:56px;color:#8a8a8a">接口地址</span>' +
'<input class="m-url" data-field="apiUrl" style="flex:1" value="' + esc(m.apiUrl || '') + '" placeholder="https://api.deepseek.com/v1/chat/completions">' +
'</div>' +
'<div class="row">' +
'<span style="width:56px;color:#8a8a8a">模型名</span>' +
'<input class="m-model" data-field="model" style="flex:1" value="' + esc(m.model || '') + '" placeholder="' + esc((p && p.defaultModel) || 'deepseek-chat') + '">' +
'<span style="width:30px;color:#8a8a8a;margin-left:10px">Key</span>' +
'<input class="m-key" type="password" style="flex:1" value="' + esc(m.apiKey || '') + '" placeholder="' + (m.hasApiKey ? '已保存(留空不修改)' : '请填写 API Key') + '">' +
'</div>' +
'</div></div>';
}).join('');
Array.from(box.querySelectorAll('.model-item')).forEach(item => {
const idx = Number(item.dataset.index);
item.addEventListener('dragstart', (e) => {
modelDragIndex = idx;
item.classList.add('dragging');
if (e.dataTransfer) { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', String(idx)); }
});
item.addEventListener('dragend', () => {
item.classList.remove('dragging');
Array.from(box.querySelectorAll('.model-item')).forEach(x => x.classList.remove('drop-target'));
modelDragIndex = null;
});
item.addEventListener('dragover', (e) => {
e.preventDefault();
if (modelDragIndex !== null && modelDragIndex !== idx) item.classList.add('drop-target');
});
item.addEventListener('dragleave', () => item.classList.remove('drop-target'));
item.addEventListener('drop', (e) => {
e.preventDefault();
item.classList.remove('drop-target');
if (modelDragIndex === null || modelDragIndex === idx) return;
const moved = modelDraft.splice(modelDragIndex, 1)[0];
modelDraft.splice(idx, 0, moved);
renderModelList();
});
item.querySelector('.m-provider').addEventListener('change', (e) => {
modelDraft[idx].provider = e.target.value;
modelDraft[idx].apiUrl = '';
modelDraft[idx].model = '';
applyPresetToDraft(modelDraft[idx], true);
item.querySelector('.m-url').value = modelDraft[idx].apiUrl || '';
item.querySelector('.m-model').value = modelDraft[idx].model || '';
item.querySelector('.m-mode').textContent = modelDraft[idx].apiMode ? ('接口类型 ' + modelDraft[idx].apiMode) : '';
});
item.querySelector('.m-del').addEventListener('click', () => {
modelDraft.splice(idx, 1);
renderModelList();
});
});
}
$('#modelList').addEventListener('input', (e) => {
const item = e.target.closest('.model-item');
if (!item) return;
const idx = Number(item.dataset.index);
if (!modelDraft[idx]) return;
const field = e.target.dataset.field;
if (field) modelDraft[idx][field] = e.target.value;
if (e.target.classList.contains('m-key')) modelDraft[idx].apiKey = e.target.value;
});
handlers.presets = (d) => {
presets = d.items || [];
if (modelDraft.length) renderModelList();
if (!loaded.modelDone) { loaded.modelDone = true; post({ type: 'getModel' }); }
};
handlers.model = (d) => {
$('#inProxy').value = d.proxy || '';
modelDraft = (d.models || []).map((m, i) => {
let provider = m.provider || '';
if (!provider) { const hit = presets.find(p => p.apiUrl && p.apiUrl === m.apiUrl); provider = hit ? hit.id : 'custom'; }
return { id: m.id || ('m' + i), provider: provider, apiUrl: m.apiUrl || '', apiKey: '',
model: m.model || '', apiMode: m.apiMode || 'chat', hasApiKey: !!m.hasApiKey };
}).filter(m => m.apiUrl || m.model);
if (!modelDraft.length) {
const item = { id: newModelId(), provider: (presets[0] || {}).id || 'custom', apiUrl: '', apiKey: '',
model: '', apiMode: '', hasApiKey: false };
applyPresetToDraft(item, true);
modelDraft.push(item);
}
renderModelList();
const usable = modelDraft.filter(m => m.apiUrl && m.model);
$('#stModelState').textContent = usable.length
? ('已配置 ' + usable.length + ' 个模型,按顺序尝试:' + usable.map(m => m.model).join(' → '))
: '当前没有可用的模型配置:自动回复只会退化成固定文案「您好,已收到您的问题…」。';
if (d.historyLimit !== undefined) {
const all = d.historyAll === true || Number(d.historyLimit) === 0;
$('#selHistoryMode').value = all ? 'all' : 'partial';
const n = Number(d.historyLimit);
$('#inHistoryLimit').value = Number.isInteger(n) && n > 0 ? n : 6;
$('#inHistoryLimit').disabled = all;
}
};
$('#btnAddModel').onclick = () => {
const item = { id: newModelId(), provider: (presets[0] || {}).id || 'custom', apiUrl: '', apiKey: '',
model: '', apiMode: '', hasApiKey: false };
applyPresetToDraft(item, true);
modelDraft.push(item);
renderModelList();
};
$('#btnSaveModel').onclick = () => {
const rows = Array.from(document.querySelectorAll('#modelList .model-item')).map(item => {
const idx = Number(item.dataset.index);
const m = modelDraft[idx] || {};
return { id: m.id, provider: item.querySelector('.m-provider').value,
apiUrl: item.querySelector('.m-url').value.trim(),
model: item.querySelector('.m-model').value.trim(),
apiKey: item.querySelector('.m-key').value.trim(), apiMode: m.apiMode || '' };
});
post({ type: 'saveModel', models: rows, proxy: $('#inProxy').value.trim() });
};
// ---------- 邮件 ----------
handlers.mail = (d) => {
$('#mailEnabled').checked = !!d.enabled;
$('#mailProvider').value = d.provider || '';
$('#mailHost').value = d.host || '';
$('#mailPort').value = d.port ?? 465;
$('#mailSecure').checked = !!d.secure;
$('#mailStartTls').checked = !!d.startTls;
$('#mailRejectUnauthorized').checked = !!d.rejectUnauthorized;
$('#mailUser').value = d.user || '';
$('#mailAuthCodeEnv').value = d.authCodeEnv || '';
$('#mailAuthCode').value = d.authCode || '';
$('#mailFrom').value = d.from || '';
$('#mailSenderName').value = d.senderName || '';
$('#mailTo').value = (d.to || []).join('、');
$('#mailCc').value = (d.cc || []).join('、');
$('#mailSubjectPrefix').value = d.subjectPrefix || '';
$('#mailDedupMs').value = d.dedupMs ?? 600000;
$('#riskSoundEnabled').checked = !!d.riskSoundEnabled;
$('#riskSoundPath').value = d.riskSoundPath || '';
};
$('#btnSaveMail').onclick = () => {
const rawDedup = $('#mailDedupMs').value.trim();
post({ type: 'saveMail',
enabled: $('#mailEnabled').checked,
provider: $('#mailProvider').value.trim(),
host: $('#mailHost').value.trim(),
port: Number($('#mailPort').value) || 465,
secure: $('#mailSecure').checked,
startTls: $('#mailStartTls').checked,
rejectUnauthorized: $('#mailRejectUnauthorized').checked,
user: $('#mailUser').value.trim(),
authCodeEnv: $('#mailAuthCodeEnv').value.trim(),
authCode: $('#mailAuthCode').value.trim(),
from: $('#mailFrom').value.trim(),
senderName: $('#mailSenderName').value.trim(),
to: splitList($('#mailTo').value),
cc: splitList($('#mailCc').value),
subjectPrefix: $('#mailSubjectPrefix').value.trim(),
dedupMs: rawDedup === '' ? 600000 : Number(rawDedup),
riskSoundEnabled: $('#riskSoundEnabled').checked,
riskSoundPath: $('#riskSoundPath').value.trim() });
};
$('#btnPickRiskSound').onclick = () => post({ type: 'pickAudioFile' });
$('#btnTestRiskSound').onclick = () => post({ type: 'playAudio', path: $('#riskSoundPath').value.trim() });
// 提醒声音独立保存:勾选、选择、清除都立即写盘,避免只点「保存系统设置」导致丢失
const saveRiskSound = () => post({ type: 'saveRiskSound',
enabled: $('#riskSoundEnabled').checked, path: $('#riskSoundPath').value.trim() });
$('#riskSoundEnabled').onchange = saveRiskSound;
$('#btnClearRiskSound').onclick = () => {
$('#riskSoundPath').value = '';
saveRiskSound();
};
handlers.audioPicked = (d) => {
if (!d.ok) return;
$('#riskSoundPath').value = d.path || '';
$('#riskSoundEnabled').checked = true;
saveRiskSound();
};
$('#btnTestMail').onclick = () => {
$('#stMailTest').textContent = '正在保存并发送…';
// 先保存再测试,避免改了配置没保存就点测试
$('#btnSaveMail').onclick();
setTimeout(() => post({ type: 'testMail' }), 500);
};
// ---------- 服务与检索高级设置 ----------
function numOr(sel, fallback) {
const raw = $(sel).value.trim();
return raw === '' ? fallback : Number(raw);
}
handlers.serverOptions = (d) => {
$('#svPort').value = d.port ?? 3456;
$('#svHost').value = d.host || '';
$('#svControlToken').value = d.controlToken || '';
$('#svDailyPauseTime').value = d.dailyPauseTime || '';
$('#svClassifierModel').value = d.classifierModel || '';
$('#svHandoffMode').value = d.manualHandoffClassifierMode || 'ambiguous';
$('#svMaxProducts').value = d.maxProductCandidates ?? 3;
$('#svMaxFaq').value = d.maxFaqItems ?? 5;
$('#svMaxTone').value = d.maxToneExamples ?? 3;
$('#svMaxGuidelines').value = d.maxReplyGuidelinesChars ?? 1200;
$('#svMinDelay').value = d.minReplyDelayMs ?? 3000;
$('#svMaxDelay').value = d.maxReplyDelayMs ?? 8000;
$('#svPageMinDelay').value = d.minPageDelayMs ?? 150;
$('#svPageMaxDelay').value = d.maxPageDelayMs ?? 400;
$('#svOrderCacheSec').value = Math.round((d.orderCacheMs ?? 300000) / 1000);
$('#svRiskStopOnHit').checked = d.riskStopOnHit !== false;
$('#svModelTimeout').value = d.modelTimeoutMs ?? 45000;
$('#svMock').checked = d.mockWhenNoApiKey !== false;
};
$('#btnSaveServerOptions').onclick = () => {
// 上限低于下限时按下限处理,避免保存出无效区间
const minDelay = numOr('#svMinDelay', 3000);
const pageMinDelay = numOr('#svPageMinDelay', 150);
post({
type: 'saveServerOptions',
port: numOr('#svPort', 3456),
host: $('#svHost').value.trim(),
controlToken: $('#svControlToken').value.trim(),
dailyPauseTime: $('#svDailyPauseTime').value.trim(),
classifierModel: $('#svClassifierModel').value.trim(),
manualHandoffClassifierMode: $('#svHandoffMode').value,
maxProductCandidates: numOr('#svMaxProducts', 3),
maxFaqItems: numOr('#svMaxFaq', 5),
maxToneExamples: numOr('#svMaxTone', 3),
maxReplyGuidelinesChars: numOr('#svMaxGuidelines', 1200),
minReplyDelayMs: minDelay,
maxReplyDelayMs: Math.max(minDelay, numOr('#svMaxDelay', 8000)),
minPageDelayMs: pageMinDelay,
maxPageDelayMs: Math.max(pageMinDelay, numOr('#svPageMaxDelay', 400)),
orderCacheMs: Math.max(0, numOr('#svOrderCacheSec', 300)) * 1000,
riskStopOnHit: $('#svRiskStopOnHit').checked,
modelTimeoutMs: numOr('#svModelTimeout', 45000),
mockWhenNoApiKey: $('#svMock').checked
});
};
$('#btnReloadServerOptions').onclick = () => post({ type: 'getServerOptions' });
$('#btnSaveArchive').onclick = () => {
const all = $('#selHistoryMode').value === 'all';
const raw = String($('#inHistoryLimit').value || '').trim();
const n = raw === '' ? 6 : Number(raw);
if (!all && (!Number.isInteger(n) || n < 1 || n > 500)) { toast('读取条数请填 1~500 的整数', false); return; }
post({ type: 'saveArchive', historyAll: all, historyLimit: n });
toast(all ? '已设为读取全部聊天记录' : ('已设为读取最近 ' + n + ' 条聊天记录'), true);
};
$('#selHistoryMode').onchange = () => {
$('#inHistoryLimit').disabled = $('#selHistoryMode').value === 'all';
};
// ---------- 图片保存 ----------
function updateImageRulePreview() {
const parts = ['根目录'];
if ($('#imgGroupShop').checked) parts.push('店铺ID');
if ($('#imgGroupOrder').checked) parts.push('订单号');
$('#imgRulePreview').textContent =
'实际保存路径:' + parts.join(' / ') + ' / 001.jpg;识别不到订单号时,用「未归档订单」作为订单目录名。';
}
handlers.imagesettings = (d) => {
$('#imgEnabled').checked = d.enabled !== false;
$('#imgFileAsImage').checked = d.fileAsImage !== false;
$('#imgDir').value = d.dir || '';
$('#imgGroupShop').checked = d.groupByShop !== false;
$('#imgGroupOrder').checked = d.groupByOrder !== false;
$('#imgAssignMode').value = d.assignMode || 'hybrid';
$('#imgConcurrentSec').value = d.concurrentSec || 60;
$('#imgBatchSec').value = d.batchSec || 180;
$('#imgHistorySec').value = d.historySec || 600;
$('#imgCountCheck').checked = d.countCheck !== false;
$('#imgKeywordFixedCount').value = d.keywordFixedCount || '';
$('#imgCountNote').checked = d.countNoteEnabled !== false;
$('#imgReceiptReply').checked = d.receiptReplyEnabled === true;
$('#imgReceiptShortage').value = d.receiptShortageReply || '';
$('#imgReceiptOverflow').value = d.receiptOverflowReply || '';
$('#imgAdjust').checked = d.adjustEnabled !== false;
$('#imgAdjustReply').checked = d.adjustReplyEnabled !== false;
$('#imgAdjustReplace').value = d.adjustReplaceReply || '';
$('#imgAdjustDelete').value = d.adjustDeleteReply || '';
$('#imgReplacedDir').value = d.replacedDirName || '';
$('#imgAdjustReplaceWords').value = d.adjustReplaceWords || '';
$('#imgAdjustDeleteWords').value = d.adjustDeleteWords || '';
$('#imgAdjustResendWords').value = d.adjustResendWords || '';
$('#imgAdjustPointWords').value = d.adjustPointWords || '';
$('#imgAdjustNegativeWords').value = d.adjustNegativeWords || '';
$('#imgAdjustThreshold').value = d.adjustMatchThreshold != null ? d.adjustMatchThreshold : 8;
$('#imgAdjustMode').value = d.adjustMode === 'hybrid' || d.adjustMode === 'ai' ? d.adjustMode : 'rules';
$('#imgAdjustAiConfidence').value = d.adjustAiConfidence != null ? d.adjustAiConfidence : 0.75;
$('#imgReview').checked = d.reviewEnabled !== false;
$('#imgKeepOrderTab').checked = d.keepOrderTab !== false;
const st = d.orderStatus || {};
$('#stNormal').checked = st.normal !== false;
$('#stDone').checked = st.done !== false;
$('#stRefund').checked = st.refund !== false;
updateImageRulePreview();
};
handlers.imageDir = (d) => {
$('#imgDir').value = d.path || '';
updateImageRulePreview();
};
$('#imgGroupShop').onchange = updateImageRulePreview;
$('#imgGroupOrder').onchange = updateImageRulePreview;
$('#btnSaveImageSettings').onclick = () => post({
type: 'saveImageSettings',
enabled: $('#imgEnabled').checked,
fileAsImage: $('#imgFileAsImage').checked,
dir: $('#imgDir').value.trim(),
groupByShop: $('#imgGroupShop').checked,
groupByOrder: $('#imgGroupOrder').checked,
assignMode: $('#imgAssignMode').value,
concurrentSec: Number($('#imgConcurrentSec').value || 60),
batchSec: Number($('#imgBatchSec').value || 180),
historySec: Number($('#imgHistorySec').value || 600),
countCheck: $('#imgCountCheck').checked,
keywordFixedCount: $('#imgKeywordFixedCount').value.trim(),
countNoteEnabled: $('#imgCountNote').checked,
receiptReplyEnabled: $('#imgReceiptReply').checked,
receiptShortageReply: $('#imgReceiptShortage').value.trim(),
receiptOverflowReply: $('#imgReceiptOverflow').value.trim(),
adjustEnabled: $('#imgAdjust').checked,
adjustReplyEnabled: $('#imgAdjustReply').checked,
adjustReplaceReply: $('#imgAdjustReplace').value.trim(),
adjustDeleteReply: $('#imgAdjustDelete').value.trim(),
adjustReplaceWords: $('#imgAdjustReplaceWords').value.trim(),
adjustDeleteWords: $('#imgAdjustDeleteWords').value.trim(),
adjustResendWords: $('#imgAdjustResendWords').value.trim(),
adjustPointWords: $('#imgAdjustPointWords').value.trim(),
adjustNegativeWords: $('#imgAdjustNegativeWords').value.trim(),
adjustMatchThreshold: Number($('#imgAdjustThreshold').value || 8),
adjustMode: $('#imgAdjustMode').value,
adjustAiConfidence: Number($('#imgAdjustAiConfidence').value !== '' ? $('#imgAdjustAiConfidence').value : 0.75),
replacedDirName: $('#imgReplacedDir').value.trim(),
reviewEnabled: $('#imgReview').checked,
keepOrderTab: $('#imgKeepOrderTab').checked,
orderStatus: {
normal: $('#stNormal').checked,
done: $('#stDone').checked,
refund: $('#stRefund').checked
}
});
$('#btnReloadImageSettings').onclick = () => post({ type: 'getImageSettings' });
$('#btnPickImgDir').onclick = () => post({ type: 'pickImageDir' });
$('#btnOpenImgDir').onclick = () => post({ type: 'openImageDir', path: $('#imgDir').value.trim() });
$('#btnTestModel').onclick = () => {
$('#stModelTest').textContent = '正在保存并依次测试每个模型…';
// 先落盘再测试,避免填了地址/Key 却没点保存时测到旧配置
$('#btnSaveModel').onclick();
setTimeout(() => post({ type: 'testModel' }), 500);
};
handlers.modeltest = (d) => {
const txt = (d.ok ? '连通正常:' : '失败:') + (d.detail || '');
$('#stModelTest').textContent = txt;
toast(d.ok ? '模型接口连通正常' : ('模型接口' + txt), !!d.ok);
};
$('#btnTestMail').onclick = () => {
$('#stMailTest').textContent = '正在发送…';
post({ type: 'testMail' });
};
handlers.mailtest = (d) => {
$('#stMailTest').textContent = d.ok ? '已发送,请查收' : ('失败:' + (d.error || '未知错误'));
toast(d.ok ? '测试邮件已发送' : ('发送失败:' + (d.error || '')), !!d.ok);
};
// ---------- 保存结果 ----------
handlers.saved = (d) => {
if (d.ok) toast('已保存 ' + d.name, true);
else toast('保存失败:' + (d.error || ''), false);
};
handlers.toast = (d) => {
toast(d.text || '', !!d.ok);
};
// ---------- 日志 ----------
let logText = '';
handlers.logs = (d) => { logText = d.text || ''; applyLogFilter(); };
function applyLogFilter() {
const kw = $('#inLogFilter').value.trim();
const lines = logText.split('\n');
$('#taLogs').value = kw ? lines.filter(l => l.indexOf(kw) >= 0).join('\n') : logText;
$('#taLogs').scrollTop = $('#taLogs').scrollHeight;
}
$('#btnRefreshLogs').onclick = () => post({ type: 'getLogs' });
$('#inLogFilter').oninput = applyLogFilter;
let logTimer = null;
$('#chkLogAuto').onchange = (e) => {
clearInterval(logTimer); logTimer = null;
if (e.target.checked) logTimer = setInterval(() => post({ type: 'getLogs' }), 3000);
};
// ---------- 关于 ----------
$('#btnOpenCfg').onclick = () => post({ type: 'openConfigDir' });
// ---------- 标题栏 ----------
$('#btnMin').onclick = () => post({ type: 'minimize' });
$('#btnMax').onclick = () => post({ type: 'maximize' });
$('#btnClose').onclick = () => post({ type: 'close' });
// 最大化 / 还原时切换图标,和系统窗口按钮保持一致
const SVG_MAX = '<svg width="12" height="12" viewBox="0 0 10 10" aria-hidden="true"><rect x="1.9" y="1.9" width="6.2" height="6.2" rx="0.8" fill="none" stroke="currentColor" stroke-width="1.1"/></svg>';
const SVG_RESTORE = '<svg width="12" height="12" viewBox="0 0 10 10" aria-hidden="true"><rect x="1.8" y="3.3" width="4.9" height="4.9" rx="0.8" fill="none" stroke="currentColor" stroke-width="1.1"/><path d="M3.8 3.3V2.3c0-.3.2-.5.5-.5h3.4c.3 0 .5.2.5.5v3.4c0 .3-.2.5-.5.5H6.7" fill="none" stroke="currentColor" stroke-width="1.1"/></svg>';
function setMaximizedIcon(maximized) {
const btn = $('#btnMax');
btn.title = maximized ? '还原' : '最大化';
btn.innerHTML = maximized ? SVG_RESTORE : SVG_MAX;
}
handlers.windowState = (d) => setMaximizedIcon(!!d.maximized);
// 标题栏拖拽:由前端指针事件驱动原生移动窗口,避免与 WebView2 抢鼠标捕获
let dragActive = false, dragOriginX = 0, dragOriginY = 0, dragMoved = false;
const dragBar = $('#drag');
dragBar.onpointerdown = (e) => {
if (e.button !== 0) return;
e.preventDefault();
dragBar.setPointerCapture(e.pointerId);
dragActive = true;
dragMoved = false;
dragOriginX = e.screenX;
dragOriginY = e.screenY;
};
dragBar.onpointermove = (e) => {
if (!dragActive) return;
const k = window.devicePixelRatio || 1;
const dx = Math.round((e.screenX - dragOriginX) * k);
const dy = Math.round((e.screenY - dragOriginY) * k);
if (!dragMoved) {
// 3px 阈值:单击/双击时不要把窗口挪动
if (Math.abs(dx) < 3 && Math.abs(dy) < 3) return;
dragMoved = true;
}
if (!dx && !dy) return;
dragOriginX = e.screenX;
dragOriginY = e.screenY;
post({ type: 'dragmove', dx, dy });
};
const endDrag = (e) => {
if (!dragActive) return;
dragActive = false;
try { dragBar.releasePointerCapture(e.pointerId); } catch (_) {}
};
dragBar.onpointerup = endDrag;
dragBar.onpointercancel = endDrag;
dragBar.ondblclick = () => post({ type: 'maximize' });
// ---------- 边框缩放:贴边 6px 内的手柄才接收事件 ----------
const H = 6;
document.addEventListener('mousemove', (e) => {
const x = e.clientX, y = e.clientY, W = innerWidth, Hh = innerHeight;
document.querySelectorAll('.handles div').forEach(d => {
const t = d.dataset.e;
let on = false;
if (t.includes('n')) on ||= y <= H;
if (t.includes('s')) on ||= y >= Hh - H;
if (t.includes('w')) on ||= x <= H;
if (t.includes('e')) on ||= x >= W - H;
d.style.pointerEvents = on ? 'auto' : 'none';
});
});
let rz = null;
document.querySelectorAll('.handles div').forEach(d => d.addEventListener('mousedown', (e) => {
rz = { x:e.screenX, y:e.screenY, e:d.dataset.e }; e.preventDefault();
}));
addEventListener('mousemove', (e) => {
if (!rz) return;
const dx = e.screenX - rz.x, dy = e.screenY - rz.y;
if (!dx && !dy) return;
let w = dx, h = dy;
if (rz.e === 'n') { w = 0; } else if (rz.e === 's') { w = 0; }
else if (rz.e === 'w') { h = 0; } else if (rz.e === 'e') { h = 0; }
const k = window.devicePixelRatio || 1;
post({ type:'resize', dx: Math.round(w * k), dy: Math.round(h * k), edge: rz.e });
rz = { x:e.screenX, y:e.screenY, e:rz.e };
});
addEventListener('mouseup', () => { rz = null; });
// ---------- 网络验证:登录 / 注册 / 卡密充值 ----------
let uiActive = false;
let uiBooted = false;
let authAccount = '';
function bootUi() {
if (uiBooted) return;
uiBooted = true;
post({ type: 'getShops' });
post({ type: 'status' });
setInterval(() => { if (uiActive) post({ type: 'status' }); }, 5000);
}
const authOverlay = $('#authOverlay');
const authMsgEl = $('#authMsg');
let authTab = 'login';
let authBusy = false;
function authSetMsg(text, ok) {
authMsgEl.textContent = text || '';
authMsgEl.className = 'auth-msg' + (ok ? ' ok' : '');
}
function authSetBusy(busy) {
authBusy = busy;
$('#authSubmit').disabled = busy;
$('#authRetry').disabled = busy;
}
function authShowTab(name) {
authTab = name;
document.querySelectorAll('#authOverlay .auth-tabs button').forEach(b => {
b.classList.toggle('on', b.dataset.tab === name);
});
document.querySelectorAll('#authOverlay .auth-pane').forEach(p => {
p.classList.toggle('on', p.dataset.pane === name);
});
$('#authSubmit').textContent = name === 'login' ? '登录' : (name === 'register' ? '注册' : '充值');
authSetMsg('');
}
document.querySelectorAll('#authOverlay .auth-tabs button').forEach(b => {
b.onclick = () => authShowTab(b.dataset.tab);
});
// 回填上次勾选「记住账号密码」保存的账号密码,只在用户尚未输入时填充
let authPrefilled = false;
function authFillSaved(d) {
if (authPrefilled) return;
const remember = !!d.remember;
$('#authRemember').checked = remember;
const u = document.querySelector('#authOverlay [data-pane="login"] [data-k="username"]');
const p = document.querySelector('#authOverlay [data-pane="login"] [data-k="password"]');
if (remember) {
if (u && !u.value) u.value = d.savedUsername || d.username || '';
if (p && !p.value) p.value = d.savedPassword || '';
authPrefilled = true;
}
}
function authPaneValue(key) {
const el = document.querySelector('#authOverlay .auth-pane.on [data-k="' + key + '"]');
return el ? el.value : '';
}
function authSubmit() {
if (authBusy) return;
const username = authPaneValue('username').trim();
if (!username) { authSetMsg('请输入账号', false); return; }
if (authTab === 'login') {
const password = authPaneValue('password');
if (!password) { authSetMsg('请输入密码', false); return; }
authSetBusy(true); authSetMsg('正在登录…', true);
post({ type: 'authLogin', username, password, remember: !!($('#authRemember').checked) });
} else if (authTab === 'register') {
const password = authPaneValue('password');
if (password.length < 6) { authSetMsg('密码至少 6 位', false); return; }
if (password !== authPaneValue('confirm')) { authSetMsg('两次输入的密码不一致', false); return; }
authSetBusy(true); authSetMsg('正在注册…', true);
post({ type: 'authRegister', username, password });
} else {
const cardKey = authPaneValue('card').trim();
if (!cardKey) { authSetMsg('请输入卡密', false); return; }
authSetBusy(true); authSetMsg('正在充值…', true);
post({ type: 'authRecharge', username, cardKey });
}
}
$('#authSubmit').onclick = authSubmit;
$('#authRetry').onclick = () => {
if (authBusy) return;
authSetBusy(true); authSetMsg('正在重新验证…', true);
post({ type: 'authRetry' });
};
// 标题栏账号弹窗:显示账号与授权,支持卡密充值和退出登录
let accPopOpen = false;
function accPopMsg(text, ok) {
const el = $('#accPopMsg');
el.textContent = text || '';
el.classList.toggle('ok', !!ok);
}
function showAccPop() {
const badge = $('#authBadge').getBoundingClientRect();
const pop = $('#accPop');
pop.style.top = Math.round(badge.bottom + 6) + 'px';
pop.style.left = Math.max(8, Math.round(badge.left - 20)) + 'px';
pop.classList.add('on');
accPopOpen = true;
accPopMsg('');
}
function hideAccPop() {
$('#accPop').classList.remove('on');
accPopOpen = false;
}
$('#authBadge').onclick = (e) => {
e.stopPropagation();
if (accPopOpen) hideAccPop(); else showAccPop();
};
$('#accPop').onclick = (e) => e.stopPropagation();
document.addEventListener('click', () => { if (accPopOpen) hideAccPop(); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && accPopOpen) hideAccPop(); });
$('#accPopCard').addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); $('#accPopRecharge').click(); }
});
$('#accPopRecharge').onclick = () => {
const cardKey = $('#accPopCard').value.trim();
if (!cardKey) { accPopMsg('请输入卡密', false); return; }
if (!uiActive) { accPopMsg('请先登录后再充值', false); return; }
accPopMsg('正在充值…', true);
post({ type: 'authRecharge', username: authAccount, cardKey });
};
$('#accPopLogout').onclick = () => {
if (!uiActive) { accPopMsg('当前未登录', false); return; }
hideAccPop();
post({ type: 'authLogout' });
};
authOverlay.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); authSubmit(); }
});
handlers.authState = (d) => {
const ok = !!d.ok;
uiActive = ok;
authAccount = d.username || authAccount;
authSetBusy(!!d.busy);
$('#authStateLine').textContent = d.summary || '';
$('#authBadge').textContent = ok ? (d.summary || '已验证') : '未验证';
$('#authBadge').classList.toggle('on', ok);
$('#accPopName').textContent = ok ? (authAccount || '—') : '—';
if (d.appVersion) $('#abVer').textContent = 'v' + d.appVersion;
// 弹窗里账号已单独显示,这里只保留到期 / 余额信息
const detail = (d.summary || '').replace(/^账号:[^·]*·?\s*/, '');
$('#accPopState').textContent = ok ? (detail || '已授权') : (d.message || '未授权');
authFillSaved(d);
if (ok) {
authOverlay.style.display = 'none';
bootUi();
} else {
hideAccPop();
authOverlay.style.display = 'flex';
authSetMsg(d.message || '', !!d.actionOk || !!d.busy);
}
};
handlers.authResult = (d) => {
authSetBusy(false);
// 验证页内的结果统一显示在页内消息区,不使用悬浮提示
if (d.message) authSetMsg(d.message, !!d.ok);
if (accPopOpen && d.message) {
accPopMsg(d.message, !!d.ok);
if (d.ok && d.action === 'recharge') $('#accPopCard').value = '';
}
if (d.ok && d.action === 'register') {
// 注册成功后停留在注册页,由用户自己切到登录页
document.querySelectorAll('#authOverlay [data-pane="register"] [data-k="password"], #authOverlay [data-pane="register"] [data-k="confirm"]')
.forEach(i => i.value = '');
}
if (d.ok && d.action === 'recharge') {
document.querySelectorAll('#authOverlay [data-k="card"]').forEach(i => i.value = '');
}
if (d.ok && d.action === 'logout') {
document.querySelectorAll('#authOverlay input[type="password"]').forEach(i => i.value = '');
}
};
// ---------- 版本更新 ----------
function updMsg(text, ok) {
const el = $('#updMsg');
el.textContent = text || '';
el.classList.toggle('ok', !!ok);
}
function updShow() { $('#updMask').classList.add('on'); }
function updHide() { $('#updMask').classList.remove('on'); }
handlers.updateState = (d) => {
const status = d.status || '';
if (d.currentVersion) $('#abVer').textContent = 'v' + d.currentVersion;
if (status === 'available') {
$('#updTitle').textContent = d.forced ? '需要更新到新版本' : '发现新版本';
$('#updVer').textContent = '最新版本 ' + (d.latestVersion || '') +
' · 当前 ' + (d.currentVersion || '') +
(d.sizeBytes ? ' · ' + (d.sizeBytes / 1048576).toFixed(1) + ' MB' : '');
$('#updNotes').textContent = d.notes || '本次更新暂无说明';
$('#updBarWrap').classList.remove('on');
$('#updBar').style.width = '0%';
$('#updNow').disabled = false;
$('#updLater').style.display = d.forced ? 'none' : '';
updMsg('');
$('#updStatus').textContent = '发现新版本 ' + (d.latestVersion || '');
updShow();
} else if (status === 'downloading') {
const p = Math.max(0, Math.min(100, d.percent || 0));
$('#updBarWrap').classList.add('on');
$('#updBar').style.width = p + '%';
$('#updNow').disabled = true;
updMsg('正在下载更新包… ' + p + '%', true);
$('#updStatus').textContent = '正在下载更新包… ' + p + '%';
updShow();
} else if (status === 'error') {
$('#updBarWrap').classList.remove('on');
$('#updNow').disabled = false;
$('#updLater').style.display = '';
updMsg(d.message || '更新失败', false);
$('#updStatus').textContent = d.message || '更新失败';
updShow();
} else if (status === 'ready') {
$('#updBarWrap').classList.remove('on');
$('#updNow').disabled = true;
$('#updLater').style.display = 'none';
updMsg(d.message || '新版本已替换,请重新打开程序', true);
$('#updStatus').textContent = '已更新,请重新打开程序';
} else if (status === 'none') {
$('#updStatus').textContent = d.message
? ('检查更新失败:' + d.message)
: ('已是最新版本 ' + (d.currentVersion || ''));
}
};
$('#updNow').onclick = () => {
updMsg('准备下载更新包…', true);
post({ type: 'updateDownload' });
};
$('#updLater').onclick = updHide;
$('#btnCheckUpdate').onclick = () => {
$('#updStatus').textContent = '正在检查更新…';
post({ type: 'checkUpdate' });
};
authSetBusy(true);
authSetMsg('正在连接验证服务器…', true);
// ---------- 启动 ----------
handlers.switchPage = (d) => { if (d.page) switchPage(d.page); };
</script>
</body>
</html>