feat: 2026-07-12~13 全量更新 - AI对话链路改造+H5 v4/v5+坐席端v5+上下文感知诊断+知识库迭代3

## H5 员工端 v4 (2026-07-13 00:48 已部署)
- 人工按钮三态文案统一为"人工坐席"
- 按钮位置移至发送键和语音按钮上方(垂直堆叠)
- 点按钮直接调 store.shakeAgent(),删除 CallAgentModal 弹窗动画
- 截图快捷键提示改为"截图->粘贴:Alt+Shift+A-Ctrl+V ---> Ctrl+V"
- 移动端隐藏截图提示(CSS 媒体查询)
- AI转人工提示改为"已为您呼叫人工坐席,请稍等!"
- 坐席接入提示改为"坐席正在查看您的信息,请等待处理回复!"
- 删除"摇铃呼叫坐席"入口和文案
- 删除孤儿组件 MessageList.vue + shake 动画 CSS

## H5 员工端 v5 (2026-07-13 02:08 已部署)
- RightPanel v2.1:删除"软件安装"和"资源权限"标签页
- 移除标签栏,智能推荐(DynamicRecommend)直接展示
- 删除 SoftwareDownloads/ApprovalLinks 引用和相关 CSS

## AI 对话链路全栈改造 Phase 1-6 (已部署)
- Phase 1: Dify JSON输出 + 后端blocking解析 + 双WS推送 + 错误降级
- Phase 2: 关键词收窄(~25强意图词) + 两级分类Prompt + 删除前端checkApprovalIntent
- Phase 3: WS扩展(ai_thinking+dynamic_recommend) + ai_structured气泡 + RightPanel v2 + 选项回传
- Phase 4: VisionService接入 + 图片消息融合(5秒窗口) + 降级策略
- Phase 5: 坐席端ai_thinking指示器 + ai_structured/byod_card渲染 + handleNewMessage修复
- Phase 6: diagnosis_stage(6值) + response_time_ms计时 + 慢响应告警(>10s)

## 坐席端 v5 (2026-07-13 01:38 已部署)
- ai_structured/byod_card 只读渲染
- AI思考指示器 UI
- handleNewMessage 透传 msg_type/extra_data 修复
- 布局优化v2.0: QuickReplyBar L1+L2悬浮 + ReplyBox左右分区 + 右栏260/560px切换
- 键盘快捷键v2.3: 纯数字路由 + ESC分层撤销 + Shift+Space用event.code

## 上下文感知智能诊断闭环 (2026-07-12 已部署)
- 三层诊断(API→Script→AI) + 三段排队(VIP→info_locked→not locked)
- 答题插队 + 五场景关闭
- 迁移052(6表+6列) + queue_service + quiz_service + closing_service
- H5前端: QueueWaiting + RightPanel双Tab + InputBar三态 + ResolveConfirmCard
- 坐席前端: pending_close结单流程 + 信息锁定(Dify步骤完成+有效回答率≥70%)

## 知识库迭代3 (2026-07-12 已部署)
- 分诊交互(H5+坐席+Dify独立应用)
- 拓扑预览(ECharts只读)
- 代答排除(4种匹配器: keyword/regex/intent/category)
- 迁移051 + 44文件43测试通过

## 后端变更
- 6个Python文件改造(h5_ai_task.py/h5.py/ai_service.py/closing_service.py等)
- funny_phrase_service.py: shake/connected/keyword 默认文案更新
- session_service.py: 企微消息文案同步
- 新增: queue.py/quiz.py/triage.py/exclusion_rules.py 等API端点
- 新增: diagnostic.py/quiz.py/triage_session.py 等模型
- 新增: closing_service/queue_service/quiz_service/triage_service 等服务

## 文档更新
- CHANGELOG.md: 新增 [未发布] 区全部变更记录
- 项目管理主文档 v2.5: 新增v0.7.3版本 + 已完成看板 + 最近搞定
- 版本记录: 新增v0.7.3条目
- AI对话链路实施计划: Phase 1-6 全部标记已实施
- 新增架构图/时序图/类图(mermaid)

