Skip to content

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: agent显示问题

douran10f8601fb8e2
diff --git a/jiuwenclaw/agentserver/skill_manager.py b/jiuwenclaw/agentserver/skill_manager.py
index c5d1da1bff..9c9c7ca09f 100644
--- a/jiuwenclaw/agentserver/skill_manager.py
+++ b/jiuwenclaw/agentserver/skill_manager.py
@@ -989,6 +989,19 @@ class SkillManager:
return []
return mirrors
+ @staticmethod
+ def _normalize_lang_suffix(name: str) -> str:
+ """将 xxxx_zh.MD / xxxx_en.MD 规范为 xxxx.MD(去除 _zh/_en 后缀)。"""
+ stem, suffix = name.rpartition(".")[0], name.rpartition(".")[2]
+ suffix_lower = suffix.lower()
+ if suffix_lower in ("md", "mdx"):
+ stem_lower = stem.lower()
+ if stem_lower.endswith("_zh"):
+ stem = stem[:-3]
+ elif stem_lower.endswith("_en"):
+ stem = stem[:-3]
+ return f"{stem}.{suffix}" if stem else name
+
@staticmethod
def _generate_agent_data_for_workspace(workspace_root: Path) -> None:
"""Generate agent/workspace/agent-data.json from agent tree."""
@@ -1000,16 +1013,34 @@ class SkillManager:
return
folder_data: dict[str, list[dict[str, str | bool]]] = {}
+ seen_paths: dict[str, set[str]] = {}
for entry in sorted(agent_root.rglob("*")):
if not entry.is_file():
continue
relative_file_path = entry.relative_to(agent_root).as_posix()
relative_folder_path = entry.parent.relative_to(agent_root).as_posix()
folder_key = root_folder_key if relative_folder_path == "." else relative_folder_path
+
+ display_name = SkillManager._normalize_lang_suffix(entry.name)
+ display_path = (
+ f"agent/{relative_folder_path}/{display_name}".replace("/.", "/").replace("//", "/")
+ if relative_folder_path != "."
+ else f"agent/{display_name}"
+ )
+ # 模板中 HEARTBEAT/PRINCIPLE/TONE 在 agent 根目录,运行时在 agent/home/,统一映射到 home
+ if folder_key == root_folder_key and display_name.lower() in ("heartbeat.md", "principle.md", "tone.md"):
+ folder_key = "home"
+ display_path = f"agent/home/{display_name}"
+
+ seen = seen_paths.setdefault(folder_key, set())
+ if display_path in seen:
+ continue
+ seen.add(display_path)
+
folder_data.setdefault(folder_key, []).append(
{
- "name": entry.name,
- "path": f"agent/{relative_file_path}",
+ "name": display_name,
+ "path": display_path,
"isMarkdown": entry.suffix.lower() in {".md", ".mdx"},
}
)
diff --git a/jiuwenclaw/app_web.py b/jiuwenclaw/app_web.py
index 03e98aa595..d6f0c727c0 100644
--- a/jiuwenclaw/app_web.py
+++ b/jiuwenclaw/app_web.py
@@ -47,6 +47,19 @@ def _default_dist_dir() -> Path:
return root / "web" / "dist"
+def _normalize_lang_suffix(name: str) -> str:
+ """将 xxxx_zh.MD / xxxx_en.MD 规范为 xxxx.MD(去除 _zh/_en 后缀)。"""
+ stem, suffix = name.rpartition(".")[0], name.rpartition(".")[2]
+ suffix_lower = suffix.lower()
+ if suffix_lower in ("md", "mdx"):
+ stem_lower = stem.lower()
+ if stem_lower.endswith("_zh"):
+ stem = stem[:-3]
+ elif stem_lower.endswith("_en"):
+ stem = stem[:-3]
+ return f"{stem}.{suffix}" if stem else name
+
+
def _generate_agent_data(project_root: Path) -> None:
"""Generate agent/workspace/agent-data.json from agent tree."""
agent_root = (project_root / "agent").resolve()
@@ -59,16 +72,34 @@ def _generate_agent_data(project_root: Path) -> None:
raise NotADirectoryError("agent is not a directory")
folder_data: dict[str, list[dict[str, str | bool]]] = {}
+ seen_paths: dict[str, set[str]] = {} # folder_key -> normalized paths,用于去重
for entry in sorted(agent_root.rglob("*")):
if not entry.is_file():
continue
relative_file_path = entry.relative_to(agent_root).as_posix()
relative_folder_path = entry.parent.relative_to(agent_root).as_posix()
folder_key = root_folder_key if relative_folder_path == "." else relative_folder_path
+
+ display_name = _normalize_lang_suffix(entry.name)
+ display_path = (
+ f"agent/{relative_folder_path}/{display_name}".replace("/.", "/").replace("//", "/")
+ if relative_folder_path != "."
+ else f"agent/{display_name}"
+ )
+ # 模板中 HEARTBEAT/PRINCIPLE/TONE 在 agent 根目录,运行时在 agent/home/,统一映射到 home
+ if folder_key == root_folder_key and display_name.lower() in ("heartbeat.md", "principle.md", "tone.md"):
+ folder_key = "home"
+ display_path = f"agent/home/{display_name}"
+
+ seen = seen_paths.setdefault(folder_key, set())
+ if display_path in seen:
+ continue # 同一文件夹内 _zh 与 _en 并存时只保留先出现的
+ seen.add(display_path)
+
folder_data.setdefault(folder_key, []).append(
{
- "name": entry.name,
- "path": f"agent/{relative_file_path}",
+ "name": display_name,
+ "path": display_path,
"isMarkdown": entry.suffix.lower() in {".md", ".mdx"},
}
)
@@ -527,8 +558,15 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
self._write_json(403, {"error": "forbidden_path"})
return
if not full_path.exists():
- self._write_json(404, {"error": "file_not_found", "fullPath": str(full_path)})
- return
+ if file_arg.replace("\\", "/") == "agent/workspace/agent-data.json":
+ try:
+ _generate_agent_data(self.project_root)
+ except Exception as exc: # noqa: BLE001
+ self._write_json(500, {"error": "generate_failed", "detail": str(exc)})
+ return
+ if not full_path.exists():
+ self._write_json(404, {"error": "file_not_found", "fullPath": str(full_path)})
+ return
try:
data = full_path.read_text(encoding="utf-8")
except OSError as exc:
diff --git a/jiuwenclaw/scripts/generate-agent-folders.js b/jiuwenclaw/scripts/generate-agent-folders.js
index 89c833921e..4ecb98eaaa 100644
--- a/jiuwenclaw/scripts/generate-agent-folders.js
+++ b/jiuwenclaw/scripts/generate-agent-folders.js
@@ -28,14 +28,43 @@ try {
const isMarkdownFile = (fileName) => fileName.endsWith('.md') || fileName.endsWith('.mdx');
const ROOT_FOLDER_KEY = '__root__';
const folderData = {};
+ const seenPaths = {}; // folderKey -> Set of normalized paths,用于去重 _zh/_en
+
+ const normalizeLangSuffix = (name) => {
+ const lastDot = name.lastIndexOf('.');
+ if (lastDot === -1) return name;
+ const stem = name.slice(0, lastDot);
+ const suffix = name.slice(lastDot + 1);
+ if (!/\.(md|mdx)$/i.test('.' + suffix)) return name;
+ const stemLower = stem.toLowerCase();
+ if (stemLower.endsWith('_zh')) return stem.slice(0, -3) + '.' + suffix;
+ if (stemLower.endsWith('_en')) return stem.slice(0, -3) + '.' + suffix;
+ return name;
+ };
const upsertFileToFolder = (folderKey, relativeFilePath) => {
+ const rawName = path.basename(relativeFilePath);
+ const displayName = normalizeLangSuffix(rawName);
+ const relativeFolderPath = path.dirname(relativeFilePath);
+ let displayPath = relativeFolderPath === '.'
+ ? `agent/${displayName}`
+ : `agent/${relativeFolderPath.replace(/\\/g, '/')}/${displayName}`;
+ // 模板中 HEARTBEAT/PRINCIPLE/TONE 在 agent 根目录,运行时在 agent/home/,统一映射到 home
+ if (folderKey === ROOT_FOLDER_KEY && ['heartbeat.md', 'principle.md', 'tone.md'].includes(displayName.toLowerCase())) {
+ folderKey = 'home';
+ displayPath = `agent/home/${displayName}`;
+ }
+
+ if (!seenPaths[folderKey]) seenPaths[folderKey] = new Set();
+ if (seenPaths[folderKey].has(displayPath)) return;
+ seenPaths[folderKey].add(displayPath);
+
if (!folderData[folderKey]) {
folderData[folderKey] = [];
}
folderData[folderKey].push({
- name: path.basename(relativeFilePath),
- path: `agent/${relativeFilePath.replace(/\\/g, '/')}`,
+ name: displayName,
+ path: displayPath,
isMarkdown: isMarkdownFile(relativeFilePath)
});
};
diff --git a/jiuwenclaw/web/vite.config.ts b/jiuwenclaw/web/vite.config.ts
index 5b4448195e..b1f8813a2b 100644
--- a/jiuwenclaw/web/vite.config.ts
+++ b/jiuwenclaw/web/vite.config.ts
@@ -377,6 +377,24 @@ function devFileContentApi(): Plugin {
return
}
if (!fs.existsSync(fullPath)) {
+ if (filePath.replace(/\\/g, '/') === 'agent/workspace/agent-data.json') {
+ try {
+ const runResult = spawnSync(process.execPath, [generateAgentFoldersScriptPath], {
+ encoding: 'utf-8',
+ env: { ...process.env, JIUWENCLAW_ROOT: projectRootDir },
+ cwd: path.dirname(path.dirname(generateAgentFoldersScriptPath)),
+ })
+ if (runResult.status === 0 && fs.existsSync(fullPath)) {
+ const content = fs.readFileSync(fullPath, 'utf-8')
+ res.statusCode = 200
+ res.setHeader('content-type', 'text/plain; charset=utf-8')
+ res.end(content)
+ return
+ }
+ } catch {
+ /* fall through to 404 */
+ }
+ }
res.statusCode = 404
res.setHeader('content-type', 'application/json; charset=utf-8')
res.end(JSON.stringify({ error: '文件不存在', fullPath }))