diff --git a/.gitignore b/.gitignore
index 855eb0c..c286dec 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,6 +21,8 @@ dsh_desk/
conversation_blacklist.sqlite3*
message_origins.sqlite3*
+proactive_contacts.sqlite3*
+protocol_inbound_recovery.json
# 大文件/本地产物,不入库
.venv/
diff --git a/PROACTIVE_CUSTOMER_CONTACT_PLAN.md b/PROACTIVE_CUSTOMER_CONTACT_PLAN.md
new file mode 100644
index 0000000..11b44f3
--- /dev/null
+++ b/PROACTIVE_CUSTOMER_CONTACT_PLAN.md
@@ -0,0 +1,329 @@
+# 主动联系客户模块方案
+
+## 1. 建设目标
+
+在桌面端新增独立的「主动联系」板块,用于把已绑定患者信息的指定客户加入主动联系名单,批量配置发送内容,并支持:
+
+强制准入条件:客户必须已通过现有「关联 ZYT 患者信息」功能绑定真实患者档案,且绑定关系在当前账号权限下有效,才能加入本模块。此条件不能通过批量添加、导入或管理员设置绕过。
+
+- 立即发送:人工确认后,对选中的客户创建发送任务。
+- 定时发送:指定日期、时间或允许发送的时间段,按规则自动执行。
+- 批量设置:多名客户共用一套话术,也可逐个覆盖内容。
+- 全程可追踪:明确展示待发送、发送中、成功、失败、跳过、已取消等状态。
+- 安全可控:避免重复、错人、非工作时间发送,以及与自动回复抢占发送通道。
+
+本模块定位为“确定客户 + 确定内容 + 确定时间”的任务工具。第一版不让 AI 自主决定联系谁,也不让 AI 未经确认自动生成并发送营销内容。
+
+## 2. 页面入口与信息架构
+
+在左侧导航中新增「主动联系」,建议放在「任务队列」之后、「会话归档」之前。
+
+页面分为四个区域:
+
+1. 顶部概览
+ - 今日计划、待发送、发送成功、异常任务。
+ - 「添加客户」「批量设置」「立即发送」三个主操作。
+2. 客户任务列表
+ - 复选框、客户名称、绑定患者姓名/编号、绑定状态、所属企微账号、标签、发送内容摘要、计划时间、状态、最近结果。
+ - 支持按账号、标签、状态、计划日期筛选和搜索。
+3. 右侧任务编辑抽屉
+ - 编辑话术、变量预览、发送方式、时间规则和安全选项。
+4. 执行记录
+ - 展示每次尝试的时间、使用通道、结果、失败原因和操作人。
+
+建议提供三个页签:
+
+- 「联系计划」:尚未完成及执行中的任务。
+- 「客户名单」:已添加且患者绑定有效、可再次创建计划的客户池;绑定失效的历史条目单独标记为不可用,不参与选择或发送。
+- 「发送记录」:只读审计和结果查询。
+
+## 3. 核心功能
+
+### 3.1 添加客户
+
+客户来源(所有来源均执行患者绑定校验):
+
+- 从现有「通讯录 → 我的客户」中多选。
+- 从会话归档中选择已有客户。
+- 后续版本可增加 CSV 导入,但必须以当前企微账号和稳定客户 ID 做匹配,不能只靠昵称。
+
+添加时展示并保存:企微账号、客户稳定 ID、会话 ID、昵称/备注、绑定患者姓名/编号、绑定状态、标签、来源、最近会话时间和当前是否可发送。
+
+同一企微账号下相同客户不可重复加入客户池;但允许为同一客户建立多条不同日期的联系计划。
+
+#### 患者绑定准入与变更处理
+
+- 客户选择器默认只展示已绑定患者且核验通过的客户。切换查看未绑定客户时,该客户不可勾选,并提供「去绑定患者」入口。
+- 「去绑定患者」复用现有患者搜索与绑定流程。绑定成功后重新校验,再允许加入;仅填写患者姓名、备注或手工传入患者编号不算完成绑定。
+- 校验必须对应当前企微账号、目标联系人和绑定患者。一个会话中其他联系人的绑定不能作为当前客户的准入依据;如返回多条有效绑定,需明确选择本次联系对应的患者。
+- 批量添加时逐人校验,只加入通过的客户;结果明确列出成功人数、未加入客户及原因,例如“未绑定患者”“绑定已失效”“暂无法核验”。
+- 网络异常、登录过期或权限不足导致无法确认绑定时,不允许新增客户,提示恢复连接或登录后重试。
+- 创建立即发送/定时任务时保存本次选定的患者和绑定关系快照;每次实际发送前,包括重试、周期执行和重启恢复,都再次核验同一绑定仍有效。
+- 客户解绑、患者档案失效或权限失效后,客户退出可用名单,尚未发送的任务暂停并显示原因;历史发送记录保留。恢复有效绑定后需重新核对并手动恢复任务。
+- 客户改绑到另一位患者时,旧任务不可自动转给新患者;应取消旧任务并按新绑定重新创建。发送前无法核验时同样暂停,不能凭旧缓存发送。
+- 已提交给发送通道的消息无法保证撤回;绑定变更应阻止后续未提交任务,已提交任务按实际回执记录结果。
+
+绑定只要求有效患者档案和明确的联系人关联,不额外强制要求已下单、已预约或已绑定诊断记录。列表只展示识别患者所需的信息,完整病历无需复制到本模块。
+
+### 3.2 批量设置话术
+
+批量选择客户后可设置统一正文,并支持变量:
+
+- `{{客户名称}}`
+- `{{客服名称}}`
+- `{{日期}}`
+
+保存前必须生成逐人预览。变量缺失时不得直接发送,需标记为“待补充”或使用用户明确配置的兜底值。
+
+第一版建议仅支持纯文字,单条内容限制为与当前发送通道一致的安全长度。图片、文件、小程序卡片放在后续版本,避免不同发送通道的能力不一致。
+
+每个客户可以单独覆盖批量话术;列表中应清楚标记“使用批量话术”或“已单独修改”。
+
+### 3.3 立即发送
+
+立即发送不是在界面循环点击,而是批量创建独立任务:
+
+1. 用户勾选客户并点击「立即发送」。
+2. 弹出最终确认页,按账号分组展示收件人、绑定患者姓名/编号、实际正文和预计任务数。
+3. 校验账号、联系人、有效患者绑定、黑名单、重复任务、发送通道和当前可发送状态。
+4. 确认后进入专用主动发送队列,串行执行。
+5. 每一条任务分别记录结果,部分失败不影响其他客户,但不自动无限重试。
+
+### 3.4 定时发送
+
+支持两种方式:
+
+- 指定时间:例如 2026-11-02 10:30 开始发送。
+- 时间段:例如工作日 09:00–11:30、14:00–17:30,在允许窗口内依次发送。
+
+时间段任务需要设置:
+
+- 生效日期或日期范围。
+- 每周执行日。
+- 一个或多个允许发送时段。
+- 客户间隔,建议默认 20–60 秒并由管理员配置范围。
+- 错过时间段后的处理:顺延到下一个允许时段(默认)或取消本次。
+
+所有时间按本机明确显示的时区保存;数据库内部使用 UTC 时间戳,并保存创建时区,避免换时区或夏令时导致错发。
+
+定时任务由桌面端持久化调度器执行。程序关闭、企微未登录或发送通道不可用时不应悄悄丢失;恢复后先重新校验客户、患者绑定和时间窗口,再决定顺延或标记异常。无法核验或绑定失效的任务进入暂停状态,不参与顺延发送。
+
+## 4. 状态设计
+
+任务主状态建议统一为:
+
+- `draft`:草稿,信息未完整。
+- `scheduled`:已计划,等待到期。
+- `queued`:已到期,等待发送通道。
+- `paused`:暂停,等待处理;记录患者解绑、绑定变化、绑定核验失败或客户新来信等具体原因。
+- `sending`:正在执行。
+- `succeeded`:已取得明确成功回执。
+- `failed`:明确失败,可按策略重试。
+- `delivery_unknown`:结果不确定,禁止自动重发,必须人工核对。
+- `skipped`:因黑名单、客户不可用、内容为空、超出时间窗等跳过。
+- `cancelled`:用户取消。
+
+`delivery_unknown` 必须独立于失败状态。当前项目已有发送证据和不确定结果保护,主动发送应沿用同样原则,避免“实际已发出但程序没拿到回执”时重复发送。
+
+## 5. 安全规则
+
+- 发送前再次校验当前登录企微账号与任务所属账号一致。
+- 发送前再次解析稳定客户 ID,禁止仅按昵称匹配。
+- 将有效患者绑定作为添加客户、创建任务和实际发送的强制条件,由业务服务层统一校验;前端禁用按钮不能替代校验。保存患者和绑定关系快照,发送前确认目标患者未变,绑定变更处理与发送前最后核验共用互斥控制。
+- 复用现有黑名单/忽略管理;命中后标记跳过并说明原因。
+- 同一账号、客户、正文的幂等键在配置窗口内只能成功发送一次。
+- 主动联系与自动回复共用全局发送锁,客户新消息自动回复优先;主动联系固定通过协议发送,不受键鼠活动影响。
+- 客户在任务等待期间发来新消息时,默认暂停该客户的主动任务,提示人工决定“取消、改为回复、仍按原计划发送”。
+- 批量任务设置单批上限和每日上限;达到上限后停止排队并明确提示,不做规避平台限制的自动化策略。
+- 保存创建人、修改人、确认人、发送时间、实际正文、目标稳定 ID、通道和回执证据,便于审计。
+- 编辑已排队任务时生成新版本;已经进入 `sending` 的任务不可修改正文。
+
+## 6. 数据设计
+
+建议新增独立 SQLite 数据库 `proactive_contacts.sqlite3`,不要复用 `pending_replies*.json`。核心表:
+
+### `proactive_customers`
+
+- `id`
+- `account_id`
+- `conversation_id`
+- `peer_id`
+- `display_name`
+- `person_id`:现有患者绑定体系中的联系人 ID。
+- `patient_id`:明确选定的已绑定患者编号。
+- `patient_display_name`:列表展示用患者姓名。
+- `binding_state` / `binding_checked_at`:绑定核验状态和最近核验时间,仅供展示,不能替代发送前校验。
+- `binding_snapshot_json`:绑定标识、目标患者和绑定版本等必要关联信息;版本标记需由服务端提供。
+- `tags_json`
+- `source`
+- `sendable_state`
+- `created_at` / `updated_at`
+- 唯一约束:`account_id + peer_id`
+
+### `contact_campaigns`
+
+- `id`
+- `name`
+- `message_template`
+- `schedule_type`:immediate / fixed / window
+- `schedule_json`
+- `timezone`
+- `status`
+- `created_by` / `created_at` / `updated_at`
+
+### `contact_tasks`
+
+- `id`
+- `campaign_id`
+- `customer_id`
+- `patient_id` / `binding_snapshot_json`:创建任务时固定的患者及绑定关系,不能随客户改绑而静默替换。
+- `rendered_message`
+- `scheduled_at`
+- `not_before` / `expires_at`
+- `status`
+- `attempt_count`
+- `idempotency_key`
+- `last_error_code` / `last_error_message`
+- `pause_reason`:未绑定、绑定失效、绑定变化、暂无法核验等暂停原因。
+- `claimed_at` / `finished_at`
+
+### `contact_task_attempts`
+
+- `id`
+- `task_id`
+- `started_at` / `finished_at`
+- `transport`
+- `result`
+- `receipt_json`
+- `operator`
+
+数据库使用事务领取任务:只有从 `queued` 原子更新为 `sending` 成功的执行器才可发送,防止多个线程或重启恢复时重复执行。
+
+## 7. 与现有项目的集成方式
+
+现有项目可复用:
+
+- 「我的客户」读取和联系人可发送性核验。
+- `backend_client.py` 中的 `desktop_patient_context`、`search_desktop_patients`、`bind_desktop_patient`,以及现有「关联 ZYT 患者信息」界面;使用现有服务端绑定关系作为准入依据。
+- 已有协议模式的发送实现;主动联系固定使用协议通道。
+- `send_lock.py` 的发送互斥能力。
+- 黑名单/忽略管理。
+- 发送回执、结果不确定保护和运行日志。
+
+需要新增:
+
+- `proactive_contact_store.py`:客户、活动、任务、尝试记录的数据访问层。
+- `proactive_contact_scheduler.py`:到期扫描、时间窗判断、任务领取和恢复。
+- `proactive_contact_service.py`:权限、患者绑定准入及发送前复核、模板渲染、幂等和任务编排。
+- 患者绑定批量核验及变更处理:按现有接口能力补充批量查询、绑定版本标记与变更通知;解绑/改绑后更新客户可用状态并暂停未发送任务,发送前仍需复核,避免依赖通知是否及时到达。
+- 主动联系页面与新增导航入口。
+- 协议发送适配层的“明确目标发送”接口,接收指定账号、会话及正文并返回可核验结果。
+
+关键边界:主动任务不写入现有 `pending_replies.json` 或 `pending_replies.protocol.json`。现有文件表达的是“客户来信后的待回复状态”,主动联系需要自己的生命周期;执行时只共享底层发送通道、发送锁和回执验证。
+
+## 8. 权限与操作控制
+
+建议至少分为:
+
+- 查看:查看名单、计划和记录。
+- 编辑:添加客户、编辑草稿和时间规则。
+- 执行:确认立即发送、启停定时活动、重试明确失败任务。
+- 管理:配置批量上限、发送时段、变量和权限。
+
+删除已经执行过的活动时只做归档,不物理删除发送记录。
+
+所有角色均受患者绑定准入限制;患者绑定操作沿用现有权限,拥有主动联系的编辑或执行权限不代表可新增或修改患者绑定。
+
+## 9. 第一版验收标准
+
+1. 可从当前账号“我的客户”中批量添加已绑定有效患者的客户,且不会因同名选错人;未绑定客户不可加入。
+2. 可为多名客户设置统一纯文字,并预览每个人的最终正文。
+3. 可立即发送,也可指定时间或允许时间段发送。
+4. 重启程序后任务仍存在,不会重复发送成功任务。
+5. 企微账号不一致、客户不可发送、命中黑名单或超出时间窗时不会发送,并显示具体原因。
+6. 自动回复和主动联系同时出现时不会抢占同一个发送通道。
+7. 结果不确定的任务不会自动重发。
+8. 每个客户都能查询实际正文、计划时间、执行时间、结果和失败原因。
+9. 未绑定客户可通过「去绑定患者」完成现有绑定流程,校验通过后才可加入;批量添加中不合格客户被排除并展示原因。
+10. 客户解绑或改绑后,尚未发送的任务暂停;旧患者任务不会自动转给新患者。已发送记录保留。
+11. 直接调用业务接口、导入、任务重试和重启恢复均无法绕过绑定校验;核验超时、权限失效时不发送。
+12. 列表、发送确认页和历史任务能核对对应患者姓名/编号,历史任务保留当时绑定,不被后续改绑覆盖。
+
+## 10. 推荐实施顺序
+
+### 第一阶段:可控 MVP
+
+- 新页面、仅限已绑定患者的客户池、绑定入口与状态展示、纯文字批量设置。
+- 立即发送、单次指定时间、单个每日时间段。
+- SQLite 持久化、串行发送、状态与记录。
+- 黑名单、账号及患者绑定核验、解绑/改绑暂停、幂等、发送锁、重启恢复。
+
+### 第二阶段:运营能力
+
+- 多时间段、周期活动、客户标签筛选。
+- 失败任务批量处理、活动复制、数据导出。
+- 管理后台统一配置配额、时段与权限。
+
+### 第三阶段:智能辅助
+
+- AI 仅生成话术草稿和个性化建议,默认必须人工预览确认。
+- 基于客户最近会话给出联系建议,但不自动决定发送。
+- 在有明确业务规则和合规确认后,再评估更高级的自动化。
+
+## 11. 建议的默认产品规则
+
+- 必须绑定有效患者才能加入;此项为强制规则,不提供关闭开关。
+- 默认仅纯文字。
+- 默认客户间隔 30 秒。
+- 默认允许时段为工作日 09:00–18:00,由管理员调整。
+- 默认程序离线后顺延到下一个允许时段。
+- 默认客户发来新消息后暂停该客户的主动任务。
+- 默认失败最多自动重试 1 次;`delivery_unknown` 永不自动重试。
+- 每次批量点击发送前必须展示最终收件人和正文确认页。
+
+这套默认规则优先保证不重复、不发错、不抢占客户新消息回复,再逐步增加运营效率。
+
+## 12. 第一版源码交付记录(2026-10-31)
+
+已接入桌面控制台左侧「主动联系」,包含「客户名单」「联系计划」「发送记录」。使用步骤:
+
+1. 点击「添加客户」,从当前企微账号「我的客户」中选择已绑定患者的客户。未绑定客户可通过「去绑定患者」调用现有绑定窗口。
+2. 在客户名单中勾选客户,直接填写本次发送文字,无需先保存。需要长期复用时可点击「保存为客户常用文字(不创建任务)」;如各客户使用不同内容,可切换到「使用各客户已保存的文字」。支持客户名称、客服名称和日期变量。
+3. 选择立即发送、指定时间或按时间段发送。时间段支持起止日期、星期和每日一个时段。
+4. 点击「预览发送内容」,弹窗明确显示「尚未创建任务」。核对每位客户、对应患者、实际正文与时间,再点击确认创建;返回修改不会创建任务。
+5. 创建成功立即显示绿色结果、数量和批次编号,并切换到本次联系计划。任务创建结果先于发送执行返回,已发送任务仍保留在计划列表中。可暂停、核验恢复或取消未发送任务;发送记录中查看实际正文、执行结果及服务器回执。若显示「结果待核对」,可点击「核对发送结果(不重发)」;系统也会每 30 秒尝试补核验已有回执。
+
+本次落地边界:
+
+- 强制患者绑定校验使用现有服务端患者关联及患者搜索接口,无需新增服务端路由。添加时核验患者仍可访问,创建和实际发送前再次核验;绑定身份由联系人稳定 ID、患者编号、绑定 ID 及服务端更新时间共同固定。
+- 模块固定通过现有已验证协议通道发送纯文字,不模拟点击、不占用键鼠,也不要求键鼠空闲。支持与视觉或协议自动回复同时运行,保留自动回复优先及共用发送锁;当前账号需先完成协议检测及首次发送验证。
+- 独立主动调度开关;关闭自动回复监听不会关闭主动联系。完全退出程序或电脑关机时不能执行任务,重启后恢复已确认计划。
+- 第一版时区固定为页面标明的 UTC+08:00。每条任务只发送一次;时间段用于安排本批客户依次发送,未完成任务顺延至允许的下个时段,超过截止日期跳过。重复周期活动留在第二阶段。
+- 每批最多 100 位客户,每个企微账号滚动 24 小时最多 100 次发送尝试,默认间隔 30 秒。明确在发送提交前因临时占用而等待的检查不消耗配额或客户发送间隔。失败保留记录,由人工核对并重新确认新任务;结果不确定的任务不能自动重发,也不能通过恢复按钮重发。
+- 自动回复占用、发送锁占用及客户发送间隔会显示「等待自动继续」和具体原因,条件满足后自动重新核验并发送。鼠标和键盘操作不会阻塞本模块的协议发送,已移除原先等待连续空闲 5 秒的逻辑。主动暂停、解绑/改绑、客户新消息及结果不确定仍须按各自规则处理,不会当作临时占用自动恢复。旧版本已误暂停的任务,升级并重启助手后可勾选原任务执行一次「核验并恢复」,无需重建任务。
+- 本机绑定窗口中的变更会触发重新核验;其他端的解绑或改绑在刷新核验、创建任务及实际发送前被拦截。历史任务不会自动换绑到新的患者。
+- SQLite 保存客户、计划、独立任务、发送尝试及调度开关,按客服助手登录账号隔离。任务库已加入 Git 忽略规则;任务结果不会写入自动回复待处理文件。
+
+已通过 63 项相关回归测试,使用临时数据库、合成患者和模拟发送;覆盖准入校验、绑定变化、新消息、去重、时间段、恢复、互斥、账号隔离、Qt 线程联动、启动时暂停、未保存草稿、逐人文字及创建回执先于发送返回。另覆盖发送前各阶段的临时占用、等待期间不消耗配额、重启自动继续,以及原生发送适配器在明确取消提交后清理防重记录、随后仅发送一次。实际 Qt WebEngine 页面测试通过 QWebChannel 连接真实后台线程、业务层及隔离 SQLite,验证「填写但不保存 → 预览 → 确认 → 一条任务 → 最后阶段临时占用 → 等待提示 → 无需手动恢复,空闲后模拟发送一次」全流程;另检查错误提示、重复点击防护、时间段参数、未绑定禁选、内容转义和状态刷新。截图输出为 `tmp/proactive-contact-ui.png` 和 `tmp/proactive-contact-preview.png`。患者接口和发送端使用模拟对象,未向真实客户发送测试消息。
+
+绑定准入修复:ZYT 关键词接口按姓名、手机号检索,不支持直接用患者主键作为关键词。现在使用服务端绑定记录中的姓名检索,并精确匹配患者编号;按原始诊单总数翻页,避免同名或多诊单去重造成漏查。未找到、返回不完整、查询权限失效及核验期间解绑/改绑仍会阻止加入与发送。已复现原误报并完成修复,截图客户通过实际接口的只读核验;原绑定未修改,未创建发送任务。源码启动的助手需完全退出后重新打开,加载本次修复。
+
+协议直发调整:主动联系调度与最终发送前的核验均不再调用键鼠空闲检测;新增验证明确断言发送流程不会调用 `GetLastInputInfo`,同时验证自动回复占用后仍可自动继续且只发送一次。界面同步说明「直接通过协议发送,操作鼠标键盘不影响发送」。
+
+回执同步修复:主动联系使用独立、用后清理的消息库缓存,避免与自动回复读库共用副本时互相干扰。协议回调一返回即保存服务器消息编号;消息库暂时读取失败时继续尝试核对,超时仍保留回调,后续仅按账号、会话、服务器编号及正文补核验,不调用发送接口。核验成功同时更新任务、发送尝试和消息来源记录,保留原错误供审计。旧版丢失回调编号的未知记录不会仅凭相同文字自动认定成功;本次用户明确确认已发送的历史任务,在唯一匹配本地记录后备份并修正。新增回执恢复及界面指令测试,并连同协议适配等相关测试共通过 100 项。
+
+任务删除与后续回复:联系计划及发送记录均提供逐条删除、勾选批量删除和全选当前列表(每批最多 100 条)。确认窗口列明客户、正文、任务状态与删除影响;删除后同时从两处列表移除,未发送任务停止调度。正在发送的任务须等待结果返回,提交前收到删除请求会先中断提交。底层保留发送尝试、回执及去重依据,删除不能绕过 24 小时防重和发送间隔,也不撤回已发消息、不删除客户绑定。
+
+主动联系任务经回执确认发送成功后,在 Qt 主线程自动开启现有自动回复监听,无需点击开启按钮。即时发送、定时发送、重启恢复及补核验成功均适用。已有监听直接复用;若处于审核模式,则切换到自动回复模式,保留风险审核规则。启动请求完成后持久化登记,刷新页面或重启不会因同一已处理成功任务反复启动;手动停止仍有效,后续新的成功任务可再次触发。程序启动时会补处理最近 24 小时成功但尚未触发自动回复的任务。环境检测尚在进行时不提前登记启动完成,检测失败会明确显示错误;自动启动保持控制台页面,不自动收起到胶囊。
+
+协议监听每 30 秒补查最近 24 小时已确认的主动发送记录,用精确账号、会话和服务器回执匹配本地历史,将之后尚未回复的客户消息送入原有自动回复队列,解决客户在监听启动前回复而被时间水位漏掉的问题。普通新消息仍由原有监听接收;补查不发送原主动消息,不越过风险审核、暂停、失败/不确定发送保护及去重。删除主动任务不影响这一衔接,因为其发送来源记录保留。停止监听后不处理客户回复;程序及企微须保持运行。
+
+本次新增验证覆盖单条/批量删除、重启后不恢复被删任务、删除成功或未知任务后仍保留防重证据、发送前删除竞态,以及客户在监听前回复的完整协议处理和重启去重。两组相关测试分别通过 70 项与 95 项(其中部分重复回归)。真实 Qt WebEngine + QWebChannel + 后台线程 + 临时 SQLite 界面测试通过,检查删除确认/保留任务、成功任务可选、批量删除、列表与数量刷新,以及监听/审核状态更新;截图另存 `tmp/proactive-contact-delete.png`。所有发送均为模拟对象。
+
+本次交付为源码及测试,未发布云端更新、未重新打包 EXE,也未向真实客户发送验证消息。
+
+自动开启补充验证:确认发送前不启动,收到成功回执后仅触发一次;未知结果补核验成功再触发;启动完成记录跨刷新和重启保留。实际主窗口入口验证了复用已运行监听、切换自动模式、后台启动不收起窗口、等待协议检测、不提前登记检测中的启动、手动停止取消延后启动,以及启动失败提示。Qt WebEngine 全流程验证从成功发送到「自动回复已开启」无需按钮点击,并检查最终绘制画面。
+
+客户兼任助理的收信修复:同一个会话同时被配置为医疗助理接收人时,旧的收信过滤会直接标记新消息已见、移出待处理队列。现在按本地账号、会话和精确服务器回执判断当前轮次:已确认主动联系及其后续 AI 对话按客户消息入队;医疗助理通知或其他来源的发出消息结束该轮客户身份覆盖,原助理通知规则保持不变。缺少可靠回执或身份不匹配时不推测。审核、人工转交和发送结果未知的保护仍然保留。
+
+本次已使用真实本地上下文在隔离队列中复现并验证入队,不调用真实 AI 或发送。对明确确认被旧过滤规则误标已见的最新入站事件,在备份后登记 `protocol_inbound_recovery.json` 一次性恢复记录,升级重启后读取;需要精确账号/会话/消息标识匹配,已有发送尝试或该消息已转人工时不得恢复,完成标识跨重启保存。普通已见消息不会回放。双角色、恢复去重、通知边界及原有规则共 94 项相关测试通过。
diff --git a/WECOM_AUTO_ADAPTATION.md b/WECOM_AUTO_ADAPTATION.md
index 243dd42..00f74e9 100644
--- a/WECOM_AUTO_ADAPTATION.md
+++ b/WECOM_AUTO_ADAPTATION.md
@@ -1,6 +1,45 @@
# 企业微信升级自动适配修复
-## 使用
+## 2026-10-31:5.0.13.6005 修复(助手 v1.5.5)
+
+本机升级后,原规则可以匹配 `factory`、`factory_impl` 和发送函数,
+但消息构造函数 `message_ctor` 的清零指令发生变化:
+原先分别写入 `0x160..0x161` 和 `0x162`,新版合并为写入 `0x160..0x163`。
+该指令变化使后续指令前移 6 字节,原来的完整函数签名拒绝匹配。
+
+本次增加经过独立核对的完整构造函数签名变体,并保留原签名。
+仍要求 9 个完整函数、跨函数指针关系、3 个类型表和运行中代码全部通过;
+未增加版本白名单,也未扩大地址以外的通配范围。适配修订为 `relocated-text-v2`,
+新构建首次发送及服务器回执仍须单独验证。
+
+错误报告现在显示具体失败函数,例如 `message_ctor`,以及是否存在多组匹配,
+避免把全部子调用失败统称为 `factory` 失败。
+
+源码已对本机运行中的 `5.0.13.6005 x86` 完成只读校验:
+`autoAdapted=true`、`loginVerified=true`、`databaseReady=true`、`canSend=false`,
+状态为“自动适配完成,待首次发送验证”。29 项回归测试通过。
+源码界面已正常重启并确认显示上述状态及“首次发送验证”按钮。
+适配检测阶段未发送真实消息。报告:`protocol-validation-reports/auto-adaptation-6005-readonly.json`。
+
+完整程序:`dist/ZhenAI-WeCom-Assistant-v1.5.5/ZhenAI-WeCom-Assistant-v1.5.5.exe`。
+整个目录一起保留。打包自检通过;EXE 对本机客户端的只读检测也得到相同结果。
+打包时补齐了构建 Python 所需的证书策略资源,保持原证书校验,相关 3 项回归测试通过。
+合计 32 项测试通过;汇总见 `protocol-validation-reports/auto-adaptation-6005-acceptance.json`,
+界面验证与打包检测分别见 `auto-adaptation-6005-ui.json` 和 `auto-adaptation-6005-packaged.json`。
+
+后续已按用户明确授权,向当前账号唯一匹配的“高瑞”发送一次“协议通道测试,请忽略”。
+真实发送回调成功,服务器回执 `1028057`、本地消息编号 `1348`,发送账号、会话及正文均核对一致。
+发送后复检为 `native_ready`,`canSend=true`、`sendVerified=true`、`receiptVerified=true`。
+未启动自动监听。发送记录:`protocol-validation-reports/gaorui-6005-send-20261031.json`;
+复检记录:`protocol-validation-reports/gaorui-6005-after-send-20261031.json`。
+
+重新生成完整签名(必须同时提供两份哈希固定的参考文件,防止遗漏新变体):
+
+```powershell
+.\.build-venv\Scripts\python.exe -X utf8 -B tools/generate_wecom_signatures.py tmp/wecom-5.0.11/client/WXWork.exe --variant-reference 'C:\Program Files (x86)\WXWork\WXWork.exe'
+```
+
+## 2026-09-28 使用记录(旧版)
退出正在运行的旧版客服助手,再打开:
diff --git a/ai_settings.json b/ai_settings.json
index ab40dcf..8a42806 100644
Binary files a/ai_settings.json and b/ai_settings.json differ
diff --git a/app_settings.json b/app_settings.json
index c0090ae..8507fb0 100644
--- a/app_settings.json
+++ b/app_settings.json
@@ -8,7 +8,7 @@
"mouse_idle_enabled": true,
"mouse_idle_seconds": 5.0,
"send_delay_seconds": 1.0,
- "send_mode": "review",
+ "send_mode": "auto",
"review_scope": "every",
"reply_transport": "protocol",
"message_batch_window_seconds": 5.0,
diff --git a/app_version.py b/app_version.py
index c02c9ce..1e29ae5 100644
--- a/app_version.py
+++ b/app_version.py
@@ -7,7 +7,7 @@ import re
from typing import Any
-APP_VERSION = "1.5.4"
+APP_VERSION = "1.5.5"
_VERSION_PATTERN = re.compile(
r"^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
r"(?:[-+][0-9A-Za-z.-]+)?$"
diff --git a/assets/ui/console-app.js b/assets/ui/console-app.js
index a2c4c25..6593570 100644
--- a/assets/ui/console-app.js
+++ b/assets/ui/console-app.js
@@ -15,6 +15,15 @@ function esc(value){
}[ch]));
}
+function syncNavigation(name){
+ document.querySelectorAll("[data-view]").forEach(button => {
+ const selected = button.dataset.view === name;
+ button.classList.toggle("active", selected);
+ if (selected) button.setAttribute("aria-current", "page");
+ else button.removeAttribute("aria-current");
+ });
+}
+
const blacklistUi = {query: "", account: "", selected: new Set(), busy: false};
function blacklistKey(item){ return JSON.stringify([String(item.account), String(item.conversation)]); }
function visibleBlacklistItems(){
@@ -211,7 +220,7 @@ function sortLabel(mode){
function polishedIcons(html){return html.replace(glyphMatcher,glyph=>glyphLookup.get(glyph))}
function render(name){
if(!views[name])name="auto";
- document.querySelectorAll("[data-view]").forEach(b=>b.classList.toggle("active",b.dataset.view===name));
+ syncNavigation(name);
document.getElementById("main").innerHTML=polishedIcons(views[name]());
const listen=document.querySelector('[data-action="toggle-listen"]');
if(listen)listen.innerHTML=listening?`${icon("pause")}暂停监听`:`${icon("play")}恢复监听`;
@@ -648,7 +657,7 @@ automationView = function(){
${reviewScopePanel(a, autoOn)}${reviewAssistantPanel(a)}
+
已登记构建:${esc(p.supportedClient || "5.0.10.6023 x86、5.0.11.6018 x86、5.0.11.6026 x86")}。新版 x86 客户端按完整接口结构自动适配,以本页检测结果为准;结构发生变化或使用 x64 客户端时需要更新适配规则。安装盘符和目录自动识别。当前自动处理文本消息。
发送核对
客户补充消息时重新生成回复;人工已经回复时取消旧任务。发送结果不明确时保留该会话记录待核对,其他会话继续监听,防止重复发送。
协议模式按会话 ID 发送,不操作聊天窗口。切换账号或升级企业微信后,会重新校验可用性。
`;
}
return `${head("自动化设置","配置企业微信监听、消息合并与自动发送规则",`
${esc(a.wecom || "企业微信未识别")}规则已生效`)}${transportPanel}
${reviewScopePanel(a, autoOn)}${reviewAssistantPanel(a)}
监听与发送策略
${icon("activity")} ● 规则运行中${[["activity","扫描未读"],["log","提取消息"],["folder","合并消息"],["brain","请求 AI"],["send","回填发送"]].map(x=>`
`).join("")}
企业微信窗口
${icon("clipboard")} 主窗口:● ${esc(a.wecom || "未识别")}
${icon("user")} 当前账号:${esc(a.account || "—")}
${icon("globe")} DPI:${esc(STATE.dpi || "—")}
${icon("monitor")} 最小化恢复:● 已开启
消息处理
✓ 同一客户连续消息自动合并
✓ 保留最近 轮上下文${esc(a.context || 8)} 轮
✓ 一次只处理 1 个会话1 个
异常与兜底
${icon("clock")}AI 超时:${esc(a.timeout || 120)} 秒后重试2 次
${icon("alert")}发送失败:自动重试已开启
${icon("message")}固定回复:${esc(a.reply || "在的,请稍等")}
高风险转人工
● 已开启${handoffRuleTags(a.reviewRules)}
启动前检查
${statusCells([["check","企业微信已登录", STATE.wecomConnected ? "检查完成" : "等待连接"],["cloud","AI 服务正常","检查完成"],["activity","窗口坐标已校准", STATE.wecomConnected ? "检查完成" : "待校准"],["shield","规则配置有效","检查完成"]])} `;
@@ -702,7 +711,7 @@ wechatDbView = function(){
const selectedAccount = db.selectedAccount || "";
const selectedConversation = db.selectedConversation || "";
const currentAccount = accounts.find(item=>String(item.id)===String(selectedAccount)) || accounts[0] || null;
- const currentConversation = conversations.find(item=>String(item.id)===String(selectedConversation)) || conversations[0] || null;
+ const currentConversation = conversations.find(item=>String(item.id)===String(selectedConversation)) || (db.conversationDetails && String(db.conversationDetails.id)===String(selectedConversation) ? db.conversationDetails : null);
const patientContext = db.patientContext || {};
const patientBindings = patientContext.patient_bindings || [];
const patientBinding = patientBindings.find(item=>item.is_primary) || patientBindings[0] || null;
@@ -738,7 +747,7 @@ wechatDbView = function(){
? `${icon("check")} 已绑定:${esc(patientBinding.patient_name || "未命名患者")} ${esc(patientBinding.phone_masked || "")}${canBindPatient ? `` : ""}${canUnbindPatient ? `` : ""}`
: `${icon("user")} ${esc(patientPerson ? (patientPerson.display_name || "客户") + " · 未绑定患者" : (patientContext.reason || "未绑定患者"))}${canBindPatient ? `` : ""}`;
const orderPanel = !currentConversation || !canSearchPatient ? "" : wechatOrderPanel(db.orderSummary, patientBinding, patientContext);
- return `${head("微信消息库","查看本机企业微信数据库、会话与收发消息明细",`${actionState}
`)}${ribbon([["本机账号",esc(db.accountCount || 0),"users","green"],["数据库文件",esc(db.databaseCount || 0),"database"],["会话总数",esc(db.conversationCount || 0),"message"],["消息总数",esc(db.messageCount || 0),"layers","","blue"]])}${notice}${cloudNotice}${setup}
消息库账号
${esc(currentAccount ? currentAccount.updated || "" : "")}${accountRows}
数据库文件
${esc(currentAccount ? currentAccount.sizeLabel || "" : "")}${fileRows}
${esc(currentConversation ? currentConversation.name : "会话消息")}
${esc(messages.length)} / ${esc(db.messageTotal || messages.length)} 条${icon("user")} ${esc(currentConversation ? currentConversation.kind || "会话" : "未选择")}${esc(currentConversation ? currentConversation.id : "")}${blacklistControl}${patientControl}
${orderPanel}${olderControl}${messageRows}${newerControl}
`;
+ return `${head("微信消息库","查看本机企业微信数据库、会话与收发消息明细",`${actionState}`)}${ribbon([["本机账号",esc(db.accountCount || 0),"users","green"],["数据库文件",esc(db.databaseCount || 0),"database"],["会话总数",esc(db.conversationCount || 0),"message"],["消息总数",esc(db.messageCount || 0),"layers","","blue"]])}${notice}${cloudNotice}${setup}
消息库账号
${esc(currentAccount ? currentAccount.updated || "" : "")}${accountRows}
数据库文件
${esc(currentAccount ? currentAccount.sizeLabel || "" : "")}${fileRows}
${esc(currentConversation ? currentConversation.name : "会话消息")}
${esc(messages.length)} / ${esc(db.messageTotal || messages.length)} 条${icon("user")} ${esc(currentConversation ? currentConversation.kind || "会话" : "未选择")}${esc(currentConversation ? currentConversation.id : "")}${blacklistControl}${patientControl}
${orderPanel}${olderControl}${messageRows}${newerControl}
`;
};
systemView = function(){
@@ -893,12 +902,17 @@ function coreFingerprint(state){
};
} else if (view === "blacklist") {
page = {blacklist: state.blacklist};
+ } else if (view === "proactive") {
+ page = {proactive: state.proactive, sendMode: state.sendMode};
} else if (view === "wechatdb") {
const db = state.wechatDb || {};
page = {
wechatDb: {
loading: db.loading,
loadingMessage: db.loadingMessage,
+ searching: db.searching,
+ searchError: db.searchError,
+ conversationDetails: db.conversationDetails,
manualSetupRequired: db.manualSetupRequired,
sourceRoot: db.sourceRoot,
cloudBackup: db.cloudBackup,
@@ -1305,6 +1319,46 @@ document.addEventListener('focusout',()=>{
},100);
});
+function patchQueueView(main, html){
+ // A task update must not tear down the other panels (and their scroll/selection).
+ // Limit this to the read-only dashboard layouts; forms keep their existing flow.
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ const current = main.firstElementChild;
+ const next = template.content.firstElementChild;
+ if (!current?.classList.contains("screen") || !next?.classList.contains("screen")) return false;
+ const sameShape = (a,b) => a.children.length === b.children.length &&
+ [...a.children].every((child,index) => child.tagName === b.children[index].tagName && child.className === b.children[index].className);
+ if (!sameShape(current,next)) return false;
+ const patchChildren = (a,b) => {
+ [...a.children].forEach((child,index) => {
+ const replacement=b.children[index];
+ if (child.isEqualNode(replacement)) return;
+ if (child.matches(".auto-grid,.queue-view-grid") && sameShape(child,replacement)) {
+ patchChildren(child,replacement);
+ } else {
+ child.replaceWith(replacement.cloneNode(true));
+ }
+ });
+ };
+ patchChildren(current,next);
+ return true;
+}
+
+function patchWeChatDatabaseView(main, html){
+ // Search and patient responses update their own panel. Keep existing chat
+ // nodes (including decoded images), scroll position and input focus alive.
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ const regions = [...template.content.querySelectorAll("[data-db-region]")];
+ if (regions.length !== 4 || regions.some(region=>!main.querySelector(`[data-db-region="${region.dataset.dbRegion}"]`))) return false;
+ for (const region of regions){
+ const current=main.querySelector(`[data-db-region="${region.dataset.dbRegion}"]`);
+ if (current.innerHTML !== region.innerHTML) current.innerHTML=region.innerHTML;
+ }
+ return true;
+}
+
const _render = render;
render = function(name){
if(!views[name]) name = STATE.view || "auto";
@@ -1312,12 +1366,12 @@ render = function(name){
const sameView = previousView === name;
const scrollHost = document.getElementById("main");
const active=document.activeElement;
- const keepInput=sameView && active && ["archive-search","event-search","wechat-db-search","blacklist-search"].includes(active.id)
+ const keepInput=sameView && active && ["archive-search","event-search","wechat-db-search","blacklist-search","pc-candidate-search"].includes(active.id)
? {element:active,start:active.selectionStart,end:active.selectionEnd} : null;
if (scrollHost) pageScroll.set(previousView,scrollHost.scrollTop);
STATE.view = name;
listening = !!STATE.listening;
- const html = polishedIcons(views[name]());
+ const html = name === "proactive" ? views[name]() : polishedIcons(views[name]());
if (sameView && html === window.__lastHtml){
window.__coreFp = coreFingerprint(STATE);
window.__logsFp = logsFingerprint(STATE);
@@ -1334,15 +1388,18 @@ render = function(name){
const scrollSnapshot = beforeChat ? {top: beforeChat.scrollTop, height: beforeChat.scrollHeight, atBottom: beforeChat.scrollTop + beforeChat.clientHeight >= beforeChat.scrollHeight - 8} : null;
const conversationSnapshot = beforeConversations ? {top: beforeConversations.scrollTop, height: beforeConversations.scrollHeight} : null;
if (main){
- document.querySelectorAll("[data-view]").forEach(b=>b.classList.toggle("active", b.dataset.view===name));
- main.innerHTML = html;
+ syncNavigation(name);
+ const patched = sameView && !STATE.demo && (
+ (name === "wechatdb" && patchWeChatDatabaseView(main, html)) ||
+ (["auto","queue"].includes(name) && patchQueueView(main, html)));
+ if (!patched) main.innerHTML = html;
const allBlacklist = document.getElementById("blacklist-select-all");
if (allBlacklist) allBlacklist.indeterminate = allBlacklist.dataset.mixed === "1";
window.__renderedView=name;
restoreDrafts(name);
if (keepInput){
const placeholder=document.getElementById(keepInput.element.id);
- if (placeholder){
+ if (placeholder && placeholder !== keepInput.element){
placeholder.replaceWith(keepInput.element);
keepInput.element.focus({preventScroll:true});
if (keepInput.start!=null) keepInput.element.setSelectionRange(keepInput.start,keepInput.end);
@@ -1372,6 +1429,7 @@ render = function(name){
annotateEditableFields();
// Keep the same density between pages; update only the responsive layout.
if (typeof fit === "function") fit();
+ if (name === "proactive" && window.proactiveAfterRender) window.proactiveAfterRender();
};
// 数字框只写着一个数,允许范围藏在 min/max 里,谁也看不见——填超了还会被
@@ -1404,14 +1462,15 @@ window.applyState = function(payload){
const prev = STATE.view;
const previousScale=(STATE.system || {}).scale;
Object.assign(STATE, data);
+ const proactiveUpdate = data.proactive && window.proactiveStateChanged && window.proactiveStateChanged(data.proactive);
syncAttentionBadges();
if (data.system && data.system.scale!==previousScale && typeof fit==='function') fit();
STATE.ready = true;
if (typeof data.listening === "boolean") listening = data.listening;
const active = document.activeElement;
const typing = active && /^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName) && !(STATE.view === "blacklist" && active.type === "checkbox");
- const liveSearch=typing && ["archive-search","event-search","wechat-db-search","blacklist-search"].includes(active.id);
- if ((composing || (typing && !liveSearch)) && (STATE.view || prev)===prev) {
+ const liveSearch=typing && ["archive-search","event-search","wechat-db-search","blacklist-search","pc-candidate-search"].includes(active.id);
+ if ((composing || (typing && !liveSearch && !proactiveUpdate)) && (STATE.view || prev)===prev) {
window.__deferredView=prev;
return;
}
@@ -1527,7 +1586,7 @@ document.addEventListener("click", e => {
"blacklist-remove": () => removeSelectedBlacklist(),
"wechat-db-blacklist": () => {
const db = STATE.wechatDb || {};
- const current = (db.conversations || []).find(item=>String(item.id) === String(db.selectedConversation));
+ const current = (db.conversations || []).find(item=>String(item.id) === String(db.selectedConversation)) || db.conversationDetails;
if (!current || db.loading) return;
callBridgeWithFeedback("setConversationBlocked", [JSON.stringify({account: db.selectedAccount, conversation: db.selectedConversation, blocked: !current.blocked})], {button: action, pending: "正在保存忽略…"});
},
@@ -1648,7 +1707,7 @@ document.addEventListener("scroll", e => {
// The current window is always anchored to the newest row. A bottom
// scroll therefore needs no repeated refresh loop; the visible button
// below the list explicitly fetches newly arrived rows.
- } else if (nearBottom && db.conversationHasMore) {
+ } else if (nearBottom && !db.searching && db.conversationHasMore) {
method = "loadWeChatConversations";
}
if (!method || !callBridge(method)) return;
@@ -1744,8 +1803,8 @@ document.addEventListener("change", e => {
});
// CSS pixels are logical pixels: Qt/Chromium applies the monitor DPI once.
-// Preserve the familiar 1080p density without shrinking text to fit page height.
-const CONSOLE_BASE_SCALE = 0.85;
+// Use readable native CSS pixels; only an explicit user preference scales them.
+const CONSOLE_BASE_SCALE = 1;
fit = function(){
document.documentElement.classList.add("embedded");
const stage = document.getElementById("stage");
@@ -1764,7 +1823,7 @@ fit = function(){
stage.style.width = width + "px";
stage.style.height = innerHeight / scale + "px";
stage.style.setProperty("--scale", String(scale));
- stage.dataset.layout = width < 900 ? "narrow" : (width < 1440 ? "compact" : "wide");
+ stage.dataset.layout = width < 1000 ? "narrow" : (width < 1340 ? "compact" : "wide");
stage.dataset.short = String(innerHeight / scale < 800);
};
diff --git a/assets/ui/console-design.css b/assets/ui/console-design.css
new file mode 100644
index 0000000..a55f4bd
--- /dev/null
+++ b/assets/ui/console-design.css
@@ -0,0 +1,165 @@
+/*
+ * Refine the original console, preserving its visual identity.
+ * Palette: mist #F4F8FF, paper #FFFFFF, navy #102554,
+ * blue #2F6FFF, violet #8A6BFF, muted #697B9F.
+ * Keep the original system CJK typeface, 32px page titles, 18px sections.
+ * [floating icon rail] [header / status] [customers | message / actions]
+ * Keep blue-violet gradients, circular icons, rounded cards and pill tabs.
+ * Improve alignment, readability and feedback without replacing the shell.
+ * Static translucent fills preserve the original feel without backdrop blur.
+ */
+:root {
+ --muted:#697b9f;
+ --glass:rgba(255,255,255,.86);
+ --shadow:0 10px 30px rgba(78,99,162,.055),inset 0 1px 0 rgba(255,255,255,.96);
+}
+html.embedded body { font-size:14px; line-height:1.5; text-rendering:auto; }
+html.embedded #stage .workspace {
+ grid-template-columns:108px minmax(0,1fr); gap:24px; padding:18px 20px 18px 16px;
+}
+html.embedded #stage .main { padding:8px 8px 24px 0; }
+html.embedded #stage .rail {
+ border-radius:32px; padding:20px 8px 14px;
+ box-shadow:0 12px 32px rgba(76,97,162,.07),inset 0 1px 0 #fff;
+}
+html.embedded #stage .nav { gap:5px; padding:8px 0; }
+html.embedded #stage :is(.nav-btn,.nav-btn.active) {
+ width:88px; height:70px; min-height:70px; margin:0; padding:0;
+ flex-direction:column; justify-content:center; gap:7px; border-radius:18px;
+}
+html.embedded #stage :is(.nav-icon,.nav-btn.active .nav-icon) {
+ width:44px; height:44px; flex:0 0 44px;
+}
+html.embedded #stage .nav-btn.active { box-shadow:0 6px 16px rgba(87,102,227,.10); }
+html.embedded #stage .nav-btn.active .nav-icon {
+ box-shadow:0 0 0 4px rgba(75,107,255,.07),0 5px 12px rgba(79,92,255,.23);
+}
+html.embedded #stage .listener { gap:10px; margin-top:14px; }
+html.embedded #stage .listener .orb { width:48px; height:48px; }
+html.embedded #stage .system-btn { width:42px; height:42px; margin-top:12px; }
+
+#stage .page-head { min-height:88px; gap:16px; padding-bottom:22px; }
+#stage .page-head h1 { font-size:32px; line-height:1.25; letter-spacing:-.02em; }
+#stage .page-head p { font-size:14px; margin-top:7px; }
+#stage .head-actions { gap:10px; }
+#stage .btn { height:44px; font-size:14px; padding:0 19px; box-shadow:0 5px 14px rgba(73,94,157,.06); }
+#stage .btn.small { height:36px; padding:0 14px; font-size:13px; }
+#stage .btn.primary { box-shadow:0 6px 16px rgba(67,91,255,.20); }
+#stage .btn:hover { box-shadow:0 7px 18px rgba(72,92,160,.12); }
+#stage :is(button,input,select,textarea):disabled { opacity:.6; cursor:not-allowed; }
+#stage :is(button,[role="button"],a,input,select,textarea):focus-visible {
+ outline:2px solid #4779ed !important; outline-offset:3px;
+}
+#stage .panel { border-radius:22px; }
+#stage .panel-pad { padding:20px; }
+#stage .panel-title { gap:12px; margin-bottom:16px; }
+#stage .panel-title h2 { font-size:18px; line-height:1.4; }
+#stage .wave-ribbon { margin-bottom:18px; }
+#stage .wave-ribbon:after { opacity:.20; }
+#stage .metric { gap:12px; padding:0 16px; }
+#stage .metric-icon { width:48px; height:48px; flex:0 0 48px; }
+#stage .metric-copy strong { font-variant-numeric:tabular-nums; }
+#stage .review-summary-item { padding:10px 14px; min-height:44px; }
+#stage .auto-grid {
+ grid-template-columns:minmax(240px,.9fr) minmax(0,1.6fr) minmax(260px,1.05fr);
+ grid-auto-rows:minmax(230px,auto); gap:18px;
+}
+#stage .queue-row { grid-template-columns:42px minmax(0,1fr) 50px; gap:10px; padding:9px; }
+#stage .avatar { width:40px; height:40px; font-size:16px; }
+#stage .q-copy > span,#stage .q-meta { font-size:12px; }
+#stage .task-head-meta { flex-wrap:wrap; gap:6px; }
+#stage .task-actions { flex-wrap:wrap; gap:8px; }
+#stage .answer-block { font-size:14px; line-height:1.85; padding:16px; }
+#stage .copy-block { padding:15px; }
+#stage .window-status { grid-template-columns:repeat(auto-fit,minmax(76px,1fr)); }
+#stage .window-stat { min-width:0; }
+
+#stage .tabs { max-width:100%; height:auto; flex-wrap:wrap; }
+#stage .tab { height:42px; padding:0 26px; font-size:14px; }
+#stage .filter-row { height:auto; flex-wrap:wrap; gap:10px; padding:12px; }
+#stage .filter-row .search { flex:1 1 240px; min-width:0; }
+#stage :is(.input,.select,.textarea,.pc-search,.pc-form input,.pc-form select,.pc-form textarea) {
+ border-color:#dbe4f4; background:#fbfcff; border-radius:11px;
+}
+#stage :is(.input,.select,.pc-search,.pc-form input,.pc-form select) { min-height:40px; }
+#stage :is(input,textarea)::placeholder { color:#7888a5; }
+#stage .storage-actions { flex-wrap:wrap; }
+#stage .logs-grid > .panel > .btn { max-width:100%; }
+/* Do not imply measured storage proportions with a decorative pie chart. */
+#stage .donut { background:#eaf0fc; box-shadow:none; }
+
+#stage .pc-grid { grid-template-columns:minmax(0,1.6fr) minmax(340px,1fr); gap:20px; }
+#stage .pc-panel { padding:22px; }
+#stage .pc-form h2 { margin:0 0 10px; font-size:18px; color:var(--navy); line-height:1.4; }
+#stage .pc-step-number {
+ display:inline-grid; place-items:center; width:25px; height:25px; margin-right:9px;
+ background:#edf2ff; color:#3569de; border-radius:50%; font-size:12px; vertical-align:1px;
+}
+#stage .pc-toolbar { gap:10px; margin:14px 0; }
+#stage .pc-search-toolbar { align-items:flex-end; }
+#stage .pc-search-field { display:grid; gap:7px; flex:1 1 240px; min-width:0; max-width:560px; }
+#stage .pc-search-field label { font-size:12px; color:var(--muted); }
+#stage .pc-search-field .pc-search { width:100%; max-width:none; }
+#stage .pc-search-toolbar > label { min-height:44px; display:flex; align-items:center; gap:6px; }
+#stage .pc-form label { font-size:13px; margin:16px 0 8px; }
+#stage .pc-form textarea { min-height:150px; font-size:14px; padding:12px; }
+#stage .pc-form > .pc-toolbar {
+ position:sticky; bottom:0; z-index:4; background:#fff;
+ border-top:1px solid #e9eef8; padding:14px 0 2px; margin-top:16px; border-radius:0 0 14px 14px;
+}
+#stage .pc-form > .pc-toolbar .pc-primary { flex:1; }
+#stage .pc-primary { background:linear-gradient(105deg,#3777f4,#6465ec) !important; border-color:#4776ed !important; }
+#stage .pc-help { font-size:12px; line-height:1.8; }
+#stage .pc-table { font-size:13px; }
+#stage .pc-table th { padding:12px; font-size:12px; font-weight:500; background:#f6f9ff; z-index:1; }
+#stage .pc-table td { padding:14px 12px; line-height:1.65; }
+#stage .pc-table small { font-size:12px; line-height:1.6; margin-top:4px; }
+#stage .pc-table tr:hover { background:#f8faff; }
+#stage .pc-table tr:has(input[type="checkbox"]:checked) { background:#f0f5ff; }
+#stage .pc-table td:first-child:has(input[type="checkbox"]) { width:38px; }
+#stage .pc-table select {
+ width:100%; max-width:280px; min-height:36px; padding:5px 9px;
+ border:1px solid #dbe4f4; border-radius:9px; background:#fff; font-size:12px;
+}
+#stage .pc-status { font-size:12px; }
+#stage .pc-status.bound { background:#edf3ff; color:#3563c9; }
+#stage .pc-status.cancelled,#stage .pc-status.skipped { background:#eef1f7; color:#62718e; }
+#stage .pc-feedback { box-shadow:0 5px 15px rgba(53,81,145,.05); }
+#stage .pc-created strong { font-size:20px; }
+#stage .pc-modal { backdrop-filter:none; -webkit-backdrop-filter:none; }
+#stage .pc-modal .pc-preview { border-radius:22px; }
+#stage :is(.db-account,.db-conversation) { border-radius:14px; }
+#stage .db-message-bubble { font-size:14px; line-height:1.8; }
+#stage .db-message-bubble time { font-size:12px; }
+#stage .db-scroll,#stage .queue-list { scrollbar-width:thin; }
+
+/* Reflow the existing cards; keep the original navigation accessible. */
+html.embedded #stage[data-layout="compact"] .auto-grid {
+ grid-template-columns:minmax(240px,.9fr) minmax(0,1.5fr);
+}
+html.embedded #stage[data-layout="compact"] .auto-grid > * { grid-column:auto; grid-row:auto; }
+html.embedded #stage[data-layout="compact"] .pc-grid { grid-template-columns:minmax(0,1fr) minmax(300px,1fr); }
+html.embedded #stage[data-layout="narrow"] .workspace { grid-template-columns:76px minmax(0,1fr); gap:14px; padding:10px; }
+html.embedded #stage[data-layout="narrow"] .rail { padding:14px 4px 10px; border-radius:26px; }
+html.embedded #stage[data-layout="narrow"] :is(.nav-btn,.nav-btn.active) { width:64px; height:64px; min-height:64px; gap:6px; }
+html.embedded #stage[data-layout="narrow"] :is(.nav-icon,.nav-btn.active .nav-icon) { width:36px; height:36px; flex-basis:36px; }
+html.embedded #stage[data-layout="narrow"] .nav-btn > span { font-size:10px; }
+html.embedded #stage[data-layout="narrow"] .main { padding:10px 4px 16px 0; }
+html.embedded #stage[data-layout="narrow"] .page-head h1 { font-size:28px; }
+html.embedded #stage[data-layout="narrow"] .head-actions { width:100%; }
+html.embedded #stage[data-layout="narrow"] .listener .orb { width:34px; height:34px; }
+html.embedded #stage[data-layout="narrow"] :is(.auto-grid,.pc-grid) { grid-template-columns:minmax(0,1fr); }
+html.embedded #stage[data-layout="narrow"] .auto-grid > * { grid-column:auto; grid-row:auto; }
+html.embedded #stage[data-layout="narrow"] .metric { padding:0; gap:8px; border:0; }
+html.embedded #stage[data-layout="narrow"] .metric-icon { width:38px; height:38px; flex-basis:38px; }
+html.embedded #stage[data-layout="narrow"] .tab { padding:0 18px; }
+html.embedded #stage[data-layout="narrow"] .pc-panel { padding:18px; }
+html.embedded #stage[data-layout="narrow"] .pc-table { min-width:440px; }
+html.embedded #stage[data-layout="narrow"] .pc-pair { grid-template-columns:minmax(0,1fr); gap:0; }
+html.embedded #stage[data-short="true"] .brand-logo { display:grid; width:40px; height:40px; font-size:24px; margin-bottom:10px; }
+html.embedded #stage[data-short="true"] .listener { display:grid; padding:6px; gap:8px; }
+html.embedded #stage[data-short="true"] .listener .orb { width:28px; height:28px; }
+html.embedded #stage[data-short="true"] .system-btn { margin-top:8px; }
+@media (prefers-reduced-motion:reduce) {
+ #stage *,#stage *:before,#stage *:after { animation:none !important; transition:none !important; scroll-behavior:auto !important; }
+}
diff --git a/assets/ui/proactive-contact.css b/assets/ui/proactive-contact.css
new file mode 100644
index 0000000..af11e08
--- /dev/null
+++ b/assets/ui/proactive-contact.css
@@ -0,0 +1,19 @@
+.pc-grid{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(320px,1fr);gap:18px;align-items:start}
+.pc-reply-status{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;background:#fff6e8;border:1px solid #edc58e;border-radius:12px;padding:14px 18px;margin:14px 0;color:#875318}.pc-reply-status.active{background:#ebfaf2;border-color:#b1dfc5;color:#166743}.pc-reply-status p{margin:6px 0 0;line-height:1.6;font-size:13px}.pc-reply-status .btn{flex-shrink:0}
+.pc-panel{padding:20px;min-width:0}.pc-toolbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:12px 0}
+.pc-help{color:var(--muted);line-height:1.7;font-size:12px}.pc-notice{padding:12px 16px;background:#edf4ff;border:1px solid #dce6fc;border-radius:12px;margin:14px 0;white-space:pre-wrap;overflow-wrap:anywhere}
+.pc-scroll{overflow:auto;max-height:560px}.pc-table{width:100%;border-collapse:collapse;font-size:12px}.pc-table th,.pc-table td{text-align:left;padding:12px 9px;border-bottom:1px solid #edf0f7;vertical-align:top}
+.pc-table th{color:var(--muted);position:sticky;top:0;background:#f8faff}.pc-table small{display:block;color:var(--muted);margin-top:5px;max-width:290px;overflow-wrap:anywhere}
+.pc-table input[type=checkbox]{width:16px;height:16px;accent-color:#4572ed;cursor:pointer}.pc-text{white-space:pre-wrap;overflow-wrap:anywhere;max-width:400px;line-height:1.6}
+.pc-form label{display:block;font-size:12px;font-weight:600;margin:14px 0 7px}.pc-form input,.pc-form select,.pc-form textarea,.pc-search{width:100%;background:#f8faff;border:1px solid #dce3f4;border-radius:9px;padding:10px;color:#23365d;font:inherit}
+.pc-form textarea{min-height:160px;resize:vertical;line-height:1.7}.pc-pair{display:grid;grid-template-columns:1fr 1fr;gap:12px}.pc-days{display:flex;gap:8px;flex-wrap:wrap}.pc-days label{font-weight:400;margin:6px 0;display:flex;gap:4px;align-items:center}.pc-days input{width:auto}
+.pc-status{border-radius:7px;padding:3px 7px;display:inline-block;background:#edf2ff;color:#3563d2;white-space:nowrap}.pc-status.succeeded{background:#e6f7ef;color:#19825f}.pc-status.paused,.pc-status.delivery_unknown,.pc-status.failed{background:#fff0df;color:#ad6424}
+.pc-tabs{display:flex;gap:10px;margin:16px 0}.pc-empty{padding:38px 18px;text-align:center;color:var(--muted)}.pc-preview{margin-top:18px;border:1px solid #c9d9fb;border-radius:12px;padding:16px}.pc-preview article{border-top:1px solid #e5ebf6;padding:12px 0}
+.pc-search{max-width:300px}.pc-rejected{color:#ad6424;font-size:12px;margin:8px 0}.rail .nav{min-height:0;overflow-y:auto;overflow-x:hidden;flex-shrink:1;scrollbar-width:thin}
+.pc-form fieldset{border:0;padding:0;margin:0;min-width:0}.pc-primary{background:#3765eb!important;color:#fff!important;border-color:#3765eb!important;min-height:44px;font-weight:600}.pc-primary:disabled{opacity:.65;cursor:wait}.pc-step-hint{font-size:13px;line-height:1.7;color:#49618b;margin:10px 0}
+.pc-feedback{display:flex;align-items:flex-start;gap:12px;padding:17px 20px;border:1px solid #b8cbee;border-left:5px solid #527dec;border-radius:12px;background:#edf3ff;color:#274775;margin:16px 0;position:sticky;top:0;z-index:25;box-shadow:0 6px 20px #22396110;overflow-wrap:anywhere}.pc-feedback strong{display:block;font-size:16px;line-height:1.5}.pc-feedback p{margin:5px 0 0;font-size:13px;line-height:1.7;white-space:pre-wrap}.pc-feedback-icon{width:28px;height:28px;border-radius:50%;background:currentColor;flex-shrink:0;display:grid;place-items:center;font-size:18px;font-weight:bold;color:inherit;background:#d5e2ff}.pc-feedback.error{background:#fff1f0;border-color:#f2b8b4;border-left-color:#d83e35;color:#a32824}.pc-feedback.error .pc-feedback-icon{background:#ffd5d0}.pc-feedback.success{background:#ebfaf2;border-color:#b1dfc5;border-left-color:#209760;color:#166743}.pc-feedback.success .pc-feedback-icon{background:#c9eedb}.pc-inline-feedback{position:static;box-shadow:none;margin:14px 0 0;padding:12px;z-index:auto}.pc-inline-feedback strong{font-size:14px}
+.pc-created{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:18px 22px;border:1px solid #a9d9bf;border-radius:14px;background:#f0fcf6;color:#176340;margin:16px 0}.pc-created strong{font-size:21px}.pc-created p{font-size:13px;margin:6px 0 10px;line-height:1.6}.pc-task-counts{display:flex;gap:8px;flex-wrap:wrap}.pc-total{padding:0 4px}.pc-status.failed{background:#ffe7e4;color:#b52b24}
+.pc-task-notice{padding:16px 20px;border:1px solid #a9c6ed;border-left:5px solid #527dec;border-radius:12px;background:#edf4ff;color:#294a7b;margin:14px 0}.pc-task-notice.attention{background:#fff6e8;border-color:#edc58e;color:#875318}.pc-task-notice strong{font-size:16px}.pc-task-notice p{font-size:13px;line-height:1.7;margin:8px 0 0;overflow-wrap:anywhere}.pc-table small.pc-task-reason{font-size:12px;line-height:1.7;color:#516789;max-width:320px}.pc-status.queued{background:#e5efff;color:#285bbb}
+.pc-modal{position:fixed;inset:0;z-index:90;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(25,39,68,.48);backdrop-filter:blur(3px)}.pc-modal .pc-preview{width:min(760px,100%);max-height:90vh;margin:0;background:#fff;box-shadow:0 22px 80px #172b5750;padding:24px;border:1px solid #cad7f5;border-radius:18px;display:flex;flex-direction:column;min-width:0}.pc-preview h2{font-size:21px;margin:0;outline:none}.pc-preview .panel-title{flex-shrink:0;gap:16px;flex-wrap:wrap}.pc-preview>.pc-scroll{min-height:60px;overflow:auto;flex:1}.pc-preview .pc-text{max-width:none;font-size:15px;background:#f4f7fd;border:1px solid #e0e8f7;border-radius:10px;padding:14px}.pc-preview .pc-toolbar{flex-shrink:0;margin-bottom:0}.pc-preview .pc-step-hint{flex-shrink:0}.pc-preview .pc-inline-feedback{flex-shrink:0}.pc-modal .pc-preview article{padding:15px 0}
+@media(max-width:1000px){.pc-grid{grid-template-columns:1fr}.pc-scroll{max-height:450px}}
+@media(max-width:700px){.pc-modal{padding:12px}.pc-modal .pc-preview{padding:16px}.pc-created{align-items:flex-start;flex-direction:column}.pc-feedback{padding:12px}.pc-tabs{flex-wrap:wrap}}
diff --git a/assets/ui/proactive-contact.js b/assets/ui/proactive-contact.js
new file mode 100644
index 0000000..8f4fad3
--- /dev/null
+++ b/assets/ui/proactive-contact.js
@@ -0,0 +1,323 @@
+/* Patient-bound contact page. Server-rendered data is always escaped. */
+(() => {
+ const ui = {tab:'customers', selected:new Set(), tasks:new Set(), candidates:new Set(),
+ picker:false, onlyBound:true, text:'', query:'', kind:'immediate', interval:30,
+ start:'09:00', end:'18:00', start_date:'', end_date:'', at:'', weekdays:[0,1,2,3,4],
+ content_mode:'draft', pending:null, notice:null, serial:0, lastOperation:'', lastCreation:'', campaign:'', deleteIds:null,
+ searchId:'', searching:false, searchError:'', searchVersion:'', lastServerSearch:''};
+ let searchTimer=0, searchComposing=false;
+ const status = {scheduled:'待发送',queued:'等待自动继续',sending:'发送中',paused:'已暂停',
+ succeeded:'发送成功',failed:'发送失败',delivery_unknown:'结果待核对',skipped:'已跳过',cancelled:'已取消'};
+ const data = () => STATE.proactive || {};
+ const stamp = t => t ? new Date(Number(t)*1000).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false}) : '—';
+ const key = row => JSON.stringify([row.account,row.conversation]);
+ function candidatePage(){
+ const page=data().candidates||{}, search=data().candidateSearch||{};
+ const current=(!ui.searchId || search.id===ui.searchId) && String(page.query||'').trim()===ui.query.trim();
+ const all=current?(page.items||[]).map(r=>({...r,bindings:(Array.isArray(r.bindings)?r.bindings:[]).filter(b=>
+ b && String(b.id||'').trim() && Number.isInteger(Number(b.patient_id)) && Number(b.patient_id)>0 && String(b.patient_name||'').trim())})):[];
+ const bound=all.filter(r=>!r.binding_loading && !r.binding_error && r.bindings.length);
+ return {page,current,all,bound,rows:ui.onlyBound?bound:all};
+ }
+ const busy = () => !!ui.pending || !!data().busy;
+ const feedback = () => ui.notice || data().operation;
+ const pendingTitles = {preview:'正在生成预览 · 尚未创建任务',confirm:'正在创建任务,请勿重复点击',text:'正在保存文字'};
+ function send(action, extra={}) {
+ const quiet=action==='discard-preview', request_id=`pc-${Date.now()}-${++ui.serial}`;
+ if(action==='candidates'){
+ clearTimeout(searchTimer);
+ ui.lastServerSearch=data().candidateSearch?.id || ui.lastServerSearch;
+ ui.searchId=request_id;ui.searching=true;ui.searchError='';ui.candidates.clear();
+ if(!callBridge('proactiveCommand',JSON.stringify({action,request_id,...extra}))){
+ ui.searching=false;ui.searchError='界面尚未连接后台,请稍后重试。';
+ }
+ draw();return;
+ }
+ if(!quiet){
+ if(ui.pending && action!=='enable')return;
+ ui.pending={id:request_id,action};
+ ui.notice={status:'running',action,title:pendingTitles[action]||'正在处理,请稍候',message:'请等待操作结果,勿重复点击。'};
+ document.activeElement?.blur();
+ draw();
+ }
+ if (!callBridge('proactiveCommand',JSON.stringify({action,request_id,...extra}))){
+ ui.pending=null; fail('界面尚未连接后台,操作未提交。',action);
+ }
+ }
+ function draw(){ render('proactive'); }
+ function fail(message,action='preview'){
+ ui.notice={status:'error',action,title:action==='preview'?'无法预览 · 未创建任务':'操作未完成',message};draw();
+ }
+ window.proactiveStateChanged = d => {
+ const op=d.operation;
+ let changed=false;
+ const search=d.candidateSearch;
+ if(search?.serverInitiated && search.id!==ui.lastServerSearch){ui.lastServerSearch=search.id;ui.searchId=search.id;}
+ if(search && (!ui.searchId || search.id===ui.searchId)){
+ ui.searching=search.status==='running';ui.searchError=search.status==='error'?search.message:'';
+ const version=JSON.stringify(search);
+ if(version!==ui.searchVersion){
+ ui.searchVersion=version;
+ // Keep other form edits undisturbed by background binding responses.
+ const active=document.activeElement;
+ if(!active || !/^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName) || active.closest('#pc-picker'))changed=true;
+ }
+ }
+ if(op && `${op.id}:${op.status}`!==ui.lastOperation){
+ ui.lastOperation=`${op.id}:${op.status}`;changed=true;
+ if(!ui.pending || ui.pending.id===op.id){
+ ui.notice=null;
+ if(op.status!=='running')ui.pending=null;
+ if(op.action==='delete' && op.status!=='running')ui.deleteIds=null;
+ }
+ }
+ if(d.creation && d.creation.campaign!==ui.lastCreation){
+ ui.lastCreation=d.creation.campaign;ui.campaign=d.creation.campaign;ui.tab='plans';
+ ui.picker=false;ui.tasks.clear();ui.scrollTop=true;changed=true;
+ }
+ return changed;
+ };
+ window.proactiveAfterRender = () => {
+ if(ui.scrollTop){document.getElementById('main').scrollTop=0;ui.scrollTop=false;}
+ const p=data().preview;
+ if(ui.deleteIds){document.getElementById('pc-delete-title')?.focus({preventScroll:true});}
+ if(p && ui.focusedPreview!==p.id){
+ ui.focusedPreview=p.id;
+ document.getElementById('pc-preview-title')?.focus({preventScroll:true});
+ }
+ };
+ function invalidatePreview(){
+ if(data().preview){data().preview=null;document.querySelector('.pc-modal')?.remove();document.querySelector('.pc-content')?.removeAttribute('inert');send('discard-preview');}
+ }
+ function notice(inline=false){
+ const n=feedback();
+ if(!n || (inline && !['preview','confirm','text'].includes(n.action)))return '';
+ const level=['error','success','running'].includes(n.status)?n.status:'info';
+ return `
+
${level==='error'?'!':level==='success'?'✓':level==='running'?'…':'i'}
+
${esc(n.title)}${esc(n.message||'')}
`;
+ }
+ function candidates(){
+ const {page,current,all,bound,rows}=candidatePage(), search=data().candidateSearch||{};
+ const pending=all.filter(r=>r.binding_loading).length, errors=all.filter(r=>r.binding_error).length;
+ const count=current?Number(page.total||0):0;
+ const summary=`匹配 ${count} 位客户;本页显示 ${rows.length} 位${ui.onlyBound?'已绑定客户':'客户'}`;
+ const progress=ui.searchError || (ui.searching ? current && search.count ?
+ `${summary},正在读取绑定 ${search.checked||0}/${search.count},可继续搜索` : '正在搜索客户…' :
+ `${summary}${errors?`;${errors} 位绑定读取失败,可点击搜索重试`:''}`);
+ const empty=ui.searchError?'搜索未完成,请重新搜索。':!current || pending || ui.searching?'正在核验客户绑定,请稍候…':errors?'部分绑定未读取成功,请重新搜索,或取消筛选查看原因。':
+ !count?'没有匹配的客户,请检查昵称、备注或客户编号。':'本页没有已确认绑定的客户,可取消筛选查看,或翻页继续查找。';
+ return `从我的客户添加
+ 按客户昵称、备注或客户编号搜索,完全匹配优先。每页读取 20 位客户;勾选后仅显示本页已确认绑定的客户,添加时再次核验。
+
+ ${esc(progress)}
+
+
+
+ 第 ${Math.floor((current?page.offset||0:0)/20)+1} 个客户页 · 本页已绑定 ${bound.length} 位 · 搜索共匹配 ${count} 位
`;
+ }
+ function customerTable(){
+ const rows = data().customers || [];
+ return `1选择联系客户
已选 ${ui.selected.size} 位仅已绑定有效患者的客户可创建联系任务。
+
+
`;
+ }
+ function form(){
+ const working=busy();
+ if (!ui.start_date) {
+ const today = new Date().toLocaleDateString('en-CA',{timeZone:'Asia/Shanghai'});
+ ui.start_date=today; ui.end_date=today;
+ }
+ return ``;
+ }
+ function preview(){
+ const p=data().preview;
+ if (!p) return '';
+ return `确认发送内容 · ${p.tasks.length} 位客户
尚未创建任务
+ ${p.schedule?.kind==='immediate'?'确认后将创建任务,并尽快按客户间隔依次发送。':'确认后将创建任务,并按下方时间安排发送。'}返回修改不会创建任务。
+
+ ${notice(true)} `;
+ }
+ function visibleTasks(){
+ return (data().tasks||[]).filter(t=>(!ui.campaign || t.campaign===ui.campaign) && (ui.tab!=='records'||['succeeded','failed','delivery_unknown','skipped','cancelled'].includes(t.status)));
+ }
+ function taskTable(){
+ const rows=visibleTasks();
+ const chosen=rows.filter(t=>ui.tasks.has(t.id));
+ const canControl=a=>chosen.some(t=>(a==='resume'?['paused']:a==='pause'?['scheduled','queued']:['scheduled','queued','paused','failed']).includes(t.status));
+ return `${ui.tab==='records'?'发送记录':'联系计划'}
展示最近 500 条
+ ${ui.campaign?`本次任务 · 批次 ${esc(ui.campaign.slice(0,8))}
`:''}
+ 可删除单条或批量删除任务。删除未发送任务会停止执行;已发送消息不会撤回。
+ 已选 ${chosen.length} 条
+ ${ui.tab==='plans'?``:''}
+
+ `;
+ }
+ function deleteDialog(){
+ if(!ui.deleteIds)return '';
+ const rows=(data().tasks||[]).filter(t=>ui.deleteIds.includes(t.id));
+ return `确认删除 ${rows.length} 条任务?
删除后任务将从联系计划和发送记录中移除。未发送的任务停止执行,已发送消息不会撤回,客户后续回复仍可自动处理。
`;
+ }
+ function replyStatus(){
+ const active=STATE.listening && (STATE.sendMode||'auto')==='auto';
+ const error=data().autoReplyError;
+ const message=active?'自动回复已开启:客户回复后将进入自动回复流程,沿用现有患者信息和回复规则。':error?`消息已发送,自动回复启动遇到问题:${error}`:STATE.listening?'当前为审核模式;主动联系任务发送成功后,将自动切换到自动回复,仍保留风险审核规则。':'主动联系任务发送成功后会自动开启自动回复,无需手动点击。您仍可随时暂停监听。';
+ return `发送成功后自动开启回复${esc(message)}
${active?'':`
`}
`;
+ }
+ function taskNotice(){
+ const rows=(data().tasks||[]).filter(t=>['queued','paused','failed','delivery_unknown'].includes(t.status));
+ if(!rows.length)return '';
+ const attention=rows.some(t=>t.status!=='queued');
+ return `${attention?'有任务需要核对,请查看当前状态':'任务正在等待,条件满足后自动继续'}
+ ${rows.slice(0,3).map(t=>`${esc(t.name)} · ${esc(status[t.status])}:${esc(t.error||'请查看任务详情')}
`).join('')}
+ ${rows.some(t=>t.status==='paused')?'已暂停任务需要勾选后点击「核验并恢复」;等待中的任务无需手动恢复。
':''}
+ ${rows.some(t=>t.status==='delivery_unknown')?'结果待核对的消息可能已经发出。系统会自动补核对,也可点击「核对发送结果(不重发)」。
':''}
+ ${rows.length>3?`另有 ${rows.length-3} 条任务,请在联系计划或发送记录中查看。
`:''}`;
+ }
+ function creationCard(){
+ const c=data().creation;
+ if(!c)return '';
+ const tasks=(data().tasks||[]).filter(t=>t.campaign===c.campaign);
+ if(!tasks.length)return '';
+ const counts=Object.entries(status).map(([s,label])=>{
+ const n=tasks.filter(t=>t.status===s).length;
+ return n?`${label} ${n}`:'';
+ }).join('');
+ return `已创建 ${esc(c.count)} 条任务最近创建批次 ${esc(c.campaign.slice(0,8))} · 创建成功不代表已发送,请查看执行状态。
${counts}
`;
+ }
+ views.proactive = function(){
+ const d=data(), customers=d.customers||[];
+ for (const id of ui.selected) if(!customers.some(c=>c.id===id && c.valid))ui.selected.delete(id);
+ const tasks=d.tasks||[], records=tasks.filter(t=>['succeeded','failed','delivery_unknown','skipped','cancelled'].includes(t.status));
+ for(const id of ui.tasks)if(!tasks.some(t=>t.id===id&&t.status!=='sending'))ui.tasks.delete(id);
+ if(ui.campaign&&!tasks.some(t=>t.campaign===ui.campaign))ui.campaign='';
+ return `${head('主动联系','选择客户 → 填写文字 → 预览确认 → 创建任务',`
`)}
+ ${notice() || `
${esc(d.message||'填写文字后可直接预览;确认预览后才会创建任务。')}
`}
+ ${d.enabled===false?'
主动联系调度已暂停,已创建任务暂不会发送。
':''}${replyStatus()}${creationCard()}${taskNotice()}
+ ${(d.rejected||[]).map(r=>`
${esc(r.name)}:${esc(r.reason)}
`).join('')}
+ ${ui.picker?candidates():''}
${[['customers',`客户名单 · ${customers.length}`],['plans',`联系计划 · ${tasks.length}`],['records',`发送记录 · ${records.length}`]].map(([k,v])=>``).join('')}
+ ${!tasks.length?'
当前没有任务。可从客户名单填写文字、预览并创建联系计划。
':''}
+ ${ui.tab==='customers'?`
${customerTable()}${form()}
`:taskTable()}
${preview()}${deleteDialog()}
`;
+ };
+ document.addEventListener('click',e=>{
+ const tab=e.target.closest('[data-pc-tab]'), btn=e.target.closest('[data-pc]');
+ if(tab){ui.tab=tab.dataset.pcTab;ui.campaign='';ui.tasks.clear();draw();return;}
+ if(!btn || btn.disabled)return;
+ const a=btn.dataset.pc, page=data().candidates||{};
+ if(a==='picker'){ui.picker=true;send('candidates',{query:ui.query,refresh_bindings:true});draw();}
+ else if(a==='close-picker'){clearTimeout(searchTimer);ui.picker=false;ui.searching=false;callBridge('proactiveCommand',JSON.stringify({action:'cancel-candidates'}));draw();}
+ else if(a==='search'||a==='next'||a==='prev'){
+ ui.candidates.clear(); send('candidates',{query:ui.query,refresh_bindings:true,offset:a==='next'?(page.offset||0)+20:a==='prev'?Math.max(0,(page.offset||0)-20):0});
+ }else if(a==='bind'){const [account,conversation]=JSON.parse(btn.dataset.key);send('bind',{account,conversation});}
+ else if(a==='add'){
+ const current=candidatePage();
+ if(!current.current){fail('搜索条件已变化,请等待当前搜索结果后重新选择客户。','add');return;}
+ const items=current.bound.filter(r=>ui.candidates.has(key(r))).map(r=>({...r,binding_id:
+ r.bindings.find(b=>String(b.id)===String(ui['binding:'+key(r)]))?.id || (r.bindings.length===1?r.bindings[0].id:'')}));
+ if(!items.length){fail('请选择已确认绑定患者的客户。','add');return;}
+ const missing=items.find(r=>!r.binding_id);
+ if(missing){fail(`${missing.name} 已绑定多位患者,请选择本次联系的患者。`,'add');return;}
+ send('add',{items});ui.candidates.clear();
+ }else if(a==='select-all'){invalidatePreview();customersSelect();draw();}
+ else if(a==='clear'){invalidatePreview();ui.selected.clear();draw();}
+ else if(a==='save-text'||a==='preview'){
+ if(ui.content_mode==='draft')ui.text=document.getElementById('pc-text')?.value ?? ui.text;
+ if(a==='save-text'||ui.content_mode==='draft'){
+ if(!ui.text.trim()){fail('请先填写发送文字,再生成预览。',a==='save-text'?'text':'preview');return;}
+ if(new TextEncoder().encode(ui.text).length>4000){fail('发送文字过长,请缩短后重试(最多约 1300 个汉字)',a==='save-text'?'text':'preview');return;}
+ }
+ if(a==='save-text'){send('text',{ids:[...ui.selected],text:ui.text});return;}
+ send('preview',{ids:[...ui.selected],...(ui.content_mode==='draft'?{text:ui.text}:{}),schedule:{kind:ui.kind,interval:Number(ui.interval),at:ui.at,start_date:ui.start_date,end_date:ui.end_date,start:ui.start,end:ui.end,weekdays:ui.weekdays}});
+ }
+ else if(a==='confirm'){if(data().preview)send('confirm',{key:data().preview.id});}
+ else if(a==='dismiss-preview'){
+ invalidatePreview();ui.notice={status:'info',action:'preview',title:'已返回修改 · 未创建任务',message:'修改内容后请重新预览。'};draw();
+ }
+ else if(a==='created-tasks'){ui.tab='plans';ui.campaign=data().creation?.campaign||'';ui.scrollTop=true;draw();}
+ else if(a==='all-tasks'){ui.campaign='';draw();}
+ else if(['pause','resume','cancel'].includes(a)){
+ const allowed=a==='resume'?['paused']:a==='pause'?['scheduled','queued']:['scheduled','queued','paused','failed'];
+ send(a,{ids:visibleTasks().filter(t=>ui.tasks.has(t.id)&&allowed.includes(t.status)).map(t=>t.id)});ui.tasks.clear();
+ }
+ else if(a==='select-tasks'){ui.tasks=new Set(visibleTasks().filter(t=>t.status!=='sending').slice(0,100).map(t=>t.id));draw();}
+ else if(a==='clear-tasks'){ui.tasks.clear();draw();}
+ else if(a==='delete-one'||a==='delete-selected'){
+ ui.deleteIds=a==='delete-one'?[btn.dataset.id]:visibleTasks().filter(t=>ui.tasks.has(t.id)).map(t=>t.id);draw();
+ }
+ else if(a==='dismiss-delete'){ui.deleteIds=null;draw();}
+ else if(a==='confirm-delete'){if(ui.deleteIds?.length)send('delete',{ids:ui.deleteIds});}
+ else if(a==='start-replies'){if(!callBridge('startListen'))fail('自动回复尚未连接后台,请稍后重试。','start-replies');}
+ else if(a==='refresh')send('refresh');
+ else if(a==='reconcile')send('reconcile');
+ else if(a==='enable')send('enable',{enabled:data().enabled===false});
+ });
+ function customersSelect(){for(const c of data().customers||[])if(c.valid && ui.selected.size<100)ui.selected.add(c.id);}
+ document.addEventListener('input',e=>{const field=e.target.dataset.pcField;if(field && !['checkbox','select-one'].includes(e.target.type)){
+ ui[field]=e.target.value;
+ if(field!=='query')invalidatePreview();
+ else {
+ clearTimeout(searchTimer);
+ if(!e.isComposing && !searchComposing)searchTimer=setTimeout(()=>{if(ui.picker)send('candidates',{query:ui.query});},280);
+ }
+ }});
+ document.addEventListener('compositionstart',e=>{if(e.target.dataset.pcField==='query'){searchComposing=true;clearTimeout(searchTimer);}});
+ document.addEventListener('compositionend',e=>{if(e.target.dataset.pcField==='query'){
+ searchComposing=false;ui.query=e.target.value;clearTimeout(searchTimer);
+ searchTimer=setTimeout(()=>{if(ui.picker)send('candidates',{query:ui.query});},280);
+ }});
+ document.addEventListener('change',e=>{
+ const t=e.target;
+ for(const [attr,set] of [['pcCustomer',ui.selected],['pcCandidate',ui.candidates],['pcTask',ui.tasks]]){
+ if(t.dataset[attr]){
+ if(attr==='pcCustomer')invalidatePreview();
+ if(t.checked)set.add(t.dataset[attr]);else set.delete(t.dataset[attr]);
+ if(attr==='pcCustomer' && ui.selected.size===1)ui.text=(data().customers||[]).find(c=>ui.selected.has(c.id))?.template||'';
+ draw();return;
+ }
+ }
+ if(t.dataset.pcBinding){ui['binding:'+t.dataset.pcBinding]=t.value;return;}
+ if(t.dataset.pcDay!==undefined){invalidatePreview();const n=Number(t.dataset.pcDay);ui.weekdays=t.checked?[...ui.weekdays,n]:ui.weekdays.filter(d=>d!==n);return;}
+ if(t.dataset.pcField){ui[t.dataset.pcField]=t.type==='checkbox'?t.checked:t.value;if(t.dataset.pcField==='onlyBound')ui.candidates.clear();if(!['query','onlyBound'].includes(t.dataset.pcField))invalidatePreview();if(['kind','onlyBound','content_mode'].includes(t.dataset.pcField))draw();}
+ });
+ document.addEventListener('keydown',e=>{
+ if(e.target.dataset.pcField==='query' && e.key==='Enter' && !e.isComposing && !searchComposing){e.preventDefault();send('candidates',{query:ui.query,refresh_bindings:true});return;}
+ const modal=document.querySelector('.pc-modal');
+ if(!modal)return;
+ if(e.key==='Escape'&&!busy()){e.preventDefault();modal.querySelector('[data-pc=dismiss-preview],[data-pc=dismiss-delete]')?.click();}
+ if(e.key==='Tab'){
+ const controls=[...modal.querySelectorAll('button:not(:disabled)')];
+ const first=controls[0],last=controls.at(-1);
+ if(!first){e.preventDefault();return;}
+ if(e.shiftKey && (document.activeElement===first||!controls.includes(document.activeElement))){e.preventDefault();last.focus();}
+ else if(!e.shiftKey && (document.activeElement===last||!controls.includes(document.activeElement))){e.preventDefault();first.focus();}
+ }
+ });
+})();
diff --git a/assets/ui/zhenyang-ai-console.html b/assets/ui/zhenyang-ai-console.html
index ac26b87..63946c6 100644
--- a/assets/ui/zhenyang-ai-console.html
+++ b/assets/ui/zhenyang-ai-console.html
@@ -3,7 +3,7 @@
- 甄养堂 · 企业微信 AI 自动回复 v2.0
+ 甄养堂 · 客户服务工作台
+
+
-
甄
甄养堂 · 企业微信 AI 自动回复 v2.0—□×
+
操作已完成
-
+
+