## 部署路径修正
- 服务器项目根路径: /opt/wecom-it-desk/
- 所有前端dist均为ro bind mount,只能在宿主机源路径操作
- 服务器nginx /h5/ 是静态文件服务(非proxy_pass)
- elFinder上传二进制不可靠(MD5不匹配),改用base64分块上传
This commit is contained in:
Simon
2026-07-13 02:17:03 +08:00
parent bea288e414
commit 449c6d4875
176 changed files with 46637 additions and 4805 deletions
+33
View File
@@ -0,0 +1,33 @@
# =============================================================================
# 企微IT智能服务台 — 代答排除匹配器包
# =============================================================================
# 说明:策略模式实现 4 种匹配器,由 ExclusionService 责任链调度。
# 1. KeywordMatcher — 关键词匹配(逗号分隔,包含任一即命中)
# 2. RegexMatcher — 正则匹配(编译缓存 + ReDoS 超时保护)
# 3. IntentMatcher — 意图匹配(复用审批意图识别 Dify 链路)
# 4. CategoryMatcher — 分类匹配(查 triage_sessions 获取 problem_category
# =============================================================================
from app.services.matchers.base import BaseMatcher, MatchResult
from app.services.matchers.keyword_matcher import KeywordMatcher
from app.services.matchers.regex_matcher import RegexMatcher
from app.services.matchers.intent_matcher import IntentMatcher
from app.services.matchers.category_matcher import CategoryMatcher
# 匹配器注册表:match_type → Matcher 实例
MATCHER_REGISTRY: dict[str, BaseMatcher] = {
"keyword": KeywordMatcher(),
"regex": RegexMatcher(),
"intent": IntentMatcher(),
"category": CategoryMatcher(),
}
__all__ = [
"BaseMatcher",
"MatchResult",
"KeywordMatcher",
"RegexMatcher",
"IntentMatcher",
"CategoryMatcher",
"MATCHER_REGISTRY",
]
+55
View File
@@ -0,0 +1,55 @@
# =============================================================================
# 企微IT智能服务台 — 匹配器基类 + 匹配结果
# =============================================================================
# 说明:策略模式接口定义,所有匹配器必须继承 BaseMatcher 并实现 match 方法。
# =============================================================================
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional
@dataclass
class MatchResult:
"""匹配结果。
Attributes:
matched: 是否命中
matched_detail: 命中的关键词/正则/意图/分类(用于日志和测试展示)
match_position: 匹配位置(用于测试展示,如 "位置 12-18"
"""
matched: bool
matched_detail: str = ""
match_position: str = ""
class BaseMatcher(ABC):
"""匹配器基类 — 策略模式接口。
每种匹配器实现一种匹配逻辑(关键词/正则/意图/分类),
由 ExclusionService 责任链按优先级依次调用。
"""
@abstractmethod
async def match(
self,
message: str,
condition: str,
context: Optional[dict] = None,
) -> MatchResult:
"""检查消息是否匹配规则条件。
Args:
message: 用户消息文本
condition: 匹配条件
- keyword: 逗号分隔关键词列表(如 "密码过期,账号锁定"
- regex: 正则表达式(如 "密码.*过期"
- intent: 逗号分隔意图ID列表(如 "password_reset,account_unlock"
- category: 逗号分隔分类名称列表(如 "Outlook,VPN"
context: 上下文字典,可含 conversation_id, user_id, db 等
Returns:
MatchResult: 匹配结果
"""
...
@@ -0,0 +1,98 @@
# =============================================================================
# 企微IT智能服务台 — 分类匹配器
# =============================================================================
# 说明:查询 triage_sessions 表获取分诊结果的 problem_category
# 检查是否在排除分类列表中。
# 软依赖:无分诊结果时返回未命中,不影响其他匹配器执行。
# =============================================================================
import logging
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.triage_session import TriageSession
from app.services.matchers.base import BaseMatcher, MatchResult
logger = logging.getLogger(__name__)
class CategoryMatcher(BaseMatcher):
"""分类匹配器。
匹配逻辑:
1. 从 context 中获取 conversation_id 和 db
2. 查询 triage_sessions 获取最近一条分诊记录的 problem_category
3. 检查 problem_category 是否在排除分类列表中
软依赖:
- 无 conversation_id → 返回未命中
- 无 db → 返回未命中
- 无分诊记录 → 返回未命中
- 分诊记录无 problem_category → 返回未命中
Example:
condition = "Outlook,VPN,打印机"
conversation_id = "conv-123"
→ 查到最近分诊记录 problem_category = "Outlook"
→ 命中,matched_detail="分类: Outlook"
"""
async def match(
self,
message: str,
condition: str,
context: Optional[dict] = None,
) -> MatchResult:
"""检查分诊分类是否在排除列表中。
Args:
message: 用户消息文本(本匹配器不直接使用,保留接口一致性)
condition: 逗号分隔的分类名称列表
context: 上下文,需含 conversation_id 和 db
Returns:
MatchResult: 命中时 matched=True, matched_detail="分类: xxx"
"""
if not condition or not context:
return MatchResult(matched=False)
conversation_id = context.get("conversation_id")
db: Optional[AsyncSession] = context.get("db")
if not conversation_id or not db:
return MatchResult(matched=False)
excluded_categories = [s.strip() for s in condition.split(",") if s.strip()]
if not excluded_categories:
return MatchResult(matched=False)
# 查询最近一条分诊记录
try:
result = await db.execute(
select(TriageSession)
.where(TriageSession.conversation_id == conversation_id)
.order_by(TriageSession.created_at.desc())
.limit(1)
)
triage = result.scalar_one_or_none()
except Exception as e:
logger.error("分类匹配器查询分诊记录失败: %s", e)
return MatchResult(matched=False)
if not triage or not triage.problem_category:
# 无分诊结果,软依赖跳过
return MatchResult(matched=False)
# 检查分类是否在排除列表中
category = triage.problem_category
for excluded in excluded_categories:
if excluded.lower() == category.lower():
return MatchResult(
matched=True,
matched_detail=f"分类: {category}",
match_position=f"分诊分类匹配(triage_id={triage.id}",
)
return MatchResult(matched=False)
@@ -0,0 +1,142 @@
# =============================================================================
# 企微IT智能服务台 — 意图匹配器
# =============================================================================
# 说明:复用审批意图识别 Dify 链路(approval_dify_base_url + approval_dify_api_key),
# 调用 Dify 意图识别 API,检查返回意图是否在排除列表中。
# 降级处理:Dify 不可用时返回未命中(不影响其他匹配器执行)。
# =============================================================================
import logging
from typing import Optional
import httpx
from app.config import settings
from app.services.matchers.base import BaseMatcher, MatchResult
logger = logging.getLogger(__name__)
# 意图识别 System Prompt
_INTENT_SYSTEM_PROMPT = (
"你是IT服务台意图识别引擎,负责分析用户消息的意图类别。\n"
"输出约束:只输出意图ID(一个词),不要输出解释性文字。\n"
"常见意图ID包括:password_reset, account_unlock, software_install, "
"network_issue, hardware_repair, vpn_issue, email_issue, "
"approval_request, information_inquiry, complaint, other."
)
class IntentMatcher(BaseMatcher):
"""意图匹配器。
匹配逻辑:
1. 调用 Dify 意图识别 API(复用审批意图链路)
2. 获取用户消息的意图ID
3. 检查意图ID是否在排除列表中
降级处理:
- Dify 未配置或不可用 → 返回未命中
- Dify 超时 → 返回未命中
- 返回格式异常 → 返回未命中
Example:
condition = "password_reset,account_unlock"
message = "我的密码忘了,帮我重置一下"
→ Dify 返回 "password_reset"
→ 命中,matched_detail="意图: password_reset"
"""
async def _recognize_intent(self, message: str) -> Optional[str]:
"""调用 Dify 意图识别 API。
Args:
message: 用户消息文本
Returns:
Optional[str]: 识别到的意图ID,失败返回 None
"""
api_url = settings.approval_dify_base_url
api_key = settings.approval_dify_api_key
timeout = settings.approval_dify_timeout
if not api_url or not api_key:
logger.warning("审批意图识别 Dify 未配置,跳过意图匹配")
return None
try:
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.post(
f"{api_url}/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": "intent-recognition",
"messages": [
{"role": "system", "content": _INTENT_SYSTEM_PROMPT},
{"role": "user", "content": message},
],
"temperature": 0.1,
"max_tokens": 50,
},
)
resp.raise_for_status()
resp_data = resp.json()
content = resp_data["choices"][0]["message"]["content"].strip()
# 清理可能的 markdown 包裹
if content.startswith("```"):
content = content.strip("`").strip()
logger.info("意图识别结果: message=%s, intent=%s", message[:50], content)
return content
except httpx.TimeoutException:
logger.warning("意图识别 Dify 请求超时(%s秒)", timeout)
return None
except Exception as e:
logger.error("意图识别 Dify 调用异常: %s", e)
return None
async def match(
self,
message: str,
condition: str,
context: Optional[dict] = None,
) -> MatchResult:
"""检查消息意图是否在排除列表中。
Args:
message: 用户消息文本
condition: 逗号分隔的意图ID列表
context: 上下文(本匹配器不需要)
Returns:
MatchResult: 命中时 matched=True, matched_detail="意图: xxx"
"""
if not message or not condition:
return MatchResult(matched=False)
excluded_intents = [s.strip() for s in condition.split(",") if s.strip()]
if not excluded_intents:
return MatchResult(matched=False)
# 调用 Dify 意图识别
intent = await self._recognize_intent(message)
if intent is None:
# Dify 不可用,降级返回未命中
return MatchResult(matched=False)
# 检查意图是否在排除列表中(不区分大小写)
intent_lower = intent.lower()
for excluded in excluded_intents:
if excluded.lower() == intent_lower:
return MatchResult(
matched=True,
matched_detail=f"意图: {intent}",
match_position="意图识别匹配",
)
return MatchResult(matched=False)
@@ -0,0 +1,67 @@
# =============================================================================
# 企微IT智能服务台 — 关键词匹配器
# =============================================================================
# 说明:逗号分隔关键词列表,消息包含任一关键词即命中。
# 匹配不区分大小写,支持中英文混合。
# =============================================================================
import logging
from typing import Optional
from app.services.matchers.base import BaseMatcher, MatchResult
logger = logging.getLogger(__name__)
class KeywordMatcher(BaseMatcher):
"""关键词匹配器。
匹配逻辑:
1. 将 condition 按逗号分隔为关键词列表
2. 对消息文本做小写化处理
3. 消息包含任一关键词(小写化后)即命中
Example:
condition = "密码过期,账号锁定,密码错误"
message = "我的密码过期了怎么办"
→ 命中关键词 "密码过期"
"""
async def match(
self,
message: str,
condition: str,
context: Optional[dict] = None,
) -> MatchResult:
"""检查消息是否包含任一关键词。
Args:
message: 用户消息文本
condition: 逗号分隔的关键词列表
context: 上下文(本匹配器不需要)
Returns:
MatchResult: 命中时 matched=True, matched_detail=命中的关键词
"""
if not message or not condition:
return MatchResult(matched=False)
# 按逗号分隔关键词,去除空白
keywords = [kw.strip() for kw in condition.split(",") if kw.strip()]
if not keywords:
return MatchResult(matched=False)
# 消息小写化用于不区分大小写匹配
message_lower = message.lower()
for kw in keywords:
kw_lower = kw.lower()
pos = message_lower.find(kw_lower)
if pos != -1:
return MatchResult(
matched=True,
matched_detail=f"关键词: {kw}",
match_position=f"位置 {pos}-{pos + len(kw)}",
)
return MatchResult(matched=False)
@@ -0,0 +1,125 @@
# =============================================================================
# 企微IT智能服务台 — 正则匹配器
# =============================================================================
# 说明:使用 Python re.search 进行正则匹配,带编译缓存和 ReDoS 超时保护。
# 编译缓存:同一 pattern 只编译一次,缓存在类变量 _compile_cache 中。
# ReDoS 保护:使用 signal.alarm 超时机制,防止恶意正则导致 CPU 打满。
# =============================================================================
import logging
import re
import signal
from typing import Optional
from app.services.matchers.base import BaseMatcher, MatchResult
logger = logging.getLogger(__name__)
# 正则匹配超时时间(秒),防止 ReDoS
_REGEX_TIMEOUT_SEC: float = 2.0
# 正则编译缓存最大条目数
_MAX_CACHE_SIZE: int = 200
class RegexMatcher(BaseMatcher):
"""正则匹配器。
匹配逻辑:
1. 编译 condition 为正则 Pattern(带缓存)
2. 在消息文本中搜索匹配
3. 命中则返回匹配详情和位置
安全措施:
- 正则编译缓存:同一 pattern 只编译一次
- ReDoS 超时保护:匹配超过 2 秒自动中断,返回未命中
Example:
condition = "密码.*过期"
message = "我的密码好像过期了"
→ 命中,matched_detail="密码好像过期"
"""
# 类级正则编译缓存:pattern_str → compiled Pattern
_compile_cache: dict[str, re.Pattern] = {}
def _get_compiled(self, pattern_str: str) -> Optional[re.Pattern]:
"""获取编译后的正则 Pattern(带缓存)。
Args:
pattern_str: 正则表达式字符串
Returns:
Optional[re.Pattern]: 编译后的 Pattern,编译失败返回 None
"""
# 缓存命中
if pattern_str in self._compile_cache:
return self._compile_cache[pattern_str]
# 缓存清理:超过上限时清空(简单 LRU 策略)
if len(self._compile_cache) >= _MAX_CACHE_SIZE:
self._compile_cache.clear()
# 编译正则
try:
compiled = re.compile(pattern_str, re.IGNORECASE | re.MULTILINE)
self._compile_cache[pattern_str] = compiled
return compiled
except re.error as e:
logger.warning("正则编译失败: pattern=%s, error=%s", pattern_str, e)
return None
@staticmethod
def _timeout_handler(signum, frame):
"""正则匹配超时信号处理器。"""
raise TimeoutError("Regex matching timed out (possible ReDoS)")
async def match(
self,
message: str,
condition: str,
context: Optional[dict] = None,
) -> MatchResult:
"""检查消息是否匹配正则表达式。
Args:
message: 用户消息文本
condition: 正则表达式字符串
context: 上下文(本匹配器不需要)
Returns:
MatchResult: 命中时 matched=True, matched_detail=匹配到的文本
"""
if not message or not condition:
return MatchResult(matched=False)
compiled = self._get_compiled(condition)
if compiled is None:
return MatchResult(matched=False)
# 使用 signal 超时保护(仅 Unix 平台可用,Windows 降级为无超时)
try:
# 设置超时信号
old_handler = signal.signal(signal.SIGALRM, self._timeout_handler)
signal.setitimer(signal.ITIMER_REAL, _REGEX_TIMEOUT_SEC)
try:
m = compiled.search(message)
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, old_handler)
except (TimeoutError, OSError):
logger.warning("正则匹配超时(ReDoS 保护): pattern=%s", condition)
return MatchResult(matched=False)
except Exception as e:
logger.error("正则匹配异常: pattern=%s, error=%s", condition, e)
return MatchResult(matched=False)
if m:
matched_text = m.group(0)
return MatchResult(
matched=True,
matched_detail=f"正则匹配: {matched_text}",
match_position=f"位置 {m.start()}-{m.end()}",
)
return MatchResult(matched=False)