Author SHA1 Message Date
lyun 52d92c95d8 修复:智能分析空回答与工具结束条件冲突
统一自主分析工具范围与执行前校验,严格核验正常结束、最终正文和图表恢复状态,并显示空回答及恢复失败原因。

包含两次已上线修复及回归测试,保留已有回答与业务数据。

验证:1101 项 Python、469 项前端、97 项后端测试通过;前后端构建和真实模型、页面验收通过。
2026-11-03 08:56:49 +08:00
lyun 7ffb5cdb9c 优化:趋势图采用轻度平滑曲线并保留柏拉图直线 2026-11-02 16:30:53 +08:00
lyun a84ee85a84 修复:普通对话沿用模型原文并保留业务前态 2026-11-02 13:37:17 +08:00
lyun b03715cb76 新增:月度数据关键和完整指标切换及分视图默认 2026-11-02 13:23:59 +08:00
lyun 1b0274974c 修复:分析会话独立加载并保持加载布局稳定 2026-11-02 12:38:40 +08:00
lyun 903fa94c00 修复:完整展示AI原文并穿插图表,统一运行反馈与变化符号 2026-11-02 12:03:37 +08:00
64 changed files with 1977 additions and 273 deletions
+14 -1
View File
@@ -1,6 +1,17 @@
# 质量数据分析平台设计规范 # 质量数据分析平台设计规范
更新:2026-10-30 更新:2026-11-02
- 月度趋势数据表提供“关键指标 / 完整指标”切换,完整列与主汇总表共用字段口径与顺序。黑片、亮片页面首次默认完整指标,其余四类查询首次默认关键指标;各缓存页保留用户选择,查询和重置不改写选择,不增加数据请求。
## 智能分析正文与运行反馈(2026-11-02)
- 历史正文与会话列表分别读取,指定会话链接不等待列表;只有从查询条件创建会话时才加载选项。加载提示放在对应面板内部,首次读取不得显示欢迎空状态,也不得用通用大高度加载块推移会话框和输入区;列表失败不阻止已授权正文读取。
- 原生 AI 会话及报告以模型完整原文为正文,保留段落、表格和顺序,正式查询图表穿插在相关章节后;取消二次改写和统计兜底报告替换。历史兜底报告仅在保存的模型原文可恢复时恢复,原文缺失不伪造补齐。
- 会话只显示一次最终回答,运行过程保留思考与工具步骤;运行中默认展开,可手动收起。发送立即显示等待状态和计时,收到服务器开始时间后显示运行计时和旋转图标。
- 不在会话追加范围说明、进度句、错误或“部分完成”提示;真实失败、证据缺口和完成状态仍保存在后台,恢复及重试入口保留。
- 合格率变化统一为本期减比较期:下降为负 pp,上升为正 pp。用于筛选和排序的降幅指标保持原有语义,转换仅作用于展示值;图表、数据表和导出一致。
## 已确认方向 ## 已确认方向
- 保持现有导航宽度、模块顺序、筛选承载、指标横条、表格及趋势位置。(用户确认) - 保持现有导航宽度、模块顺序、筛选承载、指标横条、表格及趋势位置。(用户确认)
@@ -122,3 +133,5 @@
- 更新中的旧范围结果不能钻取、查看明细或导出;区域独立重试。任务使用真实阶段,写入即时忙碌并防重复,不显示虚构百分比或新增常驻说明。 - 更新中的旧范围结果不能钻取、查看明细或导出;区域独立重试。任务使用真实阶段,写入即时忙碌并防重复,不显示虚构百分比或新增常驻说明。
- 返回页面保留筛选、页码、滚动位置及表格高度;隐藏页面和未选管理页签不主动刷新。业务分页、全范围搜索排序和导出不变。 - 返回页面保留筛选、页码、滚动位置及表格高度;隐藏页面和未选管理页签不主动刷新。业务分页、全范围搜索排序和导出不变。
- 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。 - 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。
- 2026-11-02:趋势折线使用用户选定的 A 轻度平滑(0.15),沿横轴约束曲线;查询合格率、不良率、智能分析与导出统一。柏拉图累计线保持直线,数据点、缺失断点和计算口径不变。
+2
View File
@@ -10,6 +10,8 @@
比例转百分数乘100;两比例之差乘100才是“百分点”。例如0.96→0.95是下降1个百分点,不能先对原始比例差保留两位再换算。保留原始精度到最后展示一步。空值表示缺失/不适用,不等于零;新增/退出对象允许描述重量变化,但不补造其缺失期合格率。 比例转百分数乘100;两比例之差乘100才是“百分点”。例如0.96→0.95是下降1个百分点,不能先对原始比例差保留两位再换算。保留原始精度到最后展示一步。空值表示缺失/不适用,不等于零;新增/退出对象允许描述重量变化,但不补造其缺失期合格率。
合格率变化统一为“本期-比较期”:下降显示 -X.XX pp,上升显示 +X.XX pp,持平为 0.00 pp;可另外标注方向。rateDrop/rate_drop 是比较期减本期的降幅排序量,不能直接当作有符号变化;展示其变化时取反并按正式单位换算,排序顺序不变。优先引用工具已提供的正式变化值,不能从舍入后的两期率重新计算。
重量统一以正式kg展示。仅正式schema/返回单位明确为kg的质量字段允许按精确Decimal固定1000识别吨展示,最终仍统一kg;未知来源单位、件数、率和百分点不能按重量换算。严格比较阈值保留原始精确边界,不能用舍入值改变“低于/超过”等关系。工具formalDisplay与原始值共同给出正式展示;OwnStageRateChangePp是阶段自身率变化,ContributionPp才是对综合率的贡献,不能因同阶段同为百分点互换,也不能用舍入相邻值修正错误贡献。 重量统一以正式kg展示。仅正式schema/返回单位明确为kg的质量字段允许按精确Decimal固定1000识别吨展示,最终仍统一kg;未知来源单位、件数、率和百分点不能按重量换算。严格比较阈值保留原始精确边界,不能用舍入值改变“低于/超过”等关系。工具formalDisplay与原始值共同给出正式展示;OwnStageRateChangePp是阶段自身率变化,ContributionPp才是对综合率的贡献,不能因同阶段同为百分点互换,也不能用舍入相邻值修正错误贡献。
“汽车交通”是“新能源汽车磁钢”产业部的业务别名,统一用 filters.department=新能源汽车磁钢;不能用国内和海外的 group 多选集合替代产业部范围,两者原始记录覆盖未必相同。国内、海外是该产业部下的业务分组,查询子分组时保留 department 并添加明确 group;比较分组时用 changes+dimension=group,父筛选仍为 department。总体指全公司。规格对应 product。期间、范围、基期、发布版本要一致。默认比较上一个完整期间;如果用户未给年份和月份,从可用数据目录与上下文判断,首次使用在回答中简短说明,不把当前日历月当成已有数据月。 “汽车交通”是“新能源汽车磁钢”产业部的业务别名,统一用 filters.department=新能源汽车磁钢;不能用国内和海外的 group 多选集合替代产业部范围,两者原始记录覆盖未必相同。国内、海外是该产业部下的业务分组,查询子分组时保留 department 并添加明确 group;比较分组时用 changes+dimension=group,父筛选仍为 department。总体指全公司。规格对应 product。期间、范围、基期、发布版本要一致。默认比较上一个完整期间;如果用户未给年份和月份,从可用数据目录与上下文判断,首次使用在回答中简短说明,不把当前日历月当成已有数据月。
@@ -2,12 +2,16 @@
先读 /RULES.md 了解正式公式、单位、范围和来源语义;需要时读 /agent/mcps/quality/quality_data.json 一次了解工具。所有业务数据经原生 mcp_call 调用 quality 的 quality_data 取得。不调用数据库、execute_sql、display_chart 或 story;平台负责图表与报告。 先读 /RULES.md 了解正式公式、单位、范围和来源语义;需要时读 /agent/mcps/quality/quality_data.json 一次了解工具。所有业务数据经原生 mcp_call 调用 quality 的 quality_data 取得。不调用数据库、execute_sql、display_chart 或 story;平台负责图表与报告。
本模式开放只读文件工具 read/list/grep/search 和 quality 的 mcp_call/mcp_connect。平台负责查询前的任务澄清、数据绑定和后续追问;不使用原生 clarification、数据库选择、凭据收集、建议追问或写入工具结束任务。证据足够时,在最后一次查询返回后直接输出最终正文,并正常结束;工具返回、图表安排或进度说明不等于最终回答。
本会话使用自主调查模式。遵守RULES中的正式公式、数据语义与证据边界,不设固定全维度覆盖、维度顺序或自动补查配方。以本轮 _agentTask 的明确目标和约束为准:必要基线→观察结果→选择下次查询或验证反例→判断是否已回答。不要为了覆盖目录而查询每个产业部、分组或规格,不固定只追一个产品或一个阶段。若多个线索同样重要,应比较后再判断。 本会话使用自主调查模式。遵守RULES中的正式公式、数据语义与证据边界,不设固定全维度覆盖、维度顺序或自动补查配方。以本轮 _agentTask 的明确目标和约束为准:必要基线→观察结果→选择下次查询或验证反例→判断是否已回答。不要为了覆盖目录而查询每个产业部、分组或规格,不固定只追一个产品或一个阶段。若多个线索同样重要,应比较后再判断。
正式数值直接来自工具,不能自行重算KPI或编造缺失值。你可以解释分子分母、规模、结构及阶段的关系,清楚区分已核实事实、统计线索与待验证生产假设;引用真实 evidenceRef。工具支持的正式差值和阶段拆解可以直接引用;缺少的数据不得补零。统计关联不能宣称已证实设备、工艺、供应商或人员根因。 正式数值直接来自工具,不能自行重算KPI或编造缺失值。你可以解释分子分母、规模、结构及阶段的关系,清楚区分已核实事实、统计线索与待验证生产假设;引用真实 evidenceRef。工具支持的正式差值和阶段拆解可以直接引用;缺少的数据不得补零。统计关联不能宣称已证实设备、工艺、供应商或人员根因。
优先使用工具formalDisplay的规范数值与单位,重量最终统一kg。阶段自身率变化与对综合率贡献按metricRole明确区分;不能把OwnStageRateChangePp当ContributionPp,也不能从舍入后的阶段变化凑总体等式。只有正式原单位明确kg的质量字段可按固定1000识别吨,数量和未知单位不换算,严格阈值不舍入。 优先使用工具formalDisplay的规范数值与单位,重量最终统一kg。阶段自身率变化与对综合率贡献按metricRole明确区分;不能把OwnStageRateChangePp当ContributionPp,也不能从舍入后的阶段变化凑总体等式。只有正式原单位明确kg的质量字段可按固定1000识别吨,数量和未知单位不换算,严格阈值不舍入。
合格率变化统一为“本期-比较期”:下降显示 -X.XX pp,上升显示 +X.XX pp,持平为 0.00 pp;可另外标注方向。rateDrop/rate_drop 是比较期减本期的降幅排序量,不能直接当作有符号变化;展示其变化时取反并按正式单位换算,排序顺序不变。优先引用工具已提供的正式变化值,不能从舍入后的两期率重新计算。
当前已确认 filters、period、comparisonPeriod 是唯一范围权威。历史问答只帮助理解指代,不能恢复已取消条件。每轮使用同一个内部releaseId但不向用户展示内部ID、版本锁定或执行协议。修改用户范围需要下一轮确认;调查内只允许保持父条件、沿授权目录缩小对象。 当前已确认 filters、period、comparisonPeriod 是唯一范围权威。历史问答只帮助理解指代,不能恢复已取消条件。每轮使用同一个内部releaseId但不向用户展示内部ID、版本锁定或执行协议。修改用户范围需要下一轮确认;调查内只允许保持父条件、沿授权目录缩小对象。
原因分析须先取得整个已确认范围的正式本期/比较期基线,再决定是否缩小范围;不能用某个子分组或单个规格的率代替整个问题范围。首次compare/query保持_agentTask.filters原样,不额外添加子对象。之后的方向和深度由真实返回的线索决定。 原因分析须先取得整个已确认范围的正式本期/比较期基线,再决定是否缩小范围;不能用某个子分组或单个规格的率代替整个问题范围。首次compare/query保持_agentTask.filters原样,不额外添加子对象。之后的方向和深度由真实返回的线索决定。
+1 -1
View File
@@ -37,7 +37,7 @@ releaseId、发布版本号、候选发布状态、Story ID/slug/version 仅作
整体变化先用简短摘要说清变化方向、主要阶段和优先核查线索,再展开各节。每节先写一到三句解释已确认的现象及实际含义,必要时附一张紧凑数据表,不只连续抄表、不在“重点关注”重复全部数字。阶段数学影响沿用 stageDecomposition 的服务端结果,不能把阶段自身率变化当作对综合率贡献,也不把数学拆解称现场生产根因。亮片报废下降而投入下降更多时,要明确解释合格率仍可能下降。 整体变化先用简短摘要说清变化方向、主要阶段和优先核查线索,再展开各节。每节先写一到三句解释已确认的现象及实际含义,必要时附一张紧凑数据表,不只连续抄表、不在“重点关注”重复全部数字。阶段数学影响沿用 stageDecomposition 的服务端结果,不能把阶段自身率变化当作对综合率贡献,也不把数学拆解称现场生产根因。亮片报废下降而投入下降更多时,要明确解释合格率仍可能下降。
常规整体分析的重点规格优先结合报废增量、当前规模、率变化和分阶段有效投入确定核查优先级。单按合格率降幅返回的小批量、0率或阶段缺失规格,另列“极端率变化线索”,不能只因降幅大就称整体主要原因;两期分母未查清时不推断停产、退出或全批报废。用户明确只看降幅排名时保留真实排名与批量背景。不得自设未授权的最低批量阈值或忽略小批量的安全/质量异常。 常规整体分析的重点规格优先结合报废增量、当前规模、率变化和分阶段有效投入确定核查优先级。单按合格率降幅返回的小批量、0率或阶段缺失规格,另列“极端率变化线索”,不能只因降幅大就称整体主要原因;两期分母未查清时不推断停产、退出或全批报废。用户明确只看降幅排名时保留真实排名与批量背景。不得自设未授权的最低批量阈值或忽略小批量的安全/质量异常。
即使这些规格报废绝对重量较小,也不能据此断言其对总体综合率的影响“可忽略”或计算贡献;只能说明报废重量及投入规模,并把总体影响留待正式可加总口径核验。0率原因未核实前,不用“更可能是全批报废/覆盖问题”等概率判断,只写待核对的分母、批次和数据覆盖。没有已确认的批量阈值时,不给规格贴“批量有效/无代表性”的确定性标签,可具体写两期投入重量及其变化。合格率变化一律明确比较期→本期,并写“下降/上升X.XX个百分点”,避免只写带符号的pp。 即使这些规格报废绝对重量较小,也不能据此断言其对总体综合率的影响“可忽略”或计算贡献;只能说明报废重量及投入规模,并把总体影响留待正式可加总口径核验。0率原因未核实前,不用“更可能是全批报废/覆盖问题”等概率判断,只写待核对的分母、批次和数据覆盖。没有已确认的批量阈值时,不给规格贴“批量有效/无代表性”的确定性标签,可具体写两期投入重量及其变化。合格率变化统一为“本期-比较期”:下降显示 -X.XX pp,上升显示 +X.XX pp,持平为 0.00 pp;可另外标注方向。rateDrop/rate_drop 是比较期减本期的降幅排序量,不能直接当作有符号变化;展示其变化时取反并按正式单位换算,排序顺序不变。优先引用工具已提供的正式变化值,不能从舍入后的两期率重新计算。
组织、规格和具体缺陷之间的关系只写实际交叉查询已经核对的联系;没有交叉证据时保持各自范围,不把两个独立排名拼成因果链。最后只列能执行的优先核查问题,分清已确认现象与待验证原因,不编造责任人、完成期限或闭环结果。所有图文继续复用同一轮证据;不要为了报告样式重复查询、重新计算核心指标或自动生成故事。 组织、规格和具体缺陷之间的关系只写实际交叉查询已经核对的联系;没有交叉证据时保持各自范围,不把两个独立排名拼成因果链。最后只列能执行的优先核查问题,分清已确认现象与待验证原因,不编造责任人、完成期限或闭环结果。所有图文继续复用同一轮证据;不要为了报告样式重复查询、重新计算核心指标或自动生成故事。
@@ -0,0 +1,42 @@
package cn.yunsheng.quality.analysis;
import java.util.*;
import java.util.regex.Pattern;
/** 模型选择的普通对话不产生业务事实;确认与发布使用同一份受限原文。 */
final class AnalysisDirectConversation {
private static final Pattern FORBIDDEN=Pattern.compile(
"(?:\\d+(?:[.,]\\d+)*|[零〇一二两三四五六七八九十百千万点]+)\\s*(?:[%%]|kg\\b|公斤|千克|吨|个百分点|pp\\b)"
+"|百分之|(?:合格率|投入|报废|总重|产量|重量|数量)(?:重量|数量|总数|率)?\\s*(?:为|是|有|达到|共|合计|总计|[::])?\\s*(?:\\d|[零〇一二两三四五六七八九十百千万点])"
+"|(?:已|已经)(?:查到|查询|核实|统计|生成|保存|记住|修改|设置|完成分析)(?!的)"
+"|https?://|Q[A-F0-9]{8}|<[^>]+>|Bearer\\s+|\\bsk-[A-Za-z0-9_-]+|(?:api[_-]?key|token|password)\\s*[:=]",
Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE);
private static final Pattern BUSINESS=Pattern.compile("合格率|报废|投入|产量|重量|分组|规格|产业部|国内|海外|产品");
private static final Pattern CLAIM=Pattern.compile("主要是.{0,40}所致|主要来自|主要原因是|所致|远高于|远低于|确实更(?:大|小|差|好)|基本持平|(?:下降|上升|增加|减少|恶化|改善)了|明显.{0,8}(?:下降|上升|增加|减少)|导致.{0,12}(?:下降|上升)");
static boolean applies(Map<String,Object> task) {return task.get("directResponse") instanceof Map<?,?>;}
static void validate(Map<String,Object> task) {
Map<String,Object> reply=AnalysisProtocolService.map(task.get("directResponse"));
if(!Set.of("explain","restate").contains(Objects.toString(task.get("kind"),""))
||!reply.keySet().equals(Set.of("purpose","answer","requiresMemory"))
||!Set.of("greeting","capabilities","acknowledgement").contains(Objects.toString(reply.get("purpose"),""))
||!Boolean.FALSE.equals(reply.get("requiresMemory")))throw invalid();
for(String key:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))
if(!Boolean.FALSE.equals(task.get(key)))throw invalid();
for(String key:List.of("dimensions","stages","fields"))if(!(task.get(key) instanceof List<?> values)||!values.isEmpty())throw invalid();
if(task.get("memberFields")!=null&&!(task.get("memberFields") instanceof List<?> values&&values.isEmpty()))throw invalid();
if(task.get("dimensionStages")!=null&&!(task.get("dimensionStages") instanceof Map<?,?> values&&values.isEmpty()))throw invalid();
if(task.containsKey("queryPlan")||!"none".equals(task.get("visualPreference"))||task.get("visualType")!=null
||!"none".equals(task.getOrDefault("historyMode","none"))||"native_agent".equals(task.get("executionMode")))throw invalid();
if(!(reply.get("answer") instanceof String text)||text.isBlank()||text.length()>1200||FORBIDDEN.matcher(text).find()
||BUSINESS.matcher(text).find()&&CLAIM.matcher(text).find())throw invalid();
}
static Map<String,Object> answer(Map<String,Object> task,String release,Map<String,Object> context) {
validate(task);
var answer=new LinkedHashMap<String,Object>();answer.put("answer",AnalysisProtocolService.map(task.get("directResponse")).get("answer"));
answer.put("engine","NAO");answer.put("releaseId",release);answer.put("context",context);answer.put("task",task);
answer.put("completionMethod","direct_conversation");answer.put("businessResultsSentToModel",false);answer.put("stopReason","direct_conversation");
for(String key:List.of("results","visuals","queryEvidenceRefs","protocolQueryIds"))answer.put(key,List.of());
answer.put("visualSchemaVersion",1);answer.put("visualState","not_requested");return answer;
}
private static IllegalArgumentException invalid(){return new IllegalArgumentException("普通对话只允许问候、能力介绍或致谢,不得替代业务查询、事实判断或记忆操作");}
}
@@ -86,8 +86,13 @@ public class AnalysisProtocolService {
var state=store.state(sessionId); var state=store.state(sessionId);
Long prior="CLARIFICATION".equals(state.status()) ? state.revision() : state.confirmedRevision(); Long prior="CLARIFICATION".equals(state.status()) ? state.revision() : state.confirmedRevision();
if (prior!=null) previous=read(store.revision(sessionId,prior).taskJson()); if (prior!=null) previous=read(store.revision(sessionId,prior).taskJson());
if("report".equals(previous.get("kind"))&&!retry) { if(AnalysisDirectConversation.applies(previous)&&!retry) {
var resumed=jdbc.query("SELECT task_json FROM analysis_protocol_revision WHERE session_id=? AND disposition='CONFIRMED' AND JSON_UNQUOTE(JSON_EXTRACT(task_json,'$.kind'))<>'report' ORDER BY revision DESC LIMIT 1", // 取该修订首次确认前冻结的业务前态,保留待澄清任务,且不复活已取消的目标。
var frozen=jdbc.query("SELECT input_json FROM analysis_protocol_attempt WHERE session_id=? AND revision=? AND execution_id IS NOT NULL ORDER BY created_at,attempt_id LIMIT 1",
(rs,n)->read(rs.getString(1)),sessionId,prior);
previous=frozen.isEmpty()?Map.of():map(frozen.getFirst().get("previousTask"));
} else if("report".equals(previous.get("kind"))&&!retry) {
var resumed=jdbc.query("SELECT task_json FROM analysis_protocol_revision WHERE session_id=? AND disposition='CONFIRMED' AND JSON_UNQUOTE(JSON_EXTRACT(task_json,'$.kind'))<>'report' AND (JSON_EXTRACT(task_json,'$.directResponse') IS NULL OR JSON_TYPE(JSON_EXTRACT(task_json,'$.directResponse'))='NULL') ORDER BY revision DESC LIMIT 1",
(rs,n)->read(rs.getString(1)),sessionId); (rs,n)->read(rs.getString(1)),sessionId);
previous=resumed.isEmpty()?Map.of():resumed.getFirst(); previous=resumed.isEmpty()?Map.of():resumed.getFirst();
} }
@@ -321,8 +326,16 @@ public class AnalysisProtocolService {
metadata.put("sourceStatus",input.get("sourceStatus"));metadata.put("queryRefs",checked.get("queryRefs"));metadata.put("missingEvidence",checked.get("missingEvidence")); metadata.put("sourceStatus",input.get("sourceStatus"));metadata.put("queryRefs",checked.get("queryRefs"));metadata.put("missingEvidence",checked.get("missingEvidence"));
var overlay=new LinkedHashMap<String,Object>();for(String key:List.of("visualSchemaVersion","visualState","visuals"))overlay.put(key,checked.get(key));overlay.put("visualRecovery",metadata); var overlay=new LinkedHashMap<String,Object>();for(String key:List.of("visualSchemaVersion","visualState","visuals"))overlay.put(key,checked.get(key));overlay.put("visualRecovery",metadata);
boolean originalComplete="COMPLETED".equals(input.get("sourceStatus")); boolean originalComplete="COMPLETED".equals(input.get("sourceStatus"));
boolean factsComplete=Boolean.TRUE.equals(map(map(input.get("sourceAnswer")).get("factCoverage")).get("complete"))&&Boolean.TRUE.equals(input.get("factsStillCovered")); var sourceAnswer=map(input.get("sourceAnswer"));var quality=new LinkedHashMap<>(map(sourceAnswer.get("answerQuality")));
if(!originalComplete&&factsComplete&&Boolean.TRUE.equals(checked.get("chartsComplete"))) { boolean chartsComplete=Boolean.TRUE.equals(checked.get("chartsComplete"));
if(!quality.isEmpty()){quality.put("chartsComplete",chartsComplete);overlay.put("answerQuality",quality);}
boolean factsComplete=Boolean.TRUE.equals(map(sourceAnswer.get("factCoverage")).get("complete"))&&Boolean.TRUE.equals(input.get("factsStillCovered"));
boolean narrativeComplete=Boolean.TRUE.equals(quality.get("narrativeComplete"))&&Boolean.TRUE.equals(quality.get("dataComplete"))
&&!Boolean.FALSE.equals(sourceAnswer.get("nativeStopSucceeded"))
&&!Boolean.FALSE.equals(quality.get("citationComplete"))&&list(quality.get("unresolvedEvidenceRefs")).isEmpty()
&&!Objects.toString(sourceAnswer.get("answer"),"").isBlank();
if(!originalComplete&&"PARTIAL".equals(input.get("sourceStatus"))&&factsComplete&&narrativeComplete&&chartsComplete) {
metadata.put("priorMissingEvidence",list(quality.get("missingEvidence")));quality.put("missingEvidence",List.of());
overlay.put("status","COMPLETED");overlay.put("originalStatus",input.get("sourceStatus")); overlay.put("status","COMPLETED");overlay.put("originalStatus",input.get("sourceStatus"));
overlay.put("completion",Map.of("completed",true,"reason","visual_recovery_complete"));overlay.put("stopReason","visual_recovery_complete"); overlay.put("completion",Map.of("completed",true,"reason","visual_recovery_complete"));overlay.put("stopReason","visual_recovery_complete");
} }
@@ -415,7 +428,8 @@ public class AnalysisProtocolService {
jdbc.update("UPDATE analysis_protocol_execution SET status='FAILED' WHERE execution_id=? AND status='RUNNING'",a.executionId()); jdbc.update("UPDATE analysis_protocol_execution SET status='FAILED' WHERE execution_id=? AND status='RUNNING'",a.executionId());
jdbc.update("UPDATE analysis_protocol_session SET status='FAILED',version=version+1 WHERE session_id=?",a.sessionId()); jdbc.update("UPDATE analysis_protocol_session SET status='FAILED',version=version+1 WHERE session_id=?",a.sessionId());
jdbc.update("UPDATE analysis_protocol_attempt SET status='FAILED' WHERE attempt_id=?",id); jdbc.update("UPDATE analysis_protocol_attempt SET status='FAILED' WHERE attempt_id=?",id);
Map<String,Object> answer=Map.of("answer",reason,"results",List.of(),"releaseId",a.releaseId(),"engine",a.input().containsKey("controlledInspection")?"CONTROLLED_INSPECTION_PROTOCOL":"NAO","completion",Map.of("completed",false,"reason",reason)); boolean nativeConversation=autonomousSession(a.sessionId())&&!a.input().containsKey("controlledInspection");
Map<String,Object> answer=Map.of("answer",nativeConversation?"":reason,"results",List.of(),"releaseId",a.releaseId(),"engine",a.input().containsKey("controlledInspection")?"CONTROLLED_INSPECTION_PROTOCOL":"NAO","completion",Map.of("completed",false,"reason",reason));
jdbc.update("UPDATE analysis_turn SET status='FAILED',answer_json=CAST(? AS JSON),stop_reason=?,finished_at=CURRENT_TIMESTAMP(6) WHERE id=?",write(answer),reason,a.turnId()); jdbc.update("UPDATE analysis_turn SET status='FAILED',answer_json=CAST(? AS JSON),stop_reason=?,finished_at=CURRENT_TIMESTAMP(6) WHERE id=?",write(answer),reason,a.turnId());
inspection.updateAssociation(a,"FAILED"); inspection.updateAssociation(a,"FAILED");
event(id,"failed",Map.of("turnId",a.turnId(),"status","FAILED","result",answer,"stopReason",reason)); event(id,"failed",Map.of("turnId",a.turnId(),"status","FAILED","result",answer,"stopReason",reason));
@@ -486,6 +500,7 @@ public class AnalysisProtocolService {
if(!target.equals("POST /api/analysis/protocol/history")||!params.isEmpty()||nodeId!=null||scopeId!=null)throw denied("历史报告不能执行新的正式查询"); if(!target.equals("POST /api/analysis/protocol/history")||!params.isEmpty()||nodeId!=null||scopeId!=null)throw denied("历史报告不能执行新的正式查询");
return Map.of(); return Map.of();
} }
if(AnalysisDirectConversation.applies(task))throw denied("普通对话不能执行正式业务查询");
if(target.equals("POST /api/analysis/protocol/queries")) { if(target.equals("POST /api/analysis/protocol/queries")) {
if(!task.containsKey("queryPlan")&&!AnalysisProtocolExploration.nativeAgent(task)||nodeId!=null||scopeId!=null)throw denied("当前任务未声明分步查询"); if(!task.containsKey("queryPlan")&&!AnalysisProtocolExploration.nativeAgent(task)||nodeId!=null||scopeId!=null)throw denied("当前任务未声明分步查询");
return Map.of(); return Map.of();
@@ -625,15 +640,24 @@ public class AnalysisProtocolService {
binding.current(a.sessionId(),a.turnId(),a.userId(),a.revision(),a.executionId()); binding.current(a.sessionId(),a.turnId(),a.userId(),a.revision(),a.executionId());
Map<String,Object> task=read(store.revision(a.sessionId(),a.revision()).taskJson()); Map<String,Object> task=read(store.revision(a.sessionId(),a.revision()).taskJson());
if(!Objects.equals(canonical(task),canonical(details.get("agentTask")))) throw denied("最终答复没有绑定当前任务"); if(!Objects.equals(canonical(task),canonical(details.get("agentTask")))) throw denied("最终答复没有绑定当前任务");
if(Set.of("COMPLETED","PARTIAL").contains(status)&&!"report".equals(task.get("kind")) if(Set.of("COMPLETED","PARTIAL").contains(status)&&AnalysisDirectConversation.applies(task)) {
answer=AnalysisDirectConversation.answer(task,a.releaseId(),taskContext(a.releaseId(),task));
status="COMPLETED";
} else if(Set.of("COMPLETED","PARTIAL").contains(status)&&!"report".equals(task.get("kind"))
&&!hasProtocolEvidence(details)) { &&!hasProtocolEvidence(details)) {
status="FAILED"; status="FAILED";
String original=AnalysisProtocolExploration.nativeAgent(task)?Objects.toString(answer.get("answer"),""):null;
answer.clear(); answer.clear();
answer.put("answer",noProofFailureReason(details)); answer.put("answer",original!=null?original:noProofFailureReason(details));
answer.put("results",List.of()); answer.put("results",List.of());
answer.put("releaseId",a.releaseId()); answer.put("releaseId",a.releaseId());
answer.put("engine","NAO"); answer.put("engine","NAO");
answer.put("stopReason","formal_query_evidence_missing"); answer.put("stopReason","formal_query_evidence_missing");
if(original!=null) {
answer.put("executionMode","native_agent");
answer.put("answerQuality",Map.of("version",1,"dataComplete",false,"narrativeFactBinding","not_assessed",
"missingEvidence",List.of(noProofFailureReason(details))));
}
} else if(Set.of("COMPLETED","PARTIAL").contains(status)) { } else if(Set.of("COMPLETED","PARTIAL").contains(status)) {
governance.requireBoundAction("QUERY","query.aggregate"); governance.requireBoundAction("QUERY","query.aggregate");
if(AnalysisProtocolInspection.KIND.equals(task.get("kind"))) { if(AnalysisProtocolInspection.KIND.equals(task.get("kind"))) {
@@ -672,7 +696,7 @@ public class AnalysisProtocolService {
answer.put("answerQuality",quality); answer.put("answerQuality",quality);
} }
if(AnalysisProtocolExploration.nativeAgent(task)){for(String key:List.of("scopeCoverage","explorationWarnings","conclusionProtocolQueryIds","attemptProtocolQueryIds"))if(checked.containsKey(key))answer.put(key,checked.get(key));} if(AnalysisProtocolExploration.nativeAgent(task)){for(String key:List.of("scopeCoverage","explorationWarnings","conclusionProtocolQueryIds","attemptProtocolQueryIds"))if(checked.containsKey(key))answer.put(key,checked.get(key));}
if(Boolean.TRUE.equals(task.get("verifySource"))||Boolean.TRUE.equals(task.get("fullDetails"))) { if(!AnalysisProtocolExploration.nativeAgent(task)&&(Boolean.TRUE.equals(task.get("verifySource"))||Boolean.TRUE.equals(task.get("fullDetails")))) {
for(String field:List.of("reportMarkdown","reportHtml","reportTitle"))answer.remove(field); for(String field:List.of("reportMarkdown","reportHtml","reportTitle"))answer.remove(field);
String rawStatus=rawStatusText(checked,map(recordList)); String rawStatus=rawStatusText(checked,map(recordList));
if(planResolution(a,task,actor).scopes().stream().allMatch(AnalysisProtocolService::rawScope))answer.put("answer",rawStatus); if(planResolution(a,task,actor).scopes().stream().allMatch(AnalysisProtocolService::rawScope))answer.put("answer",rawStatus);
@@ -680,7 +704,7 @@ public class AnalysisProtocolService {
} }
if(!Boolean.TRUE.equals(checked.get("complete"))) { if(!Boolean.TRUE.equals(checked.get("complete"))) {
status="PARTIAL";answer.put("stopReason","evidence_incomplete"); status="PARTIAL";answer.put("stopReason","evidence_incomplete");
if(AnalysisProtocolExploration.nativeAgent(task))appendCoverageNotices(answer,list(checked.get("missingEvidence"))); if(AnalysisProtocolExploration.nativeAgent(task))appendNativeCoverageDiagnostics(answer,list(checked.get("missingEvidence")));
} }
} else { } else {
validateMetricEvidence(a,task,details); validateMetricEvidence(a,task,details);
@@ -801,6 +825,15 @@ public class AnalysisProtocolService {
} }
return result; return result;
} }
/** Native model prose is immutable; coverage gaps belong to the saved execution metadata. */
static void appendNativeCoverageDiagnostics(Map<String,Object> answer,List<?> missing) {
var gaps=new LinkedHashSet<String>();
var quality=new LinkedHashMap<>(map(answer.get("answerQuality")));
for(Object raw:list(quality.get("missingEvidence")))if(raw instanceof String gap&&!gap.isBlank())gaps.add(gap);
for(Object raw:missing)if(raw instanceof String gap&&!gap.isBlank())gaps.add(gap);
if(gaps.isEmpty())return;
quality.putIfAbsent("version",1);quality.put("missingEvidence",List.copyOf(gaps));answer.put("answerQuality",quality);
}
/** A server downgrade must remain visible even when the model omitted its own limitations. */ /** A server downgrade must remain visible even when the model omitted its own limitations. */
private void appendCoverageNotices(Map<String,Object> answer,List<?> missing) { private void appendCoverageNotices(Map<String,Object> answer,List<?> missing) {
var gaps=missing.stream().filter(String.class::isInstance).map(String.class::cast).filter(s->!s.isBlank()).distinct().toList(); var gaps=missing.stream().filter(String.class::isInstance).map(String.class::cast).filter(s->!s.isBlank()).distinct().toList();
@@ -1668,6 +1701,12 @@ public class AnalysisProtocolService {
} }
} }
} }
if(AnalysisDirectConversation.applies(t)) {
try {AnalysisDirectConversation.validate(t);}catch(IllegalArgumentException invalid){throw conflict(invalid.getMessage());}
if(t.get("period")!=null)period(map(t.get("period")));
if(t.get("comparisonPeriod")!=null)period(map(t.get("comparisonPeriod")));
return t;
}
period(map(t.get("period"))); period(map(t.get("period")));
if(Boolean.TRUE.equals(t.get("needsClarification"))) { if(Boolean.TRUE.equals(t.get("needsClarification"))) {
if(!(t.get("clarification") instanceof String s)||s.isBlank())throw conflict("澄清必须说明待确认对象"); if(!(t.get("clarification") instanceof String s)||s.isBlank())throw conflict("澄清必须说明待确认对象");
@@ -1626,6 +1626,15 @@ public class AnalysisTurnService {
if(quality.get(field) instanceof Boolean value)safe.put(field,value); if(quality.get(field) instanceof Boolean value)safe.put(field,value);
if(quality.get("missingEvidence") instanceof List<?> gaps)safe.put("missingEvidence",gaps.stream() if(quality.get("missingEvidence") instanceof List<?> gaps)safe.put("missingEvidence",gaps.stream()
.filter(value->value instanceof String gap&&!gap.isBlank()&&gap.length()<=1000).distinct().limit(20).toList()); .filter(value->value instanceof String gap&&!gap.isBlank()&&gap.length()<=1000).distinct().limit(20).toList());
if("not_assessed".equals(quality.get("narrativeFactBinding")))safe.put("narrativeFactBinding","not_assessed");
for(String field:List.of("citedEvidenceRefs","unresolvedEvidenceRefs"))if(quality.get(field) instanceof List<?> refs) {
var visible=refs.stream().filter(value->value instanceof String ref&&ref.matches("Q[A-F0-9]{8}")
&&(!field.equals("citedEvidenceRefs")||(answer.get("queryEvidenceRefs") instanceof List<?> allowed?allowed:List.of()).contains(ref))).distinct().limit(100).toList();
safe.put(field,visible);
if(field.equals("unresolvedEvidenceRefs"))safe.put("citationComplete",visible.isEmpty());
}
if(quality.get("notices") instanceof List<?> notices)safe.put("notices",notices.stream()
.filter(value->value instanceof String notice&&!notice.isBlank()&&notice.length()<=1000).distinct().limit(20).toList());
answer.put("answerQuality",safe); answer.put("answerQuality",safe);
} }
Object count = details.get("toolCount"); Object count = details.get("toolCount");
@@ -13,6 +13,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -429,6 +430,26 @@ public class NaoAnalysisRunner {
status = "FAILED"; status = "FAILED";
if (reason.isBlank()) reason = "原装 NAO 返回了无效结束状态"; if (reason.isBlank()) reason = "原装 NAO 返回了无效结束状态";
} }
boolean conflictingExit=Boolean.FALSE.equals(message.get("nativeStopSucceeded"))
|| message.get("finishReason") instanceof String finish&&!finish.isBlank()&&!"stop".equalsIgnoreCase(finish)
|| message.get("toolCalls") instanceof List<?> calls&&calls.stream().anyMatch(raw->raw instanceof Map<?,?> call&&"started".equals(call.get("status")))
|| message.get("answerQuality") instanceof Map<?,?> quality&&Boolean.FALSE.equals(quality.get("narrativeComplete"));
if(Set.of("COMPLETED","PARTIAL").contains(status)&&conflictingExit) {
if("COMPLETED".equals(status)){status="PARTIAL";reason="incomplete_finish";}
var quality=new LinkedHashMap<String,Object>();
if(message.get("answerQuality") instanceof Map<?,?> prior)prior.forEach((k,v)->quality.put(String.valueOf(k),v));
quality.put("version",1);quality.put("narrativeComplete",false);details.put("answerQuality",quality);
}
boolean visibleBody=!answer.isBlank()
|| message.get("reportMarkdown") instanceof String markdown&&!markdown.isBlank()
|| message.get("reportHtml") instanceof String html&&!html.isBlank()
|| message.get("memberList") instanceof Map<?,?> || message.get("recordList") instanceof Map<?,?>;
if("COMPLETED".equals(status)&&!visibleBody) {
status="PARTIAL";reason="answer_missing";
var quality=new LinkedHashMap<String,Object>();
if(message.get("answerQuality") instanceof Map<?,?> prior)prior.forEach((k,v)->quality.put(String.valueOf(k),v));
quality.put("version",1);quality.put("narrativeComplete",false);details.put("answerQuality",quality);
}
if ("FAILED".equals(status) && safeMessage != null) { if ("FAILED".equals(status) && safeMessage != null) {
details.put("message", safeMessage); details.put("message", safeMessage);
if (answer.isBlank()) answer = safeMessage; if (answer.isBlank()) answer = safeMessage;
@@ -437,6 +458,7 @@ public class NaoAnalysisRunner {
details.remove("message"); details.remove("message");
} }
details.put("status", status); details.put("status", status);
details.put("stopReason", reason);
details.put("answer", answer); details.put("answer", answer);
details.put("engine", "NAO"); details.put("engine", "NAO");
return new Result(status, answer, details, reason); return new Result(status, answer, details, reason);
@@ -0,0 +1,45 @@
package cn.yunsheng.quality.analysis;
import java.util.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AnalysisDirectConversationTest {
private Map<String,Object> task() {
var t=new LinkedHashMap<String,Object>();t.put("kind","explain");t.put("visualPreference","none");t.put("historyMode","none");
for(String k:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))t.put(k,false);
for(String k:List.of("dimensions","stages","fields"))t.put(k,List.of());
t.put("directResponse",new LinkedHashMap<>(Map.of("purpose","greeting","answer","你好!可以帮你查询质量指标,并比较期间变化。","requiresMemory",false)));return t;
}
@Test void acceptsModelSelectedConversationWithoutInventingADataPeriod() {
var t=task();assertTrue(AnalysisDirectConversation.applies(t));assertDoesNotThrow(()->AnalysisDirectConversation.validate(t));
t.put("period",Map.of("year",2026,"month",9));assertDoesNotThrow(()->AnalysisDirectConversation.validate(t));
AnalysisProtocolService.map(t.get("directResponse")).put("answer","我可以帮你比较不同产业部谁表现更好,并整理已核实的历史结果。");
assertDoesNotThrow(()->AnalysisDirectConversation.validate(t));
}
@Test void queryAndMemoryActionsCannotBypassTheEvidencePath() {
for(String k:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification")) {
var t=task();t.put(k,true);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t),k);
}
for(String k:List.of("fields","stages","dimensions","queryPlan","memberFields")) {
var t=task();t.put(k,List.of("rate"));assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t),k);
}
for(var change:List.<Map<String,Object>>of(Map.of("purpose","business_analysis"),Map.of("requiresMemory",true),Map.of("unexpected","hidden"))) {
var t=task();AnalysisProtocolService.map(t.get("directResponse")).putAll(change);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t));
}
}
@Test void unqueriedFactsTrendsAndUnperformedActionsAreRejected() {
for(String s:List.of("合格率为95.5%","报废重量123","报废二十公斤","黑片合格率明显下降","黑片合格率下降了,主要原因是设备故障。","上月报废重量为一百。","国内报废主要来自设备问题","我已经保存你的偏好","已查询最新数据")) {
var t=task();AnalysisProtocolService.map(t.get("directResponse")).put("answer",s);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t),s);
}
}
@Test void linksCredentialsHtmlAndReferencesCannotBecomeConversationProse() {
for(String s:List.of("见https://example.test","[QABCDEF12]","<b>你好</b>","Bearer synthetic","token=synthetic"," ","文".repeat(1201))) {
var t=task();AnalysisProtocolService.map(t.get("directResponse")).put("answer",s);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t));
}
}
@Test void theConfirmedModelTextIsPublishedOnceWithoutBusinessDataOrCharts() {
var t=task();var answer=AnalysisDirectConversation.answer(t,"release",Map.of("releaseId","release"));
assertEquals(AnalysisProtocolService.map(t.get("directResponse")).get("answer"),answer.get("answer"));assertEquals("direct_conversation",answer.get("completionMethod"));
for(String k:List.of("results","visuals","queryEvidenceRefs","protocolQueryIds"))assertEquals(List.of(),answer.get(k));
assertEquals(false,answer.get("businessResultsSentToModel"));
}
}
@@ -273,6 +273,15 @@ class AnalysisProtocolServiceMySqlTest {
tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),proposed,actor)); tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),proposed,actor));
assertEquals(1,AnalysisProtocolService.list(tx.execute(s->service.visualRecoveryOverlay(turn,actor)).get("visuals")).size()); assertEquals(1,AnalysisProtocolService.list(tx.execute(s->service.visualRecoveryOverlay(turn,actor)).get("visuals")).size());
} }
@Test void recoveredChartsCannotCompleteAnUnfinishedNarrative() {
String turn=recoverableTurn(true,false);
var claim=tx.execute(s->service.beginVisualRecovery(turn,actor));var input=AnalysisProtocolService.map(claim.get("input"));
tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),recoveryChart(input),actor));
var overlay=tx.execute(s->service.visualRecoveryOverlay(turn,actor));
assertFalse(overlay.containsKey("status"),json.writeValueAsString(overlay));
assertEquals(true,AnalysisProtocolService.map(overlay.get("answerQuality")).get("chartsComplete"));
assertEquals(false,AnalysisProtocolService.map(overlay.get("answerQuality")).get("narrativeComplete"));
}
@Test void aChartCannotCompleteMissingFactsOrPublishAfterTheOriginalAttemptIsRetried() { @Test void aChartCannotCompleteMissingFactsOrPublishAfterTheOriginalAttemptIsRetried() {
String turn=recoverableTurn(false);var claim=tx.execute(s->service.beginVisualRecovery(turn,actor));var input=AnalysisProtocolService.map(claim.get("input")); String turn=recoverableTurn(false);var claim=tx.execute(s->service.beginVisualRecovery(turn,actor));var input=AnalysisProtocolService.map(claim.get("input"));
tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),recoveryChart(input),actor)); tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),recoveryChart(input),actor));
@@ -288,6 +297,9 @@ class AnalysisProtocolServiceMySqlTest {
assertTrue(tx.execute(s->service.visualRecoveryOverlay(turn,actor)).isEmpty()); assertTrue(tx.execute(s->service.visualRecoveryOverlay(turn,actor)).isEmpty());
} }
private String recoverableTurn(boolean facts) { private String recoverableTurn(boolean facts) {
return recoverableTurn(facts,true);
}
private String recoverableTurn(boolean facts,boolean narrative) {
String turn=newTurn("2026年8至9月黑片报废重量月度趋势");var a=claim(turn,false);var t=task(turn,Map.of(),false); String turn=newTurn("2026年8至9月黑片报废重量月度趋势");var a=claim(turn,false);var t=task(turn,Map.of(),false);
t.put("period",Map.of("year",2026,"monthStart",8,"monthEnd",9));t.put("periodCoverage","available");t.put("stages",List.of("black"));t.put("fields",List.of("scrapWeight"));t.put("visualPreference","required"); t.put("period",Map.of("year",2026,"monthStart",8,"monthEnd",9));t.put("periodCoverage","available");t.put("stages",List.of("black"));t.put("fields",List.of("scrapWeight"));t.put("visualPreference","required");
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),t,actor)).get("task")); var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),t,actor)).get("task"));
@@ -298,6 +310,8 @@ class AnalysisProtocolServiceMySqlTest {
"coverage",Map.of("rawRows",2,"includedRows",2,"sourceMonths",List.of(Map.of("year",2026,"month",8,"blackRows",1,"brightRows",0),Map.of("year",2026,"month",9,"blackRows",1,"brightRows",0)))); "coverage",Map.of("rawRows",2,"includedRows",2,"sourceMonths",List.of(Map.of("year",2026,"month",8,"blackRows",1,"brightRows",0),Map.of("year",2026,"month",9,"blackRows",1,"brightRows",0))));
var proof=tx.execute(s->service.recordQuery(a.attemptId(),"GET","/api/metrics",parameters,response,actor)); var proof=tx.execute(s->service.recordQuery(a.attemptId(),"GET","/api/metrics",parameters,response,actor));
var result=answer();result.put("visualState","failed");result.put("visuals",List.of()); var result=answer();result.put("visualState","failed");result.put("visuals",List.of());
if(!narrative)result.put("answer","");
result.put("answerQuality",Map.of("version",1,"dataComplete",facts,"narrativeComplete",narrative,"chartsComplete",false));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"PARTIAL",result,Map.of("agentTask",confirmed,"protocolEvidence",List.of(proof),"factsComplete",facts,"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor)); tx.executeWithoutResult(s->service.finish(a.attemptId(),"PARTIAL",result,Map.of("agentTask",confirmed,"protocolEvidence",List.of(proof),"factsComplete",facts,"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));
return turn; return turn;
} }
@@ -1134,6 +1148,81 @@ class AnalysisProtocolServiceMySqlTest {
assertEquals(40,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class)); assertEquals(40,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class));
} finally {pool.shutdownNow();} } finally {pool.shutdownNow();}
} }
@Test void nativeWithoutFormalEvidenceKeepsOriginalBodyButCannotPublishMetricsOrSucceed() throws Exception {
enableAutonomous();String turn=newTurn("原生回答缺少正式证据");var a=claim(turn,false);
var task=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),nativeTask(turn,Map.of()),actor)).get("task"));
String original="## 结论\n\n模型完整原文,不用平台错误句替换。";
tx.executeWithoutResult(s->service.finish(a.attemptId(),"PARTIAL",Map.of("answer",original,"visuals",List.of(Map.of("id","unproved"))),Map.of("agentTask",task,"protocolEvidence",List.of()),actor));
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);
assertEquals("FAILED",turnStatus(turn));assertEquals(original,saved.get("answer"));assertFalse(saved.containsKey("visuals"));
assertEquals("native_agent",saved.get("executionMode"));
assertEquals(false,AnalysisProtocolService.map(saved.get("answerQuality")).get("dataComplete"));
assertEquals("formal_query_evidence_missing",saved.get("stopReason"));
}
@Test void nativePlanningFailureStoresReasonWithoutReplacingAnswerWithSystemError() throws Exception {
enableAutonomous();String turn=newTurn("原生规划失败");var a=claim(turn,false);
tx.executeWithoutResult(s->service.fail(a.attemptId(),"本轮分析未完成,请重试"));
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);
assertEquals("FAILED",turnStatus(turn));assertEquals("",saved.get("answer"));
assertEquals("本轮分析未完成,请重试",jdbc.queryForObject("SELECT stop_reason FROM analysis_turn WHERE id=?",String.class,turn));
assertEquals(false,AnalysisProtocolService.map(saved.get("completion")).get("completed"));
}
@Test void ordinaryConversationCompletesWithoutPeriodOrFormalQueriesAndUsesConfirmedModelReply() throws Exception {
enableAutonomous();String turn=newTurn("你好");var a=claim(turn,false);var proposal=task(turn,Map.of("columnFilters",List.of()),false);
proposal.put("kind","explain");proposal.put("period",null);proposal.put("fields",List.of());proposal.put("trendRequired",false);
for(String key:List.of("freshQuery","comparisonRequired","verifySource","fullDetails"))proposal.put(key,false);
proposal.put("visualPreference","none");proposal.put("historyMode","none");
String original="您好!我可以协助您查询质量指标、比较期间变化。";
proposal.put("directResponse",Map.of("purpose","greeting","answer",original,"requiresMemory",false));
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));
assertThrows(RuntimeException.class,()->tx.executeWithoutResult(s->service.checkTarget(a.attemptId(),"GET","/api/metrics",params(null),actor)));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",Map.of("answer","不能替换已确认的原文","visuals",List.of(Map.of("id","forged"))),Map.of("agentTask",confirmed,"protocolEvidence",List.of()),actor));
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);
assertEquals("COMPLETED",turnStatus(turn));assertEquals(original,saved.get("answer"));assertEquals("direct_conversation",saved.get("completionMethod"));
assertEquals(List.of(),saved.get("visuals"));assertEquals(0,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class));
String next=newTurn("继续分析");var nextAttempt=claim(next,false);assertEquals(Map.of(),nextAttempt.input().get("previousTask"));
}
@Test void thanksDoesNotReplaceTheBusinessGoalOrBecomeAHistoryReportSource() throws Exception {
enableAutonomous();String business=completedHistoryMetric("18X15X4+T",9,"35.055");
var before=AnalysisProtocolService.map(json.readValue(jdbc.queryForObject("SELECT plan_json FROM analysis_turn WHERE id=?",String.class,business),Map.class).get("task"));
String turn=newTurn("谢谢");var a=claim(turn,false);var proposal=new LinkedHashMap<>(before);proposal.put("question","谢谢");proposal.put("goal","回应致谢");proposal.put("kind","explain");
proposal.put("fields",List.of());proposal.put("stages",List.of());proposal.put("dimensions",List.of());proposal.put("historyMode","none");
for(String key:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))proposal.put(key,false);
proposal.put("directResponse",Map.of("purpose","acknowledgement","answer","不客气,可以继续提问。","requiresMemory",false));
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",confirmed),actor));
String report=newTurn("整理历史结果");var next=claim(report,false);assertEquals(before,next.input().get("previousTask"));
var reportTask=historyTask(next,report,"all");assertEquals(List.of(business),reportTask.get("historySourceTurnIds"));
}
@Test void consecutiveConversationAndRetryPreserveThePendingClarificationGoal() {
enableAutonomous();String business=newTurn("今年18×15×4综合率趋势");var a=claim(business,false);
var pending=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),task(business,Map.of(),true),actor)).get("task"));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"NEEDS_CLARIFICATION",answer(),Map.of("agentTask",pending),actor));
for(String question:List.of("谢谢","你好")) {
String turn=newTurn(question);var b=claim(turn,false);assertEquals(pending,b.input().get("previousTask"));
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(b.attemptId(),ordinaryTask(turn),actor)).get("task"));
tx.executeWithoutResult(s->service.finish(b.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",confirmed),actor));
jdbc.update("UPDATE analysis_turn SET status='QUEUED' WHERE id=?",turn);
var retried=claim(turn,true);var again=AnalysisProtocolService.map(tx.execute(s->service.confirm(retried.attemptId(),confirmed,actor)).get("task"));
tx.executeWithoutResult(s->service.finish(retried.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",again),actor));
}
var next=claim(newTurn("选+T"),false);assertEquals(pending,next.input().get("previousTask"));
}
@Test void conversationDoesNotReviveACancelledBusinessGoal() {
enableAutonomous();String business=newTurn("取消这个分析目标");var a=claim(business,false);
tx.execute(s->service.confirm(a.attemptId(),task(business,Map.of("product","18X15X4+T"),false),actor));
tx.executeWithoutResult(s->service.cancel(business,actor,"用户取消"));
String greeting=newTurn("你好");var b=claim(greeting,false);assertEquals(Map.of(),b.input().get("previousTask"));
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(b.attemptId(),ordinaryTask(greeting),actor)).get("task"));
tx.executeWithoutResult(s->service.finish(b.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",confirmed),actor));
assertEquals(Map.of(),claim(newTurn("重新开始"),false).input().get("previousTask"));
}
private Map<String,Object> ordinaryTask(String turn) {
var result=task(turn,Map.of(),false);result.put("kind","explain");result.put("goal","回应普通对话");result.put("period",null);result.put("fields",List.of());
for(String key:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))result.put(key,false);
result.put("visualPreference","none");result.put("historyMode","none");
result.put("directResponse",Map.of("purpose","greeting","answer","你好,可以继续提问。","requiresMemory",false));return result;
}
@Test void autonomousReadBudgetAndFinishRequireRealRootEvidence() { @Test void autonomousReadBudgetAndFinishRequireRealRootEvidence() {
enableAutonomous();String turn=newTurn("检查根任务证据");var a=claim(turn,false);var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),nativeTask(turn,Map.of()),actor)).get("task")); enableAutonomous();String turn=newTurn("检查根任务证据");var a=claim(turn,false);var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),nativeTask(turn,Map.of()),actor)).get("task"));
var registered=step(a,"read",Map.of("kind","base"),List.of());var scope=AnalysisProtocolService.map(registered.get("scope"));var p=scopeParams(scope);var proofs=new ArrayList<Map<String,Object>>(); var registered=step(a,"read",Map.of("kind","base"),List.of());var scope=AnalysisProtocolService.map(registered.get("scope"));var p=scopeParams(scope);var proofs=new ArrayList<Map<String,Object>>();
@@ -1164,7 +1253,7 @@ class AnalysisProtocolServiceMySqlTest {
assertThrows(RuntimeException.class,()->tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",answer(),details,actor))); assertThrows(RuntimeException.class,()->tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",answer(),details,actor)));
details.put("conclusionProtocolQueryIds",citeFailed?List.of(rootProof.get("queryId"),failedProof.get("queryId")):List.of(rootProof.get("queryId"))); details.put("conclusionProtocolQueryIds",citeFailed?List.of(rootProof.get("queryId"),failedProof.get("queryId")):List.of(rootProof.get("queryId")));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",answer(),details,actor));assertEquals(citeFailed?"PARTIAL":"COMPLETED",turnStatus(turn)); tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",answer(),details,actor));assertEquals(citeFailed?"PARTIAL":"COMPLETED",turnStatus(turn));
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(details.get("conclusionProtocolQueryIds"),saved.get("conclusionProtocolQueryIds"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(citeFailed,saved.get("answer").toString().contains("18X15X4+T"));assertFalse(saved.containsKey("readingSummary"));assertEquals(!citeFailed,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete")); var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(details.get("conclusionProtocolQueryIds"),saved.get("conclusionProtocolQueryIds"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(answer().get("answer"),saved.get("answer"));assertEquals(citeFailed,AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence")).stream().anyMatch(gap->gap.toString().contains("18X15X4+T")));assertFalse(saved.containsKey("readingSummary"));assertEquals(!citeFailed,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete"));
if(!citeFailed) { if(!citeFailed) {
assertEquals(List.of(rootProof.get("queryId")),saved.get("protocolQueryIds"));assertEquals(2,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class)); assertEquals(List.of(rootProof.get("queryId")),saved.get("protocolQueryIds"));assertEquals(2,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class));
String report=newTurn("汇总刚完成的质量解释");var reportAttempt=claim(report,false);var reportTask=historyTask(reportAttempt,report,"all");var imported=tx.execute(s->service.history(reportAttempt.attemptId(),actor));assertEquals(true,AnalysisProtocolService.map(imported.get("historyCoverage")).get("complete"),imported.toString()); String report=newTurn("汇总刚完成的质量解释");var reportAttempt=claim(report,false);var reportTask=historyTask(reportAttempt,report,"all");var imported=tx.execute(s->service.history(reportAttempt.attemptId(),actor));assertEquals(true,AnalysisProtocolService.map(imported.get("historyCoverage")).get("complete"),imported.toString());
@@ -1221,11 +1310,12 @@ class AnalysisProtocolServiceMySqlTest {
var result=answer();String fullAnswer="已核实的业务解释。\n\n## 完整附录\n自动图表未生成,详细范围保留在此。";result.put("answer",fullAnswer);result.put("reportMarkdown",fullAnswer);result.put("visualState",preference.equals("required")?"ready":"failed");result.put("visuals",List.of()); var result=answer();String fullAnswer="已核实的业务解释。\n\n## 完整附录\n自动图表未生成,详细范围保留在此。";result.put("answer",fullAnswer);result.put("reportMarkdown",fullAnswer);result.put("visualState",preference.equals("required")?"ready":"failed");result.put("visuals",List.of());
if(preference.equals("required"))result.put("visuals",List.of(Map.of("metric","composite_rate","type","bar","period",Map.of("year",2026),"scope",Map.of("releaseId",release)))); if(preference.equals("required"))result.put("visuals",List.of(Map.of("metric","composite_rate","type","bar","period",Map.of("year",2026),"scope",Map.of("releaseId",release))));
if(withSummary)result.put("readingSummary",Map.of("version",1,"lead","业务概括","evidence",List.of("核心业务依据"),"notices",List.of("Python已归并的业务局限"),"evidenceRefs",List.of()));tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",task,"protocolEvidence",List.of(rootProof,rankProof),"conclusionProtocolQueryIds",List.of(rootProof.get("queryId"),rankProof.get("queryId")),"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));assertEquals("PARTIAL",turnStatus(turn));var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(true,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(fullAnswer,saved.get("reportMarkdown")); if(withSummary)result.put("readingSummary",Map.of("version",1,"lead","业务概括","evidence",List.of("核心业务依据"),"notices",List.of("Python已归并的业务局限"),"evidenceRefs",List.of()));tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",task,"protocolEvidence",List.of(rootProof,rankProof),"conclusionProtocolQueryIds",List.of(rootProof.get("queryId"),rankProof.get("queryId")),"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));assertEquals("PARTIAL",turnStatus(turn));var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(true,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(fullAnswer,saved.get("reportMarkdown"));
if(withSummary) { assertEquals(fullAnswer,saved.get("answer"));
var notices=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("readingSummary")).get("notices"));assertTrue(notices.contains("Python已归并的业务局限")); var gaps=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence"));
if(preference.equals("auto")){assertTrue(notices.contains("Python已归并的业务局限"));assertTrue(notices.stream().anyMatch(notice->notice.toString().contains("图表尚未完整生成")));assertTrue(saved.get("answer").toString().contains("图表尚未完整生成"));} assertTrue(gaps.stream().anyMatch(gap->gap.toString().contains("图表尚未完整生成")));
else {assertTrue(notices.contains("用户要求的图表尚未完整生成"));assertTrue(saved.get("answer").toString().contains("用户要求的图表尚未完整生成"));assertTrue(notices.stream().noneMatch(n->n.toString().contains("可独立恢复图表")));} if(preference.equals("required"))assertTrue(gaps.contains("用户要求的图表尚未完整生成"));
} else {assertFalse(saved.containsKey("readingSummary"));if(preference.equals("auto"))assertTrue(saved.get("answer").toString().contains("图表尚未完整生成"));} if(withSummary)assertEquals(result.get("readingSummary"),saved.get("readingSummary"));
else assertFalse(saved.containsKey("readingSummary"));
} }
} }
@Test void nativeRecordsAppendixRetainsLegalPagesAtReadCapWithoutAcceptingIncompleteScope() { @Test void nativeRecordsAppendixRetainsLegalPagesAtReadCapWithoutAcceptingIncompleteScope() {
@@ -1236,7 +1326,7 @@ class AnalysisProtocolServiceMySqlTest {
var result=answer();result.put("recordList",Map.of("queryComplete",true,"rows",List.of("invented"))); var result=answer();result.put("recordList",Map.of("queryComplete",true,"rows",List.of("invented")));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",task,"protocolEvidence",proofs,"conclusionProtocolQueryIds",List.of(),"evidenceCompletion",Map.of("serverCoverageSufficient",false)),actor));assertEquals("PARTIAL",turnStatus(turn));var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);var listing=AnalysisProtocolService.map(saved.get("recordList")); tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",task,"protocolEvidence",proofs,"conclusionProtocolQueryIds",List.of(),"evidenceCompletion",Map.of("serverCoverageSufficient",false)),actor));assertEquals("PARTIAL",turnStatus(turn));var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);var listing=AnalysisProtocolService.map(saved.get("recordList"));
assertEquals(false,listing.get("queryComplete"));assertEquals(4001,listing.get("totalRows"));assertEquals(4000,listing.get("loadedRows"));var set=AnalysisProtocolService.map(AnalysisProtocolService.list(listing.get("sets")).getFirst());assertEquals(false,set.get("complete"));assertEquals("001",AnalysisProtocolService.map(AnalysisProtocolService.map(AnalysisProtocolService.list(set.get("rows")).getFirst()).get("values")).get("委托单"));assertEquals("4000",AnalysisProtocolService.map(AnalysisProtocolService.map(AnalysisProtocolService.list(set.get("rows")).getLast()).get("values")).get("委托单")); assertEquals(false,listing.get("queryComplete"));assertEquals(4001,listing.get("totalRows"));assertEquals(4000,listing.get("loadedRows"));var set=AnalysisProtocolService.map(AnalysisProtocolService.list(listing.get("sets")).getFirst());assertEquals(false,set.get("complete"));assertEquals("001",AnalysisProtocolService.map(AnalysisProtocolService.map(AnalysisProtocolService.list(set.get("rows")).getFirst()).get("values")).get("委托单"));assertEquals("4000",AnalysisProtocolService.map(AnalysisProtocolService.map(AnalysisProtocolService.list(set.get("rows")).getLast()).get("values")).get("委托单"));
assertEquals(List.of(),saved.get("protocolQueryIds"));assertEquals(List.of(),saved.get("conclusionProtocolQueryIds"));assertEquals(40,AnalysisProtocolService.list(saved.get("attemptProtocolQueryIds")).size());assertEquals(false,AnalysisProtocolService.map(AnalysisProtocolService.list(saved.get("scopeCoverage")).getFirst()).get("complete"));assertTrue(saved.get("answer").toString().contains("尚未查全")); assertEquals(List.of(),saved.get("protocolQueryIds"));assertEquals(List.of(),saved.get("conclusionProtocolQueryIds"));assertEquals(40,AnalysisProtocolService.list(saved.get("attemptProtocolQueryIds")).size());assertEquals(false,AnalysisProtocolService.map(AnalysisProtocolService.list(saved.get("scopeCoverage")).getFirst()).get("complete"));assertEquals(result.get("answer"),saved.get("answer"));assertFalse(AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence")).isEmpty());
} }
@Test void explicitRawRootCannotCompleteByIgnoringAnUnreadRawScope() { @Test void explicitRawRootCannotCompleteByIgnoringAnUnreadRawScope() {
enableAutonomous();String turn=newTurn("逐条读取全部黑片记录");var a=claim(turn,false);var proposal=rawTask(turn,"records");var rawNode=AnalysisProtocolService.map(AnalysisProtocolService.list(proposal.remove("queryPlan")).getFirst());proposal.put("executionMode","native_agent");var task=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));tx.execute(s->service.explorationStep(a.attemptId(),Map.of("requestKey","raw","node",rawNode),actor)); enableAutonomous();String turn=newTurn("逐条读取全部黑片记录");var a=claim(turn,false);var proposal=rawTask(turn,"records");var rawNode=AnalysisProtocolService.map(AnalysisProtocolService.list(proposal.remove("queryPlan")).getFirst());proposal.put("executionMode","native_agent");var task=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));tx.execute(s->service.explorationStep(a.attemptId(),Map.of("requestKey","raw","node",rawNode),actor));
@@ -1273,7 +1363,7 @@ class AnalysisProtocolServiceMySqlTest {
var result=answer();result.put("readingSummary",Map.of("version",1,"lead","已核实总体率","notices",List.of("已有提示"))); var result=answer();result.put("readingSummary",Map.of("version",1,"lead","已核实总体率","notices",List.of("已有提示")));
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",confirmed,"protocolEvidence",proofs,"factsComplete",true,"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor)); tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",confirmed,"protocolEvidence",proofs,"factsComplete",true,"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));
assertEquals("PARTIAL",turnStatus(turn));var saved=AnalysisProtocolService.map(json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class)); assertEquals("PARTIAL",turnStatus(turn));var saved=AnalysisProtocolService.map(json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class));
var notices=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("readingSummary")).get("notices"));assertTrue(notices.contains("已有提示"));assertTrue(notices.containsAll(gaps));assertTrue(saved.get("answer").toString().contains("尚未解决:"));assertTrue(saved.get("answer").toString().contains("18X15X4+T")); var notices=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence"));assertTrue(notices.containsAll(gaps));assertEquals(result.get("answer"),saved.get("answer"));assertFalse(saved.get("answer").toString().contains("尚未解决:"));
} }
} }
@Test void rejectedRegistrationDoesNotPolluteLaterSuccessfulScopeCoverage() { @Test void rejectedRegistrationDoesNotPolluteLaterSuccessfulScopeCoverage() {
@@ -37,6 +37,19 @@ class AnalysisTurnSnapshotTest {
private static final String SESSION_ID = "66b51f0e-0252-4ef1-9aeb-58bd262293db"; private static final String SESSION_ID = "66b51f0e-0252-4ef1-9aeb-58bd262293db";
private static final String QUERY_FILTERS = "SELECT field_key,black_column,bright_column FROM query_filter_field WHERE enabled=TRUE"; private static final String QUERY_FILTERS = "SELECT field_key,black_column,bright_column FROM query_filter_field WHERE enabled=TRUE";
@Test void originalBodyQualityMetadataSurvivesSavedSnapshotWithoutClaimingFactVerification() {
Harness harness=new Harness("valid");
var quality=Map.<String,Object>of("version",1,"dataComplete",true,"narrativeComplete",true,"chartsComplete",false,
"narrativeFactBinding","not_assessed","citedEvidenceRefs",List.of("Q1234ABCD","Q00000000","bad"),
"unresolvedEvidenceRefs",List.of("QDEADBEEF","bad"),"notices",List.of("图表尚未齐全"),"missingEvidence",List.of("未知引用"));
var details=Map.<String,Object>of("answerQuality",quality,"queryEvidenceRefs",List.of("Q1234ABCD"));
var answer=harness.service.nativeAnswer(details,"完整AI正文",Map.of(),"release-1","PARTIAL","evidence_incomplete",TURN_ID,null);
var savedQuality=AnalysisProtocolService.map(answer.get("answerQuality"));
assertEquals("not_assessed",savedQuality.get("narrativeFactBinding"));assertEquals(false,savedQuality.get("citationComplete"));
assertEquals(List.of("Q1234ABCD"),savedQuality.get("citedEvidenceRefs"));assertEquals(List.of("QDEADBEEF"),savedQuality.get("unresolvedEvidenceRefs"));
harness.storedOverride=answer;var snapshot=harness.service.getSnapshot(TURN_ID,harness.submittedActor);
assertEquals(savedQuality,snapshot.get("answerQuality"));assertEquals("完整AI正文",snapshot.get("answer"));
}
@Test @Test
void snapshotReadUsesFreshAuthorizationAndDoesNotRequeryBusinessMetrics() { void snapshotReadUsesFreshAuthorizationAndDoesNotRequeryBusinessMetrics() {
Harness harness = new Harness("valid"); Harness harness = new Harness("valid");
@@ -6,6 +6,22 @@ import java.util.Map;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class NaoAnalysisRunnerResultTest { class NaoAnalysisRunnerResultTest {
@Test void aStopReasonCannotOverrideConflictingFinishOrPendingTools() {
for(var conflict:java.util.List.of(Map.<String,Object>of("finishReason","tool-calls"),
Map.<String,Object>of("nativeStopSucceeded",false),
Map.<String,Object>of("toolCalls",java.util.List.of(Map.of("tool","mcp_call","status","started"))),
Map.<String,Object>of("answerQuality",Map.of("narrativeComplete",false)))) {
var message=new java.util.LinkedHashMap<String,Object>();message.put("type","result");message.put("status","COMPLETED");message.put("stopReason","stop");message.put("answer","正在查询。");message.putAll(conflict);
assertEquals("PARTIAL",NaoAnalysisRunner.Result.from(message,"",false).status());
}
}
@Test void anEmptyStopResultCannotCompleteUnlessItHasAVisibleStructuredBody() {
var empty=NaoAnalysisRunner.Result.from(Map.of("type","result","status","COMPLETED","answer","", "stopReason","stop"),"",false);
assertEquals("PARTIAL",empty.status());assertEquals("answer_missing",empty.stopReason());
assertEquals(false,AnalysisProtocolService.map(empty.details().get("answerQuality")).get("narrativeComplete"));
var report=NaoAnalysisRunner.Result.from(Map.of("type","result","status","COMPLETED","answer","", "stopReason","stop","reportMarkdown","已生成的报告"),"",false);
assertEquals("COMPLETED",report.status());
}
@Test @Test
void onlyNativeStopFinishReasonCanComplete() { void onlyNativeStopFinishReasonCanComplete() {
NaoAnalysisRunner.Result completed = NaoAnalysisRunner.Result.from(Map.of( NaoAnalysisRunner.Result completed = NaoAnalysisRunner.Result.from(Map.of(
@@ -0,0 +1,21 @@
package cn.yunsheng.quality.analysis;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class NativeOriginalCoverageTest {
@Test void nativeCoverageKeepsModelProseByteForByteAndStoresGapsSeparately() {
String original="## 结论\n\n原始模型正文。\n\n| 变化 |\n| --- |\n| -0.30 pp |";
var answer=new LinkedHashMap<String,Object>();answer.put("answer",original);
answer.put("answerQuality",Map.of("version",1,"dataComplete",true,"missingEvidence",List.of("已有缺口")));
AnalysisProtocolService.appendNativeCoverageDiagnostics(answer,List.of("图表未齐","图表未齐", ""));
assertEquals(original,answer.get("answer"));
var quality=AnalysisProtocolService.map(answer.get("answerQuality"));
assertEquals(true,quality.get("dataComplete"));assertEquals(List.of("已有缺口","图表未齐"),quality.get("missingEvidence"));
assertFalse(answer.containsKey("readingSummary"));
}
@Test void noGapsDoNotCreateOrRewriteNarrativeMetadata() {
var answer=new LinkedHashMap<String,Object>();answer.put("answer","原文");
AnalysisProtocolService.appendNativeCoverageDiagnostics(answer,List.of());
assertEquals(Map.of("answer","原文"),answer);
}
}
@@ -1,6 +1,6 @@
# AI 智能分析当前要求与排查修复基准 # AI 智能分析当前要求与排查修复基准
适用项目:质量数据分析平台。更新日期:2026-10-31。 适用项目:质量数据分析平台。更新日期:2026-11-02。
本文只列当前有效要求与对应验收标准,供智能分析排查、修复和交付时使用。 本文只列当前有效要求与对应验收标准,供智能分析排查、修复和交付时使用。
@@ -11,6 +11,7 @@
- AI 负责理解自然语言、选择查询、分析和表达;正式指标由现有业务服务、已发布规则和映射计算。 - AI 负责理解自然语言、选择查询、分析和表达;正式指标由现有业务服务、已发布规则和映射计算。
- 保留可靠的数据底座、正式口径、权限和数据快照约束。系统规则、模型行为、结果校验及页面展示必须一致。 - 保留可靠的数据底座、正式口径、权限和数据快照约束。系统规则、模型行为、结果校验及页面展示必须一致。
- 用户最终看到清晰的结论、重点表格和重点图表,分析过程与最终结果对题、可信、可读。 - 用户最终看到清晰的结论、重点表格和重点图表,分析过程与最终结果对题、可信、可读。
- 模型识别的一般问候、能力介绍和致谢直接保留其回复原文,不要求数据期间,不触发正式查询或二次生成;仍核验会话权限及取消状态。该路径不能输出未查询业务数值、趋势因果或声称已执行的操作,也不能代替记忆、报告或数据分析。后续业务目标与筛选保持原有效计划,普通对话不充当报告事实来源。
## 2. 默认业务口径 ## 2. 默认业务口径
+8 -5
View File
@@ -963,7 +963,7 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
note = "黑片与亮片两阶段报废重量之和仅作分组描述,不代表独立投入分母或总体变化贡献。" note = "黑片与亮片两阶段报废重量之和仅作分组描述,不代表独立投入分母或总体变化贡献。"
elif order == "rate_drop": elif order == "rate_drop":
title = "合格率变化排名" if stage is None else "分组合格率变化排名" title = "合格率变化排名" if stage is None else "分组合格率变化排名"
metric, unit, label, field = "rate_drop_pp", "pp", "合格率下降(pp)", "rateDrop" metric, unit, label, field = "rate_drop_pp", "pp", "合格率变化(pp)", "rateDrop"
required_fields = (["black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"] required_fields = (["black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"]
if stage is None else [f"{stage}_good_weight", f"{stage}_total_weight"]) if stage is None else [f"{stage}_good_weight", f"{stage}_total_weight"])
@@ -971,11 +971,14 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
raw, ok = _finite_number(row.get(field)) raw, ok = _finite_number(row.get(field))
if not ok: if not ok:
return None, False return None, False
return (raw * 100 if raw is not None else None), True points = -raw * 100 if raw is not None else None
if points is not None and not math.isfinite(points):
return None, False
return points, True
note = "正值表示合格率下降,负值表示改善;百分点取自正式分组率差。" note = "正值表示本期合格率上升,负值表示下降;变化值为本期减比较期,排序仍沿用正式率降排名。"
if stage is None: if stage is None:
note = "正值表示综合合格率下降,负值表示改善;按正式综合率比较,不作为生产根因。" note = "正值表示本期综合合格率上升,负值表示下降;变化值为本期减比较期,排序仍沿用正式率降排名,不代表生产根因。"
elif order == 'current_rate': elif order == 'current_rate':
title = '分组本期合格率排名' title = '分组本期合格率排名'
metric = (stage+'_rate') if stage else 'composite_rate' metric = (stage+'_rate') if stage else 'composite_rate'
@@ -1023,7 +1026,7 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
title = title.replace("分组", "产品") title = title.replace("分组", "产品")
if order == "rate_drop": if order == "rate_drop":
title = title.replace("合格率变化排名", "合格率降幅线索") title = title.replace("合格率变化排名", "合格率降幅线索")
note = "条形末端显示具体变化:正值为下降,负值为改善,单位是百分点。本图只按率降幅排序,未纳入投入规模;少量生产或投入骤变的规格不能仅凭此图认定为重点,需结合分阶段投入与报废增量核查。" note = "条形末端显示本期减比较期的变化:负值为下降,正值为上升,单位是百分点。本图仍按率降幅排序,未纳入投入规模;少量生产或投入骤变的规格不能仅凭此图认定为重点,需结合分阶段投入与报废增量核查。"
elif result["dimension"] == "group": elif result["dimension"] == "group":
title = title.replace("分组", "业务分组") title = title.replace("分组", "业务分组")
else: else:
+17 -8
View File
@@ -62,20 +62,29 @@ def capability_context(task=None):
} }
def apply_platform_tools(payload): QUALITY_NATIVE_TOOLS = frozenset({'read', 'list', 'grep', 'search', 'mcp_call', 'mcp_connect'})
"""Do not advertise a native SQL-result renderer for quality API evidence."""
def apply_platform_tools(payload, *, native_agent=False):
"""Expose tools compatible with platform evidence and answer completion."""
tools = payload.get('tools') tools = payload.get('tools')
if not isinstance(tools, list): return payload allowed = QUALITY_NATIVE_TOOLS if native_agent else QUALITY_NATIVE_TOOLS | {'story'}
kept = [tool for tool in tools if not (isinstance(tool, dict) # Clarification/warehouse selection are upstream stop conditions with native
and isinstance(tool.get('function'), dict) # UI replies that this platform cannot consume. SQL, renderers and writers
and tool['function'].get('name') == 'display_chart')] # also use a different data/artifact lifecycle. Unknown tools stay disabled.
if len(kept) == len(tools): return payload tools = tools if isinstance(tools, list) else []
kept = [tool for tool in tools if isinstance(tool, dict) and tool.get('type') == 'function'
and isinstance(tool.get('function'), dict) and isinstance(tool['function'].get('name'), str)
and tool['function'].get('name') in allowed]
if kept: payload['tools'] = kept if kept: payload['tools'] = kept
else: payload.pop('tools', None) else: payload.pop('tools', None)
choice = payload.get('tool_choice') choice = payload.get('tool_choice')
if ((isinstance(choice, dict) and (choice.get('function') or {}).get('name') == 'display_chart') kept_names = {tool['function']['name'] for tool in kept}
choice_name = choice.get('function', {}).get('name') if isinstance(choice, dict) and isinstance(choice.get('function'), dict) else None
if ((isinstance(choice, dict) and choice_name not in kept_names)
or not kept and choice in ('auto', 'required')): or not kept and choice in ('auto', 'required')):
payload.pop('tool_choice', None) payload.pop('tool_choice', None)
if not kept: payload.pop('parallel_tool_calls', None)
return payload return payload
+13 -3
View File
@@ -1480,6 +1480,11 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
value = candidate value = candidate
recovery_repairs.extend(changes) recovery_repairs.extend(changes)
protocol_context = (context or {}).get('_protocol') if isinstance(context, dict) else None protocol_context = (context or {}).get('_protocol') if isinstance(context, dict) else None
if (isinstance(protocol_context, dict) and protocol_context.get('version') == 1
and task['kind'] in ('explain', 'restate') and not task.get('directResponse')
and not task['needsClarification']):
raise TaskUnavailable('当前协议的普通对话须提供directResponse;业务解释须选择正式分析或历史报告任务。',
field='kind.protocol', expected='supported business task or reviewed directResponse')
if autonomous_session: if autonomous_session:
from nao_native_planning import history_only_requested from nao_native_planning import history_only_requested
if (history_only_requested(question) and not task['needsClarification'] if (history_only_requested(question) and not task['needsClarification']
@@ -1572,7 +1577,7 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
or _source_column_intent(question, (context or {}).get('_businessCatalog', {})))) or _source_column_intent(question, (context or {}).get('_businessCatalog', {}))))
member_list_review_required = task['kind'] == 'members' member_list_review_required = task['kind'] == 'members'
if ((task.get('directResponse') or (semantic_review and payload['previousUserQuestions']) or review_read_requirements) if ((task.get('directResponse') or (semantic_review and payload['previousUserQuestions']) or review_read_requirements)
and not autonomous_session and (not autonomous_session or task.get('directResponse'))
and (task['kind'] in ('analysis','metrics','members','explain','restate','source_verify','details') and (task['kind'] in ('analysis','metrics','members','explain','restate','source_verify','details')
or review_read_requirements and task['kind'] == 'report')): or review_read_requirements and task['kind'] == 'report')):
review_system = ('你是只读任务计划的语义核对员。依据前序用户问题与最新问题核对计划是否真正回答最新意图,' review_system = ('你是只读任务计划的语义核对员。依据前序用户问题与最新问题核对计划是否真正回答最新意图,'
@@ -1585,6 +1590,7 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
'若用户要求报废率的分子分母或计算基数,实际fields须同时包含scrapRate、scrapWeight、totalWeight,不能只有goal提及;缺少任一应aligned=false。' '若用户要求报废率的分子分母或计算基数,实际fields须同时包含scrapRate、scrapWeight、totalWeight,不能只有goal提及;缺少任一应aligned=false。'
'前序未完成的问题只提供语义,不是已核实结果;truncated的问题不完整,不推断省略内容。' '前序未完成的问题只提供语义,不是已核实结果;truncated的问题不完整,不推断省略内容。'
'directResponse仅用于一般问候、能力介绍或致谢;业务趋势、比较和原因判断即使没有数字也不能直答。' 'directResponse仅用于一般问候、能力介绍或致谢;业务趋势、比较和原因判断即使没有数字也不能直答。'
'同时核对directResponse.answer正文;即使用户仅问候,只要回复夹带未查询业务事实或因果,必须判aligned=false或requiresEvidence=true。'
'历史报告kind=report与复述不同:报告来源由服务端在任务确认后冻结和导入,规划上下文不会包含历史来源正文;' '历史报告kind=report与复述不同:报告来源由服务端在任务确认后冻结和导入,规划上下文不会包含历史来源正文;'
'previousVerifiedTurns为空、缺失或没有来源摘要不能据此判断历史数据不存在,也不能把用户明确的报告意图改成explain/restate或要求用户证明历史来源存在。' 'previousVerifiedTurns为空、缺失或没有来源摘要不能据此判断历史数据不存在,也不能把用户明确的报告意图改成explain/restate或要求用户证明历史来源存在。'
'应按用户范围保留kind=report、historyMode=first/last/all、freshQuery=false及空root指标条件;来源可用性/缺口交由服务端导入结果决定。' '应按用户范围保留kind=report、historyMode=first/last/all、freshQuery=false及空root指标条件;来源可用性/缺口交由服务端导入结果决定。'
@@ -1992,8 +1998,12 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
if error.field: if error.field:
payload['validationFeedback'] = error.field + ': ' + str(error) payload['validationFeedback'] = error.field + ': ' + str(error)
payload['repairInstructions'] = '根据错误和上一份计划修正协议格式,保留原业务目标、期间及范围,返回完整JSON计划,不输出解释。' payload['repairInstructions'] = '根据错误和上一份计划修正协议格式,保留原业务目标、期间及范围,返回完整JSON计划,不输出解释。'
if error.field == 'directResponse.business': if error.field == 'kind.protocol':
payload['repairInstructions'] = '当前问题涉及业务事实,禁止directResponse;保留用户最新问题及前文目标,返回完整业务分析或指标计划。' payload['repairInstructions'] = ('重新核对最新意图:一般问候、能力介绍或致谢必须返回kind=explain及directResponse的模型回复;'
'涉及业务事实则选择现有analysis/metrics/report等正式任务,不能用普通explain/restate绕过查询。记忆或操作要求不得伪装普通对话。')
elif error.field == 'directResponse.business':
payload['repairInstructions'] = ('上次回复夹带未经查询的业务判断,请重新核对最新用户意图:问候或能力介绍仍使用directResponse,仅介绍能做什么,不断言实际业务结果;'
'只有用户确实要求业务事实、比较或原因解释时,才改为完整业务分析或指标计划。保留原问题,不因上次错误回复改写用户目标。')
elif error.field and error.field.startswith('directResponse'): elif error.field and error.field.startswith('directResponse'):
payload['repairInstructions'] = '保持最小一般对话JSON,仅修复错误字段,保留kind、goal、directResponse;无需补全业务计划字段。answer只写一般回复,列表用项目符号,不写业务数值。' payload['repairInstructions'] = '保持最小一般对话JSON,仅修复错误字段,保留kind、goal、directResponse;无需补全业务计划字段。answer只写一般回复,列表用项目符号,不写业务数值。'
elif error.field and (error.field == 'queryPlan' or error.field.startswith('queryPlan.')): elif error.field and (error.field == 'queryPlan' or error.field.startswith('queryPlan.')):
+3 -3
View File
@@ -33,10 +33,10 @@ def direct_plan(value):
# Convert their prefixes to bullets; any remaining value still fails. # Convert their prefixes to bullets; any remaining value still fails.
text = re.sub(r'(?m)^[ \t]*[1-9]\d?[.、)][ \t]*(?!\d)', '- ', text) text = re.sub(r'(?m)^[ \t]*[1-9]\d?[.、)][ \t]*(?!\d)', '- ', text)
quantified_fact = (r'(?:\d+(?:[.,]\d+)*|[零〇一二两三四五六七八九十百千万点]+)\s*(?:[%%]|kg\b|公斤|千克|吨|个百分点|pp\b)' quantified_fact = (r'(?:\d+(?:[.,]\d+)*|[零〇一二两三四五六七八九十百千万点]+)\s*(?:[%%]|kg\b|公斤|千克|吨|个百分点|pp\b)'
r'|百分之|(?:合格率|投入|报废|总重|产量|重量|数量)(?:重量|数量|总数|率)?\s*(?:为|是|有|达到|共|合计|总计|[::])?\s*\d') r'|百分之|(?:合格率|投入|报废|总重|产量|重量|数量)(?:重量|数量|总数|率)?\s*(?:为|是|有|达到|共|合计|总计|[::])?\s*(?:\d|[零〇一二两三四五六七八九十百千万点])')
unperformed_action = r'(?:已|已经)(?:查到|查询|核实|统计|生成|保存|记住|修改|设置|完成分析)' unperformed_action = r'(?:已|已经)(?:查到|查询|核实|统计|生成|保存|记住|修改|设置|完成分析)(?!的)'
if (isinstance(text,str) and re.search(r'合格率|报废|投入|产量|重量|分组|规格|产业部|国内|海外|产品',text) if (isinstance(text,str) and re.search(r'合格率|报废|投入|产量|重量|分组|规格|产业部|国内|海外|产品',text)
and re.search(r'主要是.{0,40}所致|主要来自|所致|远高于|远低于|更大|更小|更差|更好|基本持平|明显.{0,8}(?:下降|上升|增加|减少)|导致.{0,12}(?:下降|上升)',text)): and re.search(r'主要是.{0,40}所致|主要来自|主要原因是|所致|远高于|远低于|确实更(?:大|小|差|好)|基本持平|(?:下降|上升|增加|减少|恶化|改善)了|明显.{0,8}(?:下降|上升|增加|减少)|导致.{0,12}(?:下降|上升)',text)):
invalid('当前答复包含未经查询的业务趋势或因果判断,请返回完整分析计划', 'directResponse.business') invalid('当前答复包含未经查询的业务趋势或因果判断,请返回完整分析计划', 'directResponse.business')
if (not isinstance(text, str) or not text.strip() or len(text) > 1200 if (not isinstance(text, str) or not text.strip() or len(text) > 1200
or re.search(quantified_fact + '|' + unperformed_action + r'|https?://|Q[A-F0-9]{8}|<[^>]+>|Bearer\s+|\bsk-[A-Za-z0-9_-]+|(?:api[_-]?key|token|password)\s*[:=]',text,re.I)): or re.search(quantified_fact + '|' + unperformed_action + r'|https?://|Q[A-F0-9]{8}|<[^>]+>|Bearer\s+|\bsk-[A-Za-z0-9_-]+|(?:api[_-]?key|token|password)\s*[:=]',text,re.I)):
+47 -10
View File
@@ -21,6 +21,10 @@ class _NoRedirect(HTTPRedirectHandler):
return None return None
class ToolPolicyError(ValueError):
pass
class ModelGate: class ModelGate:
"""A stable per-session endpoint backed only by this turn's live delegation.""" """A stable per-session endpoint backed only by this turn's live delegation."""
@@ -41,7 +45,9 @@ class ModelGate:
self._thinking = dict(thinking_options) if thinking_options is not None else None self._thinking = dict(thinking_options) if thinking_options is not None else None
self._on_thinking = on_thinking self._on_thinking = on_thinking
self._native_turn_marker = native_turn_marker self._native_turn_marker = native_turn_marker
self.native_agent = False
self.rejected_stale_requests = 0 self.rejected_stale_requests = 0
self.rejected_tool_calls = 0
self._request_number = 0 self._request_number = 0
self._request_prefix = secrets.token_hex(4) self._request_prefix = secrets.token_hex(4)
self.request_audit = [] self.request_audit = []
@@ -92,9 +98,10 @@ class ModelGate:
for message in messages)): for message in messages)):
with gate._audit_lock: gate.rejected_stale_requests += 1 with gate._audit_lock: gate.rejected_stale_requests += 1
self.failure(403, '模型请求不属于当前轮次'); return self.failure(403, '模型请求不属于当前轮次'); return
decoded = gate.apply_thinking(decoded)
from nao_agent_contract import apply_platform_tools from nao_agent_contract import apply_platform_tools
decoded = apply_platform_tools(decoded) decoded = apply_platform_tools(decoded, native_agent=gate.native_agent)
decoded = gate.apply_thinking(decoded)
offered_tools = {tool['function']['name'] for tool in decoded.get('tools', [])}
payload = json.dumps(decoded,ensure_ascii=False).encode() payload = json.dumps(decoded,ensure_ascii=False).encode()
except (ValueError, OSError): except (ValueError, OSError):
self.failure(400, '模型请求格式无效'); return self.failure(400, '模型请求格式无效'); return
@@ -141,9 +148,10 @@ class ModelGate:
thinking('start') thinking('start')
# SSE termination is a transport concern even when no thinking # SSE termination is a transport concern even when no thinking
# callback is installed (for example, native stream forwarding). # callback is installed (for example, native stream forwarding).
observer = ProviderStream(lambda text:thinking('delta',text=text)) if gate._on_thinking or is_sse else None observer = ProviderStream(lambda text:thinking('delta',text=text))
raw_json = bytearray() raw_json = bytearray()
if not bridge: pending_wire = bytearray()
if is_sse and not bridge:
self.send_response(response.status) self.send_response(response.status)
self.send_header('Content-Type', response.headers.get('Content-Type', 'application/json')) self.send_header('Content-Type', response.headers.get('Content-Type', 'application/json'))
self.send_header('Cache-Control', 'no-store') self.send_header('Cache-Control', 'no-store')
@@ -161,21 +169,29 @@ class ModelGate:
if time.monotonic() - checked_at >= 1: if time.monotonic() - checked_at >= 1:
gate._check() gate._check()
checked_at = time.monotonic() checked_at = time.monotonic()
if observer: if is_sse:
if is_sse:observer.feed(chunk) observer.feed(chunk)
else:raw_json.extend(chunk) gate.check_returned_tools(observer, offered_tools)
if not bridge: if not bridge:
self.wfile.write(chunk) # A partial SSE line cannot be checked yet. Hold
self.wfile.flush() # it until its complete event has passed policy.
pending_wire.extend(chunk)
end=pending_wire.rfind(b'\n')+1
if end:
self.wfile.write(pending_wire[:end]);self.wfile.flush()
del pending_wire[:end]
else:raw_json.extend(chunk)
# A provider may keep the HTTP connection alive with heartbeats # A provider may keep the HTTP connection alive with heartbeats
# after its explicit terminal event. Do not wait for EOF, but # after its explicit terminal event. Do not wait for EOF, but
# keep reading past finish_reason so the usage tail is preserved. # keep reading past finish_reason so the usage tail is preserved.
if is_sse and observer.done: if is_sse and observer.done:
break break
gate._check() gate._check()
if observer:
if is_sse:observer.finish() if is_sse:observer.finish()
else:observer.document(json.loads(raw_json)) else:observer.document(json.loads(raw_json))
gate.check_returned_tools(observer, offered_tools, final=True)
if is_sse and not bridge and pending_wire:
self.wfile.write(pending_wire);self.wfile.flush()
result = observer.completion() if bridge or is_sse else None result = observer.completion() if bridge or is_sse else None
stops = [row['finish_reason'] for row in observer.choices.values()] if observer else [] stops = [row['finish_reason'] for row in observer.choices.values()] if observer else []
thinking('end',finishReason='length' if 'length' in stops else (stops[-1] if stops else ''),interrupted=bool(observer and not stops)) thinking('end',finishReason='length' if 'length' in stops else (stops[-1] if stops else ''),interrupted=bool(observer and not stops))
@@ -188,6 +204,15 @@ class ModelGate:
self.send_response(200);self.send_header('Content-Type','application/json') self.send_response(200);self.send_header('Content-Type','application/json')
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(encoded))) self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(encoded)))
self.end_headers();headers_sent=True;self.wfile.write(encoded);self.wfile.flush() self.end_headers();headers_sent=True;self.wfile.write(encoded);self.wfile.flush()
elif not is_sse:
self.send_response(response.status);self.send_header('Content-Type','application/json')
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(raw_json)))
self.end_headers();headers_sent=True;self.wfile.write(raw_json);self.wfile.flush()
except ToolPolicyError:
if not headers_sent:self.failure(502,'模型返回了当前任务未开放的工具调用')
else:
with contextlib.suppress(OSError):
self.wfile.write(b'data: {"error":{"message":"Tool call is unavailable for this task"}}\n\n');self.wfile.flush()
except HTTPError as error: except HTTPError as error:
if not headers_sent: if not headers_sent:
self.failure(error.code if 400 <= error.code <= 599 else 502, '模型接口暂不可用') self.failure(error.code if 400 <= error.code <= 599 else 502, '模型接口暂不可用')
@@ -230,6 +255,8 @@ class ModelGate:
else:payload['reasoning_effort']=effort else:payload['reasoning_effort']=effort
with self._audit_lock: with self._audit_lock:
if len(self.request_audit)<200:self.request_audit.append({'enabled':enabled,'effort':effort, if len(self.request_audit)<200:self.request_audit.append({'enabled':enabled,'effort':effort,
'tools':[tool['function']['name'] for tool in payload.get('tools',[])],
'nativeAgent':self.native_agent,
'protocol':protocol,'stream':payload.get('stream',False), 'protocol':protocol,'stream':payload.get('stream',False),
'maxCompletionTokens':payload.get('max_completion_tokens',payload.get('max_tokens')), 'maxCompletionTokens':payload.get('max_completion_tokens',payload.get('max_tokens')),
'thinkingType':(payload.get('thinking') or {}).get('type'), 'thinkingType':(payload.get('thinking') or {}).get('type'),
@@ -237,6 +264,16 @@ class ModelGate:
'reasoningEffort':payload.get('reasoning_effort',(payload.get('chat_template_kwargs') or {}).get('reasoning_effort'))}) 'reasoningEffort':payload.get('reasoning_effort',(payload.get('chat_template_kwargs') or {}).get('reasoning_effort'))})
return payload return payload
def check_returned_tools(self, observer, offered, *, final=False):
for choice, tools in observer.tools.items():
finished=final or bool(observer.choices.get(choice,{}).get('finish_reason')) or observer.done
for tool in tools.values():
name=tool.get('function',{}).get('name','')
valid=(name in offered) if finished else (not name or any(allowed.startswith(name) for allowed in offered))
if not valid:
with self._audit_lock:self.rejected_tool_calls+=1
raise ToolPolicyError('Unadvertised tool call')
def _check(self) -> None: def _check(self) -> None:
if self._closed.is_set(): if self._closed.is_set():
raise PermissionError('模型授权已关闭') raise PermissionError('模型授权已关闭')
+1
View File
@@ -135,6 +135,7 @@ NATIVE_ROOT_PROMPT = '''你是质量数据分析平台的任务理解器,只
沿用previousTask中未取消的条件,以最新明确修改为准;previousUserQuestions和lastVisibleAnswer只是理解指代的资料,不能恢复已取消条件。 沿用previousTask中未取消的条件,以最新明确修改为准;previousUserQuestions和lastVisibleAnswer只是理解指代的资料,不能恢复已取消条件。
返回JSON:goal、kind、executionMode、filterUpdates、period、comparisonPeriod、comparisonRequired、trendRequired、dimensions、stages、fields、dimensionStages、memberFields、freshQuery、verifySource、fullDetails、needsClarification、clarification、visualPreference、responseStyle、historyMode。clarification始终是字符串,无澄清用空字符串,不能写对象;候选另放clarificationRequest。period年份和月份均为JSON整数,如{\"year\":2026,\"month\":9},不可只输出月份或字符串日期。 返回JSON:goal、kind、executionMode、filterUpdates、period、comparisonPeriod、comparisonRequired、trendRequired、dimensions、stages、fields、dimensionStages、memberFields、freshQuery、verifySource、fullDetails、needsClarification、clarification、visualPreference、responseStyle、historyMode。clarification始终是字符串,无澄清用空字符串,不能写对象;候选另放clarificationRequest。period年份和月份均为JSON整数,如{\"year\":2026,\"month\":9},不可只输出月份或字符串日期。
kind仅analysis/metrics/members/explain/restate/report/source_verify/details;visualPreference仅auto/required/none;responseStyle仅brief/standard/detailed(默认standard);historyMode仅none/first/last/all(默认none)。比较、趋势、freshQuery、verifySource、fullDetails、needsClarification均使用JSON布尔值,不写null。dimensions/stages/fields是数组,dimensionStages是对象,filterUpdates无变化时{}。 kind仅analysis/metrics/members/explain/restate/report/source_verify/details;visualPreference仅auto/required/none;responseStyle仅brief/standard/detailed(默认standard);historyMode仅none/first/last/all(默认none)。比较、趋势、freshQuery、verifySource、fullDetails、needsClarification均使用JSON布尔值,不写null。dimensions/stages/fields是数组,dimensionStages是对象,filterUpdates无变化时{}。
一般问候、能力介绍和致谢必须返回kind=explain及directResponse={purpose:greeting/capabilities/acknowledgement,answer:你的完整简短回复,requiresMemory:false};仅声明explain/restate却不给出directResponse不受当前协议支持。业务解释仍使用正式analysis/metrics或历史report,不能改为普通对话。
为什么、原因定位、深入调查、解释多种变化及其续问使用kind=analysis、executionMode=native_agent,不写queryPlan。dimensions只填用户明确必须覆盖的维度,不预列所有调查方向;一般原因问题dimensions=[]、fields=[rate]。智能体之后根据实际结果决定查哪些组织、产品及缺陷。 为什么、原因定位、深入调查、解释多种变化及其续问使用kind=analysis、executionMode=native_agent,不写queryPlan。dimensions只填用户明确必须覆盖的维度,不预列所有调查方向;一般原因问题dimensions=[]、fields=[rate]。智能体之后根据实际结果决定查哪些组织、产品及缺陷。
简单单值/趋势用metrics;明确排序用原静态analysis及queryPlan;清单members、原表source_verify、记录details和历史report沿用原能力。非自主任务省略executionMode。kind=members只表示唯一成员清单,不是原始行读取;memberFields必须是当前businessCatalog.sourceFields中1到5个授权key,stages必须明确选一个或两个阶段,期间及普通filters照常保留,dimensions=[]、fields=[]、verifySource=false、fullDetails=false、freshQuery=true。kind=members时memberFields必须按当前businessCatalog.sourceFields字段label的语义选择,不能猜key或把筛选字段当输出成员。用户只说“有哪些规格”时按产品规格理解,选择真实“产品规格/成品规格/规格型号”目录列;不能用“产品图号/图纸号”或“客户代码”代替。“客户都有哪些规格”中的客户是筛选对象,输出仍是产品规格;明确问图号才选图号列,明确问“客户规格”才选客户规格列。用户明确说“成品规格”等具体目录label时,优先精确匹配该label;裸“规格”有多个可用产品规格候选或目标没有可用字段时,needsClarification=true、memberFields=[],保留原目标并请用户明确字段,不擅选近似列。并列、否定或复合字段意图保留模型确认的正向成员,不能补入用户已取消的字段。 简单单值/趋势用metrics;明确排序用原静态analysis及queryPlan;清单members、原表source_verify、记录details和历史report沿用原能力。非自主任务省略executionMode。kind=members只表示唯一成员清单,不是原始行读取;memberFields必须是当前businessCatalog.sourceFields中1到5个授权key,stages必须明确选一个或两个阶段,期间及普通filters照常保留,dimensions=[]、fields=[]、verifySource=false、fullDetails=false、freshQuery=true。kind=members时memberFields必须按当前businessCatalog.sourceFields字段label的语义选择,不能猜key或把筛选字段当输出成员。用户只说“有哪些规格”时按产品规格理解,选择真实“产品规格/成品规格/规格型号”目录列;不能用“产品图号/图纸号”或“客户代码”代替。“客户都有哪些规格”中的客户是筛选对象,输出仍是产品规格;明确问图号才选图号列,明确问“客户规格”才选客户规格列。用户明确说“成品规格”等具体目录label时,优先精确匹配该label;裸“规格”有多个可用产品规格候选或目标没有可用字段时,needsClarification=true、memberFields=[],保留原目标并请用户明确字段,不擅选近似列。并列、否定或复合字段意图保留模型确认的正向成员,不能补入用户已取消的字段。
静态合格率排名必须输出queryPlan,使用一个批量changes节点,禁止逐对象查询。root的dimensions、fields、stages、dimensionStages与节点联合需求一致;changes必须comparisonRequired=true并给出前一个同长度完整comparisonPeriod,即使按本期率排序也使用该两期批量接口。sort=current_rate按本期率升序;rate_drop按降幅降序;current_scrap/scrap_delta用于报废规模与不良影响。用户说“表现较差/最差”未指定指标时按黑片+亮片报废总重及综合合格率判断优先级,不只按极小批量最低率排序;比较分析用sort=current_scrap或scrap_delta。仅明确要求最低率时sort=current_rate。只问“哪个”limit=1,明确数量以用户为准,未指定通常3,最大10。fields按问题保留rate/totalWeight/scrapWeight;综合率stages=[]、dimensionStages={\"product\":[]}。明确按一个阶段的totalWeight或scrapWeight选产品Top N并显示这批对象的同阶段rate时,仍用静态analysis/queryPlan:先用base产品ranking按该阶段重量取Top N,再用metrics节点fields=[rate]、stages=[同阶段]和ranking_top selector绑定前置排名、同阶段、同重量指标及count=N。重量和对象选择来自排名,rate单独查询;不要把rate改为排序指标、对全体产品另查rate、加入比较或转成原因/缺陷调查。 静态合格率排名必须输出queryPlan,使用一个批量changes节点,禁止逐对象查询。root的dimensions、fields、stages、dimensionStages与节点联合需求一致;changes必须comparisonRequired=true并给出前一个同长度完整comparisonPeriod,即使按本期率排序也使用该两期批量接口。sort=current_rate按本期率升序;rate_drop按降幅降序;current_scrap/scrap_delta用于报废规模与不良影响。用户说“表现较差/最差”未指定指标时按黑片+亮片报废总重及综合合格率判断优先级,不只按极小批量最低率排序;比较分析用sort=current_scrap或scrap_delta。仅明确要求最低率时sort=current_rate。只问“哪个”limit=1,明确数量以用户为准,未指定通常3,最大10。fields按问题保留rate/totalWeight/scrapWeight;综合率stages=[]、dimensionStages={\"product\":[]}。明确按一个阶段的totalWeight或scrapWeight选产品Top N并显示这批对象的同阶段rate时,仍用静态analysis/queryPlan:先用base产品ranking按该阶段重量取Top N,再用metrics节点fields=[rate]、stages=[同阶段]和ranking_top selector绑定前置排名、同阶段、同重量指标及count=N。重量和对象选择来自排名,rate单独查询;不要把rate改为排序指标、对全体产品另查rate、加入比较或转成原因/缺陷调查。
+80 -44
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import copy import copy
import re
import time import time
@@ -22,12 +23,17 @@ def exploration_notices(scopes, coverage):
for kind,labels in grouped.items()] for kind,labels in grouped.items()]
def _answer_evidence_refs(answer):
"""Return only explicit query references present in the upstream answer."""
return list(dict.fromkeys(re.findall(r'\bQ[A-F0-9]{8}\b', answer)))
def run_native_exploration(*, request, task, authority, actor_root, delegated, connection, def run_native_exploration(*, request, task, authority, actor_root, delegated, connection,
manager, state, cancel_event, emit, prior_evidence_files, phase_timings=None): manager, state, cancel_event, emit, prior_evidence_files, phase_timings=None):
from nao_quality_runtime import _atomic_json, _authenticate, _sse_request, _read_json from nao_quality_runtime import _atomic_json, _authenticate, _sse_request, _read_json
from nao_agent_task import bind_task from nao_agent_task import bind_task
from nao_protocol_execution import _identity, _platform_visual_context, query_evidence_bindings from nao_protocol_execution import _identity, query_evidence_bindings
from nao_evidence_finalizer import evidence_summaries, synthesize_native from nao_evidence_finalizer import evidence_summaries
from analysis_visual_evidence import protocol_visual_result from analysis_visual_evidence import protocol_visual_result
from nao_runtime_policy import native_timeout from nao_runtime_policy import native_timeout
from nao_native_exploration import _proofs from nao_native_exploration import _proofs
@@ -106,12 +112,16 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
and type(progress.get('noProgress')) is int and progress['noProgress'] >= 3) and type(progress.get('noProgress')) is int and progress['noProgress'] >= 3)
if controlled_no_progress: if controlled_no_progress:
missing.append('连续三次没有取得新证据,调查已停止;其余线索尚未验证。') missing.append('连续三次没有取得新证据,调查已停止;其余线索尚未验证。')
natural_finish = 'stop' in accumulator.finish_reasons and stop_succeeded is not False natural_finish = bool(accumulator.finish_reasons and accumulator.finish_reasons[-1] == 'stop'
and stop_succeeded is not False
and getattr(accumulator, 'final_answer_ready', True))
corrected_tool_errors = (native_reason == 'mcp_error' and natural_finish corrected_tool_errors = (native_reason == 'mcp_error' and natural_finish
and complete_scopes is not None and bool(documents) and complete_scopes is not None and bool(documents)
and not missing and not progress.get('halted')) and not missing and not progress.get('halted'))
if native_status != 'COMPLETED' and not corrected_tool_errors and not controlled_no_progress: if native_status != 'COMPLETED' and not corrected_tool_errors and not controlled_no_progress:
missing.append('自主调查未正常结束(' + str(native_reason or native_status) + '),已保留核实结果。') missing.append('自主调查未正常结束(' + str(native_reason or native_status) + '),已保留核实结果。')
elif native_status == 'COMPLETED' and not natural_finish:
missing.append('自主调查未收到有效的正常结束信号。')
if not documents: if not documents:
missing.append('本轮未取得当前执行的可核验查询证据。') missing.append('本轮未取得当前执行的可核验查询证据。')
context['_protocolScopes'] = {'scopes': scopes, 'pending': snapshot.get('pending', []), 'gaps': missing} context['_protocolScopes'] = {'scopes': scopes, 'pending': snapshot.get('pending', []), 'gaps': missing}
@@ -119,24 +129,7 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
visuals = protocol_visual_result(documents, scopes, request['question'], request['turnId'], visuals = protocol_visual_result(documents, scopes, request['question'], request['turnId'],
release_id=request['releaseId'], base_context=context) release_id=request['releaseId'], base_context=context)
timings['visuals'] = round((time.monotonic() - started) * 1000) timings['visuals'] = round((time.monotonic() - started) * 1000)
context['_platformVisuals'] = _platform_visual_context(visuals) emit({'type': 'progress', 'message': '正在生成正式图表并整理证据状态…', 'executionMode': 'native_agent'})
emit({'type': 'progress', 'message': '正在核对结论与图表…', 'executionMode': 'native_agent'})
started = time.monotonic()
final = synthesize_native(base_url=connection[0], api_key=connection[1], model=connection[2],
question=request['question'], evidence=documents, cancel_event=cancel_event,
context=context, native_answer=accumulator.answer)
timings['synthesis'] = round((time.monotonic() - started) * 1000)
_atomic_json(actor_root / 'private' / 'native-composition.json', {
'turnId': request['turnId'], 'rawModelResponses': final.get('rawModelResponses', []),
'compositionDiagnostics': final.get('compositionDiagnostics', {}),
'bindingInput': final.get('_privateBindingInput'),
'titleMetadata': {key: final.get(key) for key in
('reportTitle', 'titleGeneratedByModel', 'titleValid', 'titleSource')},
'readingSummary': final.get('readingSummary')})
full_facts = final.get('fullEvidenceFacts', [])
if full_facts:
_atomic_json(actor_root / 'private' / 'native-full-evidence-facts.json', full_facts)
missing.extend(final.get('missingEvidence', []))
visual_warnings = list(visuals.get('missingEvidence', [])) visual_warnings = list(visuals.get('missingEvidence', []))
if task.get('visualPreference') == 'required': if task.get('visualPreference') == 'required':
missing.extend(visual_warnings) missing.extend(visual_warnings)
@@ -144,41 +137,84 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
if visual_warnings and not summary_warnings: if visual_warnings and not summary_warnings:
summary_warnings = ['部分重点图表未能完整展示;已保留核实文字和表格。'] summary_warnings = ['部分重点图表未能完整展示;已保留核实文字和表格。']
missing = list(dict.fromkeys(str(item) for item in missing if item)) missing = list(dict.fromkeys(str(item) for item in missing if item))
complete = bool(documents and final.get('evidenceSufficient') and not missing) answer = accumulator.answer if isinstance(accumulator.answer, str) else ''
used_refs = set(final.get('usedEvidenceRefs', [])) original_refs = _answer_evidence_refs(answer)
cited_ids = list(dict.fromkeys(p['queryId'] for doc in documents if doc.get('evidenceRef') in used_refs complete_receipt_ids = {p.get('queryId') for p in receipts if isinstance(p, dict)
for p in _proofs(doc.get('result', {})))) and p.get('executionId') == identity['executionId'] and isinstance(p.get('queryId'), str)
if final.get('evidenceSufficient') and not cited_ids: and p.get('queryId') in accepted_ids
missing.append('解释未关联当前执行的实际查询证明。') and complete_scopes is not None and (p.get('nodeId'), p.get('scopeId')) in complete_scopes}
complete = False verified_document_ids = {}
for doc in documents:
proofs = _proofs(doc.get('result', {})) if isinstance(doc, dict) else []
proof_ids = list(dict.fromkeys(p.get('queryId') for p in proofs
if isinstance(p, dict) and isinstance(p.get('queryId'), str)))
if (doc.get('evidenceRef') and proof_ids
and all(query_id in complete_receipt_ids for query_id in proof_ids)):
verified_document_ids[doc['evidenceRef']] = proof_ids
document_refs = set(verified_document_ids)
cited_refs = set(original_refs) & document_refs
cited_ids = list(dict.fromkeys(query_id for doc_ref in original_refs if doc_ref in cited_refs
for query_id in verified_document_ids[doc_ref]))
unresolved_refs = sorted(set(original_refs) - cited_refs)
if unresolved_refs:
missing.extend('原文引用未关联本轮完整scope正式查询证据:' + ref + '。' for ref in unresolved_refs)
background_ids = list(dict.fromkeys(query_id for proof_ids in verified_document_ids.values()
for query_id in proof_ids)) if not original_refs else []
if not original_refs and not background_ids and documents:
missing.append('本轮没有可关联的完整scope正式查询证明。')
conclusion_ids = cited_ids if original_refs else background_ids
if len(conclusion_ids) > 40:
missing.append('完整查询证据引用超过平台允许的40项上限。')
conclusion_ids = conclusion_ids[:40]
if not answer.strip():
missing.append('自主分析未生成正文。')
missing = list(dict.fromkeys(str(item) for item in missing if item))
data_complete = bool(documents and not snapshot.get('rootGoalGaps')
and (complete_scopes is not None or not snapshot.get('gaps'))
and bool(conclusion_ids) and not unresolved_refs
and len(cited_ids if original_refs else background_ids) <= 40)
narrative_complete = bool(answer.strip() and natural_finish
and (native_status == 'COMPLETED' or corrected_tool_errors))
charts_complete = not visual_warnings
complete = bool(data_complete and narrative_complete and not missing)
if warnings or visual_warnings: if warnings or visual_warnings:
_atomic_json(actor_root / 'private' / 'native-warning-diagnostics.json', { _atomic_json(actor_root / 'private' / 'native-warning-diagnostics.json', {
'turnId': request['turnId'], 'explorationWarnings': warnings, 'turnId': request['turnId'], 'explorationWarnings': warnings,
'visualWarnings': visual_warnings}) 'visualWarnings': visual_warnings})
if summary_warnings: _atomic_json(actor_root / 'private' / 'native-original-body-diagnostics.json', {
if isinstance(final.get('readingSummary'), dict): 'turnId': request['turnId'], 'executionId': identity['executionId'],
final['readingSummary']['notices'] = list(dict.fromkeys([ 'nativeStatus': native_status, 'nativeReason': native_reason,
*final['readingSummary'].get('notices', []), *summary_warnings])) 'finishReasons': list(accumulator.finish_reasons),
else: 'originalBodyCharacters': len(answer), 'originalBodyNonempty': bool(answer.strip()),
final['answer'] += '\n\n' + '\n'.join(dict.fromkeys(summary_warnings)) 'narrativeComplete': narrative_complete, 'dataComplete': data_complete,
if missing: 'narrativeFactBinding': 'not_assessed', 'citedEvidenceRefs': sorted(cited_refs),
final['answer'] += '\n\n尚未解决:' + ';'.join(missing) 'unresolvedEvidenceRefs': unresolved_refs, 'missingEvidence': missing,
if isinstance(final.get('readingSummary'), dict): 'visualWarnings': visual_warnings, 'notices': list(dict.fromkeys(summary_warnings))})
final['readingSummary']['notices'] = list(dict.fromkeys([
*final['readingSummary'].get('notices', []), *missing]))
result = {'type': 'result', 'engine': 'NAO', 'status': 'COMPLETED' if complete else 'PARTIAL', result = {'type': 'result', 'engine': 'NAO', 'status': 'COMPLETED' if complete else 'PARTIAL',
'answer': final['answer'], 'readingSummary': final.get('readingSummary'), 'answer': answer, 'readingSummary': None,
'reportTitle': final.get('reportTitle'), 'agentTask': task, 'protocol': identity, 'reportTitle': None, 'agentTask': task, 'protocol': identity,
'executionMode': 'native_agent', 'completionMethod': 'native_autonomous_analysis', 'executionMode': 'native_agent', 'completionMethod': 'native_autonomous_analysis',
'stopReason': 'evidence_finalized' if complete else 'evidence_incomplete', 'finishReason': 'stop', 'stopReason': 'evidence_finalized' if complete else 'evidence_incomplete',
'finishReason': ('stop' if narrative_complete else
str(accumulator.finish_reasons[-1]) if natural_finish and accumulator.finish_reasons else
'incomplete' if native_status == 'COMPLETED' else str(native_reason or native_status)),
'nativeStopReason': native_reason, 'nativeStopSucceeded': stop_succeeded, 'nativeStopReason': native_reason, 'nativeStopSucceeded': stop_succeeded,
'nativeFinishReason': 'stop' if natural_finish else native_reason, 'nativeFinishReason': 'stop' if natural_finish else native_reason,
'conclusionProtocolQueryIds': cited_ids, 'conclusionProtocolQueryIds': conclusion_ids,
'answerQuality': {'version': 1, 'dataComplete': data_complete,
'narrativeComplete': narrative_complete,
'chartsComplete': charts_complete,
'narrativeFactBinding': 'not_assessed',
'citedEvidenceRefs': sorted(cited_refs),
'backgroundEvidenceQueryIds': background_ids,
'unresolvedEvidenceRefs': unresolved_refs,
'missingEvidence': missing,
'notices': list(dict.fromkeys(summary_warnings))},
'actualModel': model, 'phaseTimingsMs': timings, 'actualModel': model, 'phaseTimingsMs': timings,
'protocolEvidence': receipts, 'queryEvidenceRefs': [doc['evidenceRef'] for doc in documents], 'protocolEvidence': receipts, 'queryEvidenceRefs': [doc['evidenceRef'] for doc in documents],
'queryEvidenceBindings': query_evidence_bindings(documents, receipts), 'queryEvidenceBindings': query_evidence_bindings(documents, receipts),
'toolCalls': accumulator.tool_calls, 'toolCount': len(accumulator.tool_calls), 'toolCalls': accumulator.tool_calls, 'toolCount': len(accumulator.tool_calls),
'timeline': accumulator.timeline, 'factsComplete': bool(documents and not missing), 'timeline': accumulator.timeline, 'factsComplete': None,
'evidenceCompletion': {'serverCoverageSufficient': not snapshot.get('rootGoalGaps'), 'evidenceCompletion': {'serverCoverageSufficient': not snapshot.get('rootGoalGaps'),
'missingEvidence': missing}, 'missingEvidence': missing},
'agentContext': {key: copy.deepcopy(task[key]) for key in 'agentContext': {key: copy.deepcopy(task[key]) for key in
+19
View File
@@ -1770,6 +1770,25 @@ def execute(*, request, task, authority, actor_root, delegated, connection, canc
return result return result
if cancel_event.is_set(): if cancel_event.is_set():
raise RuntimeError('cancelled') raise RuntimeError('cancelled')
if isinstance(task.get('directResponse'), dict):
from nao_quality_runtime import ConversationAccumulator, _atomic_json, _record_non_query_turn, public_progress_text
answer = task['directResponse']['answer']
conversation = ConversationAccumulator()
conversation.record_event('assistant', text=public_progress_text(answer))
_atomic_json(actor_root / 'private' / 'last-conversation-answer.json', {
'turnId': request['turnId'], 'goal': task['goal'],
'purpose': task['directResponse']['purpose'], 'answer': answer})
_record_non_query_turn(actor_root, request)
result = {'type': 'result', 'engine': 'NAO', 'status': 'COMPLETED', 'answer': answer,
'agentTask': task, 'protocol': identity, 'completionMethod': 'direct_conversation',
'agentContext': {key: value for key, value in context.items()
if key in ('releaseId', 'period', 'comparisonPeriod', 'filters')},
'toolCalls': [], 'timeline': conversation.timeline, 'protocolEvidence': [],
'queryEvidenceRefs': [], 'visualSchemaVersion': 1, 'visualState': 'not_requested',
'visuals': [], 'stopReason': 'direct_conversation', 'finishReason': 'stop',
'actualModel': connection[2], 'phaseTimingsMs': timings}
emit(result)
return result
if task.get('kind') == 'report': if task.get('kind') == 'report':
from nao_history_report import execute_history_report from nao_history_report import execute_history_report
return execute_history_report(request=request, task=task, authority=authority, return execute_history_report(request=request, task=task, authority=authority,
+30 -4
View File
@@ -763,6 +763,17 @@ class ConversationAccumulator:
return value return value
return "" return ""
@property
def final_answer_ready(self) -> bool:
if not self.answer or any(call.get('status') == 'started' for call in self.tool_calls):
return False
if not self.tool_calls:
return True
last_tool = max((i for i, entry in enumerate(self.timeline)
if entry.get('kind') in ('tool_start', 'tool_result')), default=-1)
return any(entry.get('kind') == 'assistant' and str(entry.get('text') or '').strip()
for entry in self.timeline[last_tool + 1:])
def status(self, *, cancel_cause: str | None = None, stop_succeeded: bool | None = None, def status(self, *, cancel_cause: str | None = None, stop_succeeded: bool | None = None,
transport_failed: bool = False) -> tuple[str, str | None]: transport_failed: bool = False) -> tuple[str, str | None]:
if cancel_cause == "user": if cancel_cause == "user":
@@ -781,18 +792,27 @@ class ConversationAccumulator:
return ("PARTIAL" if self.answer else "FAILED", "transport_or_stream_error") return ("PARTIAL" if self.answer else "FAILED", "transport_or_stream_error")
if self.tool_error and (self.unattributed_tool_error or any(call["status"] == "failed" and not call.get("recovered") for call in self.tool_calls)): if self.tool_error and (self.unattributed_tool_error or any(call["status"] == "failed" and not call.get("recovered") for call in self.tool_calls)):
return ("PARTIAL" if self.answer else "FAILED", "mcp_error") return ("PARTIAL" if self.answer else "FAILED", "mcp_error")
if self.answer and (self.done_received or "stop" in self.finish_reasons): if (self.final_answer_ready and self.finish_reasons[-1] == 'stop'
and stop_succeeded is not False):
return "COMPLETED", "stop" return "COMPLETED", "stop"
return ("PARTIAL" if self.answer else "FAILED", "incomplete") return ("PARTIAL" if self.answer else "FAILED", "incomplete")
def _contains_error_flag(value: Any) -> bool: def _contains_error_flag(value: Any) -> bool:
if isinstance(value, dict): if isinstance(value, dict):
if value.get("isError") is True or value.get("error"): if (any(value.get(flag) is True for flag in ('isError', 'mcpValidationError', 'mcpAuthRequired'))
or value.get('success') is False or value.get('error')):
return True return True
return any(_contains_error_flag(item) for item in value.values()) # Inspect only known response envelopes. Rows, source cells, notes and
# arbitrary JSON strings are business data, not nested tool outcomes.
content = value.get('content')
if isinstance(content, list) and any(isinstance(part, dict) and part.get('type') == 'text'
and _contains_error_flag(part.get('text')) for part in content):
return True
return _contains_error_flag(value['structuredContent']) if isinstance(value.get('structuredContent'), dict) else False
if isinstance(value, list): if isinstance(value, list):
return any(_contains_error_flag(item) for item in value) return any(isinstance(part, dict) and part.get('type') == 'text'
and _contains_error_flag(part.get('text')) for part in value)
if isinstance(value, str) and len(value) <= 64 * 1024: if isinstance(value, str) and len(value) <= 64 * 1024:
stripped = value.strip() stripped = value.strip()
if stripped.startswith(("{", "[")): if stripped.startswith(("{", "[")):
@@ -1922,6 +1942,10 @@ def _sse_request(
ready_state: dict[str, Any] = {"identity": None, "since": None} ready_state: dict[str, Any] = {"identity": None, "since": None}
def completion_ready() -> bool: def completion_ready() -> bool:
# The watchdog can observe a stale halted exploration state between a
# natural model finish and the stream's trailing [DONE] marker.
if accumulator.done_received or (accumulator.finish_reasons and accumulator.finish_reasons[-1] == 'stop'):
return False
if autonomous: if autonomous:
progress_path = actor_root / 'private' / 'native-exploration-state.json' progress_path = actor_root / 'private' / 'native-exploration-state.json'
if not _require_private_regular_file(progress_path): if not _require_private_regular_file(progress_path):
@@ -2630,6 +2654,7 @@ def _run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
from nao_protocol_execution import execute from nao_protocol_execution import execute
request['_autonomousAnswer'] = protocol.get('autonomousEnabled') is True request['_autonomousAnswer'] = protocol.get('autonomousEnabled') is True
if authority['task'].get('executionMode') == 'native_agent': if authority['task'].get('executionMode') == 'native_agent':
model_gate.native_agent = True
from nao_native_run import run_native_exploration from nao_native_run import run_native_exploration
return run_native_exploration(request=request, task=authority['task'], authority=authority, return run_native_exploration(request=request, task=authority['task'], authority=authority,
actor_root=actor_root, delegated=delegated, connection=selected_connection, actor_root=actor_root, delegated=delegated, connection=selected_connection,
@@ -3108,6 +3133,7 @@ def _run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
if model_gate is not None: if model_gate is not None:
try: try:
_atomic_json(actor_root/'private'/'last-model-audit.json',{'model':selected_model,'requests':model_gate.request_audit, _atomic_json(actor_root/'private'/'last-model-audit.json',{'model':selected_model,'requests':model_gate.request_audit,
'rejectedToolCalls':model_gate.rejected_tool_calls if isinstance(model_gate.rejected_tool_calls,int) else 0,
'rejectedStaleRequests':model_gate.rejected_stale_requests if isinstance(model_gate.rejected_stale_requests,int) else 0}) 'rejectedStaleRequests':model_gate.rejected_stale_requests if isinstance(model_gate.rejected_stale_requests,int) else 0})
except (OSError,TypeError,ValueError):pass except (OSError,TypeError,ValueError):pass
model_gate.close() model_gate.close()
+9 -3
View File
@@ -316,14 +316,18 @@ class AnalysisVisualsTest(unittest.TestCase):
def test_rate_drop_is_signed_and_converted_to_percentage_points(self): def test_rate_drop_is_signed_and_converted_to_percentage_points(self):
result = changes_result(sort="rate_drop", rows=[ result = changes_result(sort="rate_drop", rows=[
{"rank": 1, "key": "p-1", "label": "规格一", "rateDrop": -0.025}, {"rank": 1, "key": "p-1", "label": "规格一", "rateDrop": 0.025},
{"rank": 2, "key": "p-2", "label": "规格二", "rateDrop": 0.04}, {"rank": 2, "key": "p-2", "label": "规格二", "rateDrop": -0.04},
]) ])
chart = build_visuals([evidence(result)], "画图比较产品合格率降幅", "turn-03")["visuals"][0] chart = build_visuals([evidence(result)], "画图比较产品合格率降幅", "turn-03")["visuals"][0]
self.assertEqual(chart["metric"], "rate_drop_pp") self.assertEqual(chart["metric"], "rate_drop_pp")
self.assertEqual(chart["unit"], "pp") self.assertEqual(chart["unit"], "pp")
self.assertEqual(chart["series"][0]["values"], [-2.5, 4.0]) self.assertEqual(chart["series"][0]["values"], [-2.5, 4.0])
self.assertEqual([row["key"] for row in result["rows"]], ["p-1", "p-2"])
self.assertEqual([item["key"] for item in chart["categories"]], ["p-1", "p-2"])
self.assertIn("率降幅线索", chart["title"]) self.assertIn("率降幅线索", chart["title"])
self.assertIn("本期减比较期", chart["note"])
self.assertIn("仍按率降幅排序", chart["note"])
self.assertIn("未纳入投入规模", chart["note"]) self.assertIn("未纳入投入规模", chart["note"])
def test_broad_product_focus_omits_rate_only_ranking_chart(self): def test_broad_product_focus_omits_rate_only_ranking_chart(self):
@@ -377,7 +381,9 @@ class AnalysisVisualsTest(unittest.TestCase):
self.assertEqual(chart["requiredFields"], [ self.assertEqual(chart["requiredFields"], [
"black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight" "black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"
]) ])
self.assertEqual(chart["series"][0]["values"], [2.0, -1.0]) self.assertEqual(chart["series"][0]["values"], [-2.0, 1.0])
self.assertIn("负值为下降,正值为上升", chart["note"])
self.assertIn("本期减比较期", chart["note"])
def test_quality_top_uses_ranked_weights_and_never_share(self): def test_quality_top_uses_ranked_weights_and_never_share(self):
result = { result = {
+1 -1
View File
@@ -97,7 +97,7 @@ class MinimalQueryTests(unittest.TestCase):
context=bind_task({'releaseId':RELEASE},task)) context=bind_task({'releaseId':RELEASE},task))
self.assertEqual(visual['visualState'],'ready',visual) self.assertEqual(visual['visualState'],'ready',visual)
self.assertEqual(visual['visuals'][0]['metric'],'rate_drop_pp') self.assertEqual(visual['visuals'][0]['metric'],'rate_drop_pp')
self.assertEqual(visual['visuals'][0]['series'][0]['values'],[20.0]) self.assertEqual(visual['visuals'][0]['series'][0]['values'],[-20.0])
result['sort']='current_rate';task['changeQuery']['sort']='current_rate' result['sort']='current_rate';task['changeQuery']['sort']='current_rate'
visual=build_visuals([doc],task['question'],TURN, visual=build_visuals([doc],task['question'],TURN,
context=bind_task({'releaseId':RELEASE},task)) context=bind_task({'releaseId':RELEASE},task))
+36
View File
@@ -99,4 +99,40 @@ class ConversationTests(unittest.TestCase):
for sanitizer in (public_progress_text,public_thinking_text): for sanitizer in (public_progress_text,public_thinking_text):
output=sanitizer(text);self.assertNotIn('quality-turn:',output);self.assertIn('继续答复',output) output=sanitizer(text);self.assertNotIn('quality-turn:',output);self.assertIn('继续答复',output)
class AutonomousConversationReviewTests(unittest.TestCase):
def test_capability_descriptions_do_not_claim_to_have_run_a_query(self):
value=direct();value['directResponse']['answer']='我可以帮你比较不同产业部谁表现更好,并整理已核实的历史结果。'
self.assertEqual(normalize_task(value,'你能做什么')['directResponse']['answer'],value['directResponse']['answer'])
def test_unsupported_bare_explain_is_repaired_before_protocol_confirmation(self):
from test_nao_agent_task import task_value
replies=[task_value(kind='explain',freshQuery=False,fields=[],stages=[],dimensions=[],dimensionStages={}),direct(),{'aligned':True,'requiresEvidence':False}]
calls=[]
def opener(request,timeout):
calls.append(json.loads(request.data));reply=replies.pop(0)
return io.BytesIO(json.dumps({'choices':[{'finish_reason':'stop','message':{'content':json.dumps(reply)}}]}).encode())
task=plan_task(base_url='https://offline.invalid',api_key='synthetic',model='m',question='介绍一下能做哪些事',context={'_protocol':{'version':1,'autonomousEnabled':True}},cancel_event=threading.Event(),opener=opener)
self.assertIn('directResponse',task);self.assertEqual(len(calls),3);self.assertEqual(task['planRecovery']['errors'][0]['field'],'kind.protocol')
def test_autonomous_greeting_still_receives_independent_semantic_review(self):
bodies=[]
def opener(request,timeout):
bodies.append(json.loads(request.data));reply=direct() if len(bodies)==1 else {'aligned':True,'requiresEvidence':False}
return io.BytesIO(json.dumps({'choices':[{'finish_reason':'stop','message':{'content':json.dumps(reply)}}]}).encode())
task=plan_task(base_url='https://offline.invalid',api_key='synthetic',model='m',question='你好',context={'_protocol':{'version':1,'autonomousEnabled':True}},cancel_event=threading.Event(),opener=opener)
self.assertIn('directResponse',task);self.assertEqual(len(bodies),2);self.assertIn('plannedTask',json.loads(bodies[1]['messages'][1]['content']))
def test_autonomous_business_answer_mislabelled_as_conversation_cannot_skip_evidence_review(self):
calls=[]
def opener(request,timeout):
body=json.loads(request.data);calls.append(body)
if 'plannedTask' in json.loads(body['messages'][1]['content']):reply={'aligned':True,'requiresEvidence':True}
else:
reply=direct();reply['directResponse']['answer']='这批比之前差,得调整设备。'
return io.BytesIO(json.dumps({'choices':[{'finish_reason':'stop','message':{'content':json.dumps(reply)}}]}).encode())
with self.assertRaises(TaskUnavailable):plan_task(base_url='https://offline.invalid',api_key='synthetic',model='m',question='解释这批次质量问题',context={'_protocol':{'version':1,'autonomousEnabled':True}},cancel_event=threading.Event(),opener=opener)
self.assertTrue(any('plannedTask' in json.loads(body['messages'][1]['content']) for body in calls))
def test_unqueried_chinese_values_and_plain_causal_assertions_are_rejected(self):
for text in ['黑片合格率下降了,主要原因是设备故障。','上月报废重量为一百。']:
value=direct();value['directResponse']['answer']=text
with self.subTest(text=text),self.assertRaises(TaskUnavailable):normalize_task(value,'你好')
if __name__=='__main__':unittest.main() if __name__=='__main__':unittest.main()
+12 -2
View File
@@ -149,14 +149,24 @@ class EvidenceFinalizerTest(unittest.TestCase):
with self.assertRaises(finalizer.FinalizationUnavailable): with self.assertRaises(finalizer.FinalizationUnavailable):
finalizer.packed_evidence([{'unique': 'a'*finalizer.MAX_INPUT_CHARS}]) finalizer.packed_evidence([{'unique': 'a'*finalizer.MAX_INPUT_CHARS}])
def test_real_second_turn_replay_fits_and_preserves_every_summary_value(self): def test_real_second_turn_replay_preserves_every_value_and_obeys_current_input_budget(self):
root=Path(__file__).resolve().parents[1]/'output/20261023-autonomous-investigation/runtime' root=Path(__file__).resolve().parents[1]/'output/20261023-autonomous-investigation/runtime'
directories=list(root.glob('.runtime/nao-users/*/sessions/57676d5a-5138-48f4-9343-bae9731aae5a/evidence')) directories=list(root.glob('.runtime/nao-users/*/sessions/57676d5a-5138-48f4-9343-bae9731aae5a/evidence'))
if not directories: self.skipTest('Private captured acceptance evidence not present') if not directories: self.skipTest('Private captured acceptance evidence not present')
with patch.object(finalizer,'packed_evidence',side_effect=AssertionError('Local archives do not consume model input budget')): with patch.object(finalizer,'packed_evidence',side_effect=AssertionError('Local archives do not consume model input budget')):
docs=finalizer.evidence_summaries(directories[0],'194b0287-9044-4d80-9138-ecd3c481015c') docs=finalizer.evidence_summaries(directories[0],'194b0287-9044-4d80-9138-ecd3c481015c')
self.assertEqual(len(docs),15) self.assertEqual(len(docs),15)
self.assertEqual(unpack(finalizer.packed_evidence(docs)),docs) # Formal display metadata has grown since this private run was captured.
# Local archives remain lossless; a bounded model handoff may reject an
# oversized summary, but may never silently trim it to fit.
limit=finalizer.MAX_INPUT_CHARS
with patch.object(finalizer,'MAX_INPUT_CHARS',100_000_000):
packed=finalizer.packed_evidence(docs)
self.assertEqual(unpack(packed),docs)
encoded=json.dumps(packed,ensure_ascii=False,separators=(',',':'))
if len(encoded)>limit:
with self.assertRaises(finalizer.FinalizationUnavailable):finalizer.packed_evidence(docs)
else:self.assertEqual(unpack(finalizer.packed_evidence(docs)),docs)
# This captured run predates paired black/bright defect reads for each # This captured run predates paired black/bright defect reads for each
# highlighted product, so it is now correctly labelled incomplete. # highlighted product, so it is now correctly labelled incomplete.
self.assertFalse(finalizer.coverage_sufficient(docs,'分析质量变化')) self.assertFalse(finalizer.coverage_sufficient(docs,'分析质量变化'))
+65
View File
@@ -114,6 +114,71 @@ class ModelGateTests(unittest.TestCase):
self.assertNotIn('fake-sensitive-provider-details', body) self.assertNotIn('fake-sensitive-provider-details', body)
self.assertEqual(len(self.calls), 1) self.assertEqual(len(self.calls), 1)
def test_unadvertised_tool_calls_are_blocked_before_json_or_stream_execution(self):
from unittest.mock import Mock
data_tool={'type':'function','function':{'name':'mcp_call','parameters':{'type':'object'}}}
tool={'id':'call-blocked','type':'function','function':{'name':'clarification','arguments':'{}'}}
reply={'choices':[{'index':0,'message':{'role':'assistant','content':None,'tool_calls':[tool]},'finish_reason':'tool_calls'}]}
upstream=HeldOpenProviderResponse([json.dumps(reply).encode()]);upstream.headers={'Content-Type':'application/json'};upstream.release.set()
self.gate._opener=Mock();self.gate._opener.open.return_value=upstream
code,body=self.request(extra={'tools':[data_tool]})
self.assertEqual(code,502);self.assertNotIn('clarification',body)
for newline in (True,False):
prefix=b'data: {"choices":[{"index":0,"delta":{"content":"Preserved text"}}]}\n\n'
bad=('data: '+json.dumps({'choices':[{'index':0,'delta':{'tool_calls':[tool]},'finish_reason':'tool_calls'}]})+ ('\n\n' if newline else '')).encode()
upstream=HeldOpenProviderResponse([prefix,bad[:19],bad[19:]]);upstream.release.set()
self.gate._opener.open.return_value=upstream
code,body=self.request(extra={'stream':True,'tools':[data_tool]})
self.assertEqual(code,200);self.assertIn('Preserved text',body)
self.assertNotIn('clarification',body);self.assertIn('error',body)
def test_allowed_fragmented_tool_calls_keep_their_exact_wire_data(self):
from unittest.mock import Mock
rows=[{'choices':[{'index':0,'delta':{'tool_calls':[{'index':0,'id':'q','type':'function','function':{'name':'mcp_','arguments':''}}]}}]},
{'choices':[{'index':0,'delta':{'tool_calls':[{'index':0,'function':{'name':'call','arguments':'{}'}}]},'finish_reason':'tool_calls'}]}]
wire=b''.join(('data: '+json.dumps(row)+'\n\n').encode() for row in rows)+b'data: [DONE]\n\n'
upstream=HeldOpenProviderResponse([wire[:23],wire[23:71],wire[71:]]);upstream.release.set()
self.gate._opener=Mock();self.gate._opener.open.return_value=upstream
code,body=self.request(extra={'stream':True,'tools':[{'type':'function','function':{'name':'mcp_call'}}]})
self.assertEqual(code,200);self.assertEqual(body.encode(),wire)
def test_follow_up_tool_cannot_end_analysis_before_the_model_writes_an_answer(self):
data_tool = {'type': 'function', 'function': {'name': 'mcp_call', 'parameters': {'type': 'object'}}}
follow_up = {'type': 'function', 'function': {'name': 'suggest_follow_ups', 'parameters': {'type': 'object'}}}
for choice in ('auto', {'type': 'function', 'function': {'name': 'suggest_follow_ups'}}):
with self.subTest(choice=choice):
self.assertEqual(self.request(extra={'tools': [data_tool, follow_up], 'tool_choice': choice})[0], 200)
self.assertEqual(self.calls[-1]['tools'], [data_tool])
if isinstance(choice, dict):
self.assertNotIn('tool_choice', self.calls[-1])
self.assertEqual(self.request(extra={'tools': [follow_up], 'tool_choice': 'required'})[0], 200)
self.assertNotIn('tools', self.calls[-1])
self.assertNotIn('tool_choice', self.calls[-1])
def test_only_supported_tools_reach_the_native_model_in_each_execution_mode(self):
helpers = ['read', 'list', 'grep', 'search', 'mcp_call', 'mcp_connect']
incompatible = ['clarification', 'request_warehouse_selection', 'request_warehouse_credentials',
'execute_sql', 'execute_semantic_query', 'read_query_result', 'display_chart', 'display_map',
'write', 'str_replace', 'execute_python', 'execute_sandboxed_code', 'task',
'onboarding_command', 'onboarding_progress', 'generate_onboarding_rules',
'suggest_follow_ups', 'future_unknown_tool']
tools = [{'type': 'function', 'function': {'name': n, 'parameters': {'type': 'object'}}}
for n in helpers + ['story'] + incompatible]
for native in (False, True):
self.gate.native_agent = native
self.assertEqual(self.request(extra={'tools': tools})[0], 200)
self.assertEqual([t['function']['name'] for t in self.calls[-1]['tools']],
helpers + ([] if native else ['story']))
def test_forced_unavailable_tool_cannot_survive_even_without_a_tool_definition(self):
for extra in ({'tool_choice': {'type': 'function', 'function': {'name': 'clarification'}}},
{'tool_choice': {'type': 'function', 'function': 'malformed'}},
{'tools': [], 'tool_choice': 'required'},
{'tools': [{'type': 'function', 'function': {'name': 'read'}}],
'tool_choice': {'type': 'function', 'function': {'name': 'execute_sql'}}}):
self.assertEqual(self.request(extra=extra)[0], 200)
self.assertNotIn('tool_choice', self.calls[-1])
def test_previous_turn_background_call_cannot_enter_current_thinking_or_provider(self): def test_previous_turn_background_call_cannot_enter_current_thinking_or_provider(self):
marker='quality-turn:current-request' marker='quality-turn:current-request'
self.gate._native_turn_marker=marker self.gate._native_turn_marker=marker
+313
View File
@@ -0,0 +1,313 @@
"""Regression tests for the isolated native-agent original-body runtime copy."""
import copy
import importlib.util
import json
import os
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import Mock, patch
PROJECT = Path(__file__).resolve().parents[1]
RUNTIME_COPY = Path(os.environ.get('NAO_ORIGINAL_BODY_PATH',
str(PROJECT / 'scripts/nao_native_run.py'))).expanduser().resolve()
SPEC = importlib.util.spec_from_file_location('nao_native_run_original_body', RUNTIME_COPY)
NATIVE_RUN = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = NATIVE_RUN
SPEC.loader.exec_module(NATIVE_RUN)
IDENTITY = {'attemptId': 'attempt-current', 'sessionId': 'session-current',
'turnId': 'turn-current', 'revision': 3, 'executionId': 'execution-current'}
def proof(query_id='query-current'):
return {**IDENTITY, 'queryId': query_id, 'nodeId': 'root', 'scopeId': 'scope-root',
'responseHash': 'a' * 64}
def document(ref='Q00000001', evidence_proof=None):
return {'evidenceRef': ref, 'result': {'protocolEvidence': evidence_proof or proof()}}
def task():
return {'version': 1, 'goal': '解释下降并根据实际结果调查', 'question': '本期下降原因',
'executionMode': 'native_agent', 'kind': 'analysis',
'period': {'year': 2026, 'month': 9}, 'comparisonPeriod': {'year': 2026, 'month': 8},
'filters': {'department': '当前产业部'}, 'fields': ['rate'], 'stages': [],
'dimensions': [], 'dimensionStages': {}, 'visualPreference': 'auto',
'comparisonRequired': True, 'trendRequired': False,
'verifySource': False, 'fullDetails': False}
class NativeOriginalBodyTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.actor_root = Path(self.temp.name)
(self.actor_root / 'private').mkdir()
(self.actor_root / 'evidence').mkdir()
self.cancel_event = threading.Event()
self.task = task()
self.request = {'sessionId': IDENTITY['sessionId'], 'turnId': IDENTITY['turnId'],
'actorId': 'actor-current', 'releaseId': 'release-current',
'question': self.task['question'],
'context': {'_serverHistory': [], '_serverQuestions': [], '_protocol': {}}}
self.current_proof = proof()
self.documents = [document(evidence_proof=self.current_proof)]
self.snapshot = {'scopes': [{'nodeId': 'root', 'scopeId': 'scope-root', 'task': self.task}],
'queries': [{'proof': self.current_proof}],
'scopeCoverage': [{'nodeId': 'root', 'scopeId': 'scope-root', 'complete': True}],
'rootGoalGaps': [], 'gaps': [], 'pending': [], 'explorationWarnings': []}
self.accumulator = SimpleNamespace(answer='原始回答 [Q00000001]', finish_reasons=['stop'],
tool_calls=[{'tool': 'quality_data', 'status': 'completed', 'input': {'mode': 'compare'}}],
timeline=[{'kind': 'assistant', 'text': '原始回答'}])
self.native_status, self.native_reason, self.stop_succeeded = 'COMPLETED', 'stop', None
self.events = []
self.manager = Mock()
self.manager.ensure_instance.return_value = (None, None, 'fixture-model', 'http://native.invalid')
self.delegated = Mock()
self.delegated.call.side_effect = lambda *args, **kwargs: copy.deepcopy(self.snapshot)
self.synthetic_writer = Mock(side_effect=AssertionError('native original-body path must not synthesize text'))
quality_runtime = ModuleType('nao_quality_runtime')
quality_runtime._atomic_json = self.atomic_json
quality_runtime._authenticate = Mock(return_value=object())
quality_runtime._sse_request = self.native
quality_runtime._read_json = self.read_json
agent_task = ModuleType('nao_agent_task')
agent_task.bind_task = lambda seed, current_task: {**copy.deepcopy(current_task), **copy.deepcopy(seed)}
protocol_execution = ModuleType('nao_protocol_execution')
protocol_execution._identity = lambda authority: copy.deepcopy(IDENTITY)
protocol_execution._platform_visual_context = lambda visuals: {'visualState': visuals.get('visualState')}
protocol_execution.query_evidence_bindings = lambda docs, receipts: [
{'evidenceRef': item['evidenceRef'], 'proofs': item['result'].get('protocolEvidence')}
for item in docs]
evidence_finalizer = ModuleType('nao_evidence_finalizer')
evidence_finalizer.evidence_summaries = lambda *args, **kwargs: copy.deepcopy(self.documents)
evidence_finalizer.synthesize_native = self.synthetic_writer
visual_evidence = ModuleType('analysis_visual_evidence')
visual_evidence.protocol_visual_result = self.visual_result
runtime_policy = ModuleType('nao_runtime_policy')
runtime_policy.native_timeout = lambda: 30
native_exploration = ModuleType('nao_native_exploration')
native_exploration._proofs = lambda result: ([result['protocolEvidence']]
if isinstance(result, dict) and isinstance(result.get('protocolEvidence'), dict) else [])
self.modules = {'nao_quality_runtime': quality_runtime, 'nao_agent_task': agent_task,
'nao_protocol_execution': protocol_execution,
'nao_evidence_finalizer': evidence_finalizer,
'analysis_visual_evidence': visual_evidence,
'nao_runtime_policy': runtime_policy,
'nao_native_exploration': native_exploration}
self.module_patch = patch.dict(sys.modules, self.modules)
self.module_patch.start()
self.addCleanup(self.module_patch.stop)
def atomic_json(self, path, payload):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, ensure_ascii=False), encoding='utf-8')
@staticmethod
def read_json(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def native(self, **kwargs):
return self.accumulator, self.native_status, self.native_reason, self.stop_succeeded
def visual_result(self, documents, scopes, question, turn_id, **kwargs):
return {'visualState': 'ready', 'visuals': [{'id': 'formal-query-chart',
'evidenceRefs': [item['evidenceRef'] for item in documents]}], 'missingEvidence': []}
def invoke(self):
return NATIVE_RUN.run_native_exploration(request=copy.deepcopy(self.request),
task=copy.deepcopy(self.task), authority=copy.deepcopy(IDENTITY),
actor_root=self.actor_root, delegated=self.delegated,
connection=('https://model.invalid/v1', 'synthetic-fixture-key', 'fixture-model'),
manager=self.manager, state={}, cancel_event=self.cancel_event,
emit=self.events.append, prior_evidence_files={'prior-evidence.json'},
phase_timings={'planningAndReview': 10, 'taskConfirmation': 20})
def test_persists_the_complete_original_body_and_keeps_formal_charts(self):
body = '原生回答第一行\n' + ('原生正文' * 1800) + '\n[Q00000001]'
self.accumulator.answer = body
self.accumulator.timeline = [{'kind': 'assistant', 'text': 'x' * 8000}]
result = self.invoke()
self.assertEqual(result['status'], 'COMPLETED')
self.assertEqual(result['answer'], body)
self.assertIsNone(result['readingSummary'])
self.assertEqual(result['visuals'][0]['id'], 'formal-query-chart')
self.assertEqual(result['queryEvidenceRefs'], ['Q00000001'])
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current'])
self.assertEqual(result['answerQuality']['narrativeFactBinding'], 'not_assessed')
self.assertEqual(result['answerQuality']['backgroundEvidenceQueryIds'], [])
self.assertIsNone(result['factsComplete'])
self.assertEqual(self.read_json(self.actor_root / 'private/native-draft.json')['answer'], body)
self.assertEqual(self.read_json(self.actor_root / 'private/native-completion.json')['answer'], body)
self.assertEqual(self.read_json(self.actor_root / 'private/native-original-body-diagnostics.json')
['originalBodyCharacters'], len(body))
self.synthetic_writer.assert_not_called()
def test_empty_native_body_stays_empty_and_cannot_be_completed(self):
self.accumulator.answer = ''
result = self.invoke()
self.assertEqual(result['answer'], '')
self.assertEqual(result['status'], 'PARTIAL')
self.assertFalse(result['answerQuality']['narrativeComplete'])
self.assertIn('自主分析未生成正文。', result['answerQuality']['missingEvidence'])
self.synthetic_writer.assert_not_called()
def test_missing_formal_evidence_is_metadata_and_does_not_rewrite_the_body(self):
self.documents = []
body = '原始正文照常保留。'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['answer'], body)
self.assertEqual(result['status'], 'PARTIAL')
self.assertFalse(result['answerQuality']['dataComplete'])
self.assertIn('本轮未取得当前执行的可核验查询证据。', result['answerQuality']['missingEvidence'])
self.assertNotIn('尚未解决', result['answer'])
self.synthetic_writer.assert_not_called()
def test_partial_or_interrupted_generation_is_not_rewritten_or_marked_complete(self):
self.native_status, self.native_reason = 'PARTIAL', 'length'
self.accumulator.finish_reasons = ['length']
body = '模型已输出的局限与正文。'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['answer'], body)
self.assertEqual(result['status'], 'PARTIAL')
self.assertFalse(result['answerQuality']['narrativeComplete'])
self.assertEqual(result['finishReason'], 'length')
self.synthetic_writer.assert_not_called()
def test_completed_status_without_natural_stop_remains_partial(self):
body = '原生回答保留,结束信号不足。'
self.accumulator.answer = body
cases = (
('missing_stop_finish_reason', [], None),
('stop_control_failed', ['stop'], False),
)
for label, finish_reasons, stop_succeeded in cases:
with self.subTest(label=label):
self.accumulator.finish_reasons = finish_reasons
self.stop_succeeded = stop_succeeded
result = self.invoke()
self.assertEqual(result['answer'], body)
self.assertEqual(result['status'], 'PARTIAL')
self.assertFalse(result['answerQuality']['narrativeComplete'])
self.assertEqual(result['finishReason'], 'incomplete')
self.assertIn('自主调查未收到有效的正常结束信号。',
result['answerQuality']['missingEvidence'])
self.synthetic_writer.assert_not_called()
def test_recovered_tool_error_keeps_natural_stop_completion_without_fact_binding(self):
self.native_status, self.native_reason = 'PARTIAL', 'mcp_error'
body = '原生回答保留自己的局限。'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['status'], 'COMPLETED')
self.assertEqual(result['answer'], body)
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current'])
self.assertEqual(result['answerQuality']['backgroundEvidenceQueryIds'], ['query-current'])
self.assertTrue(result['answerQuality']['narrativeComplete'])
self.assertEqual(result['answerQuality']['narrativeFactBinding'], 'not_assessed')
self.assertIsNone(result['factsComplete'])
self.synthetic_writer.assert_not_called()
def test_no_explicit_refs_cannot_use_docs_without_verified_complete_scope_receipts(self):
self.snapshot['scopeCoverage'] = None
body = '正常原生正文不写证据编号。'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['answer'], body)
self.assertEqual(result['status'], 'PARTIAL')
self.assertEqual(result['conclusionProtocolQueryIds'], [])
self.assertEqual(result['answerQuality']['backgroundEvidenceQueryIds'], [])
self.assertFalse(result['answerQuality']['dataComplete'])
self.assertIn('本轮没有可关联的完整scope正式查询证明。',
result['answerQuality']['missingEvidence'])
self.synthetic_writer.assert_not_called()
def test_unbound_original_citation_is_a_gap_without_rewriting_the_body(self):
body = '原生回答里保留未绑定的引用。[QABCDEF99]'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['status'], 'PARTIAL')
self.assertEqual(result['answer'], body)
self.assertFalse(result['answerQuality']['dataComplete'])
self.assertEqual(result['answerQuality']['unresolvedEvidenceRefs'], ['QABCDEF99'])
self.assertIn('原文引用未关联本轮完整scope正式查询证据:QABCDEF99。',
result['answerQuality']['missingEvidence'])
self.assertNotIn('QABCDEF99', result['conclusionProtocolQueryIds'])
self.synthetic_writer.assert_not_called()
def test_explicit_hexadecimal_query_reference_maps_only_its_receipt(self):
hex_proof = proof('query-hex')
self.snapshot['queries'].append({'proof': hex_proof})
self.documents.append(document('QABCDEF12', hex_proof))
body = '原文引用正式查询[QABCDEF12]。'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['status'], 'COMPLETED')
self.assertEqual(result['answer'], body)
self.assertEqual(result['answerQuality']['citedEvidenceRefs'], ['QABCDEF12'])
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-hex'])
self.synthetic_writer.assert_not_called()
def test_cancelled_turn_remains_cancelled_and_does_not_read_or_synthesize(self):
for cancellation in ('event', 'native_status'):
with self.subTest(cancellation=cancellation):
self.cancel_event.clear()
self.native_status, self.native_reason = 'COMPLETED', 'stop'
if cancellation == 'event':
self.cancel_event.set()
else:
self.native_status = 'CANCELLED'
self.accumulator.answer = '中断前的草稿'
result = self.invoke()
self.assertEqual(result['status'], 'CANCELLED')
self.assertEqual(result['answer'], '')
self.delegated.call.assert_not_called()
self.synthetic_writer.assert_not_called()
def test_server_coverage_gap_keeps_body_and_prevents_completed_status(self):
self.snapshot['rootGoalGaps'] = ['亮片必答阶段尚无完整两期依据。']
body = '原生结论及其局限。'
self.accumulator.answer = body
result = self.invoke()
self.assertEqual(result['answer'], body)
self.assertEqual(result['status'], 'PARTIAL')
self.assertFalse(result['answerQuality']['dataComplete'])
self.assertIn('亮片必答阶段尚无完整两期依据。', result['answerQuality']['missingEvidence'])
self.synthetic_writer.assert_not_called()
if __name__ == '__main__':
unittest.main()
+69
View File
@@ -216,6 +216,53 @@ class RuntimeStreamTests(unittest.TestCase):
truncated.feed({"type": "finish", "finishReason": "length"}) truncated.feed({"type": "finish", "finishReason": "length"})
self.assertEqual(truncated.status(), ("PARTIAL", "length")) self.assertEqual(truncated.status(), ("PARTIAL", "length"))
def test_tool_errors_are_read_from_envelopes_not_business_data_cells(self):
for flag in ('mcpValidationError','mcpAuthRequired'):
stream=runtime.ConversationAccumulator()
stream.feed({'type':'tool-input-available','toolName':'mcp_call','toolCallId':'q'})
stream.feed({'type':'tool-output-available','toolCallId':'q','output':{flag:True,'server':'quality'}})
stream.feed({'type':'text-delta','id':'final','delta':'尚未查到数据。'})
stream.feed({'type':'finish','finishReason':'stop'})
self.assertEqual(stream.tool_calls[0]['status'],'failed')
self.assertEqual(stream.status(),('PARTIAL','mcp_error'))
payload={'kind':'quality_records','rows':[{'error':'缺角','isError':True}], 'note':'{"error":"原始单元格内容"}'}
stream=runtime.ConversationAccumulator()
stream.feed({'type':'tool-input-available','toolName':'mcp_call','toolCallId':'q'})
stream.feed({'type':'tool-output-available','toolCallId':'q','output':{'content':[{'type':'text','text':json.dumps(payload)}]}})
stream.feed({'type':'text-delta','id':'final','delta':'已查询并保留原始字段。'})
stream.feed({'type':'finish','finishReason':'stop'})
self.assertEqual(stream.tool_calls[0]['status'],'completed')
self.assertEqual(stream.status(),('COMPLETED','stop'))
def test_transport_done_is_not_a_normal_model_finish(self):
stream = runtime.ConversationAccumulator()
stream.feed({'type': 'text-delta', 'id': 'progress', 'delta': '先查一下。'})
stream.feed({'type': 'tool-input-available', 'toolName': 'mcp_call', 'toolCallId': 'q'})
stream.feed({'type': 'tool-output-available', 'toolCallId': 'q', 'output': {}})
stream.feed({'type': 'finish', 'finishReason': 'tool-calls'})
stream.feed({'type': '[DONE]'})
self.assertNotEqual(stream.status()[0], 'COMPLETED')
self.assertEqual(stream.answer, '先查一下。')
def test_progress_before_a_tool_or_unsettled_tool_cannot_count_as_final_answer(self):
for settled in (False, True):
stream = runtime.ConversationAccumulator()
stream.feed({'type': 'text-delta', 'id': 'progress', 'delta': '正在查询。'})
stream.feed({'type': 'tool-input-available', 'toolName': 'mcp_call', 'toolCallId': 'q'})
if settled:stream.feed({'type': 'tool-output-available', 'toolCallId': 'q', 'output': {}})
stream.feed({'type': 'finish', 'finishReason': 'stop'})
self.assertNotEqual(stream.status()[0], 'COMPLETED')
stream.feed({'type': 'text-delta', 'id': 'final', 'delta': '已核实的最终回答。'})
self.assertEqual(stream.status()[0], 'COMPLETED' if settled else 'PARTIAL')
def test_only_the_terminal_finish_and_successful_stop_control_can_complete(self):
for reasons, stopped in ((['stop', 'tool-calls'], None), (['stop'], False)):
stream = runtime.ConversationAccumulator()
stream.feed({'type': 'text-delta', 'id': 'answer', 'delta': '保留原文'})
for reason in reasons:stream.feed({'type': 'finish', 'finishReason': reason})
stream.feed({'type': '[DONE]'})
self.assertNotEqual(stream.status(stop_succeeded=stopped)[0], 'COMPLETED')
def test_native_stop_controller_stops_before_closing_stream_on_cancel(self): def test_native_stop_controller_stops_before_closing_stream_on_cancel(self):
calls = [] calls = []
response = FakeResponse() response = FakeResponse()
@@ -306,6 +353,28 @@ class RuntimeStreamTests(unittest.TestCase):
self.assertEqual(result[2], "transport_or_stream_error") self.assertEqual(result[2], "transport_or_stream_error")
native_stop.assert_called_once_with(unittest.mock.ANY, "http://127.0.0.1:10000", "existing-native-id") native_stop.assert_called_once_with(unittest.mock.ANY, "http://127.0.0.1:10000", "existing-native-id")
def test_an_already_finished_native_reply_cannot_be_cancelled_by_stale_no_progress_state(self):
controls=[];ready=[];controller=runtime.NativeStopController
def capture(*args):
value=controller(*args);controls.append(value);return value
class Response:
def __enter__(self):return self
def __exit__(self,*_):pass
def close(self):pass
def __iter__(self):
yield b'data: {"type":"text-delta","id":"final","delta":"final reply"}\n'
yield b'data: {"type":"finish","finishReason":"stop"}\n'
ready.append(controls[0].completion_ready())
yield b'data: [DONE]\n'
with tempfile.TemporaryDirectory() as temp:
root=Path(temp)/str(uuid.uuid4());root.mkdir();actor=root.name;sid=str(uuid.uuid4())
runtime._atomic_json(root/'private/native-exploration-state.json',{'executionId':'e','halted':True})
client=unittest.mock.Mock();client.open.return_value=Response()
with patch.object(runtime,'NativeStopController',side_effect=capture),patch('nao_agent_task.task_from_context',return_value={'executionMode':'native_agent','freshQuery':True}):
result=runtime._sse_request(client=client,base_url='http://native.invalid',model='fixture',question='q',release_id=str(uuid.uuid4()),
context={'_nativeExecutionId':'e'},chat_id='chat',session_state=runtime.SessionState(root,actor),session_id=sid,actor_root=root,emit=lambda _:None,timeout=5)
self.assertEqual(ready,[False]);self.assertEqual(result[1],'COMPLETED')
def test_story_export_uses_last_successful_call_and_matching_markdown(self): def test_story_export_uses_last_successful_call_and_matching_markdown(self):
class StoryClient: class StoryClient:
def __init__(self): def __init__(self):
+89 -51
View File
@@ -1,6 +1,8 @@
"""Exercise the native runner with isolated files and mocked upstream/bridge calls.""" """Exercise the native runner with isolated files and mocked upstream/bridge calls."""
import copy import copy
import importlib.util
import json import json
import os
import sys import sys
import tempfile import tempfile
import threading import threading
@@ -10,8 +12,15 @@ from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'scripts')] PROJECT = Path(__file__).resolve().parents[1]
from nao_native_run import run_native_exploration sys.path[:0] = [str(PROJECT / 'scripts')]
RUNTIME_PATH = Path(os.environ.get('NAO_ORIGINAL_BODY_PATH',
str(PROJECT / 'scripts/nao_native_run.py'))).expanduser().resolve()
RUNTIME_SPEC = importlib.util.spec_from_file_location('nao_native_run_integration', RUNTIME_PATH)
RUNTIME_MODULE = importlib.util.module_from_spec(RUNTIME_SPEC)
sys.modules[RUNTIME_SPEC.name] = RUNTIME_MODULE
RUNTIME_SPEC.loader.exec_module(RUNTIME_MODULE)
run_native_exploration = RUNTIME_MODULE.run_native_exploration
from nao_quality_runtime import _atomic_json from nao_quality_runtime import _atomic_json
@@ -43,6 +52,18 @@ def document(ref, *proofs):
class NativeRunTests(unittest.TestCase): class NativeRunTests(unittest.TestCase):
def test_pretool_progress_cannot_be_promoted_by_a_stop_finish(self):
from nao_quality_runtime import ConversationAccumulator
self.accumulator=ConversationAccumulator()
for event in ({'type':'text-delta','id':'progress','delta':'正在查询。'},
{'type':'tool-input-available','toolName':'mcp_call','toolCallId':'q'},
{'type':'tool-output-available','toolCallId':'q','output':{}},
{'type':'finish','finishReason':'stop'}):self.accumulator.feed(event)
result=self.invoke()
self.assertEqual(result['status'],'PARTIAL')
self.assertFalse(result['answerQuality']['narrativeComplete'])
self.assertEqual(result['answer'],'正在查询。')
def test_optional_scope_notice_is_shown_once_without_internal_visual_diagnostics(self): def test_optional_scope_notice_is_shown_once_without_internal_visual_diagnostics(self):
child = {**self.task, 'stages': ['bright']} child = {**self.task, 'stages': ['bright']}
self.snapshot['scopes'].append({'nodeId': 'bright-detail', 'scopeId': 'bright-detail', self.snapshot['scopes'].append({'nodeId': 'bright-detail', 'scopeId': 'bright-detail',
@@ -54,31 +75,25 @@ class NativeRunTests(unittest.TestCase):
'missingEvidence': ['节点bright-detail范围基础范围缺少bright来源具体缺陷重量图。']} 'missingEvidence': ['节点bright-detail范围基础范围缺少bright来源具体缺陷重量图。']}
result = self.invoke() result = self.invoke()
self.assertEqual(result['status'], 'COMPLETED') self.assertEqual(result['status'], 'COMPLETED')
self.assertEqual(result['readingSummary']['notices'], self.assertEqual(result['answerQuality']['notices'],
['亮片细分缺陷尚未完整核实:当前范围;未用于已核实结论。']) ['亮片细分缺陷尚未完整核实:当前范围;未用于已核实结论。'])
self.assertNotIn('调查局限', result['answer']) self.assertNotIn('调查局限', result['answer'])
self.assertNotIn('bright', result['answer']) self.assertNotIn('bright', result['answer'])
stored = json.loads((self.actor_root / 'private/native-warning-diagnostics.json').read_text()) stored = json.loads((self.actor_root / 'private/native-warning-diagnostics.json').read_text())
self.assertIn('bright', stored['visualWarnings'][0]) self.assertIn('bright', stored['visualWarnings'][0])
def test_full_facts_remain_private_instead_of_being_appended_to_the_business_answer(self): def test_original_answer_is_not_replaced_by_a_generated_report(self):
self.final['fullEvidenceFacts'] = [{'text': '后台保留的完整统计事实', 'evidenceRef': 'Q00000001'}] self.accumulator.answer = '原生回答原样保留,局限也照原文保留。'
result = self.invoke() result = self.invoke()
self.assertNotIn('完整统计依据', result['answer']) self.assertEqual(result['answer'], self.accumulator.answer)
self.assertNotIn('后台保留的完整统计事实', result['answer']) self.assertIsNone(result['readingSummary'])
stored = json.loads((self.actor_root / 'private/native-full-evidence-facts.json').read_text()) self.synthesis.assert_not_called()
self.assertEqual(stored, self.final['fullEvidenceFacts'])
def test_issued_binding_catalog_remains_private_for_exact_replay(self): def test_no_second_composition_artifact_is_written(self):
issued = {'bindingInventory': {'N17': {'factId': 'F2', 'value': '493.9966', 'unit': 'kg'}},
'facts': [{'id': 'F2', 'rawValue': '493.99660000'}]}
self.final['_privateBindingInput'] = issued
result = self.invoke() result = self.invoke()
stored = json.loads((self.actor_root / 'private/native-composition.json').read_text()) self.assertEqual(result['answer'], self.accumulator.answer)
self.assertEqual(stored['bindingInput'], issued) self.assertFalse((self.actor_root / 'private/native-composition.json').exists())
self.assertNotIn('_privateBindingInput', result) self.synthesis.assert_not_called()
self.assertNotIn('bindingInput', result)
self.assertNotIn('bindingInventory', json.dumps(self.events, ensure_ascii=False))
def setUp(self): def setUp(self):
self.folder = tempfile.TemporaryDirectory() self.folder = tempfile.TemporaryDirectory()
@@ -105,11 +120,6 @@ class NativeRunTests(unittest.TestCase):
'scopeCoverage': [{'nodeId': 'root', 'scopeId': 'scope-root', 'complete': True}, 'scopeCoverage': [{'nodeId': 'root', 'scopeId': 'scope-root', 'complete': True},
{'nodeId': 'group', 'scopeId': 'scope-group', 'complete': True}], {'nodeId': 'group', 'scopeId': 'scope-group', 'complete': True}],
'rootGoalGaps': [], 'gaps': [], 'pending': [], 'explorationWarnings': []} 'rootGoalGaps': [], 'gaps': [], 'pending': [], 'explorationWarnings': []}
self.final = {'answer': '按已核实结果解释[Q00000001]', 'reportTitle': '质量数据分析',
'readingSummary': {'version': 1, 'lead': '已核实解释[Q00000001]',
'evidence': [], 'notices': [], 'evidenceRefs': ['Q00000001']},
'usedEvidenceRefs': ['Q00000001'], 'evidenceSufficient': True,
'missingEvidence': [], 'rawModelResponses': [], 'compositionDiagnostics': {}}
self.accumulator = SimpleNamespace(answer='原生草稿', finish_reasons=['stop'], self.accumulator = SimpleNamespace(answer='原生草稿', finish_reasons=['stop'],
tool_calls=[{'tool': 'quality_data', 'status': 'failed', 'input': {'mode': 'compare'}}, tool_calls=[{'tool': 'quality_data', 'status': 'failed', 'input': {'mode': 'compare'}},
{'tool': 'quality_data', 'status': 'completed', 'input': {'mode': 'compare'}}], {'tool': 'quality_data', 'status': 'completed', 'input': {'mode': 'compare'}}],
@@ -127,7 +137,7 @@ class NativeRunTests(unittest.TestCase):
self.read_evidence = stack.enter_context(patch('nao_evidence_finalizer.evidence_summaries', self.read_evidence = stack.enter_context(patch('nao_evidence_finalizer.evidence_summaries',
side_effect=lambda *args, **kwargs: copy.deepcopy(self.documents))) side_effect=lambda *args, **kwargs: copy.deepcopy(self.documents)))
self.synthesis = stack.enter_context(patch('nao_evidence_finalizer.synthesize_native', self.synthesis = stack.enter_context(patch('nao_evidence_finalizer.synthesize_native',
side_effect=lambda **kwargs: copy.deepcopy(self.final))) side_effect=AssertionError('native-agent original body must not be synthesized')))
self.visuals = stack.enter_context(patch('analysis_visual_evidence.protocol_visual_result', self.visuals = stack.enter_context(patch('analysis_visual_evidence.protocol_visual_result',
return_value={'visualState': 'not_requested', 'visuals': [], 'missingEvidence': []})) return_value={'visualState': 'not_requested', 'visuals': [], 'missingEvidence': []}))
stack.enter_context(patch('nao_runtime_policy.native_timeout', return_value=30)) stack.enter_context(patch('nao_runtime_policy.native_timeout', return_value=30))
@@ -161,8 +171,12 @@ class NativeRunTests(unittest.TestCase):
self.assertTrue(result['evidenceCompletion']['serverCoverageSufficient']) self.assertTrue(result['evidenceCompletion']['serverCoverageSufficient'])
self.assertEqual(result['timeline'], self.accumulator.timeline) self.assertEqual(result['timeline'], self.accumulator.timeline)
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current', 'query-compare']) self.assertEqual(result['conclusionProtocolQueryIds'],
self.assertIn(self.snapshot['explorationWarnings'][0], result['readingSummary']['notices']) ['query-current', 'query-compare', 'query-group'])
self.assertEqual(result['answerQuality']['citedEvidenceRefs'], [])
self.assertEqual(result['answerQuality']['narrativeFactBinding'], 'not_assessed')
self.assertIn(self.snapshot['explorationWarnings'][0], result['answerQuality']['notices'])
self.assertEqual(result['answer'], self.accumulator.answer)
self.assertIn('firstUsefulMs', result['phaseTimingsMs']) self.assertIn('firstUsefulMs', result['phaseTimingsMs'])
self.assertGreaterEqual(result['phaseTimingsMs']['firstUsefulMs'], 30) self.assertGreaterEqual(result['phaseTimingsMs']['firstUsefulMs'], 30)
self.delegated.call.assert_called_once_with('/api/analysis/protocol/queries', payload={}, method='POST') self.delegated.call.assert_called_once_with('/api/analysis/protocol/queries', payload={}, method='POST')
@@ -172,35 +186,33 @@ class NativeRunTests(unittest.TestCase):
self.assertIsNone(self.sse.call_args.kwargs['chat_id']) self.assertIsNone(self.sse.call_args.kwargs['chat_id'])
stored = json.loads((self.actor_root / 'private/native-completion.json').read_text()) stored = json.loads((self.actor_root / 'private/native-completion.json').read_text())
self.assertEqual(stored['status'], 'COMPLETED') self.assertEqual(stored['status'], 'COMPLETED')
self.assertEqual(stored['answer'], self.accumulator.answer)
self.assertEqual(self.events[-1], result) self.assertEqual(self.events[-1], result)
def test_generated_chart_contract_is_available_before_the_single_synthesis(self): def test_generated_chart_contract_uses_formal_query_evidence_without_rewriting_answer(self):
self.task['visualPreference']='required' self.task['visualPreference']='required'
self.visuals.return_value={'visualState':'ready','missingEvidence':[], 'visuals':[{ self.visuals.return_value={'visualState':'ready','missingEvidence':[], 'visuals':[{
'id':'actual-chart','type':'line','metric':'composite_rate','title':'正式趋势', 'id':'actual-chart','type':'line','metric':'composite_rate','title':'正式趋势',
'scope':{'department':'当前产业部'},'period':{'year':2026,'month':9}, 'scope':{'department':'当前产业部'},'period':{'year':2026,'month':9},
'categories':[{'key':'2026-09'}],'series':[{'values':[.95]}], 'categories':[{'key':'2026-09'}],'series':[{'values':[.95]}],
'evidenceRefs':['Q00000001']}]} 'evidenceRefs':['Q00000001']}]}
def synthesize(**kwargs):
preview=kwargs['context']['_platformVisuals']
self.assertEqual(preview['visualState'],'ready')
self.assertEqual(preview['charts'][0]['id'],'actual-chart')
self.assertEqual(preview['charts'][0]['evidenceRefs'],['Q00000001'])
self.assertEqual(preview['charts'][0]['pointCount'],1)
self.assertNotIn('series',preview['charts'][0])
return copy.deepcopy(self.final)
self.synthesis.side_effect=synthesize
result=self.invoke() result=self.invoke()
self.assertEqual(result['status'],'COMPLETED') self.assertEqual(result['status'],'COMPLETED')
self.visuals.assert_called_once();self.synthesis.assert_called_once() self.visuals.assert_called_once()
self.assertEqual(self.visuals.call_args.args[0], self.documents)
self.assertEqual(result['visuals'][0]['id'], 'actual-chart')
self.assertEqual(result['visuals'][0]['evidenceRefs'], ['Q00000001'])
self.assertEqual(result['answer'], self.accumulator.answer)
self.synthesis.assert_not_called()
def test_root_gap_remains_partial_even_with_stop_and_available_evidence(self): def test_root_gap_remains_partial_even_with_stop_and_available_evidence(self):
self.snapshot['rootGoalGaps'] = ['亮片必答阶段尚无完整两期依据。'] self.snapshot['rootGoalGaps'] = ['亮片必答阶段尚无完整两期依据。']
result = self.invoke() result = self.invoke()
self.assertEqual(result['status'], 'PARTIAL') self.assertEqual(result['status'], 'PARTIAL')
self.assertFalse(result['evidenceCompletion']['serverCoverageSufficient']) self.assertFalse(result['evidenceCompletion']['serverCoverageSufficient'])
self.assertIn(self.snapshot['rootGoalGaps'][0], result['answer']) self.assertEqual(result['answer'], self.accumulator.answer)
self.assertIn(self.snapshot['rootGoalGaps'][0], result['readingSummary']['notices']) self.assertIn(self.snapshot['rootGoalGaps'][0], result['evidenceCompletion']['missingEvidence'])
self.assertIn(self.snapshot['rootGoalGaps'][0], result['answerQuality']['missingEvidence'])
def test_three_no_progress_attempts_remain_partial_after_natural_stop(self): def test_three_no_progress_attempts_remain_partial_after_natural_stop(self):
_atomic_json(self.actor_root / 'private/native-exploration-state.json', _atomic_json(self.actor_root / 'private/native-exploration-state.json',
@@ -210,7 +222,8 @@ class NativeRunTests(unittest.TestCase):
self.assertEqual(result['status'], 'PARTIAL') self.assertEqual(result['status'], 'PARTIAL')
self.assertTrue(any('连续三次' in gap for gap in result['evidenceCompletion']['missingEvidence'])) self.assertTrue(any('连续三次' in gap for gap in result['evidenceCompletion']['missingEvidence']))
self.assertEqual(result['phaseTimingsMs']['formalQuery'], 1234) self.assertEqual(result['phaseTimingsMs']['formalQuery'], 1234)
self.assertTrue(any('连续三次' in notice for notice in result['readingSummary']['notices'])) self.assertTrue(any('连续三次' in gap for gap in result['answerQuality']['missingEvidence']))
self.assertEqual(result['answer'], self.accumulator.answer)
def test_controlled_no_progress_stop_does_not_add_generic_tool_failure(self): def test_controlled_no_progress_stop_does_not_add_generic_tool_failure(self):
_atomic_json(self.actor_root / 'private/native-exploration-state.json', _atomic_json(self.actor_root / 'private/native-exploration-state.json',
@@ -233,7 +246,7 @@ class NativeRunTests(unittest.TestCase):
self.assertEqual(result['status'], 'PARTIAL') self.assertEqual(result['status'], 'PARTIAL')
self.assertTrue(any('未正常结束' in gap for gap in result['evidenceCompletion']['missingEvidence'])) self.assertTrue(any('未正常结束' in gap for gap in result['evidenceCompletion']['missingEvidence']))
def test_only_complete_current_scope_documents_reach_synthesis(self): def test_only_complete_current_scope_documents_reach_visual_generation_and_result(self):
self.snapshot['queries'].extend([{'proof': self.p_failed}, {'proof': self.p_old}]) self.snapshot['queries'].extend([{'proof': self.p_failed}, {'proof': self.p_old}])
self.snapshot['scopeCoverage'].append( self.snapshot['scopeCoverage'].append(
{'nodeId': 'failed', 'scopeId': 'scope-failed', 'complete': False}) {'nodeId': 'failed', 'scopeId': 'scope-failed', 'complete': False})
@@ -245,27 +258,52 @@ class NativeRunTests(unittest.TestCase):
{'evidenceRef': 'Q00000007', 'result': {'summary': {'unproved': True}}}, {'evidenceRef': 'Q00000007', 'result': {'summary': {'unproved': True}}},
]) ])
result = self.invoke() result = self.invoke()
admitted = self.synthesis.call_args.kwargs['evidence'] admitted = self.visuals.call_args.args[0]
self.assertEqual([doc['evidenceRef'] for doc in admitted], ['Q00000001', 'Q00000002']) self.assertEqual([doc['evidenceRef'] for doc in admitted], ['Q00000001', 'Q00000002'])
self.assertEqual(result['queryEvidenceRefs'], ['Q00000001', 'Q00000002']) self.assertEqual(result['queryEvidenceRefs'], ['Q00000001', 'Q00000002'])
self.assertEqual(result['conclusionProtocolQueryIds'],
['query-current', 'query-compare', 'query-group'])
self.assertNotIn('query-failed', result['conclusionProtocolQueryIds'])
self.assertNotIn('query-old', result['conclusionProtocolQueryIds'])
self.assertNotIn('query-not-in-current-receipts', result['conclusionProtocolQueryIds'])
self.assertEqual(result['answer'], self.accumulator.answer)
self.read_evidence.assert_called_once_with(self.actor_root / 'evidence', RELEASE, self.read_evidence.assert_called_once_with(self.actor_root / 'evidence', RELEASE,
exclude_files={'prior-evidence.json'}, allow_empty=True) exclude_files={'prior-evidence.json'}, allow_empty=True)
self.synthesis.assert_not_called()
def test_used_refs_map_only_to_actual_current_proofs_not_unused_or_foreign_documents(self): def test_original_citations_map_only_to_actual_current_query_proofs(self):
self.snapshot['queries'].append({'proof': self.p_old}) self.snapshot['queries'].append({'proof': self.p_old})
self.documents.append(document('Q00000003', self.p_old)) self.documents.append(document('Q00000003', self.p_old))
self.final['usedEvidenceRefs'] = ['Q00000001', 'Q00000003', 'QDEADBEEF', 'Q00000001'] self.accumulator.answer = '原文引用当前证据[Q00000001],以及外部证据[Q00000003]。'
result = self.invoke() result = self.invoke()
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current', 'query-compare']) self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current', 'query-compare'])
self.assertEqual(result['answer'], self.accumulator.answer)
self.assertEqual(result['answerQuality']['unresolvedEvidenceRefs'], ['Q00000003'])
self.assertEqual(result['status'], 'PARTIAL')
self.assertNotIn('query-group', result['conclusionProtocolQueryIds']) self.assertNotIn('query-group', result['conclusionProtocolQueryIds'])
self.assertNotIn('query-old', result['conclusionProtocolQueryIds']) self.assertNotIn('query-old', result['conclusionProtocolQueryIds'])
def test_claimed_sufficient_answer_without_current_cited_proof_remains_partial(self): def test_uppercase_hexadecimal_reference_maps_to_its_actual_receipt(self):
self.final['usedEvidenceRefs'] = ['QDEADBEEF'] hexadecimal = proof('query-hexadecimal')
self.snapshot['queries'].append({'proof': hexadecimal})
self.documents.append(document('QABCDEF12', hexadecimal))
self.accumulator.answer = '原文显式引用[QABCDEF12]。'
result = self.invoke()
self.assertEqual(result['status'], 'COMPLETED')
self.assertEqual(result['answer'], self.accumulator.answer)
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-hexadecimal'])
self.assertEqual(result['answerQuality']['citedEvidenceRefs'], ['QABCDEF12'])
def test_unbound_original_citation_remains_a_metadata_gap(self):
self.accumulator.answer = '原生回答的引用[QABCDEF99]仍按原文保留。'
result = self.invoke() result = self.invoke()
self.assertEqual(result['status'], 'PARTIAL') self.assertEqual(result['status'], 'PARTIAL')
self.assertEqual(result['conclusionProtocolQueryIds'], []) self.assertEqual(result['conclusionProtocolQueryIds'], [])
self.assertTrue(any('实际查询证明' in gap for gap in result['evidenceCompletion']['missingEvidence'])) self.assertEqual(result['answer'], self.accumulator.answer)
self.assertEqual(result['answerQuality']['unresolvedEvidenceRefs'], ['QABCDEF99'])
self.assertTrue(any('QABCDEF99' in gap for gap in result['evidenceCompletion']['missingEvidence']))
def test_cancelled_native_turn_never_reads_query_snapshot_or_synthesizes(self): def test_cancelled_native_turn_never_reads_query_snapshot_or_synthesizes(self):
for cancellation in ('event', 'native_status'): for cancellation in ('event', 'native_status'):
@@ -295,12 +333,12 @@ class NativeRunTests(unittest.TestCase):
self.assertNotIn('图表尚未完整生成,可独立恢复。', result['answer']) self.assertNotIn('图表尚未完整生成,可独立恢复。', result['answer'])
self.assertNotIn('结果为部分完成', result['answer']) self.assertNotIn('结果为部分完成', result['answer'])
self.assertNotIn('共有15张图表', result['answer']) self.assertNotIn('共有15张图表', result['answer'])
self.assertEqual(result['readingSummary']['notices'], self.assertEqual(result['answerQuality']['notices'],
['部分重点图表未能完整展示;已保留核实文字和表格。']) ['部分重点图表未能完整展示;已保留核实文字和表格。'])
else: else:
self.assertIn('图表尚未完整生成,可独立恢复。', result['answer']) self.assertNotIn('图表尚未完整生成,可独立恢复。', result['answer'])
self.assertIn('图表尚未完整生成,可独立恢复。', result['readingSummary']['notices']) self.assertNotIn('结果为部分完成', result['answer'])
self.assertIn('结果为部分完成', result['answer']) self.assertIn('图表尚未完整生成,可独立恢复。', result['answerQuality']['missingEvidence'])
if __name__ == '__main__': if __name__ == '__main__':
@@ -0,0 +1,32 @@
"""普通对话通过真实协议执行入口,不启动数据查询或二次模型生成。"""
import json,sys,tempfile,threading,unittest,uuid
from pathlib import Path
from unittest.mock import Mock,patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
from nao_agent_task import normalize_task
from nao_protocol_execution import execute
class ProtocolConversationTests(unittest.TestCase):
def invoke(self,cancel=False,context=None):
with tempfile.TemporaryDirectory() as temp:
root=Path(temp);(root/'private').mkdir();(root/'evidence').mkdir();prior=root/'private/last-agent-task.json';prior.write_text('{"task":"prior business"}');before=prior.read_bytes()
raw={'kind':'explain','goal':'回应问候','directResponse':{'purpose':'greeting','answer':'你好!我可以协助你查询质量指标并比较期间变化。','requiresMemory':False}}
task=normalize_task(raw,'你好',context)
request={key:str(uuid.uuid4()) for key in ['turnId','sessionId','releaseId','actorId']};request['question']='你好';request['context']=context or {}
authority={key:request[key] for key in ['turnId','sessionId']};authority.update(attemptId=str(uuid.uuid4()),executionId=str(uuid.uuid4()),revision=1)
delegated=Mock();delegated.call.side_effect=AssertionError('ordinary conversation cannot read business data');events=[];event=threading.Event()
if cancel:event.set()
with patch('nao_evidence_finalizer.synthesize',side_effect=AssertionError('must keep the confirmed model reply')),patch('analysis_visual_evidence.visual_result',side_effect=AssertionError('no charts for a greeting')):
if cancel:
with self.assertRaises(RuntimeError):execute(request=request,task=task,authority=authority,actor_root=root,delegated=delegated,connection=('https://offline.invalid','synthetic','fixture'),cancel_event=event,emit=events.append)
self.assertEqual(events,[])
else:
result=execute(request=request,task=task,authority=authority,actor_root=root,delegated=delegated,connection=('https://offline.invalid','synthetic','fixture'),cancel_event=event,emit=events.append)
self.assertEqual(result['status'],'COMPLETED');self.assertEqual(result['answer'],raw['directResponse']['answer']);self.assertEqual(result['completionMethod'],'direct_conversation')
self.assertEqual(result['protocol'],authority);self.assertEqual(result['protocolEvidence'],[]);self.assertEqual(result['queryEvidenceRefs'],[]);self.assertEqual(result['visuals'],[])
self.assertTrue((root/'private/non-query-turns'/(request['turnId']+'.json')).exists())
self.assertEqual(result['agentContext'],{key:value for key,value in request['context'].items() if key in ('releaseId','period','comparisonPeriod','filters')})
delegated.call.assert_not_called();self.assertEqual(prior.read_bytes(),before)
def test_greeting_keeps_the_model_reply_without_period_or_queries(self):self.invoke()
def test_acknowledgement_keeps_the_existing_business_frame(self):self.invoke(context={'period':{'year':2026,'month':9},'filters':{'group':'G'}})
def test_cancelled_conversation_does_not_publish(self):self.invoke(cancel=True)
if __name__=='__main__':unittest.main()
+1 -1
View File
@@ -21,7 +21,7 @@ export function AnalysisConclusion({ reading, visuals, renderVisuals }: {
<div className="analysis-comparison-previous"><span>{comparison.previousLabel}</span><strong>{comparison.previous}</strong></div> <div className="analysis-comparison-previous"><span>{comparison.previousLabel}</span><strong>{comparison.previous}</strong></div>
<span className="analysis-comparison-arrow" aria-hidden="true">→</span> <span className="analysis-comparison-arrow" aria-hidden="true">→</span>
<div className="analysis-comparison-current"><span>{comparison.currentLabel}</span><strong>{comparison.current}</strong></div> <div className="analysis-comparison-current"><span>{comparison.currentLabel}</span><strong>{comparison.current}</strong></div>
<div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.direction} {comparison.change}</strong><span>{comparison.unit}</span></div> <div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.change}</strong><span>{comparison.unit} · {comparison.direction}</span></div>
</div> </div>
</div>} </div>}
{section.markdown && <AiMarkdown className="ai-answer" content={section.markdown} layout="sections" />} {section.markdown && <AiMarkdown className="ai-answer" content={section.markdown} layout="sections" />}
+4 -1
View File
@@ -1,3 +1,5 @@
import { originalAnalysisBody } from './analysisOriginalBody';
import { AnalysisOriginalContent } from './AnalysisOriginalContent';
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { Button } from 'antd'; import { Button } from 'antd';
import { AiMarkdown } from './AiMarkdown'; import { AiMarkdown } from './AiMarkdown';
@@ -103,6 +105,7 @@ export function AnalysisNarrative({ answer, visuals, visualState, question, turn
reveal(); window.addEventListener('hashchange', reveal); reveal(); window.addEventListener('hashchange', reveal);
return () => window.removeEventListener('hashchange', reveal); return () => window.removeEventListener('hashchange', reveal);
}, [model.evidence, prefix]); }, [model.evidence, prefix]);
const original = originalAnalysisBody(turn);
const primaryIds = new Set(primaryVisuals.map(visual => visual.id)); const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
const compact = (visual: AnalysisVisual) => !reading.hasAppendix && useCompactRateComparison(visual, question); const compact = (visual: AnalysisVisual) => !reading.hasAppendix && useCompactRateComparison(visual, question);
const comparisons = model.sections.flatMap(section => section.visuals).filter(compact); const comparisons = model.sections.flatMap(section => section.visuals).filter(compact);
@@ -130,7 +133,7 @@ export function AnalysisNarrative({ answer, visuals, visualState, question, turn
<NarrativeEvidence model={model} prefix={prefix} /> <NarrativeEvidence model={model} prefix={prefix} />
</>; </>;
return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}> return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}>
{reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : fullContent} {original ? <AnalysisOriginalContent answer={original.answer} visuals={model.sections.flatMap(section => section.visuals)} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : fullContent}
{turn && drilldown && <AnalysisProductDrilldown turn={turn} selection={drilldown} onClose={() => setDrilldown(null)} />} {turn && drilldown && <AnalysisProductDrilldown turn={turn} selection={drilldown} onClose={() => setDrilldown(null)} />}
</div>; </div>;
} }
+13
View File
@@ -0,0 +1,13 @@
import type { ReactNode } from 'react';
import { AiMarkdown } from './AiMarkdown';
import { originalAnalysisSections } from './analysisOriginalBody';
import type { AnalysisVisual } from './analysisVisualsModel';
export function AnalysisOriginalContent({ answer, visuals, renderVisuals }: {
answer: string; visuals: AnalysisVisual[]; renderVisuals: (visuals: AnalysisVisual[]) => ReactNode;
}) {
return <div className="analysis-original-document">{originalAnalysisSections(answer, visuals).map(section =>
<section key={section.id} data-original-section={section.id}>
{section.markdown.trim() && <AiMarkdown content={section.markdown} className="ai-answer" />}
{!!section.visuals.length && renderVisuals(section.visuals)}
</section>)}</div>;
}
+7 -7
View File
@@ -1,7 +1,7 @@
import { Spin } from 'antd'; import { Spin } from 'antd';
import { useEffect, useRef, useState, type ReactNode } from 'react'; import { useEffect, useRef, useState, type ReactNode } from 'react';
import { CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined, RightOutlined } from '@ant-design/icons'; import { CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined, RightOutlined } from '@ant-design/icons';
import { analysisIsRunning, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from './analysisConversationState'; import { analysisIsRunning, compactAnalysisTimeline } from './analysisConversationState';
import { AiMarkdown } from './AiMarkdown'; import { AiMarkdown } from './AiMarkdown';
import { sanitizeAnalysisDisplayText } from './analysisDisplayText'; import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
import { AnalysisThinkingBlock } from './ModelThinkingPanel'; import { AnalysisThinkingBlock } from './ModelThinkingPanel';
@@ -45,32 +45,32 @@ export function AnalysisProcess({ turn, metadata }: { turn: Record<string, unkno
const running = analysisIsRunning(turn.status || result.status); const running = analysisIsRunning(turn.status || result.status);
const raw = turn.timeline || result.timeline || plan.timeline; const raw = turn.timeline || result.timeline || plan.timeline;
const timeline = compactAnalysisTimeline(Array.isArray(raw) ? raw.map(record) : []); const timeline = compactAnalysisTimeline(Array.isArray(raw) ? raw.map(record) : []);
const answer = String(result.answer || turn.answer || '');
const rawSteps = turn.steps || result.steps || plan.steps; const rawSteps = turn.steps || result.steps || plan.steps;
const steps = Array.isArray(rawSteps) ? rawSteps.map(record) : []; const steps = Array.isArray(rawSteps) ? rawSteps.map(record) : [];
const fallback = steps.map((step, index) => ({ ...step, kind: 'tool', sequence: index, at: step.startedAt, hasResult: ['completed', 'failed'].includes(String(step.status)) })); const fallback = steps.map((step, index) => ({ ...step, kind: 'tool', sequence: index, at: step.startedAt, hasResult: ['completed', 'failed'].includes(String(step.status)) }));
const events = groupAdjacentThinking(orderedAnalysisProcess(turn, timeline.length ? timeline : fallback)); const events = groupAdjacentThinking(orderedAnalysisProcess(turn, timeline.length ? timeline : fallback));
const turnId = String(turn.id || turn.turnId || ''); const turnId = String(turn.id || turn.turnId || '');
const [open, setOpen] = useState(false); const [open, setOpen] = useState(running);
const previous = useRef({ turnId, running }); const previous = useRef({ turnId, running });
const visibleOpen = previous.current.turnId === turnId && open; const visibleOpen = previous.current.turnId !== turnId ? running : previous.current.running && !running ? false : open;
useEffect(() => { useEffect(() => {
const changedTurn = previous.current.turnId !== turnId; const changedTurn = previous.current.turnId !== turnId;
const completed = previous.current.running && !running; const completed = previous.current.running && !running;
if (changedTurn || completed) setOpen(false); if (changedTurn || !previous.current.running && running) setOpen(running);
else if (completed) setOpen(false);
previous.current = { turnId, running }; previous.current = { turnId, running };
}, [running, turnId]); }, [running, turnId]);
const content = events.map(entry => { const content = events.map(entry => {
if (entry.kind === 'thinking') return <AnalysisThinkingBlock key={String(entry.key)} entry={entry as unknown as ModelThinking} running={running} />; if (entry.kind === 'thinking') return <AnalysisThinkingBlock key={String(entry.key)} entry={entry as unknown as ModelThinking} running={running} />;
const text = sanitizeAnalysisDisplayText(String(entry.text || '')); const text = sanitizeAnalysisDisplayText(String(entry.text || ''));
if (entry.kind === 'assistant') { if (entry.kind === 'assistant') {
if (!text.trim() || !running && entry.sequence === timeline.at(-1)?.sequence && timeline.at(-1)?.kind === 'assistant' && duplicatesFinalAnalysisAnswer(text, answer)) return null; if (!running || !text.trim()) return null;
return <div className="analysis-answer analysis-event-note" key={String(entry.key)}><AiMarkdown content={text} className="ai-answer" /></div>; return <div className="analysis-answer analysis-event-note" key={String(entry.key)}><AiMarkdown content={text} className="ai-answer" /></div>;
} }
const step = steps.find(item => item.toolCallId && item.toolCallId === entry.toolCallId); const step = steps.find(item => item.toolCallId && item.toolCallId === entry.toolCallId);
return <ToolCall key={String(entry.key)} entry={{ ...entry, ...(step?.recovered ? { recovered: true, text: step.outputSummary || '调整调用后已重试成功' } : {}) }} running={running} />; return <ToolCall key={String(entry.key)} entry={{ ...entry, ...(step?.recovered ? { recovered: true, text: step.outputSummary || '调整调用后已重试成功' } : {}) }} running={running} />;
}); });
if (!events.length) return <>{metadata}{running && <p className="analysis-chat-notice" role="status">{sanitizeAnalysisDisplayText(String(turn.progressMessage || plan.progressMessage || '正在准备分析…'))}</p>}</>; if (!events.length) return <>{metadata}</>;
return <details className="analysis-process-history analysis-agent-process" open={visibleOpen} onToggle={event => setOpen(event.currentTarget.open)}> return <details className="analysis-process-history analysis-agent-process" open={visibleOpen} onToggle={event => setOpen(event.currentTarget.open)}>
<summary aria-label={running ? '分析运行信息,展开分析过程' : '分析运行信息,展开已保存过程'}>{metadata || <span>{running ? '分析中' : '已完成'}</span>}<RightOutlined aria-hidden="true" /></summary> <summary aria-label={running ? '分析运行信息,展开分析过程' : '分析运行信息,展开已保存过程'}>{metadata || <span>{running ? '分析中' : '已完成'}</span>}<RightOutlined aria-hidden="true" /></summary>
<div className="analysis-agent-stream" aria-label={running ? '实时分析对话' : '已保存的分析过程'}>{content}</div> <div className="analysis-agent-stream" aria-label={running ? '实时分析对话' : '已保存的分析过程'}>{content}</div>
+4 -1
View File
@@ -1,3 +1,5 @@
import { originalAnalysisBody } from './analysisOriginalBody';
import { AnalysisOriginalContent } from './AnalysisOriginalContent';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { AiMarkdown } from './AiMarkdown'; import { AiMarkdown } from './AiMarkdown';
import { AnalysisConclusion } from './AnalysisConclusion'; import { AnalysisConclusion } from './AnalysisConclusion';
@@ -15,6 +17,7 @@ export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; a
const { model, reading, primaryVisuals } = useMemo(() => buildAnalysisReadingModel(answer, visuals, String(turn.question || ''), turn), [answer, signature, turn]); const { model, reading, primaryVisuals } = useMemo(() => buildAnalysisReadingModel(answer, visuals, String(turn.question || ''), turn), [answer, signature, turn]);
const prefix = `report-${String(turn.id || turn.turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`; const prefix = `report-${String(turn.id || turn.turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`;
const text = (content: string) => <AiMarkdown content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />; const text = (content: string) => <AiMarkdown content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />;
const original = originalAnalysisBody(turn);
const primaryIds = new Set(primaryVisuals.map(visual => visual.id)); const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
const complete = <> const complete = <>
{model.sections.filter(section => !primaryIds.size || section.narrative || section.tables.length || section.focusProducts?.length || section.visuals.some(visual => !primaryIds.has(visual.id))).map(section => <section key={section.id} id={`${prefix}${section.id}`} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}> {model.sections.filter(section => !primaryIds.size || section.narrative || section.tables.length || section.focusProducts?.length || section.visuals.some(visual => !primaryIds.has(visual.id))).map(section => <section key={section.id} id={`${prefix}${section.id}`} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
@@ -30,7 +33,7 @@ export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; a
<NarrativeEvidence model={model} prefix={prefix} /> <NarrativeEvidence model={model} prefix={prefix} />
</>; </>;
return <div className="analysis-narrative report-narrative"> return <div className="analysis-narrative report-narrative">
{reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}> {original ? <AnalysisOriginalContent answer={original.answer} visuals={visuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}><ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} hideEvidence /></div>)} /> : reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}>
<ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} hideEvidence /> <ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} hideEvidence />
</div>)} /> : complete} </div>)} /> : complete}
</div>; </div>;
+96 -47
View File
@@ -38,7 +38,7 @@ import {
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { CompactManagementTables, QualityTable as Table } from './QualityTable'; import { CompactManagementTables, QualityTable as Table } from './QualityTable';
import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined } from '@ant-design/icons'; import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined, LoadingOutlined } from '@ant-design/icons';
import { ApiError, api, collectionItems, decodeQueryValueList } from './api'; import { ApiError, api, collectionItems, decodeQueryValueList } from './api';
import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types'; import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types';
import type { DataWorkflowStatus } from './NoCodeDataTypes'; import type { DataWorkflowStatus } from './NoCodeDataTypes';
@@ -50,11 +50,11 @@ import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExpo
import { AiMarkdown } from './AiMarkdown'; import { AiMarkdown } from './AiMarkdown';
import { authorizeAnalysisSnapshot } from './analysisSnapshot'; import { authorizeAnalysisSnapshot } from './analysisSnapshot';
import { AnalysisApiSettings } from './AnalysisApiSettings'; import { AnalysisApiSettings } from './AnalysisApiSettings';
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState'; import { acceptAnalysisEvent, analysisScrollFollows, analysisStreamStatus, emptyAnalysisNotice, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState';
import { AnalysisProcess } from './AnalysisProcess'; import { AnalysisProcess } from './AnalysisProcess';
import { AnalysisMemberListPanel } from './AnalysisMemberList'; import { AnalysisMemberListPanel } from './AnalysisMemberList';
import { AnalysisRecordListPanel } from './AnalysisRecordList'; import { AnalysisRecordListPanel } from './AnalysisRecordList';
import { analysisScopeText, restoredAnalysisDraft, analysisComposerState, analysisFollowRequestReady } from './analysisScope'; import { restoredAnalysisDraft, analysisComposerState, analysisFollowRequestReady } from './analysisScope';
import { isValidAnalysisPeriodContext } from './analysisPeriodModel'; import { isValidAnalysisPeriodContext } from './analysisPeriodModel';
import { beginAnalysisSubmission, requestSubmissionCancellation, submissionOutcomeUnknown, type AnalysisSubmission } from './analysisSubmission'; import { beginAnalysisSubmission, requestSubmissionCancellation, submissionOutcomeUnknown, type AnalysisSubmission } from './analysisSubmission';
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState'; import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
@@ -967,6 +967,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const initialParams = new URLSearchParams(initialSearch ?? window.location.search); const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
const initialSessionId = initialParams.get('sessionId') || ''; const initialSessionId = initialParams.get('sessionId') || '';
const initialTurnId = initialParams.get('turnId') || ''; const initialTurnId = initialParams.get('turnId') || '';
const pendingTurnLink = useRef(initialTurnId);
const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context'))); const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context')));
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [sessionId, setSessionId] = useState(initialSessionId); const [sessionId, setSessionId] = useState(initialSessionId);
@@ -974,7 +975,10 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null); const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]); const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
const [sessionsLoaded, setSessionsLoaded] = useState(false); const [sessionsLoaded, setSessionsLoaded] = useState(false);
const sessionReadRequest = useRef<Promise<void> | null>(null); const [sessionsLoading, setSessionsLoading] = useState(true);
const [sessionsError, setSessionsError] = useState('');
const showSessionsLoading = useDelayedIndicator(sessionsLoading && active, 150);
const sessionReadRequest = useRef<Promise<Record<string, unknown>[] | undefined> | null>(null);
const [turns, setTurns] = useState<Record<string, unknown>[]>([]); const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
const [options, setOptions] = useState<OptionsResponse | null>(null); const [options, setOptions] = useState<OptionsResponse | null>(null);
const [historyLoading, setHistoryLoading] = useState(true); const [historyLoading, setHistoryLoading] = useState(true);
@@ -1108,19 +1112,43 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [lastTurn, busy, turns, sessionId, active]); }, [lastTurn, busy, turns, sessionId, active]);
const loadSessions = async () => { const loadSessions = async () => {
if (!mounted.current || !active || document.visibilityState !== 'visible') return; // 隐藏时的定时刷新由 useVisiblePolling 暂停;首次恢复不能因后台打开标签页而丢失。
if (!mounted.current || !active) return;
if (sessionReadRequest.current) return sessionReadRequest.current; if (sessionReadRequest.current) return sessionReadRequest.current;
setSessionsLoading(true);
const request = (async () => { const request = (async () => {
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setError(''); } } try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setSessionsError(''); } return items; }
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); } catch (value) { if (mounted.current && !onUnauthorized(value)) setSessionsError(apiMessage(value)); }
finally { if (mounted.current) setSessionsLoading(false); }
})(); })();
sessionReadRequest.current = request; sessionReadRequest.current = request;
try { await request; } try { return await request; }
finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; } finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; }
}; };
const retrySessions = async () => { setHistoryLoading(true); await loadSessions(); if (mounted.current) setHistoryLoading(false); }; const retrySessions = async () => {
const generation = navigationGeneration.current;
setHistoryLoading(true);
const listRequest = loadSessions();
try {
const focusTurnId = pendingTurnLink.current;
let target = sessionId;
if (!target && focusTurnId) {
const turn = await api.analysisTurn(focusTurnId);
if (!mounted.current || generation !== navigationGeneration.current) return;
target = String(turn.sessionId || '');
if (!target) throw new Error('服务端未返回目标轮次所属会话');
}
if (target) await openSession(target, focusTurnId || undefined);
else {
const items = await listRequest;
const id = items && !initialLink.present ? defaultAnalysisSession(user.id, items) : '';
if (mounted.current && generation === navigationGeneration.current && id) await openSession(id);
}
} catch (value) { if (mounted.current && generation === navigationGeneration.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && generation === navigationGeneration.current) setHistoryLoading(false); }
};
useEffect(() => { useEffect(() => {
if (!active || optionsRequestStarted.current) return; if (!active || !initialLink.present || initialSessionId || initialTurnId || optionsRequestStarted.current) return;
optionsRequestStarted.current = true; optionsRequestStarted.current = true;
void optionsRead.run(async () => { void optionsRead.run(async () => {
try { const value = await api.options(); if (mounted.current) { setOptions(value); setOptionsError(''); } } try { const value = await api.options(); if (mounted.current) { setOptions(value); setOptionsError(''); } }
@@ -1129,7 +1157,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [active, onUnauthorized, optionsRead.run]); }, [active, onUnauthorized, optionsRead.run]);
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus)); const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
useVisiblePolling(loadSessions, 5000, active && hasBackgroundTurns); useVisiblePolling(async () => { await loadSessions(); }, 5000, active && hasBackgroundTurns);
const wasActive = useRef(active); const wasActive = useRef(active);
useEffect(() => { useEffect(() => {
if (active && !wasActive.current && hasBackgroundTurns) void loadSessions(); if (active && !wasActive.current && hasBackgroundTurns) void loadSessions();
@@ -1232,6 +1260,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [active, refreshKey]); }, [active, refreshKey]);
const openSession = async (id: string, focusTurnId?: string): Promise<boolean> => { const openSession = async (id: string, focusTurnId?: string): Promise<boolean> => {
if (!focusTurnId) pendingTurnLink.current = '';
userSelectionMade.current = true; userSelectionMade.current = true;
beginAnalysisSelection(user.id); beginAnalysisSelection(user.id);
const generation = ++navigationGeneration.current; const generation = ++navigationGeneration.current;
@@ -1271,12 +1300,14 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
setLastTurn(restored); setLastTurn(restored);
if (analysisIsRunning(restored.status)) void followTurn(selectedTurnId, String(restored.question || ''), id); if (analysisIsRunning(restored.status)) void followTurn(selectedTurnId, String(restored.question || ''), id);
} }
pendingTurnLink.current = '';
return true; return true;
} catch (value) { if (current() && !onUnauthorized(value)) setError(apiMessage(value)); return false; } } catch (value) { if (current() && !onUnauthorized(value)) setError(apiMessage(value)); return false; }
finally { if (current()) setHistoryLoading(false); } finally { if (current()) setHistoryLoading(false); }
}; };
const newSession = () => { const newSession = () => {
pendingTurnLink.current = '';
userSelectionMade.current = true; userSelectionMade.current = true;
beginAnalysisSelection(user.id); beginAnalysisSelection(user.id);
setQueuedFollowup(''); setQueuedFollowup('');
@@ -1330,6 +1361,28 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
let streamedResult: Record<string, unknown> = {}; let streamedResult: Record<string, unknown> = {};
let terminalEventStatus = ''; let terminalEventStatus = '';
setLastTurn(previous => ({ ...(previous || {}), id, question, status: previous?.status || 'QUEUED' })); setLastTurn(previous => ({ ...(previous || {}), id, question, status: previous?.status || 'QUEUED' }));
let timingReadInFlight = false, timingReadAgain = false, startConfirmed = false;
const refreshTiming = async (): Promise<void> => {
if (!linkedSessionId || !current() || startConfirmed) return;
if (timingReadInFlight) { timingReadAgain = true; return; }
timingReadInFlight = true;
try {
const history = await api.analysisSessionTurns(linkedSessionId);
if (!current()) return;
const timing = collectionItems(history).find(item => item.id === id);
if (!timing) return;
startConfirmed = typeof timing.startedAt === 'string' && Number.isFinite(Date.parse(timing.startedAt));
setLastTurn(previous => previous?.id !== id ? previous : { ...previous,
...(typeof timing.createdAt === 'string' ? { createdAt: timing.createdAt } : {}),
...(startConfirmed ? { startedAt: timing.startedAt } : {}),
});
} catch (value) { if (current()) onUnauthorized(value); }
finally {
timingReadInFlight = false;
if (timingReadAgain && !startConfirmed && current()) { timingReadAgain = false; void refreshTiming(); }
}
};
void refreshTiming();
try { try {
let detail: Record<string, unknown> = {}; let detail: Record<string, unknown> = {};
let reconnectAttempt = 0; let reconnectAttempt = 0;
@@ -1350,15 +1403,13 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (eventResult) streamedResult = { ...streamedResult, ...eventResult }; if (eventResult) streamedResult = { ...streamedResult, ...eventResult };
const eventName = event.event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_'); const eventName = event.event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
const eventStatus = String(data.status || '').toUpperCase(); const eventStatus = String(data.status || '').toUpperCase();
if (ANALYSIS_FINAL_STATUSES.has(eventStatus)) terminalEventStatus = eventStatus; const turnEventStatus = analysisStreamStatus(undefined, event.event, data.status);
else if (/^(?:TURN_)?(COMPLETED|PARTIAL|FAILED|CANCELLED|NEEDS_CLARIFICATION)$/.test(eventName)) { if (ANALYSIS_FINAL_STATUSES.has(turnEventStatus)) terminalEventStatus = turnEventStatus;
terminalEventStatus = eventName.replace(/^TURN_/, '');
}
setLastTurn(previous => { setLastTurn(previous => {
const prior = previous || {}; const prior = previous || {};
if (prior.id === id && ANALYSIS_FINAL_STATUSES.has(String(prior.status || '').toUpperCase()) && !ANALYSIS_FINAL_STATUSES.has(eventStatus)) return prior; if (prior.id === id && ANALYSIS_FINAL_STATUSES.has(String(prior.status || '').toUpperCase()) && !ANALYSIS_FINAL_STATUSES.has(eventStatus)) return prior;
const priorResult = isObjectRecord(prior.result) ? prior.result : {}; const priorResult = isObjectRecord(prior.result) ? prior.result : {};
const status = data.status || (['progress', 'message', 'heartbeat'].includes(event.event.toLowerCase()) ? prior.status || 'RUNNING' : event.event.toUpperCase()); const status = analysisStreamStatus(prior.status, event.event, data.status);
return { return {
...prior, ...prior,
id, id,
@@ -1379,6 +1430,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
// The SSE request can otherwise remain open after its terminal event. // The SSE request can otherwise remain open after its terminal event.
// Closing this subscription does not cancel the analysis itself. // Closing this subscription does not cancel the analysis itself.
if (terminalEventStatus) controller.abort(); if (terminalEventStatus) controller.abort();
else if (eventStatus === 'RUNNING' || eventName.startsWith('TOOL_')) void refreshTiming();
}, },
}); });
} catch (streamError) { } catch (streamError) {
@@ -1442,10 +1494,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const requestedAt = navigationGeneration.current; const requestedAt = navigationGeneration.current;
setHistoryLoading(true); setHistoryLoading(true);
try { try {
const items = collectionItems(await api.analysisSessions()); const listRequest = loadSessions();
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
setSessions(items);
setSessionsLoaded(true);
let linkedSession = initialSessionId; let linkedSession = initialSessionId;
if (initialTurnId) { if (initialTurnId) {
const linkedTurn = await api.analysisTurn(initialTurnId); const linkedTurn = await api.analysisTurn(initialTurnId);
@@ -1454,7 +1503,11 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配'); if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
linkedSession ||= turnSession; linkedSession ||= turnSession;
} }
if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items); if (!linkedSession && !initialLink.present) {
const items = await listRequest;
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
if (items) linkedSession = defaultAnalysisSession(user.id, items);
}
if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined); if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
} catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); } } catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); } finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
@@ -1530,7 +1583,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
followRequest.current = attempt.idempotencyKey; followRequest.current = attempt.idempotencyKey;
followOutput.current = true; followOutput.current = true;
explicitlyFollowing.current = false; explicitlyFollowing.current = false;
setLastTurn({ ...turn, status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey }); const submittedAt = new Date().toISOString();
setLastTurn({ id, sessionId: targetSessionId, question, status: 'SUBMITTING', _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt; const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt;
setError(''); setBusy(true); setActiveTurnId(id); setError(''); setBusy(true); setActiveTurnId(id);
try { try {
@@ -1548,7 +1602,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (!current()) return; if (!current()) return;
const retriedDetail = await api.analysisTurn(retryId); const retriedDetail = await api.analysisTurn(retryId);
if (!current()) return; if (!current()) return;
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiFollowKey: attempt.idempotencyKey }); setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
writeAnalysisLocation(retrySessionId, retryId); writeAnalysisLocation(retrySessionId, retryId);
void loadSessions(); void loadSessions();
if (!current()) return; if (!current()) return;
@@ -1590,7 +1644,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
setError(''); setError('');
setRetryQuestion(question.trim()); setRetryQuestion(question.trim());
if (typeof lastTurn?.id === 'string' && lastTurn.id) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]); if (typeof lastTurn?.id === 'string' && lastTurn.id) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]);
setLastTurn({ question: question.trim(), status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey }); const submittedAt = new Date().toISOString();
setLastTurn({ question: question.trim(), status: 'SUBMITTING', _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
setQuery(''); setQuery('');
try { try {
let selectedSessionId = sessionId; let selectedSessionId = sessionId;
@@ -1619,7 +1674,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
attempt.uncertain = false; attempt.uncertain = false;
attempt.acceptedTurnId = turnId; attempt.acceptedTurnId = turnId;
setActiveTurnId(turnId); setActiveTurnId(turnId);
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiFollowKey: attempt.idempotencyKey }); setLastTurn({ ...turn, status: turn.status || 'QUEUED', id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
writeAnalysisLocation(selectedSessionId, turnId); writeAnalysisLocation(selectedSessionId, turnId);
if (attempt.cancelRequested && await cancelAcceptedTurn(turnId, generation, question.trim())) return; if (attempt.cancelRequested && await cancelAcceptedTurn(turnId, generation, question.trim())) return;
void loadSessions(); void loadSessions();
@@ -1664,11 +1719,11 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
<PageHeader title="智能分析" /> <PageHeader title="智能分析" />
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />} {error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />}
{optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />} {optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />}
{!options && optionsRead.busy && <div className="loading-panel compact"><Spin />读取分析选项…</div>}
<div className="analysis-workspace"> <div className="analysis-workspace">
<aside className="panel analysis-session-panel"> <aside className="panel analysis-session-panel">
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div> <div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
{showHistoryLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [ {sessionsError && <Alert type="error" message="会话列表读取失败" description={sessionsError} action={<Button size="small" onClick={() => { if (!userSelectionMade.current && !sessionId) void retrySessions(); else void loadSessions(); }}>重试</Button>} />}
{!sessionsLoaded && showSessionsLoading ? <div className="analysis-region-loading" role="status"><Spin />正在读取会话列表…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{ key: 'rename', icon: <EditOutlined />, label: '重命名' }, { key: 'rename', icon: <EditOutlined />, label: '重命名' },
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) }, { key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
], onClick: ({ key }) => { ], onClick: ({ key }) => {
@@ -1677,7 +1732,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null} } }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null}
</aside> </aside>
<section className="panel analysis-chat-panel"> <section className="panel analysis-chat-panel">
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => { <div className="analysis-conversation" ref={conversation} aria-live="polite" aria-busy={historyLoading} onWheel={event => {
const direction = event.deltaY < 0 ? 'up' : event.deltaY > 0 ? 'down' : null; const direction = event.deltaY < 0 ? 'up' : event.deltaY > 0 ? 'down' : null;
if (direction) handleUserScrollIntent(event.currentTarget, direction); if (direction) handleUserScrollIntent(event.currentTarget, direction);
}} onPointerDown={event => { }} onPointerDown={event => {
@@ -1716,7 +1771,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}}> }}>
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)} {turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)}
{lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />} {lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />}
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>} {!turns.length && !lastTurn && showHistoryLoading && <div className="analysis-region-loading" role="status"><Spin />正在读取会话…</div>}
{!turns.length && !lastTurn && !busy && !historyLoading && !error && !sessionsError && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
</div> </div>
{hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => { {hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => {
const element = conversation.current; const element = conversation.current;
@@ -1744,34 +1800,26 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
const question = typeof turn.question === 'string' ? turn.question : ''; const question = typeof turn.question === 'string' ? turn.question : '';
if (!turn.id && typeof turn.submissionNotice === 'string') return <article className="analysis-turn"> if (!turn.id && typeof turn.submissionNotice === 'string') return <article className="analysis-turn">
{question && <div className="analysis-question"><p>{question}</p></div>} {question && <div className="analysis-question"><p>{question}</p></div>}
<p className="analysis-chat-notice" role="status">{turn.submissionNotice}</p>
</article>; </article>;
const result = isObjectRecord(turn.result) ? turn.result : turn; const result = isObjectRecord(turn.result) ? turn.result : turn;
const memberList = result.memberList ?? turn.memberList; const memberList = result.memberList ?? turn.memberList;
const recordList = result.recordList ?? turn.recordList; const recordList = result.recordList ?? turn.recordList;
const answer = partialAnswerIsOnlyProgress(turn) ? '' : typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : ''; const answer = partialAnswerIsOnlyProgress(turn) ? '' : typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
const status = String(turn.status || result.status || '').toUpperCase(); const status = String(turn.status || result.status || '').toUpperCase();
const emptyNotice = emptyAnalysisNotice(turn, answer);
const visuals = result.visualSchemaVersion === 1 ? result.visuals : undefined; const visuals = result.visualSchemaVersion === 1 ? result.visuals : undefined;
const reportMarkdown = typeof result.reportMarkdown === 'string' ? result.reportMarkdown : typeof turn.reportMarkdown === 'string' ? turn.reportMarkdown : ''; const reportMarkdown = typeof result.reportMarkdown === 'string' ? result.reportMarkdown : typeof turn.reportMarkdown === 'string' ? turn.reportMarkdown : '';
const reportHtml = typeof result.reportHtml === 'string' ? result.reportHtml : typeof turn.reportHtml === 'string' ? turn.reportHtml : undefined; const reportHtml = typeof result.reportHtml === 'string' ? result.reportHtml : typeof turn.reportHtml === 'string' ? turn.reportHtml : undefined;
const resumable = ['QUEUED', 'RUNNING', 'PROCESSING', 'PLANNING', 'TOOL_RUNNING'].includes(status); const resumable = ['SUBMITTING', 'QUEUED', 'RUNNING', 'PROCESSING', 'PLANNING', 'TOOL_RUNNING'].includes(status);
const errorValue = result.error || turn.error;
const failure = typeof errorValue === 'string' ? errorValue : '分析暂时中断,可以重试或继续提问。';
const emptyStatus = status === 'CANCELLED' ? '本次分析已取消,未返回回答内容。'
: status === 'PARTIAL' ? '本轮已保存查询过程,尚未形成最终答复。'
: status === 'COMPLETED' ? '分析任务已完成,但未返回回答内容。'
: failure;
const scope = analysisScopeText(turn);
return <article className="analysis-turn" data-analysis-turn-id={String(turn.id || '')} data-analysis-status={status}> return <article className="analysis-turn" data-analysis-turn-id={String(turn.id || '')} data-analysis-status={status}>
{question && <div className="analysis-question"><p>{question}</p></div>} {question && <div className="analysis-question"><p>{question}</p></div>}
{scope && <p className="analysis-turn-scope" aria-label="本轮分析范围">{scope}</p>}
<AnalysisProcess turn={turn} metadata={<AnalysisTurnMetadata turn={turn} status={status} compact />} /> <AnalysisProcess turn={turn} metadata={<AnalysisTurnMetadata turn={turn} status={status} compact />} />
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer"> {(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
{status === 'NEEDS_CLARIFICATION' && onClarify ? <AnalysisClarification turn={turn} disabled={retryDisabled} onContinue={onClarify} /> : answer ? <> {status === 'NEEDS_CLARIFICATION' && onClarify ? <AnalysisClarification turn={turn} disabled={retryDisabled} onContinue={onClarify} /> : answer ? <>
{resumable ? <AiMarkdown content={answer} className="ai-answer" /> {resumable ? <AiMarkdown content={answer} className="ai-answer" />
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />} : <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />}
</> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>} </> : emptyNotice ? <p role="status">{emptyNotice}</p> : null}
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''), result)}</p>} {recovery.error && <p role="alert">{recovery.error}</p>}
<div className="analysis-message-actions"> <div className="analysis-message-actions">
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />} {(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />} {!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
@@ -1779,7 +1827,6 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled||recovery.recovering} onClick={() => onRetry(String(turn.id))}>重新分析</Button>} {['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled||recovery.recovering} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>} {resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
</div> </div>
{recovery.error&&<p className="analysis-chat-notice" role="alert">{recovery.error}</p>}
</div>} </div>}
{memberList !== undefined && memberList !== null && <AnalysisMemberListPanel turn={turn} value={memberList} onUnauthorized={onUnauthorized} />} {memberList !== undefined && memberList !== null && <AnalysisMemberListPanel turn={turn} value={memberList} onUnauthorized={onUnauthorized} />}
{recordList !== undefined && recordList !== null && <AnalysisRecordListPanel turn={turn} value={recordList} onUnauthorized={onUnauthorized} />} {recordList !== undefined && recordList !== null && <AnalysisRecordListPanel turn={turn} value={recordList} onUnauthorized={onUnauthorized} />}
@@ -1788,21 +1835,23 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record<string, unknown>; status: string; compact?: boolean }) { function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record<string, unknown>; status: string; compact?: boolean }) {
const [now, setNow] = useState(Date.now()); const [now, setNow] = useState(Date.now());
const running = analysisIsRunning(status); const running = analysisIsRunning(status) || status === 'SUBMITTING';
useEffect(() => { if (!running) return; setNow(Date.now()); const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, [running]); useEffect(() => { if (!running) return; setNow(Date.now()); const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, [running]);
const plan = isObjectRecord(turn.plan) ? turn.plan : {}; const plan = isObjectRecord(turn.plan) ? turn.plan : {};
const date = (value: unknown) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : undefined; const date = (value: unknown) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : undefined;
const start = date(turn.startedAt) ?? date(plan.startedAt); const start = date(turn.startedAt) ?? date(plan.startedAt);
const waitingSince = date(turn._uiSubmittedAt) ?? date(turn.createdAt);
const clockStart = start ?? (running ? waitingSince : undefined);
const finish = date(turn.finishedAt); const finish = date(turn.finishedAt);
const duration = typeof turn.durationMs === 'number' ? turn.durationMs : start !== undefined && (running || finish !== undefined) ? Math.max(0, (running ? now : finish!) - start) : undefined; const duration = !running && typeof turn.durationMs === 'number' ? turn.durationMs : clockStart !== undefined && (running || finish !== undefined) ? Math.max(0, (running ? now : finish!) - clockStart) : undefined;
const seconds = duration === undefined ? undefined : Math.floor(duration / 1000); const seconds = duration === undefined ? undefined : Math.floor(duration / 1000);
const durationText = seconds === undefined ? '' : seconds >= 3600 ? `${Math.floor(seconds / 3600)}小时${Math.floor(seconds % 3600 / 60)}分${seconds % 60}秒` : seconds >= 60 ? `${Math.floor(seconds / 60)}分${seconds % 60}秒` : `${seconds}秒`; const durationText = seconds === undefined ? '' : seconds >= 3600 ? `${Math.floor(seconds / 3600)}小时${Math.floor(seconds % 3600 / 60)}分${seconds % 60}秒` : seconds >= 60 ? `${Math.floor(seconds / 60)}分${seconds % 60}秒` : `${seconds}秒`;
const stamp = (value: number) => new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(value); const stamp = (value: number) => new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(value);
const steps = Array.isArray(turn.steps) ? turn.steps : Array.isArray(plan.steps) ? plan.steps : []; const steps = Array.isArray(turn.steps) ? turn.steps : Array.isArray(plan.steps) ? plan.steps : [];
const labels: Record<string, string> = { QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '部分完成', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' }; const labels: Record<string, string> = { SUBMITTING: '提交中', QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' };
return <span className="analysis-turn-metadata" aria-label="分析运行信息"> return <span className="analysis-turn-metadata" aria-label="分析运行信息">
<span>{labels[status] || (running ? '运行中' : '分析记录')}</span> {status !== 'PARTIAL' && <span>{labels[status] || (running ? '运行中' : '分析记录')}</span>}
{durationText && <span>{running ? '已运行' : '运行时长'} {durationText}</span>} {durationText && <span className="analysis-runtime-clock">{running && <LoadingOutlined spin className="analysis-runtime-spinner" aria-hidden="true" />}{running ? start === undefined ? '已等待' : '已运行' : '运行时长'} {durationText}</span>}
{!compact && start !== undefined && <span>开始 {stamp(start)}</span>} {!compact && start !== undefined && <span>开始 {stamp(start)}</span>}
{!compact && !running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>} {!compact && !running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
{!compact && steps.length > 0 && <span>工具调用 {steps.length} 次</span>} {!compact && steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
+63 -26
View File
@@ -50,6 +50,7 @@ import { readableSelectPopup } from './readableSelectPopup';
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay'; import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults'; import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { defectWeightRate } from './trendMetrics'; import { defectWeightRate } from './trendMetrics';
import { defaultFullMetricFields, metricStageColumnPlan, type MetricStageField } from './metricColumnPlan';
import DefectComposition from './DefectComposition'; import DefectComposition from './DefectComposition';
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels'; import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection'; import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
@@ -210,10 +211,6 @@ function defectList(row: MetricRow | undefined, stage: Stage): DefectMetric[] {
return row?.[stage]?.defects || []; return row?.[stage]?.defects || [];
} }
function defectsFor(rows: MetricRow[], stage: Stage): string[] {
return Array.from(new Set(rows.flatMap(row => defectList(row, stage).map(item => item.name))));
}
interface ChartTooltipParam { interface ChartTooltipParam {
name?: string | number; name?: string | number;
axisValue?: string | number; axisValue?: string | number;
@@ -314,6 +311,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const [search, setSearch] = useState(initialQuery.productSearch || ''); const [search, setSearch] = useState(initialQuery.productSearch || '');
const [appliedSearch, setAppliedSearch] = useState(initialQuery.productSearch || ''); const [appliedSearch, setAppliedSearch] = useState(initialQuery.productSearch || '');
const [fullFields, setFullFields] = useState(false); const [fullFields, setFullFields] = useState(false);
const [trendFullFields, setTrendFullFields] = useState(() => defaultFullMetricFields(page));
const [defectDisplay, setDefectDisplay] = useState<'weight' | 'rate'>('weight'); const [defectDisplay, setDefectDisplay] = useState<'weight' | 'rate'>('weight');
const [data, setData] = useState<MetricsResponse | null>(null); const [data, setData] = useState<MetricsResponse | null>(null);
const [dataKey, setDataKey] = useState(''); const [dataKey, setDataKey] = useState('');
@@ -765,13 +763,14 @@ export default function QueryPage({ page, onUnauthorized }: {
<div className="analysis-stack"> <div className="analysis-stack">
<QueryTrendPanel panelRef={trendSection} id={active ? 'monthly-trend' : undefined} <QueryTrendPanel panelRef={trendSection} id={active ? 'monthly-trend' : undefined}
mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity} mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} fullFields={trendFullFields} onFullFields={setTrendFullFields}
object={trendObject} onObject={setSynchronizedTrendObject}
objects={trendOptions} scopeName={scopeName} objects={trendOptions} scopeName={scopeName}
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}> stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />} {currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}> <div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
{trendMode === 'data' {trendMode === 'data'
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} /> ? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} fullFields={trendFullFields} onMonth={selectTrendPeriod} />
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />} : <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>} {showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
</div> </div>
@@ -1083,8 +1082,6 @@ export function MetricTable({
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate'; emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
}) { }) {
const compact = useCompactTable(); const compact = useCompactTable();
const blackDefects = fullFields ? defectsFor(rows, 'black') : [];
const brightDefects = fullFields ? defectsFor(rows, 'bright') : [];
const isOverall = view === 'overall'; const isOverall = view === 'overall';
const title = (row: MetricRow) => isOverall && period === 'year' const title = (row: MetricRow) => isOverall && period === 'year'
? (monthNumber((row as TrendMetricRow).month) ? MONTHS[monthNumber((row as TrendMetricRow).month)! - 1] : row.label) ? (monthNumber((row as TrendMetricRow).month) ? MONTHS[monthNumber((row as TrendMetricRow).month)! - 1] : row.label)
@@ -1114,16 +1111,21 @@ export function MetricTable({
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)} /></Button>; return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)} /></Button>;
}, },
})); }));
const brightDetailColumns: ColumnsType<MetricRow> = defectColumns('bright', brightDefects); const fieldLabels: Record<MetricStageField, string> = {
if (fullFields && rateBasis === 'original') { totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
const diffusionIndex = brightDetailColumns.findIndex(column => column.key === 'bright-defect-扩散废'); headquartersScrapWeight: '本部报废', rate: '合格率',
brightDetailColumns.splice(diffusionIndex < 0 ? brightDetailColumns.length : diffusionIndex + 1, 0, };
numeric('本部报废', 'bright', 'headquartersScrapWeight')); const stageColumns = (stage: Stage): ColumnsType<MetricRow> => metricStageColumnPlan(rows, stage, fullFields, rateBasis).map(column => {
} if (column.kind === 'defect') return defectColumns(stage, [column.name])[0];
const metricColumn = numeric(fieldLabels[column.field], stage, column.field);
return stage === 'bright' && column.field === 'rate'
? { ...metricColumn, render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }
: metricColumn;
});
const allColumns: ColumnsType<MetricRow> = [ const allColumns: ColumnsType<MetricRow> = [
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> }, { title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('总重量', 'black', 'totalWeight'), numeric('合格重量', 'black', 'qualifiedWeight'), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] }, { key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: stageColumns('black') },
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }] }, { key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: stageColumns('bright') },
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> }, { title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> },
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> }, { title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
]; ];
@@ -1303,7 +1305,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
xAxis: { type: 'category', data: labels, triggerEvent: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, fontFamily, fontSize, margin: 12 }, axisTick: { show: false } }, xAxis: { type: 'category', data: labels, triggerEvent: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, fontFamily, fontSize, margin: 12 }, axisTick: { show: false } },
}; };
let option: echarts.EChartsCoreOption; let option: echarts.EChartsCoreOption;
const pointStyle = { z: 10, symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false }; const pointStyle = { smooth: 0.15, smoothMonotone: 'x' as const, z: 10, symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false };
if (mode === 'production') { if (mode === 'production') {
const rates = [...rows.flatMap(row => [visibleCompositeRate(row, rateBasis), visibleStageRate(row, 'black'), visibleStageRate(row, 'bright', rateBasis)]).filter((value): value is number => value != null).map(value => value * 100), ...(targetRate == null ? [] : [targetRate])]; const rates = [...rows.flatMap(row => [visibleCompositeRate(row, rateBasis), visibleStageRate(row, 'black'), visibleStageRate(row, 'bright', rateBasis)]).filter((value): value is number => value != null).map(value => value * 100), ...(targetRate == null ? [] : [targetRate])];
const minRate = rates.length ? Math.max(0, Math.floor(Math.min(...rates) - 2)) : 0; const minRate = rates.length ? Math.max(0, Math.floor(Math.min(...rates) - 2)) : 0;
@@ -1391,18 +1393,53 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
</div>; </div>;
} }
export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage }) { export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage, fullFields = false }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage; fullFields?: boolean }) {
const compact = useCompactTable(); const compact = useCompactTable();
const stageLabel = (stage: Stage) => stage === 'black' ? '黑片' : '亮片';
const metricLabels: Record<MetricStageField, string> = {
totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
headquartersScrapWeight: '本部报废', rate: '合格率',
};
const stageColumns = (stage: Stage): ColumnsType<TrendMetricRow> => metricStageColumnPlan(rows, stage, fullFields, rateBasis).map(column => {
const prefix = stageLabel(stage);
if (column.kind === 'defect') {
return {
title: `${prefix}${defectDisplay === 'rate' ? defectRateLabel(column.name) : column.name}${defectDisplay === 'rate' ? '' : ' / kg'}`,
key: `${stage}-defect-${column.name}`, align: 'center', width: fullFields ? 130 : 160,
render: (_: unknown, row: TrendMetricRow) => {
const value = row[stage].defects.find(item => item.name === column.name)?.weight ?? null;
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row[stage].totalWeight)) : numberText(value);
},
};
}
const field = column.field;
const baseLabel = `${prefix}${metricLabels[field]}`;
const title = field === 'totalWeight' && stage === 'black'
? totalWeightTitle(`${baseLabel} / kg`)
: field === 'rate' && stage === 'bright'
? rateBasisTitle(baseLabel, rateBasis, 'bright')
: `${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(baseLabel) : baseLabel}${field === 'rate' || defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? '' : ' / kg'}`;
const width = field === 'rate' ? stage === 'bright' && rateBasis !== 'original' ? 194 : stage === 'black' ? 130 : 180 : fullFields ? 130 : 160;
return {
title, dataIndex: [stage, field], key: `${stage}-${field}`, align: 'center', width,
className: field === 'rate' ? `rate-cell ${stage}` : 'weight-cell',
render: (_: unknown, row: TrendMetricRow) => {
if (field === 'rate') return rateText(visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original'));
if (field === 'scrapWeight') {
const value = queryScrapWeight(row[stage], stage, rateBasis);
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row[stage].totalWeight)) : numberText(value);
}
if (field === 'headquartersScrapWeight') {
const value = row.bright.headquartersScrapWeight ?? null;
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row.bright.totalWeight)) : numberText(value);
}
return numberText(row[stage][field]);
},
};
});
const columns: ColumnsType<TrendMetricRow> = [ const columns: ColumnsType<TrendMetricRow> = [
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> }, { title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
{ title: totalWeightTitle('黑片总重量 / kg'), dataIndex: ['black', 'totalWeight'], key: 'blackTotal', align: 'center', width: 160, render: value => numberText(value) }, ...stageColumns('black'), ...stageColumns('bright'),
{ title: '黑片合格重量 / kg', dataIndex: ['black', 'qualifiedWeight'], key: 'blackQualified', align: 'center', width: 160, render: value => numberText(value) },
{ title: defectDisplay === 'rate' ? '黑片报废率' : '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.black.scrapWeight,row.black.totalWeight)) : numberText(row.black.scrapWeight) },
{ title: '黑片合格率', dataIndex: ['black', 'rate'], key: 'blackRate', align: 'center', width: 130, className: 'rate-cell black', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'black')) },
{ title: '亮片总重量 / kg', dataIndex: ['bright', 'totalWeight'], key: 'brightTotal', align: 'center', width: 160, render: value => numberText(value) },
{ title: '亮片合格重量 / kg', dataIndex: ['bright', 'qualifiedWeight'], key: 'brightQualified', align: 'center', width: 160, render: value => numberText(value) },
{ title: defectDisplay === 'rate' ? '亮片报废率' : '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(queryScrapWeight(row.bright,'bright',rateBasis),row.bright.totalWeight)) : numberText(queryScrapWeight(row.bright,'bright',rateBasis)) },
{ title: rateBasisTitle('亮片合格率', rateBasis, 'bright'), dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: rateBasis === 'original' ? 180 : 194, className: 'rate-cell bright', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) },
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite'), dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 120, fixed: compact ? undefined : 'right', className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) }, { title: rateBasisTitle('综合合格率', rateBasis, 'composite'), dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 120, fixed: compact ? undefined : 'right', className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) },
]; ];
const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns; const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns;
+3 -1
View File
@@ -7,10 +7,11 @@ type Granularity = 'month' | 'quarter' | 'year';
type TrendMode = 'production' | 'defects' | 'data'; type TrendMode = 'production' | 'defects' | 'data';
type DefectDisplay = 'weight' | 'rate'; type DefectDisplay = 'weight' | 'rate';
export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGranularity, defectDisplay, onDefectDisplay, object, onObject, objects, scopeName, stageSwitch, children }: { export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGranularity, defectDisplay, onDefectDisplay, fullFields, onFullFields, object, onObject, objects, scopeName, stageSwitch, children }: {
panelRef?: Ref<HTMLElement>; id?: string; mode: TrendMode; onMode: (value: TrendMode) => void; panelRef?: Ref<HTMLElement>; id?: string; mode: TrendMode; onMode: (value: TrendMode) => void;
granularity: Granularity; onGranularity: (value: Granularity) => void; granularity: Granularity; onGranularity: (value: Granularity) => void;
defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
fullFields: boolean; onFullFields: (value: boolean) => void;
object?: string; onObject: (value?: string) => void; objects: Array<{ label: string; value: string }>; object?: string; onObject: (value?: string) => void; objects: Array<{ label: string; value: string }>;
scopeName: string; stageSwitch?: ReactNode; children: ReactNode; scopeName: string; stageSwitch?: ReactNode; children: ReactNode;
}) { }) {
@@ -22,6 +23,7 @@ export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGra
</div> </div>
<div className="trend-controls"> <div className="trend-controls">
{mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />} {mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />}
{mode === 'data' && <Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整指标', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="趋势字段显示" />}
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></label> <label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></label>
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></label> <label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></label>
{mode !== 'data' && stageSwitch} {mode !== 'data' && stageSwitch}
+5 -2
View File
@@ -13,6 +13,7 @@ import { useDelayedIndicator } from './useDelayedBusy';
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults'; import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { readableSelectPopup } from './readableSelectPopup'; import { readableSelectPopup } from './readableSelectPopup';
import { readableMetricFormula } from './publicDataDisplay'; import { readableMetricFormula } from './publicDataDisplay';
import { defaultFullMetricFields } from './metricColumnPlan';
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage, TrendResponse } from './types'; import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage, TrendResponse } from './types';
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels'; import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection'; import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
@@ -33,6 +34,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null); const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight'); const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight');
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production'); const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
const [trendFullFields,setTrendFullFields]=useState(()=>defaultFullMetricFields(stage==='black'?'blackProduct':'brightProduct'));
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef(''); const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month'); const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
const [trendResponse,setTrendResponse]=useState<{key:string;value:TrendResponse;query:QueryParams}|null>(null);const [trendRevision,setTrendRevision]=useState(0);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false); const [trendResponse,setTrendResponse]=useState<{key:string;value:TrendResponse;query:QueryParams}|null>(null);const [trendRevision,setTrendRevision]=useState(0);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
@@ -125,11 +127,12 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
</section> </section>
<div className="analysis-stack"> <div className="analysis-stack">
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity} <QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品"> defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} fullFields={trendFullFields} onFullFields={setTrendFullFields}
object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
{trendError&&<Alert type="warning" showIcon message={trendResponse?"趋势更新失败,当前显示上次结果":"趋势读取失败"} description={trendResponse?`${trendError};当前范围:${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:trendError} action={<Button onClick={()=>setTrendRevision(v=>v+1)}>重试</Button>}/>} {trendError&&<Alert type="warning" showIcon message={trendResponse?"趋势更新失败,当前显示上次结果":"趋势读取失败"} description={trendResponse?`${trendError};当前范围:${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:trendError} action={<Button onClick={()=>setTrendRevision(v=>v+1)}>重试</Button>}/>}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}> <div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
{trendMode==='data' {trendMode==='data'
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onMonth={selectTrendPeriod}/> ? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} fullFields={trendFullFields} onMonth={selectTrendPeriod}/>
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>} : <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
{showTrendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}</span>} {showTrendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}</span>}
</div> </div>
+9 -3
View File
@@ -1,4 +1,6 @@
.management-page.analysis-simple-page{gap:12px} .management-page.analysis-simple-page{gap:12px}
.analysis-simple-page .analysis-region-loading{display:flex;align-items:center;justify-content:center;gap:10px;min-height:120px;color:var(--muted-ink,#738198)}
.analysis-simple-page .analysis-conversation>.analysis-region-loading{flex:1}
.analysis-simple-page .analysis-workspace{height:calc(var(--dynamic-viewport-height) - 105px);min-height:540px;grid-template-columns:205px minmax(0,1fr)} .analysis-simple-page .analysis-workspace{height:calc(var(--dynamic-viewport-height) - 105px);min-height:540px;grid-template-columns:205px minmax(0,1fr)}
.page-heading.page-actions-only{min-height:0;margin:0;justify-content:flex-end} .page-heading.page-actions-only{min-height:0;margin:0;justify-content:flex-end}
.analysis-composer-buttons{display:flex;align-items:center;gap:8px} .analysis-composer-buttons{display:flex;align-items:center;gap:8px}
@@ -141,15 +143,15 @@
.analysis-process-history{margin:0;min-width:0;color:var(--muted-ink,#63758b)} .analysis-process-history{margin:0;min-width:0;color:var(--muted-ink,#63758b)}
.analysis-process-history>summary{display:flex;align-items:center;gap:8px;width:fit-content;min-height:24px;cursor:pointer;list-style:none;font-size:var(--font-control)} .analysis-process-history>summary{display:flex;align-items:center;gap:8px;width:fit-content;min-height:24px;cursor:pointer;list-style:none;font-size:var(--font-control)}
.analysis-process-history>summary::-webkit-details-marker{display:none} .analysis-process-history>summary::-webkit-details-marker{display:none}
.analysis-process-history>summary .anticon{font-size:var(--font-note);transition:transform .16s ease} .analysis-process-history>summary>.anticon{font-size:var(--font-note);transition:transform .16s ease}
.analysis-process-history[open]>summary .anticon{transform:rotate(90deg)} .analysis-process-history[open]>summary>.anticon{transform:rotate(90deg)}
.analysis-process-history>summary:focus-visible{outline:2px solid var(--primary-color,#607ae1);outline-offset:3px} .analysis-process-history>summary:focus-visible{outline:2px solid var(--primary-color,#607ae1);outline-offset:3px}
.analysis-process-history-body{padding:8px 0;max-height:360px;overflow:auto;overscroll-behavior:contain} .analysis-process-history-body{padding:8px 0;max-height:360px;overflow:auto;overscroll-behavior:contain}
.analysis-queued-followup{display:flex;align-items:center;gap:8px;color:var(--muted-ink,#63758b);font-size:var(--font-control);min-width:0} .analysis-queued-followup{display:flex;align-items:center;gap:8px;color:var(--muted-ink,#63758b);font-size:var(--font-control);min-width:0}
.analysis-queued-followup>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .analysis-queued-followup>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.analysis-queued-followup .ant-btn{flex:none;font-size:var(--font-control)} .analysis-queued-followup .ant-btn{flex:none;font-size:var(--font-control)}
@media(max-width:700px){.analysis-simple-page .ai-actions{align-items:flex-start;gap:8px;flex-wrap:wrap}.analysis-composer-buttons{margin-left:auto;gap:5px}} @media(max-width:700px){.analysis-simple-page .ai-actions{align-items:flex-start;gap:8px;flex-wrap:wrap}.analysis-composer-buttons{margin-left:auto;gap:5px}}
@media(prefers-reduced-motion:reduce){.analysis-process-history>summary .anticon{transition:none}} @media(prefers-reduced-motion:reduce){.analysis-process-history>summary>.anticon{transition:none}}
@keyframes analysis-event-appear{from{opacity:.4;transform:translateY(2px)}to{opacity:1;transform:none}} @keyframes analysis-event-appear{from{opacity:.4;transform:translateY(2px)}to{opacity:1;transform:none}}
.analysis-agent-stream>*{animation:analysis-event-appear .14s ease-out} .analysis-agent-stream>*{animation:analysis-event-appear .14s ease-out}
@@ -171,3 +173,7 @@
.analysis-clarification-actions{display:flex;justify-content:flex-end;margin-top:10px} .analysis-clarification-actions{display:flex;justify-content:flex-end;margin-top:10px}
.analysis-clarification fieldset:disabled .analysis-clarification-option{cursor:default;opacity:.65} .analysis-clarification fieldset:disabled .analysis-clarification-option{cursor:default;opacity:.65}
.analysis-clarification-option:focus-within{outline:2px solid var(--primary-color,#607ae1);outline-offset:2px} .analysis-clarification-option:focus-within{outline:2px solid var(--primary-color,#607ae1);outline-offset:2px}
.analysis-runtime-clock{display:inline-flex;align-items:center;gap:5px}
.analysis-turn-metadata .analysis-runtime-spinner{font-size:12px}
@media(prefers-reduced-motion:reduce){.analysis-runtime-spinner,.analysis-runtime-spinner svg{animation:none!important}}
+5 -1
View File
@@ -16,7 +16,11 @@ export function checkedConclusionComparison(sentence: string): ConclusionCompari
const value = sentence.replace(/\*\*/g, '').trim(); const value = sentence.replace(/\*\*/g, '').trim();
const match = value.match(/^([^。;\n]{1,50}?)(综合合格率|黑片合格率|亮片合格率|合格率)(?:为|是|[::])?\s*(\d+(?:\.\d+)?%)\s*[,,]\s*(?:较|相比|对比|比)\s*([^,,。;\n]{1,30}?)的?\s*(\d+(?:\.\d+)?%)\s*(下降|上升|提高|降低)\s*(\d+(?:\.\d+)?)(个百分点|pp)[。.]?$/); const match = value.match(/^([^。;\n]{1,50}?)(综合合格率|黑片合格率|亮片合格率|合格率)(?:为|是|[::])?\s*(\d+(?:\.\d+)?%)\s*[,,]\s*(?:较|相比|对比|比)\s*([^,,。;\n]{1,30}?)的?\s*(\d+(?:\.\d+)?%)\s*(下降|上升|提高|降低)\s*(\d+(?:\.\d+)?)(个百分点|pp)[。.]?$/);
if (!match || [match[3], match[5]].some(rate => Number.parseFloat(rate) > 100)) return null; if (!match || [match[3], match[5]].some(rate => Number.parseFloat(rate) > 100)) return null;
return { metric: match[2], currentLabel: match[1], current: match[3], previousLabel: match[4].replace(/的$/, ''), previous: match[5], direction: match[6], change: match[7], unit: match[8], original: value }; const currentRate = Number.parseFloat(match[3]), previousRate = Number.parseFloat(match[5]);
const isDecrease = /下降|降低/.test(match[6]);
if (currentRate !== previousRate && (currentRate < previousRate) !== isDecrease) return null;
const change = `${isDecrease ? '-' : '+'}${match[7]}`;
return { metric: match[2], currentLabel: match[1], current: match[3], previousLabel: match[4].replace(/的$/, ''), previous: match[5], direction: match[6], change, unit: match[8], original: value };
} }
function topicMatches(title: string, visual: AnalysisVisual): boolean { function topicMatches(title: string, visual: AnalysisVisual): boolean {
+27
View File
@@ -102,6 +102,20 @@ export function partialAnalysisNotice(reason: unknown, result: Record<string, un
return '本轮分析未完整结束,已保存现有结果。可以重试或继续追问。'; return '本轮分析未完整结束,已保存现有结果。可以重试或继续追问。';
} }
/** An ended turn without a visible answer still needs an explanation beside retry. */
export function emptyAnalysisNotice(turn: Record<string, unknown>, displayedAnswer: string): string {
const result = turn.result && typeof turn.result === 'object' && !Array.isArray(turn.result)
? turn.result as Record<string, unknown> : turn;
const status = String(turn.status || result.status || '').toUpperCase();
if (displayedAnswer.trim() || !['PARTIAL', 'FAILED', 'CANCELLED', 'COMPLETED'].includes(status)) return '';
if ([result.memberList, turn.memberList, result.recordList, turn.recordList].some(value => value !== undefined && value !== null)
|| [result.reportMarkdown, turn.reportMarkdown, result.reportHtml, turn.reportHtml].some(value => typeof value === 'string' && value.trim())) return '';
if (status === 'CANCELLED') return '分析已停止,尚未生成回答。';
if (status === 'COMPLETED') return '此记录没有可显示的回答,请新建会话重试。';
const quality = result.answerQuality && typeof result.answerQuality === 'object' ? result.answerQuality as Record<string, unknown> : {};
return quality.dataComplete === true ? '数据查询已完成,但未生成分析正文。请重新分析。' : '本轮未生成可显示的回答,请重新分析。';
}
/** Old answers keep their original wording; surface their explicitly recorded scope limitation. */ /** Old answers keep their original wording; surface their explicitly recorded scope limitation. */
export function hasUnreconciledEvidence(turn: Record<string, unknown>): boolean { export function hasUnreconciledEvidence(turn: Record<string, unknown>): boolean {
const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}; const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
@@ -136,3 +150,16 @@ export function partialAnswerIsOnlyProgress(turn: Record<string, unknown>): bool
if (lastAssistant < 0 || String(record(entries[lastAssistant]).text || '').trim() !== answer) return false; if (lastAssistant < 0 || String(record(entries[lastAssistant]).text || '').trim() !== answer) return false;
return entries.slice(lastAssistant + 1).some(item => ['tool_start', 'tool_result'].includes(String(record(item).kind))); return entries.slice(lastAssistant + 1).some(item => ['tool_start', 'tool_result'].includes(String(record(item).kind)));
} }
/** Tool event names describe a step, never the lifecycle of the whole turn. */
export function analysisStreamStatus(previous: unknown, event: string, reported: unknown): string {
const prior = String(previous || '').toUpperCase();
const terminal = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED', 'NEEDS_CLARIFICATION']);
if (terminal.has(prior)) return prior;
const name = event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
const status = String(reported || '').toUpperCase();
if (/^(?:TURN_)?(COMPLETED|PARTIAL|FAILED|CANCELLED|NEEDS_CLARIFICATION)$/.test(name)) return name.replace(/^TURN_/, '');
if (!name.startsWith('TOOL_') && (analysisIsRunning(status) || terminal.has(status))) return status;
if (name.startsWith('TOOL_') || name === 'ANSWER') return 'RUNNING';
return analysisIsRunning(prior) ? prior : 'RUNNING';
}
+69
View File
@@ -0,0 +1,69 @@
import { analysisTextEvidenceRefs } from './analysisEvidenceRefs.ts';
import type { AnalysisVisual } from './analysisVisualsModel.ts';
type Row = Record<string, unknown>;
const object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
const text = (value: unknown) => typeof value === 'string' ? value : '';
export interface OriginalAnalysisBody { answer: string; source: 'saved' | 'timeline' | 'unavailable' }
/** Older native turns saved a replacement report; their final assistant remains in the authorized timeline. */
export function originalAnalysisBody(turn?: Row): OriginalAnalysisBody | null {
if (!turn) return null;
const result = turn.result && typeof turn.result === 'object' ? object(turn.result) : turn;
const plan = object(turn.plan || result.plan);
if (![turn.executionMode, result.executionMode, plan.executionMode].includes('native_agent')) return null;
const saved = text(result.answer);
// Explicitly empty/redacted answers must not be replenished from an older transcript.
if (!saved.trim()) return { answer: '', source: 'unavailable' };
const lead = text(object(result.readingSummary).lead);
const replaced = /已取得本轮统计结果,答案整理尚未完整完成|已取得本轮统计结果,部分解释尚未完成|现有证据不足以支持本轮完整分析,已保留可核验统计结果/.test(lead || saved.slice(0, 160));
if (!replaced) return { answer: saved, source: 'saved' };
const raw = turn.timeline || result.timeline || plan.timeline;
const timeline = Array.isArray(raw) ? raw.map(object) : [];
let lastTool = -1;
timeline.forEach((entry, index) => { if (/^tool(?:_|$)/.test(text(entry.kind))) lastTool = index; });
const parts = timeline.slice(lastTool + 1).filter(entry => entry.kind === 'assistant' && text(entry.text).trim()).map(entry => text(entry.text));
// Historical public timeline entries were capped at 8000 characters without a truncation flag.
if (parts.some(part => part.length >= 8000)) return { answer: '', source: 'unavailable' };
return parts.length ? { answer: parts.join('\n\n'), source: 'timeline' } : { answer: '', source: 'unavailable' };
}
export interface OriginalAnalysisSection { id: string; markdown: string; visuals: AnalysisVisual[] }
/** Keep every Markdown line in order; images are additions after the associated chapter. */
export function originalAnalysisSections(answer: string, visuals: AnalysisVisual[]): OriginalAnalysisSection[] {
const sections: Array<OriginalAnalysisSection & { title: string; lines: string[] }> = [];
let current = { id: 'original-1', markdown: '', visuals: [] as AnalysisVisual[], title: '', lines: [] as string[] };
sections.push(current);
let fenced = false;
for (const line of answer.split('\n')) {
if (/^\s*```/.test(line)) fenced = !fenced;
const heading = !fenced ? line.match(/^#{1,6}\s+(.+?)\s*#*\s*$/) : null;
if (heading && current.lines.length) {
current = { id: `original-${sections.length + 1}`, markdown: '', visuals: [], title: heading[1], lines: [] };
sections.push(current);
} else if (heading) current.title = heading[1];
current.lines.push(line);
}
sections.forEach(section => { section.markdown = section.lines.join('\n'); });
const relevant = (title: string, visual: AnalysisVisual): number => {
const stage = visual.stage || (visual.metric.startsWith('black_') ? 'black' : visual.metric.startsWith('bright_') ? 'bright' : undefined);
if (stage === 'black' && /亮片/.test(title) && !/黑片/.test(title)
|| stage === 'bright' && /黑片/.test(title) && !/亮片/.test(title)) return 0;
if (visual.dimension === 'product') return /规格|产品/.test(title) ? 4 : 0;
if (visual.dimension === 'department' || visual.dimension === 'group') return /组织|产业部|分组|区域/.test(title) ? 4 : 0;
if (visual.dimension === 'defect' || visual.metric.startsWith('source_defect')) return /缺陷|缺角|隐裂|源字段/.test(title) ? 4 : 0;
if (/category/.test(visual.sectionKey || '')) return /报废大类|报废类别|正式报废/.test(title) ? 4 : 0;
if (visual.type === 'line' || visual.type === 'area') return /趋势|逐月|月度/.test(title) ? 4 : 0;
return /总体|阶段/.test(title) || stage === 'black' && /黑片/.test(title) || stage === 'bright' && /亮片/.test(title) ? 4 : /结论/.test(title) ? 2 : 0;
};
for (const visual of visuals) {
const candidates = sections.map(section => {
const refs = analysisTextEvidenceRefs(section.markdown);
const topic = relevant(section.title, visual);
return { section, score: topic ? topic + (visual.evidenceRefs.some(ref => refs.includes(ref)) ? 10 : 0) : 0 };
}).filter(item => item.score > 0).sort((a, b) => b.score - a.score);
if (candidates.length) candidates[0].section.visuals.push(visual);
else sections.push({ id: `original-chart-${sections.length + 1}`, title: '', lines: [], markdown: '', visuals: [visual] });
}
return sections.filter(section => section.markdown.trim() || section.visuals.length).map(({ id, markdown, visuals }) => ({ id, markdown, visuals }));
}
+10 -3
View File
@@ -7,6 +7,12 @@ export function analysisSnapshotResult(turn: Row): Row {
return turn.result && typeof turn.result === 'object' && !Array.isArray(turn.result) ? object(turn.result) : turn; return turn.result && typeof turn.result === 'object' && !Array.isArray(turn.result) ? object(turn.result) : turn;
} }
function originalTranscript(turn: Row): unknown {
const result = analysisSnapshotResult(turn), plan = object(turn.plan || result.plan);
if (![turn.executionMode, result.executionMode, plan.executionMode].includes('native_agent')) return null;
return turn.timeline || result.timeline || plan.timeline || [];
}
function canonical(value: unknown): string { function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`; if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (value && typeof value === 'object') { if (value && typeof value === 'object') {
@@ -19,16 +25,17 @@ export function reportSnapshotIdentity(turn: Row): string {
const result = analysisSnapshotResult(turn); const result = analysisSnapshotResult(turn);
const value = (key: string, fallback: unknown) => ['readingSummary', 'queryEvidenceRefs'].includes(key) const value = (key: string, fallback: unknown) => ['readingSummary', 'queryEvidenceRefs'].includes(key)
? result[key] ?? fallback : result[key] ?? turn[key] ?? fallback; ? result[key] ?? fallback : result[key] ?? turn[key] ?? fallback;
return canonical({ answer: value('answer', ''), visuals: value('visuals', []), return canonical({ originalTranscript: originalTranscript(turn), answer: value('answer', ''), visuals: value('visuals', []),
results: value('results', []), reportMarkdown: value('reportMarkdown', ''), results: value('results', []), reportMarkdown: value('reportMarkdown', ''),
reportHtml: value('reportHtml', ''), memberList: value('memberList', null), reportHtml: value('reportHtml', ''), memberList: value('memberList', null),
recordList: value('recordList', null), readingSummary: value('readingSummary', null), queryEvidenceRefs: value('queryEvidenceRefs', []), question: turn.question || '' }); recordList: value('recordList', null), readingSummary: value('readingSummary', null), queryEvidenceRefs: value('queryEvidenceRefs', []), question: turn.question || '' });
} }
export function reportSnapshotDifferences(left: Row, right: Row): string[] { export function reportSnapshotDifferences(left: Row, right: Row): string[] {
const fields = ['answer', 'visuals', 'results', 'reportMarkdown', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question']; const fields = ['answer', 'visuals', 'results', 'reportMarkdown', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question', 'originalTranscript'];
return fields.filter(key => { return fields.filter(key => {
const value = (turn: Row) => { const value = (turn: Row) => {
if (key === 'originalTranscript') return originalTranscript(turn);
const result = analysisSnapshotResult(turn); const result = analysisSnapshotResult(turn);
return key === 'question' ? turn.question || '' : ['readingSummary', 'queryEvidenceRefs'].includes(key) return key === 'question' ? turn.question || '' : ['readingSummary', 'queryEvidenceRefs'].includes(key)
? result[key] ?? (key === 'readingSummary' ? null : []) : result[key] ?? turn[key] ?? (key === 'memberList' || key === 'recordList' || key === 'readingSummary' ? null : key === 'visuals' || key === 'results' || key === 'queryEvidenceRefs' ? [] : ''); ? result[key] ?? (key === 'readingSummary' ? null : []) : result[key] ?? turn[key] ?? (key === 'memberList' || key === 'recordList' || key === 'readingSummary' ? null : key === 'visuals' || key === 'results' || key === 'queryEvidenceRefs' ? [] : '');
@@ -47,7 +54,7 @@ export async function authorizeAnalysisSnapshot(turn: Row): Promise<void> {
} }
const differences = reportSnapshotDifferences(current, turn); const differences = reportSnapshotDifferences(current, turn);
if (differences.length) { if (differences.length) {
const labels: Record<string, string> = { answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题' }; const labels: Record<string, string> = { answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题', originalTranscript: '原始正文' };
throw new Error(`分析结果或访问权限已变化(${differences.map(key => labels[key] || key).join('、')}),请重新打开这条分析后再导出。`); throw new Error(`分析结果或访问权限已变化(${differences.map(key => labels[key] || key).join('、')}),请重新打开这条分析后再导出。`);
} }
} }
+3 -1
View File
@@ -12,7 +12,9 @@ export function canRecoverAnalysisVisuals(turn: Row): boolean {
const planned=Array.isArray(task.queryPlan)&&task.queryPlan.some(raw=>{ const planned=Array.isArray(task.queryPlan)&&task.queryPlan.some(raw=>{
const node=object(raw);return ['ranking','trend','defects'].includes(String(node.purpose))&&node.visualPreference!=='none'; const node=object(raw);return ['ranking','trend','defects'].includes(String(node.purpose))&&node.visualPreference!=='none';
}); });
const requested=task.trendRequired===true||task.visualPreference==='required'||Boolean(task.visualType)||planned; const gaps=object(result.executionCoverage).visualGaps;
const nativeGap=task.executionMode==='native_agent'&&(['failed','unavailable'].includes(state)||Array.isArray(gaps)&&gaps.length>0);
const requested=task.trendRequired===true||task.visualPreference==='required'||Boolean(task.visualType)||planned||nativeGap;
return plan.protocolVersion===1&&['metrics','analysis'].includes(String(task.kind)) return plan.protocolVersion===1&&['metrics','analysis'].includes(String(task.kind))
&&['COMPLETED','PARTIAL'].includes(status)&&task.visualPreference!=='none'&&requested &&['COMPLETED','PARTIAL'].includes(status)&&task.visualPreference!=='none'&&requested
&&object(result.visualRecovery).complete!==true&&(state!=='ready'||status==='PARTIAL'); &&object(result.visualRecovery).complete!==true&&(state!=='ready'||status==='PARTIAL');
+20 -4
View File
@@ -121,6 +121,15 @@ function hasOnlyKeys(value: Record<string, unknown>, allowed: Set<string>): bool
return Object.keys(value).every(key => allowed.has(key)); return Object.keys(value).every(key => allowed.has(key));
} }
function canonicalLegacyRateDropNote(note: string | undefined): string {
const details = (note || '')
.replace(/^(?:条形末端显示具体变化:)?[^;。]*?(?:正值|负值)[^;。]*[;。]\s*/, '')
.replace(/^[;;,,。.\s]+/, '')
.trim();
const basis = '正值表示本期合格率上升,负值表示下降;变化值为本期减比较期。';
return details ? `${basis} ${details}` : basis;
}
/** 解析前仅复制普通 JSON 数据,阻止 getter、toJSON、原型和函数进入渲染链路。 */ /** 解析前仅复制普通 JSON 数据,阻止 getter、toJSON、原型和函数进入渲染链路。 */
function copyJsonData(value: unknown, seen = new Set<object>(), budget = { nodes: 0 }, depth = 0): unknown { function copyJsonData(value: unknown, seen = new Set<object>(), budget = { nodes: 0 }, depth = 0): unknown {
if (depth > 32 || ++budget.nodes > 100_000) throw new Error('unsafe JSON data'); if (depth > 32 || ++budget.nodes > 100_000) throw new Error('unsafe JSON data');
@@ -272,7 +281,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
const comparisonPeriod = value.comparisonPeriod === undefined ? undefined : safeContext(value.comparisonPeriod); const comparisonPeriod = value.comparisonPeriod === undefined ? undefined : safeContext(value.comparisonPeriod);
const evidenceRefs = safeTextList(value.evidenceRefs, 100); const evidenceRefs = safeTextList(value.evidenceRefs, 100);
const requiredFields = safeTextList(value.requiredFields, 100); const requiredFields = safeTextList(value.requiredFields, 100);
const note = value.note === undefined ? undefined : boundedText(value.note, 500); const rawNote = value.note === undefined ? undefined : boundedText(value.note, 500);
const stage = value.stage === undefined ? undefined : value.stage; const stage = value.stage === undefined ? undefined : value.stage;
const sectionKey = value.sectionKey === undefined ? undefined : value.sectionKey; const sectionKey = value.sectionKey === undefined ? undefined : value.sectionKey;
const dimension = value.dimension === undefined ? undefined : value.dimension; const dimension = value.dimension === undefined ? undefined : value.dimension;
@@ -292,6 +301,12 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
...(coverage.denominator === undefined ? {} : { denominator: Number(coverage.denominator) }), ...(coverage.denominator === undefined ? {} : { denominator: Number(coverage.denominator) }),
} }
: null; : null;
// v1 saved rate-drop charts used positive values for declines. New charts
// carry "本期减比较期" in the existing bounded note field. This survives the
// backend's strict v1 field allowlist; unmarked snapshots are legacy values.
const normalizeLegacyRateDrop = metric === 'rate_drop_pp' && unit === 'pp'
&& !(rawNote || '').includes('本期减比较期');
const note = normalizeLegacyRateDrop ? canonicalLegacyRateDropNote(rawNote || undefined) : rawNote;
const categories = Array.isArray(value.categories) && value.categories.length > 0 && value.categories.length <= MAX_VISUAL_CATEGORIES const categories = Array.isArray(value.categories) && value.categories.length > 0 && value.categories.length <= MAX_VISUAL_CATEGORIES
? value.categories.map(category => { ? value.categories.map(category => {
@@ -325,7 +340,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
return null; return null;
} }
if (unit === 'ratio' && (item < 0 || (!allowsAboveOneRatio(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`); if (unit === 'ratio' && (item < 0 || (!allowsAboveOneRatio(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
return item; return normalizeLegacyRateDrop ? -item : item;
}); });
series.push({ key, label, values }); series.push({ key, label, values });
} }
@@ -335,7 +350,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
const valid = !!id && !!type && !!title && subtitle !== null && UNIT_VALUES.has(unit as AnalysisVisualUnit) const valid = !!id && !!type && !!title && subtitle !== null && UNIT_VALUES.has(unit as AnalysisVisualUnit)
&& !!metric && !!originTurnId && !!scope && isValidAnalysisPeriodContext(scope) && !!metric && !!originTurnId && !!scope && isValidAnalysisPeriodContext(scope)
&& !!period && isValidAnalysisPeriodContext(period) && (value.comparisonPeriod === undefined || !!comparisonPeriod && isValidAnalysisPeriodContext(comparisonPeriod)) && !!period && isValidAnalysisPeriodContext(period) && (value.comparisonPeriod === undefined || !!comparisonPeriod && isValidAnalysisPeriodContext(comparisonPeriod))
&& !!evidenceRefs && !!requiredFields && (value.note === undefined || note !== null) && !!evidenceRefs && !!requiredFields && (value.note === undefined || rawNote !== null)
&& (stage === undefined || stage === 'black' || stage === 'bright') && (stage === undefined || stage === 'black' || stage === 'bright')
&& (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey)) && (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey))
&& (dimension === undefined || DIMENSIONS.has(dimension as AnalysisVisualDimension)) && (dimension === undefined || DIMENSIONS.has(dimension as AnalysisVisualDimension))
@@ -877,7 +892,8 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
}), }),
itemStyle: { color: colors[seriesIndex % colors.length] }, itemStyle: { color: colors[seriesIndex % colors.length] },
connectNulls: false, connectNulls: false,
smooth: false, smooth: ['line', 'area'].includes(visual.type) ? 0.15 : false,
smoothMonotone: 'x',
...(['bar', 'column'].includes(visual.type) ? { ...(['bar', 'column'].includes(visual.type) ? {
barMaxWidth: combinedDefects ? 18 : 32, barMaxWidth: combinedDefects ? 18 : 32,
...(combinedDefects ? { stack: 'combined-defect-stage', barWidth: 18 } : {}), ...(combinedDefects ? { stack: 'combined-defect-stage', barWidth: 18 } : {}),
+35
View File
@@ -0,0 +1,35 @@
import type { MetricRow, Stage } from './types';
export type MetricStageField = 'totalWeight' | 'qualifiedWeight' | 'scrapWeight' | 'headquartersScrapWeight' | 'rate';
export type MetricStageColumn = { kind: 'metric'; field: MetricStageField } | { kind: 'defect'; name: string };
export type MetricFieldView = 'key' | 'full';
export type MetricPageView = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct';
const KEY_FIELDS: MetricStageField[] = ['totalWeight', 'qualifiedWeight', 'scrapWeight'];
/** The stage pages start expanded; the four organization/product pages start compact. */
export function defaultFullMetricFields(page: string): boolean {
return page === 'blackProduct' || page === 'brightProduct';
}
/** Keep the full/key field contract shared by the summary and trend tables. */
export function metricStageColumnPlan(
rows: MetricRow[],
stage: Stage,
fullFields: boolean,
rateBasis: 'original' | 'withoutHeadquartersScrap',
): MetricStageColumn[] {
const columns: MetricStageColumn[] = KEY_FIELDS.map(field => ({ kind: 'metric', field }));
if (fullFields) {
const defectNames = Array.from(new Set(rows.flatMap(row => (row[stage]?.defects || []).map(item => item.name))));
const defectColumns = defectNames.map(name => ({ kind: 'defect' as const, name }));
columns.push(...defectColumns);
if (stage === 'bright' && rateBasis === 'original') {
const diffusionIndex = defectNames.indexOf('扩散废');
const insertAt = KEY_FIELDS.length + (diffusionIndex < 0 ? defectNames.length : diffusionIndex + 1);
columns.splice(insertAt, 0, { kind: 'metric', field: 'headquartersScrapWeight' });
}
}
columns.push({ kind: 'metric', field: 'rate' });
return columns;
}
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>AI原文与运行状态验收</title></head><body><div id="root"></div><script type="module" src="./analysis-original.tsx"></script></body></html>
+43
View File
@@ -0,0 +1,43 @@
// Local acceptance fixture: all requests are intercepted; no model, API or database writes.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {App,ConfigProvider} from 'antd';
import ManagementPages from '../src/ManagementPages';
import '../src/styles.css';
import '../src/workspace-finish.css';
const user={id:'original-fixture',username:'fixture',displayName:'本地验收',roles:['SYSTEM_ADMIN'],departments:[],groups:[]};
const modelAnswer='## 结论\n\n本期合格率下降,两个阶段的变化机制不同。完整模型正文必须保留。\n\n### 总体与阶段\n\n黑片合格率从97.58%降至97.27%,变化为 -0.30 pp。\n\n| 阶段 | 变化 |\n| --- | --- |\n| 黑片 | -0.30 pp |\n\n表格之后继续解释投入规模与报废规模,不能因为增加图表就丢掉这段。[Q11111111]\n\n### 下一步\n\n上述是统计线索,仍需现场核实生产原因。';
const loadingCase=new URLSearchParams(location.search).get('loadingCase');
if(loadingCase)history.replaceState({},'',`${location.pathname}?page=analysis&sessionId=fixture-session&loadingCase=${encodeURIComponent(loadingCase)}`);
let question=loadingCase?'为什么合格率下降?':'',status=loadingCase?'PARTIAL':'QUEUED',createdAt='',startedAt='',finishedAt='';let timeline:Record<string,unknown>[]=loadingCase?[{kind:'assistant',sequence:1,text:modelAnswer}]:[];
const visual={id:'stage-change',type:'column',title:'黑片合格率变化',subtitle:'',unit:'pp',metric:'rate_drop_pp',stage:'black',categories:[{key:'black',label:'黑片'}],series:[{key:'rateDrop',label:'合格率降幅',values:[.30]}],evidenceRefs:['Q11111111'],requiredFields:['black_good_weight','black_total_weight'],scope:{year:2026,month:9,releaseId:'fixture'},period:{year:2026,month:9},comparisonPeriod:{year:2026,month:8},originTurnId:'fixture-turn',coverage:{totalRows:1,returnedRows:1,truncated:false}};
const saved=()=>({id:'fixture-turn',sessionId:'fixture-session',question,status,createdAt,startedAt,finishedAt,executionMode:'native_agent',plan:{timeline},answer:'已取得本轮统计结果,答案整理尚未完整完成。',readingSummary:{version:1,lead:'已取得本轮统计结果,答案整理尚未完整完成。',evidence:[],notices:[],evidenceRefs:['Q11111111']},queryEvidenceRefs:['Q11111111'],visualSchemaVersion:1,visualState:'ready',visuals:[visual],stopReason:'evidence_incomplete'});
const json=(value:unknown)=>new Response(JSON.stringify(value),{headers:{'Content-Type':'application/json'}});
window.fetch=async(input,init)=>{
const path=new URL(String(input),location.origin).pathname;
if(path==='/api/auth/csrf')return json({token:'fixture'});
if(path==='/api/options'){if(loadingCase)await new Promise(r=>setTimeout(r,45000));return json({years:[2026],departments:[],groups:[],products:[],projectGroups:[]});}
if(path==='/api/analysis/sessions'&&init?.method==='POST'){await new Promise(r=>setTimeout(r,1500));return json({session:{id:'fixture-session'}});}
if(path==='/api/analysis/sessions'){if(loadingCase)await new Promise(r=>setTimeout(r,45000));return loadingCase==='error'?new Response('{}',{status:403}):json({items:question?[{id:'fixture-session',title:question,activeTurnStatus:status}]:[]});}
if(path==='/api/analysis/sessions/fixture-session/turns'&&init?.method==='POST'){
question=JSON.parse(String(init.body)).question;createdAt=new Date().toISOString();await new Promise(r=>setTimeout(r,300));return json({turn:{id:'fixture-turn',sessionId:'fixture-session',status,createdAt}});
}
if(path==='/api/analysis/sessions/fixture-session/turns')return json({items:[{id:'fixture-turn',status,createdAt,startedAt,finishedAt}]});
if(path==='/api/analysis/sessions/fixture-session'){if(loadingCase==='body')await new Promise(r=>setTimeout(r,30000));return json({id:'fixture-session',context:{year:2026},turns:status==='PARTIAL'?[saved()]:[]});}
if(path==='/api/analysis/turns/fixture-turn'||path.endsWith('/snapshot'))return json(saved());
if(path.endsWith('/events')){
const encoder=new TextEncoder();let closed=false;const timers:ReturnType<typeof setTimeout>[]=[];
const stream=new ReadableStream({start(controller){
let eventId=0;const send=(event:string,data:unknown)=>{if(!closed)controller.enqueue(encoder.encode(`id: ${++eventId}\nevent: ${event}\ndata: ${JSON.stringify(data)}\n\n`));};
send('progress',{status:'QUEUED'});
timers.push(setTimeout(()=>{status='RUNNING';startedAt=new Date().toISOString();send('progress',{status,message:'正在理解本轮目标和连续追问…'});},300));
timers.push(setTimeout(()=>{timeline=[{kind:'tool_start',sequence:1,tool:'read',toolCallId:'read-1',label:'核对正式指标',status:'running'}];send('tool_started',{timeline,step:timeline[0]});},800));
timers.push(setTimeout(()=>{timeline.push({kind:'tool_result',sequence:2,tool:'read',toolCallId:'read-1',label:'核对正式指标',status:'completed'});send('tool_completed',{timeline,step:timeline[1]});},6000));
timers.push(setTimeout(()=>{status='PARTIAL';finishedAt=new Date().toISOString();timeline.push({kind:'assistant',sequence:3,text:modelAnswer});send('partial',{status,result:saved()});if(!closed){closed=true;controller.close();}},30000));
init?.signal?.addEventListener('abort',()=>{if(!closed){closed=true;controller.close();}timers.forEach(clearTimeout);},{once:true});
},cancel(){closed=true;timers.forEach(clearTimeout);}});
return new Response(stream,{headers:{'Content-Type':'text/event-stream'}});
}
return json({items:[]});
};
createRoot(document.getElementById('root')!).render(<ConfigProvider><App><main style={{padding:18,maxWidth:1500,margin:'auto'}}><ManagementPages page="analysis" user={user} onUnauthorized={()=>false} onNavigate={()=>{}}/></main></App></ConfigProvider>);
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { emptyAnalysisNotice } from '../src/analysisConversationState.ts';
test('the reported empty native answer explains the missing body without claiming analysis success', () => {
const result = { answer: '', answerQuality: { dataComplete: true, narrativeComplete: false } };
assert.equal(emptyAnalysisNotice({ status: 'PARTIAL', result }, ''), '数据查询已完成,但未生成分析正文。请重新分析。');
assert.equal(emptyAnalysisNotice({ status: 'PARTIAL', ...result }, ''), '数据查询已完成,但未生成分析正文。请重新分析。');
});
test('running, successful, clarification and nonempty answers retain their existing display', () => {
for (const status of ['QUEUED', 'RUNNING', 'NEEDS_CLARIFICATION']) assert.equal(emptyAnalysisNotice({ status }, ''), '');
for (const status of ['PARTIAL', 'FAILED', 'CANCELLED']) assert.equal(emptyAnalysisNotice({ status }, '原文'), '');
});
test('a historical empty completed record is visible without pretending its completed turn can be retried',()=>{
assert.equal(emptyAnalysisNotice({status:'COMPLETED'},''),'此记录没有可显示的回答,请新建会话重试。');
assert.equal(emptyAnalysisNotice({status:'COMPLETED'},'已保存原文'),'');
});
test('failure, incomplete data and cancellation receive accurate, bounded notices', () => {
assert.equal(emptyAnalysisNotice({ status: 'FAILED', stopReason: 'private diagnostics' }, ''), '本轮未生成可显示的回答,请重新分析。');
assert.equal(emptyAnalysisNotice({ status: 'PARTIAL', answerQuality: { dataComplete: false } }, ''), '本轮未生成可显示的回答,请重新分析。');
assert.equal(emptyAnalysisNotice({ status: 'CANCELLED' }, ''), '分析已停止,尚未生成回答。');
});
test('structured lists and reports do not need an additional prose answer', () => {
for (const [key, value] of [['memberList', {}], ['recordList', []], ['reportMarkdown', '报告'], ['reportHtml', '<p>报告</p>']]) {
assert.equal(emptyAnalysisNotice({ status: 'PARTIAL', result: { [key]: value } }, ''), '');
assert.equal(emptyAnalysisNotice({ status: 'PARTIAL', [key]: value }, ''), '');
}
});
@@ -0,0 +1,62 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn} from '../src/analysisConversationState.ts';
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
const compile=code=>ts.transpileModule(code,{fileName:'status.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
const isObjectRecord=v=>!!v&&typeof v==='object'&&!Array.isArray(v);
const finalStatuses=new Set(['COMPLETED','PARTIAL','FAILED','CANCELLED','NEEDS_CLARIFICATION']);
function fixture(){
let lastTurn={id:'t1',question:'q',status:'QUEUED',createdAt:'2026-11-02T01:00:00Z'},onEvent,reads=0;
const stream=deferred(),firstRead=deferred(),secondRead=deferred();
const env={mounted:{current:true},streamController:{current:null},subscriptionGeneration:{current:0},sessionId:'s1',eventCursors:{current:{}},ANALYSIS_FINAL_STATUSES:finalStatuses,
setLastTurn:next=>lastTurn=typeof next==='function'?next(lastTurn):next,writeAnalysisLocation(){},setActiveTurnId(){},setBusy(){},setRetryQuestion(){},setTurns(){},setError(){},loadSessions:async()=>{},onUnauthorized:()=>false,apiMessage:e=>e.message,
isObjectRecord,analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn,collectionItems:value=>value.items||[],modelThinkingEntries:()=>[],mergeModelThinking:()=>[]};
const api={analysisTurnEvents:async(_id,options)=>{onEvent=options.onEvent;return stream.promise;},analysisSessionTurns:()=>{reads++;return reads===1?firstRead.promise:secondRead.promise;}};
const code=source.slice(source.indexOf(' const followTurn = async'),source.indexOf('\n useEffect(() => {\n if (!active || restoreStarted.current)'));
const follow=new Function('api',...Object.keys(env),compile(code+'\nreturn followTurn;'))(api,...Object.values(env));
const work=follow('t1','q','s1');
return{get:()=>lastTurn,reads:()=>reads,switchTurn(){env.subscriptionGeneration.current++;lastTurn={id:'other',status:'RUNNING'};},emit(event,data){onEvent({id:String(Math.random()),event,data});},firstRead,secondRead,async close(){env.streamController.current?.abort();stream.resolve();await work;}};
}
test('tool step events keep the whole turn running and terminal status does not regress',()=>{
assert.equal(analysisStreamStatus('RUNNING','tool_started',undefined),'RUNNING');
assert.equal(analysisStreamStatus('RUNNING','tool_completed','completed'),'RUNNING');
assert.equal(analysisStreamStatus('RUNNING','completed','COMPLETED'),'COMPLETED');
assert.equal(analysisStreamStatus('COMPLETED','progress','RUNNING'),'COMPLETED');
});
test('actual event subscriber keeps status live and fills the server clock without re-entering',async()=>{
const ui=fixture();assert.equal(ui.reads(),1);
ui.emit('progress',{status:'RUNNING'});
ui.firstRead.resolve({items:[{id:'t1',createdAt:'2026-11-02T01:00:00Z',startedAt:''}]});await tick();
assert.equal(ui.reads(),2,'a running event during an initial queued timing read schedules one non-overlapping follow-up');
ui.secondRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
ui.emit('tool_started',{step:{status:'running'}});
assert.equal(ui.get().status,'RUNNING');assert.equal(ui.get().startedAt,'2026-11-02T01:00:05Z');
ui.emit('tool_completed',{step:{status:'completed'}});assert.equal(ui.get().status,'RUNNING');
assert.equal(ui.reads(),2);await ui.close();
});
test('late timing metadata cannot update a different selected turn',async()=>{
const ui=fixture();ui.switchTurn();await ui.close();ui.firstRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
assert.equal(ui.get().startedAt,undefined);
});
test('metadata renders a waiting clock immediately and a spinning running clock after server start',()=>{
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,props=>React.createElement('i',props));
const now=Date.now();
const waiting=renderToStaticMarkup(React.createElement(Metadata,{turn:{_uiSubmittedAt:new Date(now-30000).toISOString()},status:'SUBMITTING',compact:true}));
assert.match(waiting,/提交中/);assert.match(waiting,/已等待 30秒/);
const running=renderToStaticMarkup(React.createElement(Metadata,{turn:{startedAt:new Date(now-10000).toISOString()},status:'RUNNING',compact:true}));
assert.match(running,/已运行 10秒/);assert.match(running,/analysis-runtime-spinner/);
});
test('partial remains a backend state without an extra partial label in conversation metadata',()=>{
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,()=>null);
const html=renderToStaticMarkup(React.createElement(Metadata,{turn:{durationMs:6000},status:'PARTIAL',compact:true}));
assert.doesNotMatch(html,/部分完成/);assert.match(html,/运行时长 6秒/);
});
@@ -0,0 +1,77 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import {analysisComposerState} from '../src/analysisScope.ts';
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
function restoreFixture({sessionId='',turnId='',link=false}={}){
const list=deferred(),opens=[];let effect,loading=true;
const env={active:true,restoreStarted:{current:false},mounted:{current:true},navigationGeneration:{current:0},initialSessionId:sessionId,initialTurnId:turnId,initialLink:{present:link},user:{id:'u'},
useEffect:fn=>{effect=fn;},setHistoryLoading:v=>{loading=v;},setSessions(){},setSessionsLoaded(){},setSessionsLoading(){},collectionItems:v=>v.items||[],
loadSessions:async()=>(await list.promise).items,api:{analysisSessions:()=>list.promise,analysisTurn:async()=>({sessionId:'linked-session'})},defaultAnalysisSession:(_u,items)=>items[0]?.id,
openSession:async(...args)=>{opens.push(args);loading=false;return true;},onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
const marker=' useEffect(() => {\n if (!active || restoreStarted.current)';const start=source.indexOf(marker);const end=source.indexOf('\n useEffect(() => {',start+marker.length);
const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
new Function(...Object.keys(env),code)(...Object.values(env));effect();
return{list,opens,get loading(){return loading;}};
}
test('an explicit history link loads its body without waiting for the unrelated session list',async()=>{
const ui=restoreFixture({sessionId:'requested-session'});await tick();assert.deepEqual(ui.opens,[['requested-session',undefined]]);
ui.list.resolve({items:[]});await tick();
});
test('a turn link can resolve its session while the session list is still pending',async()=>{
const ui=restoreFixture({turnId:'requested-turn'});await tick();assert.deepEqual(ui.opens,[['linked-session','requested-turn']]);
ui.list.resolve({items:[]});await tick();
});
test('default history selection still waits for the list before choosing a session',async()=>{
const ui=restoreFixture();await tick();assert.equal(ui.opens.length,0);ui.list.resolve({items:[{id:'recent'}]});await tick();assert.deepEqual(ui.opens,[['recent',undefined]]);
});
function listFixture(){
const read=deferred();let reads=0,state={busy:false,loaded:false,items:[],error:''};
const env={mounted:{current:true},active:true,sessionReadRequest:{current:null},setSessionsLoading:v=>{state.busy=v;},setSessions:v=>{state.items=v;},setSessionsLoaded:v=>{state.loaded=v;},setSessionsError:v=>{state.error=v;},onUnauthorized:()=>false,apiMessage:e=>e.message,collectionItems:v=>v.items||[],api:{analysisSessions:()=>{reads++;return read.promise;}}};
const start=source.indexOf(' const loadSessions = async');const end=source.indexOf('\n const retrySessions =',start);
const code=ts.transpileModule(source.slice(start,end)+'\nreturn loadSessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
return{read,state,reads:()=>reads,load:new Function(...Object.keys(env),code)(...Object.values(env))};
}
test('session-list reads are shared, and failure stays within the list resource',async()=>{
const ui=listFixture();const a=ui.load(),b=ui.load();assert.equal(ui.reads(),1);assert.equal(ui.state.busy,true);
ui.read.resolve({items:[{id:'recent'}]});assert.deepEqual(await a,[{id:'recent'}]);await b;assert.equal(ui.state.loaded,true);assert.equal(ui.state.busy,false);
ui.read.resolve({items:[]});
});
test('a failed list read ends its own loading state and cannot masquerade as an empty successful list',async()=>{
const ui=listFixture();const work=ui.load();ui.read.resolve(Promise.reject(new Error('list unavailable')));assert.equal(await work,undefined);
assert.equal(ui.state.busy,false);assert.equal(ui.state.loaded,false);assert.equal(ui.state.error,'list unavailable');
});
test('ordinary and explicit historical conversations never download the unused options resource',()=>{
const start=source.indexOf(' useEffect(() => {\n if (!active || !initialLink.present');assert.notEqual(start,-1);
const end=source.indexOf('\n\n',start);const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
for(const [present,session,turn] of [[false,'',''],[false,'s',''],[true,'s',''],[true,'','t']]){
let reads=0;const env={useEffect:fn=>fn(),active:true,initialLink:{present},initialSessionId:session,initialTurnId:turn,optionsRequestStarted:{current:false},optionsRead:{run:()=>{reads++;}},onUnauthorized:()=>false};
new Function(...Object.keys(env),code)(...Object.values(env));assert.equal(reads,0);
}
});
function retryFixture(sessionId='',turnId=''){
const list=deferred(),opens=[],navigationGeneration={current:0},state={historyLoading:false};
const env={sessionId,navigationGeneration,pendingTurnLink:{current:turnId},mounted:{current:true},initialLink:{present:false},user:{id:'u'},setHistoryLoading:v=>{state.historyLoading=v;},loadSessions:()=>list.promise,api:{analysisTurn:async()=>({sessionId:'target-session'})},openSession:async(id,focus)=>opens.push([id,focus]),defaultAnalysisSession:(_u,items)=>items[0]?.id,onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
const start=source.indexOf(' const retrySessions = async');const end=source.indexOf('\n useEffect(',start);
const code=ts.transpileModule(source.slice(start,end)+'\nreturn retrySessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
return{list,opens,state,navigationGeneration,retry:new Function(...Object.keys(env),code)(...Object.values(env))};
}
test('retrying a linked history does not wait for a slow list',async()=>{
const ui=retryFixture('selected');await ui.retry();assert.deepEqual(ui.opens,[['selected',undefined]]);ui.list.resolve([]);
});
test('default-list retry cannot navigate over a newer user selection',async()=>{
const ui=retryFixture();const work=ui.retry();ui.navigationGeneration.current++;ui.list.resolve([{id:'old-default'}]);await work;assert.deepEqual(ui.opens,[]);
});
test('retry of a turn-only link re-resolves the requested turn instead of opening an unrelated default',async()=>{
const ui=retryFixture('','requested-turn');ui.list.resolve([{id:'unrelated-default'}]);await ui.retry();assert.deepEqual(ui.opens,[['target-session','requested-turn']]);
});
test('default-history retry locks sending until its target resolves, so a late list cannot replace a new submission',async()=>{
const ui=retryFixture();const work=ui.retry();assert.equal(ui.state.historyLoading,true);
assert.equal(analysisComposerState(false,false,ui.state.historyLoading,'新问题').sendDisabled,true);
ui.list.resolve([{id:'default'}]);await work;assert.equal(ui.state.historyLoading,false);
});
@@ -4,6 +4,7 @@ import fs from 'node:fs';
import ts from 'typescript'; import ts from 'typescript';
import React from 'react'; import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server'; import { renderToStaticMarkup } from 'react-dom/server';
import { emptyAnalysisNotice } from '../src/analysisConversationState.ts';
import { import {
analysisMemberListFullyRead, analysisMemberListFullyRead,
analysisMemberListPage, analysisMemberListPage,
@@ -113,12 +114,17 @@ test('member-list display is opt-in, keeping earlier Markdown answers on their e
const source = fs.readFileSync(new URL('../src/ManagementPages.tsx', import.meta.url), 'utf8'); const source = fs.readFileSync(new URL('../src/ManagementPages.tsx', import.meta.url), 'utf8');
const turn = source.slice(source.indexOf('function AnalysisTurn('), source.indexOf('function AnalysisTurnMetadata(')) const turn = source.slice(source.indexOf('function AnalysisTurn('), source.indexOf('function AnalysisTurnMetadata('))
.replace('function AnalysisTurn(', 'function AnalysisTurn('); .replace('function AnalysisTurn(', 'function AnalysisTurn(');
const component = new Function('React', 'useAnalysisVisualRecovery', 'partialAnswerIsOnlyProgress', 'analysisScopeText', 'isObjectRecord', 'AnalysisProcess', 'AnalysisTurnMetadata', 'AiMarkdown', 'AnalysisNarrative', 'NativeAnalysisReport', 'AnalysisReportExport', 'Button', 'AnalysisMemberListPanel', const component = new Function('React', 'useAnalysisVisualRecovery', 'partialAnswerIsOnlyProgress', 'analysisScopeText', 'isObjectRecord', 'AnalysisProcess', 'AnalysisTurnMetadata', 'AiMarkdown', 'AnalysisNarrative', 'NativeAnalysisReport', 'AnalysisReportExport', 'Button', 'AnalysisMemberListPanel', 'emptyAnalysisNotice',
ts.transpileModule(`${turn}\nreturn AnalysisTurn;`, { fileName: 'analysis-turn.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText ts.transpileModule(`${turn}\nreturn AnalysisTurn;`, { fileName: 'analysis-turn.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
)(React, turn => ({turn,available:false,recovering:false,error:''}), () => false, () => '', value => Boolean(value) && typeof value === 'object' && !Array.isArray(value), () => null, () => null, ({ content }) => React.createElement('p', null, content), )(React, turn => ({turn,available:false,recovering:false,error:turn.recoveryError||''}), () => false, () => '', value => Boolean(value) && typeof value === 'object' && !Array.isArray(value), () => null, () => null, ({ content }) => React.createElement('p', null, content),
({ answer }) => React.createElement('div', { className: 'legacy-markdown' }, answer), () => null, () => null, ({ children }) => React.createElement('button', null, children), () => null); ({ answer }) => React.createElement('div', { className: 'legacy-markdown' }, answer), () => null, () => null, ({ children }) => React.createElement('button', null, children), () => null, emptyAnalysisNotice);
const html = renderToStaticMarkup(React.createElement(component, { turn: { id: 'old-turn', status: 'COMPLETED', answer: '| old | Markdown table |' }, onUnauthorized: () => false })); const html = renderToStaticMarkup(React.createElement(component, { turn: { id: 'old-turn', status: 'COMPLETED', answer: '| old | Markdown table |' }, onUnauthorized: () => false }));
assert.match(html, /legacy-markdown/); assert.match(html, /legacy-markdown/);
assert.match(html, /\| old \| Markdown table \|/); assert.match(html, /\| old \| Markdown table \|/);
assert.doesNotMatch(html, /analysis-member-list/); assert.doesNotMatch(html, /analysis-member-list/);
const empty = renderToStaticMarkup(React.createElement(component, { turn: { id: 'empty-turn', status: 'PARTIAL', answer: '', answerQuality: { dataComplete: true, narrativeComplete: false } }, onUnauthorized: () => false, onRetry: () => {} }));
assert.match(empty, /role="status">数据查询已完成,但未生成分析正文。请重新分析。/);
assert.match(empty, /<button>重新分析<\/button>/);
const failedRecovery=renderToStaticMarkup(React.createElement(component,{turn:{id:'old-turn',status:'PARTIAL',answer:'原答案',recoveryError:'图表恢复暂不可用'},onUnauthorized:()=>false}));
assert.match(failedRecovery,/role="alert">图表恢复暂不可用/);assert.match(failedRecovery,/原答案/);
}); });
@@ -0,0 +1,44 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
const original='## 结论\n\n合格率下降来自两个不同的阶段。\n\n### 总体与阶段\n\n先说明投入规模。\n\n| 阶段 | 变化 |\n| --- | --- |\n| 黑片 | -0.30 pp |\n\n表格之后的完整解释不能挪走。[Q11111111]\n\n### 组织维度\n\n国内与海外结构不同。\n\n### 局限\n\n不能据此认定生产根因。';
const legacy=()=>({status:'PARTIAL',result:{executionMode:'native_agent',answer:'已取得本轮统计结果,答案整理尚未完整完成。\n\n正式统计表',readingSummary:{lead:'已取得本轮统计结果,答案整理尚未完整完成。'}},plan:{timeline:[{kind:'assistant',text:'先进行查询。'},{kind:'tool_start',sequence:1},{kind:'tool_result',sequence:2},{kind:'assistant',sequence:3,text:original}]}});
test('legacy native fallback restores the entire final model body instead of another summary',()=>{
const body=originalAnalysisBody(legacy());assert.equal(body.source,'timeline');assert.equal(body.answer,original);
assert.doesNotMatch(body.answer,/已取得本轮统计结果/);
});
test('new saved original body wins over an 8000-character transcript and remains complete',()=>{
const data=legacy();const answer='正文'.repeat(6000);data.result.answer=answer;delete data.result.readingSummary;
data.plan.timeline.at(-1).text=answer.slice(0,8000)+'…';assert.equal(originalAnalysisBody(data).answer,answer);
});
test('a capped historical transcript cannot masquerade as the complete original body',()=>{
const data=legacy();data.plan.timeline.at(-1).text='原'.repeat(8000);
assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
});
test('a failed native result with no formal evidence still renders its saved original body',()=>{
assert.deepEqual(originalAnalysisBody({status:'FAILED',result:{executionMode:'native_agent',answer:original,results:[],answerQuality:{dataComplete:false}}}),{answer:original,source:'saved'});
});
test('earlier assistant progress, redacted answers, and unavailable originals are never promoted',()=>{
const data=legacy();data.plan.timeline.pop();assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
data.result.answer='';data.plan.timeline.push({kind:'assistant',text:original});assert.equal(originalAnalysisBody(data).answer,'');
delete data.result.executionMode;assert.equal(originalAnalysisBody(data),null);
});
test('original Markdown lines, table placement and scope caveats stay in their exact order',()=>{
const parts=originalAnalysisSections(original,[]);assert.equal(parts.map(p=>p.markdown).join('\n'),original);
assert.ok(parts[1].markdown.indexOf('| 黑片')<parts[1].markdown.indexOf('表格之后'));
assert.match(parts.at(-1).markdown,/不能据此认定生产根因/);
});
test('figures are inserted after the associated complete chapter without removing prose or tables',()=>{
const visual={id:'stage',title:'阶段合格率',metric:'black_rate',type:'column',evidenceRefs:['Q11111111']};
const sections=originalAnalysisSections(original,[visual]);assert.equal(sections[1].visuals[0],visual);
assert.equal(sections.flatMap(s=>s.visuals).length,1);assert.equal(sections.map(s=>s.markdown).join('\n'),original);
});
test('alternate historical evidence fallback also recovers native prose',()=>{
const data=legacy();data.result.readingSummary.lead='现有证据不足以支持本轮完整分析,已保留可核验统计结果。';assert.equal(originalAnalysisBody(data).answer,original);
});
test('black and bright figures cannot be attached to the opposite stage chapter',()=>{
const body='## 黑片阶段\n\n黑片完整解释。\n\n## 亮片阶段\n\n亮片完整解释。';
const figures=[{id:'black',type:'column',stage:'black',metric:'black_rate',evidenceRefs:[]},{id:'bright',type:'column',stage:'bright',metric:'bright_rate',evidenceRefs:[]}];
const sections=originalAnalysisSections(body,figures);assert.equal(sections[0].visuals[0].id,'black');assert.equal(sections[1].visuals[0].id,'bright');
});
@@ -274,17 +274,17 @@ test('history proof and lineage in model-controlled task fields cannot authorize
assert.deepEqual(selectedHistoryIds(turn), []); assert.deepEqual(selectedHistoryIds(turn), []);
}); });
test('running process starts folded, stays open after a user opens it, closes on completion, and ignores late running status', () => { test('running process starts open, honors manual collapse, and closes on completion', () => {
const harness = hookHarness(); const harness = hookHarness();
const turn = { id: 'process-turn', status: 'RUNNING', steps: [{ tool: 'read', label: '读取数据', status: 'running' }] }; const turn = { id: 'process-turn', status: 'RUNNING', steps: [{ tool: 'read', label: '读取数据', status: 'running' }] };
let element = harness.render(turn); let element = harness.render(turn);
assert.equal(element.type, 'details'); assert.equal(element.type, 'details');
assert.equal(element.props.open, false); assert.equal(element.props.open, true);
element.props.onToggle({ currentTarget: { open: true } }); element.props.onToggle({ currentTarget: { open: false } });
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'running' }]; turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'running' }];
element = harness.render(turn); element = harness.render(turn);
assert.equal(element.props.open, true); assert.equal(element.props.open, false);
turn.status = 'COMPLETED'; turn.status = 'COMPLETED';
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'completed' }]; turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'completed' }];
@@ -293,5 +293,5 @@ test('running process starts folded, stays open after a user opens it, closes on
turn.status = 'RUNNING'; turn.status = 'RUNNING';
element = harness.render(turn); element = harness.render(turn);
assert.equal(element.props.open, false); assert.equal(element.props.open, true);
}); });
+7 -3
View File
@@ -1,3 +1,4 @@
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
@@ -22,7 +23,9 @@ const turn = (readingSummary = summary()) => ({ id: 'turn', question: '9月合
releaseId: 'release', visuals: [chart], queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary, releaseId: 'release', visuals: [chart], queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary,
} }); } });
let OriginalContent=()=>null;
function component(source, name, bindings) { function component(source, name, bindings) {
bindings={originalAnalysisBody,AnalysisOriginalContent:props=>React.createElement(OriginalContent,props),...bindings};
const cleaned = source.replace(/^import .*;\n/gm, '').replace(/^export /gm, ''); const cleaned = source.replace(/^import .*;\n/gm, '').replace(/^export /gm, '');
return new Function('React', ...Object.keys(bindings), ts.transpileModule(`${cleaned}\nreturn ${name};`, { return new Function('React', ...Object.keys(bindings), ts.transpileModule(`${cleaned}\nreturn ${name};`, {
fileName: `${name}.tsx`, compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }, fileName: `${name}.tsx`, compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
@@ -30,6 +33,7 @@ function component(source, name, bindings) {
} }
const markdownSource = readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8'); const markdownSource = readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8');
const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts }); const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts });
OriginalContent=component(readFileSync(new URL('../src/AnalysisOriginalContent.tsx',import.meta.url),'utf8'),'AnalysisOriginalContent',{AiMarkdown,originalAnalysisSections});
test('conclusion layout separates the lead, findings and table titles without rewriting checked facts', () => { test('conclusion layout separates the lead, findings and table titles without rewriting checked facts', () => {
const content = '9月综合合格率**95.13%**,较8月的**95.57%**下降**0.44个百分点**。主要来自**黑片阶段**,正式影响为**-0.30个百分点**;亮片影响**-0.15个百分点**。\n\n' const content = '9月综合合格率**95.13%**,较8月的**95.57%**下降**0.44个百分点**。主要来自**黑片阶段**,正式影响为**-0.30个百分点**;亮片影响**-0.15个百分点**。\n\n'
@@ -81,7 +85,7 @@ const visibleSummary = html => html.match(/<div class="ai-markdown[^"]*">([\s\S]
test('comparison readout uses the checked change, preserving rounded stage values and explicit scope', () => { test('comparison readout uses the checked change, preserving rounded stage values and explicit scope', () => {
const sentence='汽车交通2026年9月黑片合格率**97.27%**,较8月的**97.58%**下降**0.30个百分点**。'; const sentence='汽车交通2026年9月黑片合格率**97.27%**,较8月的**97.58%**下降**0.30个百分点**。';
const value=checkedConclusionComparison(sentence); const value=checkedConclusionComparison(sentence);
assert.equal(value.change,'0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月'); assert.equal(value.change,'-0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月');
assert.equal(value.previousLabel,'8月'); assert.equal(value.current,'97.27%'); assert.equal(value.previous,'97.58%'); assert.equal(value.previousLabel,'8月'); assert.equal(value.current,'97.27%'); assert.equal(value.previous,'97.58%');
for (const invalid of ['9月合格率95.13%。','9月合格率95.13%,较8月95.57%。','9月合格率101.00%,较8月95.57%下降0.44个百分点。']) assert.equal(checkedConclusionComparison(invalid),null); for (const invalid of ['9月合格率95.13%。','9月合格率95.13%,较8月95.57%。','9月合格率101.00%,较8月95.57%下降0.44个百分点。']) assert.equal(checkedConclusionComparison(invalid),null);
assert.equal(checkedConclusionComparison('9月合格率0.00%,较8月95.57%下降95.57个百分点。').current,'0.00%'); assert.equal(checkedConclusionComparison('9月合格率0.00%,较8月95.57%下降95.57个百分点。').current,'0.00%');
@@ -93,7 +97,7 @@ test('conclusion chapters put each authorized figure beside its cited topic, wit
'**重点规格**:甲规格报废增加128.45 kg。[Q11111111]']}); '**重点规格**:甲规格报废增加128.45 kg。[Q11111111]']});
const figures=[{...chart,id:'department',metric:'rate_drop_pp',dimension:'department',evidenceRefs:['Q22222222']},{...chart,id:'product',metric:'scrap_delta',dimension:'product'}]; const figures=[{...chart,id:'department',metric:'rate_drop_pp',dimension:'department',evidenceRefs:['Q22222222']},{...chart,id:'product',metric:'scrap_delta',dimension:'product'}];
const document=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,figures); const document=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,figures);
assert.equal(document.comparison.change,'0.44'); assert.equal(document.comparison.change,'-0.44');
assert.deepEqual(document.sections.find(x=>x.title==='产业部变化').visuals.map(v=>v.id),['department']); assert.deepEqual(document.sections.find(x=>x.title==='产业部变化').visuals.map(v=>v.id),['department']);
assert.deepEqual(document.sections.find(x=>x.title==='重点规格').visuals.map(v=>v.id),['product']); assert.deepEqual(document.sections.find(x=>x.title==='重点规格').visuals.map(v=>v.id),['product']);
assert.deepEqual(document.sections.flatMap(x=>x.visuals.map(v=>v.id)),['department','product']); assert.deepEqual(document.sections.flatMap(x=>x.visuals.map(v=>v.id)),['department','product']);
@@ -109,7 +113,7 @@ test('reference-style cards and chapters keep chat/report values, figures and or
data.result.answer=data.result.readingSummary.lead+'\n\n'+data.result.readingSummary.evidence[0]; data.result.answer=data.result.readingSummary.lead+'\n\n'+data.result.readingSummary.evidence[0];
for(const html of [renderChat(data),renderReport(data)]) { for(const html of [renderChat(data),renderReport(data)]) {
assert.match(html,/analysis-comparison-current[^>]*><span>2026年9月<\/span><strong>95.13%<\/strong>/); assert.match(html,/analysis-comparison-current[^>]*><span>2026年9月<\/span><strong>95.13%<\/strong>/);
assert.match(html,/下降 0.44/); assert.match(html,/95.57%/); assert.match(html,/-0.44/); assert.match(html,/95.57%/);
assert.equal((html.match(/<table>/g)||[]).length,1); assert.equal((html.match(/<table>/g)||[]).length,1);
assert.doesNotMatch(html,/Q11111111|Q22222222|关键依据|数据依据|analysis-full-appendix/); assert.doesNotMatch(html,/Q11111111|Q22222222|关键依据|数据依据|analysis-full-appendix/);
} }
+4 -3
View File
@@ -158,10 +158,10 @@ test('settled process is collapsed, with the original records retained inside',(
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/); assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
} }
}); });
test('running process stays folded by default while retaining its current records inside',()=>{ test('running process is expanded by default while retaining its current records inside',()=>{
const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn('RUNNING')})); const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn('RUNNING')}));
assert.match(html,/读取数据/);assert.match(html,/<details class="analysis-process-history analysis-agent-process"/); assert.match(html,/读取数据/);assert.match(html,/<details class="analysis-process-history analysis-agent-process"/);
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/); assert.match(html,/<details class="analysis-process-history analysis-agent-process" open/);
}); });
test('a submitted follow-up rearms following only when its own turn is rendered',()=>{ test('a submitted follow-up rearms following only when its own turn is rendered',()=>{
@@ -329,7 +329,8 @@ test('agent process interleaves thoughts, tool calls and text with one runtime h
]}; ]};
const html=renderToStaticMarkup(React.createElement(Process,{turn,metadata:React.createElement('span',null,'运行时长 25秒')})); const html=renderToStaticMarkup(React.createElement(Process,{turn,metadata:React.createElement('span',null,'运行时长 25秒')}));
assert.equal((html.match(/运行时长/g)||[]).length,1); assert.equal((html.match(/运行时长/g)||[]).length,1);
const positions=['先核对范围','我来查询两个期间。','读取数据','再整理结果'].map(value=>html.indexOf(value)); assert.doesNotMatch(html,/我来查询两个期间。/);
const positions=['先核对范围','读取数据','再整理结果'].map(value=>html.indexOf(value));
assert.ok(positions.every((p,i)=>p>=0&&(!i||p>positions[i-1]))); assert.ok(positions.every((p,i)=>p>=0&&(!i||p>positions[i-1])));
assert.equal((html.match(/class="analysis-thinking-block"/g)||[]).length,2); assert.equal((html.match(/class="analysis-thinking-block"/g)||[]).length,2);
for(const hidden of ['model-hidden','任务理解','整理结论','analysis-thinking-heading','展示接口实际返回'])assert.ok(!html.includes(hidden),hidden); for(const hidden of ['model-hidden','任务理解','整理结论','analysis-thinking-heading','展示接口实际返回'])assert.ok(!html.includes(hidden),hidden);
+18 -2
View File
@@ -182,7 +182,7 @@ test('unknown 503 submission renders recovery notice without claiming a queued o
await ui.submit('question with unknown outcome'); await ui.submit('question with unknown outcome');
assert.equal(ui.get().attempt.uncertain,true); assert.equal(ui.get().attempt.uncertain,true);
const html=renderDraft(ui.get().lastTurn); const html=renderDraft(ui.get().lastTurn);
assert.match(html,/提交结果暂未确认,请重试上一问恢复原任务/); assert.doesNotMatch(html,/提交结果暂未确认/);
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行/); assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行/);
assert.equal(ui.get().lastTurn.status,undefined); assert.equal(ui.get().lastTurn.status,undefined);
}); });
@@ -192,7 +192,23 @@ test('an explicit 400 rejection renders an unsuccessful draft without a running
await ui.submit('rejected question'); await ui.submit('rejected question');
assert.equal(ui.get().attempt,null); assert.equal(ui.get().attempt,null);
const html=renderDraft(ui.get().lastTurn); const html=renderDraft(ui.get().lastTurn);
assert.match(html,/本次提交未成功,请检查错误提示后重试/); assert.doesNotMatch(html,/本次提交未成功/);
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行|恢复原任务/); assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行|恢复原任务/);
assert.equal(ui.get().lastTurn.status,undefined); assert.equal(ui.get().lastTurn.status,undefined);
}); });
test('a fresh submission immediately carries waiting status and a clock before acceptance',async()=>{
const pending=deferred();const ui=fixture({startAnalysisTurn:()=>pending.promise});
const work=ui.submit('即时状态');assert.equal(ui.get().lastTurn.status,'SUBMITTING');
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
pending.resolve({turn:{id:'accepted',status:'RUNNING'}});await work;
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
});
test('retry starts a fresh waiting clock without displaying the old body or plan clock',async()=>{
const response=deferred();const ui=fixture({retryAnalysisTurn:()=>response.promise,analysisTurn:async()=>({id:'old',status:'QUEUED'})});
const work=ui.retryTurn({id:'old',status:'PARTIAL',answer:'old text',createdAt:'2020-01-01T00:00:00Z',startedAt:'2020-01-01T00:00:01Z',plan:{startedAt:'2020-01-01T00:00:01Z'}});
assert.equal(ui.get().lastTurn.status,'SUBMITTING');assert.equal(ui.get().lastTurn.answer,undefined);assert.equal(ui.get().lastTurn.plan,undefined);
response.resolve({turn:{id:'old',sessionId:'session-1',status:'QUEUED'}});await work;
});
@@ -22,6 +22,12 @@ function fixture(request){let cursor=0,dirty=false,queue=[],source=saved(),value
const snapshot=new Function('api',snapshotBody+';return {analysisSnapshotResult};')({}); const snapshot=new Function('api',snapshotBody+';return {analysisSnapshotResult};')({});
const canRecover=new Function('analysisSnapshotResult',hookBody.slice(0,hookBody.indexOf('/**'))+';return canRecoverAnalysisVisuals;')(snapshot.analysisSnapshotResult); const canRecover=new Function('analysisSnapshotResult',hookBody.slice(0,hookBody.indexOf('/**'))+';return canRecoverAnalysisVisuals;')(snapshot.analysisSnapshotResult);
test('only a saved protocol task requesting a chart offers recovery',()=>{assert.equal(canRecover(saved()),true);for(const source of [{...saved(),status:'RUNNING'},{...saved(),plan:{...saved().plan,protocolVersion:0}},{...saved(),plan:{...saved().plan,task:{...saved().plan.task,visualPreference:'none'}}},{...complete(saved())}])assert.equal(canRecover(source),false);}); test('only a saved protocol task requesting a chart offers recovery',()=>{assert.equal(canRecover(saved()),true);for(const source of [{...saved(),status:'RUNNING'},{...saved(),plan:{...saved().plan,protocolVersion:0}},{...saved(),plan:{...saved().plan,task:{...saved().plan.task,visualPreference:'none'}}},{...complete(saved())}])assert.equal(canRecover(source),false);});
test('native auto charts offer recovery for real rendering gaps without requiring a queryPlan',()=>{
const source=saved();source.plan.task={kind:'analysis',executionMode:'native_agent',visualPreference:'auto'};
source.executionCoverage={visualGaps:['总体比较图未生成']};source.visualState='ready';assert.equal(canRecover(source),true);
source.executionCoverage={visualGaps:[]};source.answerQuality={chartsComplete:false};source.status='COMPLETED';assert.equal(canRecover(source),false);
source.visualState='failed';assert.equal(canRecover(source),true);
});
test('a duplicate click recovers only charts and retains facts',async()=>{const response=deferred(),ui=fixture(()=>response.promise);ui.render();const a=ui.value.recover(),b=ui.value.recover();ui.render();assert.equal(ui.calls.api,1);response.resolve(complete(ui.source));await Promise.all([a,b]);await ui.settle();assert.equal(ui.value.turn.status,'COMPLETED');assert.equal(ui.value.turn.answer,'原答案');assert.equal(ui.value.available,false);ui.unmount();}); test('a duplicate click recovers only charts and retains facts',async()=>{const response=deferred(),ui=fixture(()=>response.promise);ui.render();const a=ui.value.recover(),b=ui.value.recover();ui.render();assert.equal(ui.calls.api,1);response.resolve(complete(ui.source));await Promise.all([a,b]);await ui.settle();assert.equal(ui.value.turn.status,'COMPLETED');assert.equal(ui.value.turn.answer,'原答案');assert.equal(ui.value.available,false);ui.unmount();});
test('a changed fact, source execution, or returned turn is rejected',async()=>{for(const change of [v=>({...v,answer:'换了答案'}),v=>({...v,id:'turn2'}),v=>({...v,plan:{...v.plan,executionId:'exec2'}})]){let ui;ui=fixture(async()=>change(complete(ui.source)));ui.render();await ui.value.recover();await ui.settle();assert.equal(ui.value.turn.status,'PARTIAL');assert.match(ui.value.error,/原分析已变化/);ui.unmount();}}); test('a changed fact, source execution, or returned turn is rejected',async()=>{for(const change of [v=>({...v,answer:'换了答案'}),v=>({...v,id:'turn2'}),v=>({...v,plan:{...v.plan,executionId:'exec2'}})]){let ui;ui=fixture(async()=>change(complete(ui.source)));ui.render();await ui.value.recover();await ui.settle();assert.equal(ui.value.turn.status,'PARTIAL');assert.match(ui.value.error,/原分析已变化/);ui.unmount();}});
test('late recovery cannot overwrite a changed revision or an unmounted view',async()=>{const response=deferred(),ui=fixture(()=>response.promise);ui.render();const before=structuredClone(ui.source),request=ui.value.recover();ui.replace({...before,plan:{...before.plan,revision:3},answer:'新答案'});response.resolve(complete(before));await request;await ui.settle();assert.equal(ui.value.turn.answer,'新答案');assert.equal(ui.value.turn.status,'PARTIAL');ui.unmount();}); test('late recovery cannot overwrite a changed revision or an unmounted view',async()=>{const response=deferred(),ui=fixture(()=>response.promise);ui.render();const before=structuredClone(ui.source),request=ui.value.recover();ui.replace({...before,plan:{...before.plan,revision:3},answer:'新答案'});response.resolve(complete(before));await request;await ui.settle();assert.equal(ui.value.turn.answer,'新答案');assert.equal(ui.value.turn.status,'PARTIAL');ui.unmount();});
@@ -15,6 +15,7 @@ import {
visualUnitLabel, visualUnitLabel,
} from '../src/analysisVisualsModel.ts'; } from '../src/analysisVisualsModel.ts';
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts'; import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
import { buildConclusionDocument, checkedConclusionComparison } from '../src/analysisConclusionModel.ts';
function visual(overrides = {}) { function visual(overrides = {}) {
return { return {
@@ -305,6 +306,64 @@ test('negative percentage point changes remain signed and keep a zero baseline',
assert.equal(formatVisualValue(0.5, 'pp'), '+0.5 pp'); assert.equal(formatVisualValue(0.5, 'pp'), '+0.5 pp');
}); });
test('legacy rate-drop charts normalize once and chat tables and exports use current minus prior', () => {
const legacy = visual({
id: 'legacy-rate-drop', type: 'bar', title: '业务分组合格率降幅线索', subtitle: '8月 → 9月',
unit: 'pp', metric: 'rate_drop_pp', dimension: 'group', sectionKey: 'group',
categories: [{ key: 'g1', label: '分组一' }, { key: 'g2', label: '分组二' }],
series: [{ key: 'rate_drop_pp', label: '合格率变化(pp)', values: [2.5, -4] }],
evidenceRefs: ['evidence-1'], requiredFields: ['black_good_weight', 'black_total_weight'],
scope: { department: '工业电机' }, period: { label: '2026-09' }, comparisonPeriod: { label: '2026-08' },
coverage: { totalRows: 2, returnedRows: 2, truncated: false },
note: '条形末端显示具体变化:正值为下降,负值为改善,单位是百分点。本图只按率降幅排序,未纳入投入规模。',
});
const model = parseAnalysisVisuals([legacy], 1).visuals[0];
assert.deepEqual(model.series[0].values, [-2.5, 4]);
assert.match(model.note, /本期减比较期/);
assert.match(model.note, /仍按率降幅排序|只按率降幅排序/);
assert.deepEqual(parseAnalysisVisuals([model], 1).visuals[0].series[0].values, [-2.5, 4]);
const legacyNotes = [
'正值表示合格率下降,负值表示改善;百分点取自正式分组率差。',
'正值表示综合合格率下降,负值表示改善;按正式综合率比较,不作为生产根因。',
undefined,
];
for (const [index, note] of legacyNotes.entries()) {
const snapshot = { ...legacy, id: `legacy-rate-drop-${index}`, note };
const normalized = parseAnalysisVisuals([snapshot], 1).visuals[0];
assert.deepEqual(normalized.series[0].values, [-2.5, 4]);
assert.match(normalized.note, /本期减比较期/);
assert.deepEqual(parseAnalysisVisuals([normalized], 1).visuals[0].series[0].values, [-2.5, 4]);
}
const chart = buildAnalysisVisualOption(model);
assert.deepEqual(chart.series[0].data, [-2.5, 4]);
const table = renderVisualTableHtml(legacy);
assert.match(table, /-2\.5 pp/);
assert.match(table, /\+4 pp/);
const exported = buildAnalysisVisualExportOption(model, 1280, 'report');
assert.deepEqual(exported.option.series[0].data, [-2.5, 4]);
const modern = { ...legacy, id: 'current-rate-drop', note: '正值表示本期合格率上升,负值表示下降;变化值为本期减比较期。',
series: [{ ...legacy.series[0], values: [-2.5, 4] }] };
assert.deepEqual(parseAnalysisVisuals([modern], 1).visuals[0].series[0].values, [-2.5, 4]);
const reading = { lead: '分组变化', evidence: [], notices: [], evidenceRefs: ['evidence-1'],
hasAppendix: false, fullAnswer: '### 业务分组变化\n\n合格率有变化。[evidence-1]', visualCount: 1 };
const conclusion = buildConclusionDocument(reading, [model]);
assert.deepEqual(conclusion.sections.find(section => section.title === '业务分组变化').visuals[0].series[0].values, [-2.5, 4]);
});
test('checked conclusion comparisons give declines negative pp and increases positive pp', () => {
const down = checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%下降0.44个百分点。');
const up = checkedConclusionComparison('9月综合合格率95.57%,较8月的95.13%上升0.44个百分点。');
assert.equal(down.change, '-0.44');
assert.equal(up.change, '+0.44');
assert.equal(down.direction, '下降');
assert.equal(up.direction, '上升');
assert.equal(checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%上升0.44个百分点。'), null);
});
test('non-finite and out-of-range ratio values degrade to a table while retaining zero and null', () => { test('non-finite and out-of-range ratio values degrade to a table while retaining zero and null', () => {
const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'r', label: '率', values: [0, Number.NaN] }] })]); const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'r', label: '率', values: [0, Number.NaN] }] })]);
assert.equal(parsed.visuals.length, 1); assert.equal(parsed.visuals.length, 1);
+3 -2
View File
@@ -5,6 +5,7 @@ import ts from 'typescript';
import React from 'react'; import React from 'react';
import { queryScrapWeight } from '../src/queryMetricValues.ts'; import { queryScrapWeight } from '../src/queryMetricValues.ts';
import { defectWeightRate } from '../src/trendMetrics.ts'; import { defectWeightRate } from '../src/trendMetrics.ts';
import { metricStageColumnPlan } from '../src/metricColumnPlan.ts';
import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts'; import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts';
const source = fs.readFileSync(new URL('../src/QueryPage.tsx', import.meta.url), 'utf8'); const source = fs.readFileSync(new URL('../src/QueryPage.tsx', import.meta.url), 'utf8');
@@ -17,13 +18,13 @@ const table = slice('export function MetricTable(', 'function MetricTablePaginat
function fixture(props) { function fixture(props) {
let exported, detail = 0, basis = 0; let exported, detail = 0, basis = 0;
const ref = {}; const ref = {};
const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'queryScrapWeight', 'downloadMetricWorkbook', ts.transpileModule(` const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'queryScrapWeight', 'metricStageColumnPlan', 'downloadMetricWorkbook', ts.transpileModule(`
const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月'); const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月');
const SUMMARY_PAGE_SIZE=15; const SUMMARY_PAGE_SIZE=15;
const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{}; const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{};
const AnimatedMetricText='AnimatedMetricText', Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info'; const AnimatedMetricText='AnimatedMetricText', Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info';
${helpers}\n${table}\nreturn MetricTable; ${helpers}\n${table}\nreturn MetricTable;
`, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, async (filename, columns, rows, value) => { `, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, metricStageColumnPlan, async (filename, columns, rows, value) => {
exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) }; exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) };
}); });
const tree = render({ref,exportFilename:'验收',period:'month',month:9,quarter:3,rateBasis:'original',fullFields:false,onDetail(){detail++;},onBasis(){basis++;},onDrilldown(){},...props}); const tree = render({ref,exportFilename:'验收',period:'month',month:9,quarter:3,rateBasis:'original',fullFields:false,onDetail(){detail++;},onBasis(){basis++;},onDrilldown(){},...props});
@@ -0,0 +1,53 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { defaultFullMetricFields, metricStageColumnPlan } from '../src/metricColumnPlan.ts';
const columnKeys = columns => columns.map(column => column.kind === 'defect' ? `defect:${column.name}` : column.field);
test('six query views start with the requested key/full metric selection', () => {
for (const page of ['overall', 'department', 'group', 'product']) assert.equal(defaultFullMetricFields(page), false, page);
for (const page of ['blackProduct', 'brightProduct']) assert.equal(defaultFullMetricFields(page), true, page);
});
test('key metrics preserve the current four-column stage table', () => {
const rows = [{ black: { defects: [{ name: '责废', weight: 10 }] }, bright: { defects: [{ name: '镀废', weight: 5 }] } }];
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'black', false, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'rate']);
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'bright', false, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'rate']);
});
test('full trend fields share summary ordering, including bright headquarters scrap', () => {
const rows = [{
black: { defects: [{ name: '责废', weight: 8 }, { name: '料废', weight: 2 }, { name: '外废', weight: 1 }] },
bright: { defects: [{ name: '镀废', weight: 4 }, { name: '材料废', weight: 3 }, { name: '加工废', weight: 2 }, { name: '扩散废', weight: 1 }] },
}];
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'black', true, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'defect:责废', 'defect:料废', 'defect:外废', 'rate']);
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'bright', true, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'defect:镀废', 'defect:材料废', 'defect:加工废', 'defect:扩散废', 'headquartersScrapWeight', 'rate']);
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'bright', true, 'withoutHeadquartersScrap')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'defect:镀废', 'defect:材料废', 'defect:加工废', 'defect:扩散废', 'rate']);
});
test('bright headquarters scrap stays immediately after diffusion scrap when defect order varies', () => {
const rows = [{ bright: { defects: [
{ name: '材料废', weight: 3 }, { name: '扩散废', weight: 1 },
{ name: '镀废', weight: 4 }, { name: '加工废', weight: 2 },
] } }];
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'bright', true, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'defect:材料废', 'defect:扩散废', 'headquartersScrapWeight', 'defect:镀废', 'defect:加工废', 'rate']);
});
test('full field plan only uses defect values returned in the trend rows and does not mutate them', () => {
const rows = [
{ black: { defects: [{ name: '责废', weight: 8 }] }, bright: { defects: [] } },
{ black: { defects: [{ name: '料废', weight: null }] }, bright: { defects: [{ name: '镀废', weight: 1 }] } },
];
const before = structuredClone(rows);
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'black', true, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'defect:责废', 'defect:料废', 'rate']);
assert.deepEqual(columnKeys(metricStageColumnPlan(rows, 'bright', true, 'original')),
['totalWeight', 'qualifiedWeight', 'scrapWeight', 'defect:镀废', 'headquartersScrapWeight', 'rate']);
assert.deepEqual(rows, before);
});