JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix: 修复模型配置不可用时, Symphony 总谱构建失败或暂停后前端仍显示刷新中的问题
layShang264b58d4da5ef4d
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsxindex 2532a2e23f..e2b3c69b2b 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx@@ -420,6 +420,10 @@ function isBuildRunningPayload(data: { build_progress?: BuildProgress }): booleareturn data.build_progress?.status === 'running';}+function isTerminalBuildStatus(status: BuildProgress['status'] | undefined): boolean {+ return status === 'success' || status === 'error' || status === 'paused';+}+function buildStageLabel(stage: string, fallback: string, t: Translate): string {const key = BUILD_STAGE_TRANSLATION_KEYS[stage];if (!key) return fallback || stage || t('skills.graph.buildLogFallback');@@ -710,6 +714,19 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel}}, []);+ const resetBuildUiOnTerminalStatus = useCallback((data: { detail?: string; paused?: boolean; build_progress?: BuildProgress }): boolean => {+ const status = data.build_progress?.status ?? (data.paused ? 'paused' : undefined);+ if (!isTerminalBuildStatus(status)) return false;+ externalBuildRunningRef.current = false;+ setUpdating(false);+ setBuildMode(null);+ setLoading(false);+ if (status === 'error') {+ setError(data.detail || data.build_progress?.label || '技能总谱刷新失败');+ }+ return true;+ }, []);+useEffect(() => {graphRef.current = graph;}, [graph]);@@ -934,7 +951,9 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel{ timeoutMs: INDEX_UPDATE_TIMEOUT_MS },);applyBuildLog(data);- if (data.paused) {+ const isPaused = data.paused || data.build_progress?.status === 'paused';+ if (isPaused) {+ resetBuildUiOnTerminalStatus(data);return;}if (!data.success) {@@ -947,7 +966,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanelsetUpdating(false);setBuildMode(null);}- }, [applyBuildLog, loadGraph, t]);+ }, [applyBuildLog, loadGraph, resetBuildUiOnTerminalStatus, t]);const pauseBuild = useCallback(async () => {setPausingBuild(true);@@ -960,7 +979,11 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel{ timeoutMs: 60_000 },);applyBuildLog(data);- if (!data.success && !data.paused) {+ const isPaused = data.paused || data.build_progress?.status === 'paused';+ if (resetBuildUiOnTerminalStatus(data)) {+ return;+ }+ if (!data.success && !isPaused) {throw new Error(localizedServerDetail(data.detail, 'skills.graph.errors.pauseFailed', t));}} catch (err) {@@ -968,7 +991,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel} finally {setPausingBuild(false);}- }, [applyBuildLog, t]);+ }, [applyBuildLog, resetBuildUiOnTerminalStatus, t]);useEffect(() => {let stopped = false;@@ -1006,6 +1029,13 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanelif (!stopped) {setShowBuildLogPanel(true);applyBuildLog(data);+ const status = data.build_progress?.status;+ if (resetBuildUiOnTerminalStatus(data)) {+ if (status === 'success') {+ void loadGraph();+ }+ return;+ }}} catch {// 轮询只用于补充进度日志;失败不覆盖主更新请求的错误处理。@@ -1024,7 +1054,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanelwindow.clearTimeout(timer);}};- }, [applyBuildLog, updating]);+ }, [applyBuildLog, loadGraph, resetBuildUiOnTerminalStatus, updating]);useEffect(() => {if (updating) return undefined;diff --git a/jiuwenswarm/extensions/symphony/extension.py b/jiuwenswarm/extensions/symphony/extension.pyindex 58f8b62b60..df0f40ecb7 100644--- a/jiuwenswarm/extensions/symphony/extension.py+++ b/jiuwenswarm/extensions/symphony/extension.py@@ -118,6 +118,7 @@ class SymphonyExtension(BaseExtension):return payloadbuild_logger.record("update.pause_requested")task.cancel("symphony.pause_build")+ build_logger.record("update.paused")payload = {"success": True,"score_dir": str(score_dir),@@ -270,7 +271,8 @@ class SymphonyExtension(BaseExtension):)).to_dict()except asyncio.CancelledError:- build_logger.record("update.paused")+ if _build_progress(_read_build_log(score_dir)).get("status") != "paused":+ build_logger.record("update.paused")payload = {"success": False,"score_dir": str(score_dir),@@ -456,7 +458,7 @@ def _build_progress(entries: list[dict[str, Any]]) -> dict[str, Any]:"percent": 0,"status": "idle",}- latest = entries[-1]+ latest = _latest_effective_build_log_entry(entries)stage = str(latest.get("stage") or "")status = "running"if stage == "update.done":@@ -476,6 +478,15 @@ def _build_progress(entries: list[dict[str, Any]]) -> dict[str, Any]:}+def _latest_effective_build_log_entry(entries: list[dict[str, Any]]) -> dict[str, Any]:+ if not entries:+ return {}+ for entry in reversed(entries):+ if str(entry.get("stage") or "") in {"update.done", "update.failed", "update.paused"}:+ return entry+ return entries[-1]++def _build_token_usage_payload(score_dir: Path, entries: list[dict[str, Any]]) -> dict[str, Any]:status = _build_progress(entries).get("status")if status == "running":diff --git a/jiuwenswarm/symphony/config/config_template.json b/jiuwenswarm/symphony/config/config_template.jsondeleted file mode 100644index 774cc7dacd..0000000000--- a/jiuwenswarm/symphony/config/config_template.json+++ /dev/null@@ -1,66 +0,0 @@-{- "query": "extract tables from websites",-- "top_k": 2,- "method": "PROGRESSIVE",- "llm_top_k": 2,-- "progressive_batch_size": 5,- "progressive_max_tokens": 96,- "progressive_request_timeout": null,-- "trie_constrained_decoding_enabled": true,- "trie_constraint_allow_user_nodes": false,- "trie_constraint_max_candidates": 512,- "trie_constraint_fallback_payload": "User.Chat",-- "progressive_max_branch_choices": 6,- "progressive_auto_expand_child_threshold": 3,- "progressive_collapse_single_chain": true,- "progressive_max_collapse_steps": 8,- "progressive_max_parallel_branches": 3,- "progressive_enable_parallel_branches": true,- "progressive_auto_terminal_item_threshold": 12,- "progressive_branch_choice_slack": 2,- "progressive_branch_candidate_slack": 1,- "progressive_round_robin_branch_reduce": true,- "progressive_branch_max_tokens": 96,- "progressive_item_max_tokens": 128,-- "progressive_compact_boundary_codes_enabled": true,- "progressive_flatten_full_tree_in_prompt": true,- "progressive_max_exposure_depth_per_call": 99,- "progressive_exposure_threshold": 1000000000,- "progressive_force_expand_single_child": true,- "progressive_single_forward_logit_selection_enabled": false,- "progressive_selection_mode": "generate",-- "progressive_scoring_backend": "vllm",- "progressive_scoring_backend_model_path": "/data/xt/codes/FineTune/models/qwen3_30b_a3b_instruct",- "progressive_scoring_backend_tokenizer_path": "/data/xt/codes/FineTune/models/qwen3_30b_a3b_instruct",- "progressive_scoring_backend_device": "auto",- "progressive_scoring_backend_dtype": "auto",- "progressive_scoring_backend_enable_prefix_caching": true,- "progressive_scoring_backend_vllm_kwargs": {- "tensor_parallel_size": 2,- "gpu_memory_utilization": 0.8,- "base_url": "http://10.50.91.126:37000/v1",- "api_key": "haha",- "request_model": "qwen3.5_35b_a3b_instruct"- },- "progressive_scoring_backend_batching_enabled": true,- "progressive_scoring_require_single_token_codes": true,- "progressive_scoring_return_probabilities": true,- "progressive_scoring_fallback_mode": "abstain",- "progressive_scoring_max_candidates": 512,- "progressive_scoring_min_probability": null,- "progressive_scoring_trace_top_n": 10,-- "_method_options": ["PROGRESSIVE"],- "_description": {- "query": "搜索查询文本",- "top_k": "返回结果数量",- "llm_top_k": "LLM 重排序的 top_k 数量",- "method": "检索方法,可选值见 _method_options"- }-}diff --git a/jiuwenswarm/symphony/skill_retrieval/config.py b/jiuwenswarm/symphony/skill_retrieval/config.pyindex 2fb82769fc..0320daf24f 100644--- a/jiuwenswarm/symphony/skill_retrieval/config.py+++ b/jiuwenswarm/symphony/skill_retrieval/config.py@@ -7,7 +7,11 @@ from typing import Anyfrom jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.utils import get_agent_workspace_dir-from jiuwenswarm.symphony.skill_retrieval.taxonomy_config import coerce_root_categories_value+from jiuwenswarm.symphony.skill_retrieval.taxonomy_config import (+ DEFAULT_ROOT_CATEGORIES_TEXT,+ coerce_root_categories_value,+ parse_root_categories_text,+)@dataclass(frozen=True)@@ -172,7 +176,9 @@ def _as_bool(value: Any, default: bool) -> bool:def _as_optional_root_categories(value: Any) -> Any:- return coerce_root_categories_value(value, allow_path=True)+ return coerce_root_categories_value(value, allow_path=True) or parse_root_categories_text(+ DEFAULT_ROOT_CATEGORIES_TEXT+ )def _as_int(value: Any, default: int) -> int:diff --git a/jiuwenswarm/symphony/ut_test2.sh b/jiuwenswarm/symphony/ut_test2.shdeleted file mode 100644index 3c31fa21e1..0000000000--- a/jiuwenswarm/symphony/ut_test2.sh+++ /dev/null@@ -1,125 +0,0 @@-#!/bin/bash-set -e # 遇到错误立即退出--# ===================== 1. 核心变量 =====================-TEST_DIR="./marketplace/dispatch/tests"-REPORT_HTML="./outputs/unit_test_report.html"-REPORT_XML="./outputs/unit_test_result.xml"-ut_result_value="PASSED"-UV_VENV_DIR="./.venv"--# ===================== 2. 基础配置(华为云源)=====================-echo "===== 配置pip源 & 安装基础工具 ====="-pip config set global.index-url https://repo.huaweicloud.com/repository/pypi/simple-pip config set global.trusted-host repo.huaweicloud.com--# 升级系统setuptools-pip uninstall -y setuptools-pip install setuptools==68.0.0 wheel==0.41.2--# 安装uv(指定低版本兼容版本)-pip install uv -i https://repo.huaweicloud.com/repository/pypi/simple-UV_PATH=$(pip show uv | grep "Location" | awk -F ': ' '{print $2}')-export PATH="$UV_PATH/bin:$PATH"-echo "当前uv版本:$(uv --version)"--# ===================== 3. 重建虚拟环境(低版本uv兼容)=====================-echo -e "\n===== 创建uv虚拟环境 ====="-rm -rf "${UV_VENV_DIR}"-uv venv "${UV_VENV_DIR}" # 低版本uv仅支持创建,无额外参数--# 验证虚拟环境Python存在-if [ ! -f "${UV_VENV_DIR}/bin/python" ]; then- echo "❌ 虚拟环境创建失败:${UV_VENV_DIR}/bin/python 不存在"- exit 1-fi-echo "✅ 虚拟环境创建成功:${UV_VENV_DIR}"--# ===================== 4. 激活环境 + 安装依赖(低版本核心逻辑)=====================-echo -e "\n===== 激活环境并安装依赖 ====="-# 激活环境(低版本必须先激活,再装依赖)-source "${UV_VENV_DIR}/bin/activate"-echo "✅ 已激活虚拟环境,当前Python:$(which python)"--# 1. 同步pyproject.toml依赖(低版本uv sync无--venv参数)-uv cache clean-uv sync --all-extras --group dev --index-url https://repo.huaweicloud.com/repository/pypi/simple--# 2. 用虚拟环境的pip安装pysqlite3-binary(核心,低版本必须手动装)-pip install pysqlite3-binary==0.5.4.post2 --force-reinstall -i https://repo.huaweicloud.com/repository/pypi/simple--# 3. 用虚拟环境的pip安装pycryptodome(兜底)-pip install pycryptodome>=3.23.0 --force-reinstall -i https://repo.huaweicloud.com/repository/pypi/simple--# 4. 安装测试依赖(确保pytest等在虚拟环境中)-pip install pytest pytest-html pytest-cov pytest-timeout -i https://repo.huaweicloud.com/repository/pypi/simple--# ===================== 5. 前置验证(关键!)=====================-echo -e "\n===== 验证依赖安装 ====="-# 验证pysqlite3-python -c "-import pysqlite3-import sqlite3-print(f'✅ pysqlite3导入成功,sqlite3版本:{sqlite3.sqlite_version}')-" || {- echo "❌ pysqlite3导入失败!"- pip list | grep pysqlite3- exit 1-}--# 验证Crypto-python -c "-import Crypto-from Crypto.Cipher import AES-print('✅ Crypto模块导入成功')-" || {- echo "❌ Crypto导入失败!"- pip list | grep pycryptodome- exit 1-}--# ===================== 6. 执行测试(用激活的Python)=====================-echo -e "\n===== 执行单元测试 ====="-mkdir -p ./outputs-set +e--# 执行测试(全程用激活的Python,无路径问题)-python -c """-import pysqlite3-import sys-sys.modules['sqlite3'] = pysqlite3-import sqlite3-print(f'✅ 替换后sqlite3版本:{sqlite3.sqlite_version}')--from pytest import main-exit_code = main([- '${TEST_DIR}',- '--html=${REPORT_HTML}',- '--junitxml=${REPORT_XML}',- '--cov=${TEST_DIR}',- '--timeout=60'-])-sys.exit(exit_code)-"""--TEST_EXIT_CODE=$?-set -e--# ===================== 7. 结果处理 =====================-echo -e "\n===== 测试结果处理 ====="-echo "测试退出码:${TEST_EXIT_CODE}"--if [ -f "${REPORT_XML}" ]; then- head -n 10 "${REPORT_XML}"-else- echo "❌ 报告文件不存在"- TEST_EXIT_CODE=1-fi--if [ $TEST_EXIT_CODE -ne 0 ]; then- ut_result_value="FAILED"- echo "##vso[task.setvariable variable=ut_result;]${ut_result_value}"- exit 1-else- echo "✅ 所有单元测试通过!"-fi 解释代码\ No newline at end of filediff --git a/tests/unit_tests/symphony/test_extension.py b/tests/unit_tests/symphony/test_extension.pyindex a04b24d2b2..f2e191c33d 100644--- a/tests/unit_tests/symphony/test_extension.py+++ b/tests/unit_tests/symphony/test_extension.py@@ -11,6 +11,7 @@ from jiuwenswarm.extensions.symphony.extension import (SymphonyExtension,_BuildProcessLogger,_build_log_payload,+ _latest_effective_build_log_entry,)from jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethod@@ -460,6 +461,8 @@ def test_pause_build_cancels_active_build(monkeypatch, tmp_path):assert pause_result["success"] is Trueassert pause_result["paused"] is True+ assert pause_result["build_progress"]["status"] == "paused"+ assert pause_result["build_log"][-1]["stage"] == "update.paused"assert build_result["success"] is Falseassert build_result["paused"] is Trueassert build_result["build_progress"]["status"] == "paused"@@ -572,6 +575,25 @@ def test_build_log_payload_clamps_progress_count_to_total(tmp_path):assert result["build_progress"]["percent"] == 48+def test_build_log_payload_terminal_stage_wins_over_late_progress(tmp_path):+ logger = _BuildProcessLogger(tmp_path / "build_log.jsonl")+ logger.reset()+ logger.record("fingerprint.extract.start", current=14, total=15, path="demo")+ logger.record("update.failed", error="bad model")+ logger.record("fingerprint.extract.start", current=15, total=15, path="late-demo")++ result = _build_log_payload(tmp_path)++ assert result["build_progress"]["status"] == "error"+ assert result["build_progress"]["stage"] == "update.failed"+ assert result["build_progress"]["label"] == "总谱构建失败"+ assert result["build_progress"]["percent"] == 100+++def test_latest_effective_build_log_entry_handles_empty_entries():+ assert _latest_effective_build_log_entry([]) == {}++def test_build_log_payload_includes_manifest_token_usage(tmp_path):usage = {"total": {