Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/services/chat/executors/base.py
This commit is contained in:
hugo committed 2026-07-10 00:50:34 +08:00
commit 5e7e5a8717
9 files changed
+412 -106

No files matched your search

+14
View File
@@ -64,6 +64,7 @@ def try_fast_route(
iter_enabled_chat_intent_routes,
)
from app.services.faq_cache import FaqCacheService
from app.services.chat import training_hr_stats_fallback
ensure_intent_routes_loaded()
@@ -86,6 +87,19 @@ def try_fast_route(
route_name='faq_cache',
)
if not has_files and training_hr_stats_fallback.supports(user=user, agent=agent, query=query):
_log_fast_route('training_hr_stats_fallback', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
return FastRouteResult(
generator=training_hr_stats_fallback.stream_chat(
query,
user,
agent,
external_conversation_id,
session_id=session_id,
),
route_name='training_hr_stats_fallback',
)
ctx = ChatIntentRouteContext(
user=user,
agent=agent,
@@ -0,0 +1,271 @@
"""
backend/app/services/chat/training_hr_stats_fallback.py
用途:为员工培训 Agent 提供 HR 统计类与考试明细类问答的本地兜底回复。
依赖:training_service、models.ChatLog、agent_runtime_context.adapters.generic。
逻辑:当员工培训 Dify 工作流中的数据库查询链路异常时,仅对 HR 固定统计/明细问法走本地聚合,
避免把 Dify SQL 拼接错误暴露给最终用户,并统一培训阶段与日期展示口径。
"""
from __future__ import annotations
import json
import re
import time
from datetime import date, datetime
from typing import Iterable
from app.extensions import db
from app.models import ChatLog, TrainingRecord
from app.services.agent_runtime_context.adapters.generic import is_training_chat_agent
from app.services.training_service import list_training_records, summarize_training_records
from flask import current_app
_TRAINING_TOTAL_PATTERNS = (
r'多少人参加了培训',
r'参训人数',
r'参加培训人数',
)
_TRAINING_PASS_RATE_PATTERNS = (
r'通过率',
r'培训通过率',
)
_TRAINING_INCOMPLETE_PATTERNS = (
r'哪些.*没有完成培训',
r'谁.*没有完成培训',
r'未完成培训',
)
_TRAINING_MONTHLY_SCORE_PATTERNS = (
r'本月培训成绩统计',
r'本月.*成绩统计',
r'本月.*培训.*统计',
)
_TRAINING_DETAIL_PATTERNS = (
r'考试明细',
r'培训明细',
r'培训人员明细',
r'人员明细',
r'考试列表',
r'培训列表',
r'人员列表',
r'考试记录',
r'培训记录',
r'查询.*明细',
r'查看.*明细',
r'所有参与培训人员的明细',
)
_TRAINING_STAGE_LABELS = {
'video': '观看视频',
'summary': '知识点复盘',
'exam': '逐题考试',
'result': '结束',
}
def _matches_any(query: str, patterns: Iterable[str]) -> bool:
text = str(query or '').strip()
return any(re.search(pattern, text) for pattern in patterns)
def _format_date_only(value: datetime | date | None) -> str:
"""把培训相关时间统一裁成 YYYY-MM-DD,避免聊天明细里出现多余时分秒。"""
if value is None:
return '-'
if isinstance(value, datetime):
return value.date().isoformat()
return value.isoformat()
def _stage_label(stage: str | None) -> str:
"""把 training_records.stage 英文值映射成 HR 更容易理解的中文阶段。"""
normalized = str(stage or '').strip().lower()
return _TRAINING_STAGE_LABELS.get(normalized, normalized or '-')
def supports(*, user, agent, query: str) -> bool:
"""
判断是否命中员工培训 HR 统计兜底。
AI 触发时机:仅当员工培训 Agent 收到 HR 管理类统计问题时触发,
普通知识问答、普通员工提问或其他 Agent 一律不命中。
Args:
user: 当前聊天用户代理对象;需至少包含 role。
agent: 当前 Agent 代理对象;需能识别是否为员工培训 Agent。
query: 用户原始问题。
Returns:
命中返回 True,否则返回 False。
"""
if not is_training_chat_agent(agent):
return False
if str(getattr(user, 'role', '') or '').strip() not in {'admin', 'hr'}:
return False
return (
_matches_any(query, _TRAINING_TOTAL_PATTERNS)
or _matches_any(query, _TRAINING_PASS_RATE_PATTERNS)
or _matches_any(query, _TRAINING_INCOMPLETE_PATTERNS)
or _matches_any(query, _TRAINING_MONTHLY_SCORE_PATTERNS)
or _matches_any(query, _TRAINING_DETAIL_PATTERNS)
)
def _build_total_answer() -> str:
result = list_training_records()
stats = summarize_training_records(result.records)
return (
f"当前共有 {stats['total']} 人参加了培训。"
f"其中已通过 {stats['passed']} 人,未通过 {stats['failed']} 人,进行中 {stats['in_progress']} 人。"
)
def _build_pass_rate_answer() -> str:
result = list_training_records()
stats = summarize_training_records(result.records)
return (
f"当前培训通过率为 {stats['pass_rate']}%。"
f"共 {stats['total']} 人参训,已通过 {stats['passed']} 人,未通过 {stats['failed']} 人。"
)
def _build_incomplete_answer() -> str:
result = list_training_records(status='in_progress')
records = result.records
if not records:
return '当前没有未完成培训的员工,所有参训人员都已完成当前培训流程。'
preview = '、'.join(str(item.name or item.employee_id or f'记录{item.id}') for item in records[:10])
suffix = '。' if len(records) <= 10 else f' 等 {len(records)} 人。'
return f"当前共有 {len(records)} 人尚未完成培训:{preview}{suffix}"
def _build_monthly_score_answer() -> str:
result = list_training_records()
now = datetime.utcnow()
monthly_records = [
item for item in result.records
if item.completion_time
and item.completion_time.year == now.year
and item.completion_time.month == now.month
]
if not monthly_records:
return '本月暂时没有已完成结算的培训成绩记录。'
stats = summarize_training_records(monthly_records)
return (
f"本月共有 {len(monthly_records)} 条培训成绩记录。"
f"已通过 {stats['passed']} 人,未通过 {stats['failed']} 人,平均分 {stats['average_score']} 分,"
f"通过率 {stats['pass_rate']}%。"
)
def _build_detail_answer() -> str:
"""
生成培训考试明细列表。
约束:
- 培训阶段必须输出中文映射,避免 HR 直接看到 video/summary/exam/result。
- 考试时间、完成时间统一裁剪为 YYYY-MM-DD。
"""
result = list_training_records()
records = result.records
if not records:
return '当前暂无员工培训考试明细记录。'
lines = [
'根据您的查询要求,以下是所有参与培训人员的明细数据预览:',
'',
'| 序号 | 姓名 | 工号 | 部门 | 考试时间 | 考试成绩 | 培训阶段 | 是否通过 | 完成时间 |',
'| --- | --- | --- | --- | --- | --- | --- | --- | --- |',
]
for index, item in enumerate(records, start=1):
lines.append(
'| {index} | {name} | {employee_id} | {department} | {started_at} | {score} | {stage} | {passed} | {completion_time} |'.format(
index=index,
name=str(item.name or '-'),
employee_id=str(item.employee_id or '-'),
department=str(item.department or '-'),
started_at=_format_date_only(item.started_at),
score=int(item.score or 0),
stage=_stage_label(item.stage),
passed='是' if bool(item.passed) else '否',
completion_time=_format_date_only(item.completion_time),
)
)
return '\n'.join(lines)
def build_answer(query: str) -> str:
"""
生成员工培训 HR 统计兜底答案。
Args:
query: 用户原始问题;仅支持预设的统计类意图。
Returns:
面向最终用户的中文答案。
"""
if _matches_any(query, _TRAINING_TOTAL_PATTERNS):
return _build_total_answer()
if _matches_any(query, _TRAINING_PASS_RATE_PATTERNS):
return _build_pass_rate_answer()
if _matches_any(query, _TRAINING_INCOMPLETE_PATTERNS):
return _build_incomplete_answer()
if _matches_any(query, _TRAINING_DETAIL_PATTERNS):
return _build_detail_answer()
return _build_monthly_score_answer()
def stream_chat(query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
"""
以 SSE 形式返回员工培训 HR 统计兜底答案,并写入 ChatLog。
Args:
query: 用户原始问题。
user: 当前用户代理对象,必须包含 id。
agent: 当前 Agent 代理对象,必须包含 id。
conversation_id: 外部会话 ID;为空时自动生成本地标识。
session_id: 本地 ChatSession.session_id。
Yields:
与既有聊天链路兼容的 SSE data 帧。
"""
start_time = time.time()
final_conversation_id = conversation_id or f"training_hr_{int(time.time())}"
answer = build_answer(query)
yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n"
latency = int((time.time() - start_time) * 1000)
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=0,
latency=latency,
payload={
'source': 'training_hr_stats_fallback',
},
)
db.session.add(chat_log)
db.session.commit()
chat_log_id = chat_log.id
except Exception as exc:
if current_app:
current_app.logger.error('[training-hr-fallback] failed to log chat: %s', exc)
db.session.rollback()
end_data = {
'event': 'message_end',
'answer': answer,
'replace_answer': True,
'chat_log_id': chat_log_id,
'conversation_id': final_conversation_id,
'metadata': {
'source': 'training_hr_stats_fallback',
},
}
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
+11 -6
View File
@@ -110,27 +110,29 @@ class DifyService:
return ""
@staticmethod
def _friendly_workflow_failure_message(raw_error: str) -> str:
def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str:
"""
将 Dify/Tool 技术错误转成用户可读提示。
Args:
raw_error: Dify 返回的原始错误文本。
agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。
Returns:
面向用户展示的简短中文提示。
"""
text = str(raw_error or "")
lower = text.lower()
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
return "服务暂时无法访问,请稍后重试或联系管理员检查工具授权。"
return f"{resolved_agent_name}暂时无法访问查询服务,请稍后重试或联系管理员检查工具授权。"
if "ssrf" in lower or "blocked" in lower or "private or local network" in lower:
return "服务暂时无法访问,请联系管理员检查工具网络访问配置。"
return f"{resolved_agent_name}暂时无法访问查询服务,请联系管理员检查工具网络访问配置。"
if "failed to invoke tool" in lower or "tool" in lower:
return "工具调用失败,请稍后重试;如持续失败请联系管理员。"
return f"{resolved_agent_name}查询工具调用失败,请稍后重试;如持续失败请联系管理员。"
if "maximum context length" in lower or "input_tokens" in lower:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return "设备维保助手暂时无法完成查询,请稍后重试。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
@@ -1007,7 +1009,10 @@ class DifyService:
raw_workflow_error = DifyService._extract_workflow_failure_text(data)
if raw_workflow_error:
friendly_error = DifyService._friendly_workflow_failure_message(raw_workflow_error)
friendly_error = DifyService._friendly_workflow_failure_message(
raw_workflow_error,
getattr(agent, 'name', None),
)
if current_app:
current_app.logger.warning(
"[chat-stream] workflow failed request_id=%s agent_id=%s raw_error=%s",
+18
View File
@@ -60,6 +60,24 @@ def test_extract_token_usage_prefers_positive_metadata_over_zero_payload():
assert DifyService._extract_token_usage(data) == 50
def test_friendly_workflow_failure_message_uses_current_agent_name():
"""培训 Agent 的工作流失败提示不应串成“设备维保助手”文案。"""
message = DifyService._friendly_workflow_failure_message(
'workflow failed unexpectedly',
agent_name='员工培训',
)
assert message == '员工培训暂时无法完成查询,请稍后重试。'
def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agent_name():
"""工具调用失败时也应按当前 Agent 名称返回上下文一致的提示。"""
message = DifyService._friendly_workflow_failure_message(
'Failed to invoke tool: xx',
agent_name='员工培训',
)
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
def test_persist_stream_chat_record_uses_workflow_finished_tokens(app):
"""workflow_finished 首次落库应写入 data.total_tokens。"""
with app.app_context():
+1
View File
@@ -29,6 +29,7 @@
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 |
| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 |
| 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 |
| 培训 HR 统计问答兜底 | 已实现 | “员工培训”聊天页中,HR 管理员提问参训人数、通过率、未完成名单、本月成绩统计及考试明细等固定统计问题时,优先走后端本地统计兜底;明细列表会把培训阶段映射为中文(观看视频/知识点复盘/逐题考试/结束),并统一把考试时间、完成时间格式化为年月日,避免当前 Dify 工作流 SQL 改写异常导致问答失败 |
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
@@ -3,7 +3,7 @@
* features/chat/components/TrainingWorkspacePanel.vue
* 用途:在培训 Agent 的聊天页顶部提供“员工培训 + 培训管理”一体化工作区。
* 依赖:useTrainingWorkspace、lucide 图标、聊天页 currentAgent/currentUser。
* 逻辑:只在培训 Agent 下渲染;普通员工首次进入默认展开工作区,但新建/切换会话后保持收起,避免聊天过程中被自动展开打断。
* 逻辑:只在培训 Agent 下渲染;员工与 HR 管理员首次进入默认展开工作区,但新建/切换会话后保持收起,避免聊天过程中被自动展开打断。
*/
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -62,7 +62,8 @@ const stageItems = computed(() => ([
]));
const userExpandedOverride = ref<boolean | null>(null);
const shouldDefaultExpanded = computed(() => workspace.isTrainingAgent && !workspace.isAdminViewer);
// HR 管理员与普通员工首次进入培训 Agent 时都默认展开工作区;新建对话仍按既有约束强制收起。
const shouldDefaultExpanded = computed(() => workspace.isTrainingAgent);
const handleVideoTimeUpdate = (e: Event) => {
const video = e.target as HTMLVideoElement;
@@ -109,7 +110,7 @@ const applyDefaultExpandedState = () => {
emit('update:expanded', nextExpanded);
};
// 监听 Agent/角色切换,重置本地展开态:员工默认展开工作区,培训管理角色默认保留问答视图。
// 监听 Agent/角色切换,重置本地展开态:培训角色首次进入默认展开工作区。
watch(
() => [props.currentAgent?.id, workspace.isAdminViewer],
() => {
@@ -130,6 +131,20 @@ watch(
);
const isCompactMode = computed(() => !workspaceExpanded.value);
const isLearnerExamStage = computed(() => !isCompactMode.value && workspace.activeView === 'learner' && workspace.stage === 'exam');
const learnerWorkspaceGridClass = computed(() => (
'grid gap-2.5 p-3 md:grid-cols-[minmax(0,1.7fr)_208px] md:p-4 lg:gap-3 lg:grid-cols-[minmax(0,1.85fr)_220px] 2xl:grid-cols-[minmax(0,1.95fr)_240px]'
));
const learnerWorkspaceMainClass = computed(() => 'min-w-0 space-y-3');
const progressCardClass = computed(() => 'rounded-2xl border border-default bg-white p-2.5 shadow-sm');
const examPanelClass = computed(() => (
isLearnerExamStage.value
? 'rounded-2xl border border-default bg-white p-3.5 shadow-sm'
: 'rounded-2xl border border-default bg-white p-4 shadow-sm'
));
const questionNavPanelClass = computed(() => 'rounded-2xl border border-default bg-white p-2.5 shadow-sm');
const questionNavGridClass = computed(() => 'mt-2 grid grid-cols-4 gap-1');
const questionNavButtonClass = computed(() => 'flex h-7 items-center justify-center rounded-lg border text-[11px] font-semibold transition');
const compactSummary = computed(() => {
if (workspace.activeView === 'admin') {
@@ -146,7 +161,6 @@ const compactSummary = computed(() => {
return workspace.isPassed ? t('chat.training.result.passTitle') : t('chat.training.result.failTitle');
});
const trainingTitle = computed(() => String(t('chat.training.title') || '').trim());
const ruleItems = computed(() => ([
t('chat.training.rules.rule1', { total: workspace.totalQuestionCount }),
t('chat.training.rules.rule2'),
@@ -158,11 +172,24 @@ const learnerIdentityItems = computed(() => ([
{ key: 'employee-id', label: t('chat.training.learnerCard.employeeId'), value: workspace.currentUserEmployeeId },
{ key: 'department', label: t('chat.training.learnerCard.department'), value: workspace.currentUserDepartment },
]));
const examQuestionItems = computed(() => Array.from({ length: workspace.totalQuestionCount }, (_, index) => ({
index,
label: String(index + 1).padStart(2, '0'),
isActive: workspace.currentQuestionIndex === index,
})));
const answeredQuestionMap = computed(() => new Map(
workspace.answerRecords.map((item) => [item.questionId, item])
));
const examQuestionItems = computed(() => Array.from({ length: workspace.totalQuestionCount }, (_, index) => {
const isActive = workspace.stage === 'exam' && workspace.currentQuestionIndex === index;
const questionId = workspace.questionBank[index]?.id;
const answerRecord = questionId ? answeredQuestionMap.value.get(questionId) ?? null : null;
return {
index,
label: String(index + 1).padStart(2, '0'),
isActive,
status: isActive
? 'active'
: answerRecord
? answerRecord.correct ? 'correct' : 'wrong'
: 'pending',
};
}));
const canNavigateExamQuestions = computed(() => workspace.stage === 'exam');
const jumpToExamQuestion = (index: number) => {
if (!canNavigateExamQuestions.value) return;
@@ -186,20 +213,11 @@ const handleStageCardClick = (stageKey: string) => {
>
<div
v-if="isCompactMode"
class="flex flex-col gap-2 bg-white/90 px-4 py-2.5 backdrop-blur-sm md:px-5"
class="flex flex-col gap-1.5 bg-white/90 px-4 py-2 backdrop-blur-sm md:px-5"
>
<div class="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-between">
<div class="flex flex-col gap-1.5 xl:flex-row xl:items-center xl:justify-between">
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<div class="inline-flex items-center gap-2 rounded-full bg-brand-50 px-3 py-1 text-[11px] font-semibold text-brand-700">
<BookOpen class="h-3.5 w-3.5" />
{{ $t('chat.training.badge') }}
</div>
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
{{ trainingTitle }}
</div>
</div>
<div class="mt-1.5 flex flex-wrap gap-2">
<div class="flex flex-wrap gap-2">
<button
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
@@ -250,7 +268,7 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div class="flex flex-col gap-2 rounded-2xl border border-brand-100 bg-brand-50/40 px-4 py-2.5 md:flex-row md:items-center md:justify-between">
<div class="flex flex-col gap-2 rounded-2xl border border-brand-100 bg-brand-50/40 px-3.5 py-2 md:flex-row md:items-center md:justify-between">
<div class="min-w-0">
<div class="truncate text-sm font-semibold text-primary">
{{ compactSummary }}
@@ -282,20 +300,10 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div v-else class="flex flex-col gap-2 bg-white/90 px-4 py-2.5 backdrop-blur-sm md:px-5">
<div class="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-between">
<div v-else class="flex flex-col gap-1.5 bg-white/90 px-4 py-2 backdrop-blur-sm md:px-5">
<div class="flex flex-col gap-1.5 xl:flex-row xl:items-center xl:justify-between">
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<div class="inline-flex items-center gap-2 rounded-full bg-brand-50 px-3 py-1 text-[11px] font-semibold text-brand-700">
<BookOpen class="h-3.5 w-3.5" />
{{ $t('chat.training.badge') }}
</div>
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
{{ trainingTitle }}
</div>
</div>
<div class="mt-1.5 flex flex-wrap gap-2">
<div class="flex flex-wrap gap-2">
<button
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
@@ -337,7 +345,7 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div class="flex flex-col gap-2 rounded-2xl border border-brand-100 bg-brand-50/40 px-4 py-2.5 md:flex-row md:items-center md:justify-between">
<div class="flex flex-col gap-2 rounded-2xl border border-brand-100 bg-brand-50/40 px-3.5 py-2 md:flex-row md:items-center md:justify-between">
<div class="min-w-0">
<div class="truncate text-sm font-semibold text-primary">
{{ compactSummary }}
@@ -367,29 +375,29 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div v-if="!isCompactMode && workspace.activeView === 'learner'" class="grid gap-3 p-4 md:grid-cols-[minmax(0,1.25fr)_232px] md:p-5 lg:gap-4 lg:grid-cols-[minmax(0,1.4fr)_260px] 2xl:grid-cols-[minmax(0,1.55fr)_300px]">
<div class="min-w-0 space-y-4">
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-2.5 lg:flex-row lg:items-start lg:justify-between">
<div v-if="!isCompactMode && workspace.activeView === 'learner'" :class="learnerWorkspaceGridClass">
<div :class="learnerWorkspaceMainClass">
<div :class="progressCardClass">
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.progressLabel') }}
</div>
<div class="mt-1 text-xs leading-5 text-secondary md:text-sm">
<div class="mt-0.5 text-[11px] leading-4.5 text-secondary md:text-xs">
{{ $t('chat.training.progressHint') }}
</div>
</div>
<div class="rounded-xl bg-surface-soft px-3 py-2 text-center">
<div class="rounded-lg bg-surface-soft px-2.5 py-1 text-center">
<div class="text-xs text-muted">{{ $t('chat.training.progressPercent') }}</div>
<div class="text-lg font-semibold leading-none text-primary">{{ workspace.learnerProgressPercent }}%</div>
<div class="text-base font-semibold leading-none text-primary">{{ workspace.learnerProgressPercent }}%</div>
</div>
</div>
<div class="mt-3 grid grid-cols-2 gap-2 lg:grid-cols-4">
<div class="mt-2 grid grid-cols-2 gap-1 lg:grid-cols-4">
<div
v-for="(item, index) in stageItems"
:key="item.key"
class="rounded-xl border px-3 py-2.5 transition cursor-pointer hover:border-brand-300"
class="cursor-pointer rounded-xl border px-2 py-1.5 transition hover:border-brand-300"
:class="[
stageStep >= index + 1 ? 'border-brand-200 bg-brand-50/70' : 'border-default bg-surface-soft/70',
canSwitchToStage(String(item.key)) ? 'cursor-pointer hover:border-brand-300' : 'cursor-not-allowed opacity-60',
@@ -398,16 +406,16 @@ const handleStageCardClick = (stageKey: string) => {
>
<div class="flex items-center gap-2">
<div
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg"
:class="stageStep >= index + 1 ? 'bg-brand-600 text-white' : 'bg-white text-muted'"
>
<component :is="item.icon" class="h-4 w-4" />
<component :is="item.icon" class="h-3 w-3" />
</div>
<div class="min-w-0">
<div class="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted">
<div class="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted">
{{ String(index + 1).padStart(2, '0') }}
</div>
<div class="whitespace-normal text-sm font-medium leading-5 text-primary">{{ $t(item.label) }}</div>
<div class="whitespace-normal text-[12px] font-medium leading-4 text-primary">{{ $t(item.label) }}</div>
</div>
</div>
</div>
@@ -415,20 +423,11 @@ const handleStageCardClick = (stageKey: string) => {
</div>
<div v-if="workspace.stage === 'video'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
<div>
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.video.title') }}</h3>
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.video.description') }}</p>
</div>
<button
v-if="trainingExamPdfGuide"
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
>
<BookOpen class="h-4 w-4" />
{{ $t('chat.training.actions.viewExamPdf') }}
</button>
</div>
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
@@ -448,15 +447,6 @@ const handleStageCardClick = (stageKey: string) => {
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.summary.description') }}</p>
</div>
<div class="flex flex-wrap gap-2">
<button
v-if="trainingExamPdfGuide"
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
>
<BookOpen class="h-4 w-4" />
{{ $t('chat.training.actions.viewExamPdf') }}
</button>
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
@@ -491,38 +481,38 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div v-else-if="workspace.stage === 'exam' && workspace.currentQuestion" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div v-else-if="workspace.stage === 'exam' && workspace.currentQuestion" :class="examPanelClass">
<div class="flex flex-col gap-2.5 md:flex-row md:items-center md:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.exam.title') }}
</div>
<h3 class="mt-1 text-lg font-semibold text-primary">
<h3 class="mt-1 text-base font-semibold text-primary md:text-lg">
{{ $t('chat.training.exam.questionCounter', { current: workspace.currentQuestionNumber, total: workspace.totalQuestionCount }) }}
</h3>
</div>
<div class="flex flex-wrap gap-2 text-sm text-secondary">
<div class="rounded-xl bg-surface-soft px-3 py-1.5">
<div class="flex flex-wrap gap-1.5 text-xs text-secondary md:text-sm">
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
</div>
<div class="rounded-xl bg-surface-soft px-3 py-1.5">
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
</div>
</div>
</div>
<div class="mt-4 rounded-2xl border border-brand-100 bg-brand-50/40 p-3.5">
<div class="text-base font-semibold leading-7 text-primary">
<div class="mt-3 rounded-2xl border border-brand-100 bg-brand-50/40 p-3">
<div class="text-[15px] font-semibold leading-6 text-primary md:text-base">
{{ workspace.currentQuestion.prompt }}
</div>
</div>
<div class="mt-3 grid gap-2.5">
<div class="mt-2.5 grid gap-2">
<button
v-for="option in workspace.currentQuestion.options"
:key="option.id"
type="button"
class="rounded-2xl border px-4 py-2.5 text-left text-sm transition"
class="rounded-2xl border px-3.5 py-2 text-left text-sm leading-5 transition"
:class="[
workspace.selectedOptionId === option.id
? workspace.answerLocked
@@ -548,7 +538,7 @@ const handleStageCardClick = (stageKey: string) => {
<div
v-if="workspace.answerLocked"
class="mt-4 rounded-2xl border p-3.5"
class="mt-3 rounded-2xl border p-3"
:class="workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
>
<div class="flex items-center gap-2 text-sm font-semibold" :class="workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
@@ -568,7 +558,7 @@ const handleStageCardClick = (stageKey: string) => {
<div class="mt-3">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700"
@click="workspace.examReadyToSubmit ? workspace.submitExam() : workspace.moveToNextQuestion()"
>
<ClipboardCheck class="h-4 w-4" />
@@ -640,27 +630,30 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div class="min-w-0 md:sticky md:top-4 md:self-start">
<div class="rounded-2xl border border-default bg-white p-3 shadow-sm">
<div class="min-w-0 md:sticky md:top-3 md:self-start">
<div :class="questionNavPanelClass">
<div class="flex items-center gap-2">
<ClipboardCheck class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
</div>
<div class="mt-2 text-xs leading-5 text-secondary">
<div class="mt-1.5 text-[11px] leading-4.5 text-secondary">
{{ $t('chat.training.examQuestionCard.hint') }}
</div>
<div class="mt-3 grid grid-cols-4 gap-2">
<div :class="questionNavGridClass">
<button
v-for="item in examQuestionItems"
:key="item.index"
type="button"
class="flex h-10 items-center justify-center rounded-xl border text-sm font-semibold transition"
:class="[
item.isActive
questionNavButtonClass,
item.status === 'active'
? 'border-brand-500 bg-brand-600 text-white shadow-sm'
: canNavigateExamQuestions
? 'border-brand-200 bg-brand-50/60 text-brand-700 hover:bg-brand-100'
: 'cursor-not-allowed border-default bg-surface-soft text-muted',
: item.status === 'correct'
? 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
: item.status === 'wrong'
? 'border-red-200 bg-red-50 text-red-700 hover:bg-red-100'
: 'border-default bg-surface-soft text-muted hover:border-slate-300 hover:bg-slate-100',
!canNavigateExamQuestions ? 'cursor-not-allowed opacity-80' : '',
]"
:disabled="!canNavigateExamQuestions"
@click="jumpToExamQuestion(item.index)"
@@ -669,10 +662,10 @@ const handleStageCardClick = (stageKey: string) => {
</button>
</div>
<div class="my-3 h-px bg-slate-100" />
<div class="my-2.5 h-px bg-slate-100" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
<ul class="mt-2 grid gap-1 text-xs leading-5 text-secondary">
<ul class="mt-1.5 grid gap-1 text-[11px] leading-4.5 text-secondary">
<li v-for="rule in ruleItems" :key="rule" class="flex gap-2">
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
<span>{{ rule }}</span>
@@ -706,6 +706,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentQuestionIndex,
currentQuestionNumber,
currentQuestion,
questionBank,
totalQuestionCount,
passScore,
answeredCount,
@@ -1,12 +1,13 @@
/**
* 对话页:语音输入(当前功能开关关闭,保留占位与思考态取消录音)。
* features/chat/page/useChatPageVoice.ts
* 用途:封装对话页语音输入按钮行为,将浏览器录音结果回填到输入框。
* 依赖:Vue watch、shared/composables/useAudioTranscription、聊天页 message/i18n 上下文。
* 逻辑:ChatViewContent 触发按钮点击后,本文件先做思考态与浏览器能力校验,再交给转写 composable 录音并调用后端 ASR。
*/
import { watch } from 'vue';
import { getVoiceUnavailableErrorKey, useAudioTranscription } from '@/shared/composables/useAudioTranscription';
import type { Ref } from 'vue';
const VOICE_INPUT_ENABLED = false;
export interface ChatPageVoiceContext {
input: Ref<string>;
isThinking: Ref<boolean>;
@@ -14,6 +15,12 @@ export interface ChatPageVoiceContext {
t: (key: string) => string;
}
/**
* 绑定聊天页语音输入状态与操作。
* 核心逻辑:复用 useAudioTranscription 完成录音/转写;点击时只拦截思考中、转写中、非 HTTPS 或浏览器不支持的场景。
* @param ctx - 聊天页输入框、思考态、消息提示与 i18n 翻译上下文。
* @returns 语音录制状态、转写状态、点击处理函数与取消函数。
*/
export function useChatPageVoice(ctx: ChatPageVoiceContext) {
const {
isRecording: isVoiceRecording,
@@ -30,10 +37,6 @@ export function useChatPageVoice(ctx: ChatPageVoiceContext) {
});
const handleVoiceFeatureClick = () => {
if (!VOICE_INPUT_ENABLED) {
ctx.msg.info(ctx.t('chat.devComingSoon'));
return;
}
if (ctx.isThinking.value || isVoiceTranscribing.value) return;
const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) {
@@ -166,7 +166,7 @@ defineProps<{
<button
@click="kb.handleSaveMarkdown"
:disabled="kb.isMarkdownLoading || kb.isMarkdownSaving || !kb.markdownDocumentId"
class="inline-flex items-center justify-center rounded-xl bg-brand-600px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
class="inline-flex items-center justify-center rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
{{ kb.isMarkdownSaving ? kb.t('kbWorkspace.markdownModal.saving') : kb.t('kbWorkspace.markdownModal.save') }}
</button>
@@ -465,7 +465,7 @@ defineProps<{
</button>
<button
@click="kb.handleConfirmPathUpload"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Upload class="h-4 w-4" />
{{ kb.t('kbWorkspace.pathUploadModal.confirmUpload') }}