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(exe): JiuwenSwarm.exe Exception Pop-up Fix & File Download Issue Fix
ray_le741d5e6c9df2
diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex 0fe692d2dc..14a4684725 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -505,8 +505,11 @@ class TeamManager:send_file_enabled = (config.get("channels", {}).get(str(channel_id), {})- .get("send_file_allowed", False)+ .get("send_file_allowed"))+ # web channel defaults to True, others default to False+ if send_file_enabled is None:+ send_file_enabled = (channel_id == "web")if not send_file_enabled:logger.info("[TeamManager] SendFileToolkit skipped: send_file_allowed=False for channel=%s",diff --git a/jiuwenswarm/channels/desktop/desktop_app.py b/jiuwenswarm/channels/desktop/desktop_app.pyindex 5a34a45f69..e12bcd9fe4 100644--- a/jiuwenswarm/channels/desktop/desktop_app.py+++ b/jiuwenswarm/channels/desktop/desktop_app.py@@ -231,6 +231,16 @@ class _WindowApi:def install_update(self, installer_path: str) -> bool:return self._runtime.install_update(installer_path)+ def download_file(self, url: str, filename: str) -> bool:+ """通过 webview 下载文件,解决 exe 中无法使用 <a> 标签下载的问题。"""+ # 如果是相对路径,拼接完整的 URL(使用前端 web server 端口)+ if url.startswith("/"):+ full_url = f"http://{self._runtime.frontend_host}:{self._runtime.frontend_port}{url}"+ else:+ full_url = url+ logger.info("[desktop] download_file called: url=%s, filename=%s", full_url, filename)+ return self._runtime.download_file(full_url, filename)+class DesktopRuntime:def __init__(@@ -311,6 +321,79 @@ class DesktopRuntime:threading.Thread(target=_delayed_destroy, daemon=True).start()return True+ def download_file(self, url: str, filename: str) -> bool:+ """下载文件到用户下载目录(异步执行,避免阻塞 UI)。"""+ def _download() -> None:+ try:+ import urllib.request++ # 获取下载目录+ download_dir = Path.home() / "Downloads"+ if not download_dir.exists():+ download_dir.mkdir(parents=True, exist_ok=True)++ # 处理文件名冲突+ target_path = download_dir / filename+ if target_path.exists():+ base, ext = Path(filename).stem, Path(filename).suffix+ counter = 1+ while target_path.exists():+ target_path = download_dir / f"{base} ({counter}){ext}"+ counter += 1++ # 下载文件+ urllib.request.urlretrieve(url, target_path)+ logger.info("[desktop] file downloaded to: %s", target_path)++ # 下载完成后提醒用户并打开文件+ self._show_download_complete(str(target_path))+ except Exception as exc: # noqa: BLE001+ logger.error("[desktop] download failed: %s", exc)++ threading.Thread(target=_download, daemon=True).start()+ return True++ @staticmethod+ def _show_download_complete(file_path: str) -> None:+ """下载完成后提醒用户并打开文件所在文件夹。"""+ try:+ if os.name == "nt":+ import ctypes+ # Windows: 弹窗询问是否打开文件夹+ result = ctypes.windll.user32.MessageBoxW(+ 0,+ f"文件已下载到:\n{file_path}\n\n是否打开所在文件夹?",+ "下载完成",+ 0x44 # MB_YESNO + MB_ICONINFORMATION+ )+ if result == 6: # IDYES+ # 打开文件夹并选中文件+ explorer_path = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "explorer.exe")+ subprocess.Popen(+ [explorer_path, "/select,", file_path],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ creationflags=_creationflags(),+ )+ elif sys.platform == "darwin":+ # macOS: 弹窗询问+ result = subprocess.run(+ ["/usr/bin/osascript", "-e", f'''+ display alert "下载完成" message "文件已下载到:\\n{file_path}\\n\\n是否打开所在文件夹?" buttons {"取消", "打开文件夹"} default button "打开文件夹" as informational+ '''],+ capture_output=True,+ text=True,+ )+ if "打开文件夹" in result.stdout:+ # 打开文件夹并选中文件+ subprocess.Popen(+ ["/usr/bin/open", "-R", file_path],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ except Exception as exc: # noqa: BLE001+ logger.error("[desktop] failed to show download complete: %s", exc)+def install_update(self, installer_path: str) -> bool:if os.name != "nt":logger.warning("[desktop] update install is only supported on Windows")@@ -515,6 +598,9 @@ setInterval(showTip,3500);def _on_loaded_first(self) -> None:if self.window is not None:+ # 窗口首次加载后最大化(全屏会影响用户体验)+ if hasattr(self.window, "maximize"):+ self.window.maximize()self.window.events.loaded -= self._on_loaded_firstself.window.events.loaded += self._on_loadeddiff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex 3d4b2be7d0..68ae22a421 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -688,7 +688,18 @@ function FileDownloadList({files: FileDownloadItem[];className?: string;}) {- const handleDownload = (file: FileDownloadItem) => {+ const handleDownload = async (file: FileDownloadItem) => {+ // 检查是否在 PyWebView 环境中(exe 模式)+ const pywebviewApi = (window as Window & { pywebview?: { api?: { download_file?: (url: string, filename: string) => Promise<boolean> | boolean } } }).pywebview?.api;+ if (pywebviewApi?.download_file) {+ // exe 模式:通过 webview API 下载+ const success = await pywebviewApi.download_file(file.download_url, file.name || 'download');+ if (!success) {+ console.error('Download failed via pywebview API');+ }+ return;+ }+ // 浏览器模式:使用标准 <a> 标签下载const link = document.createElement('a');link.href = file.download_url;link.download = file.name || '';diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex b3e83c216e..cd528d4e78 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -97,6 +97,10 @@ def _normalize_config(config: dict[str, Any] | None) -> None:mcc = react.get("model_client_config")if isinstance(mcc, dict) and "custom_headers" in mcc:mcc["custom_headers"] = _parse_custom_headers(mcc["custom_headers"])+ # web channel enable send file tool default+ channels = config.get("channels", {})+ if channels.get("web", {}).get("send_file_allowed") is None:+ channels["web"] = {"send_file_allowed": True}def get_config():diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.pyindex e907a64064..763119a2dd 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py@@ -728,6 +728,17 @@ class XiaoyiChannel(BaseChannel):if file_attachments:logger.info(f"XiaoYi: Processed {len(file_attachments)} file(s): {', '.join(file_attachments)}")+ # ==================== INTERCEPT TEAM MODE COMMANDS ====================+ # xiaoyi channel 不支持 team 模式,拦截并直接返回提示+ text_stripped = text.strip()+ if text_stripped in ("/mode team", "/mode code.team"):+ logger.info(f"XiaoYi: Intercepted team mode command: {text_stripped}")+ response_text = "小艺:暂不支持team 模式。请使用web或者飞书频道试用"+ for url_key in list(self._ws_connections.keys()):+ await self._send_text_response(session_id, task_id, response_text, url_key, is_final=True)+ return+ # =================================================================+# ==================== DOWNLOAD AND SAVE MEDIA FILES ====================media_payload: dict[str, Any] = {}if media_files:diff --git a/scripts/jiuwenswarm_exe_entry.py b/scripts/jiuwenswarm_exe_entry.pyindex 1c3913c291..6fb95b51b9 100644--- a/scripts/jiuwenswarm_exe_entry.py+++ b/scripts/jiuwenswarm_exe_entry.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport osimport sys+import ctypesimport tracebackfrom pathlib import Path@@ -18,6 +19,18 @@ if getattr(sys, "frozen", False):except OSError:pass+ # 设置 UTF-8 编码,避免 bash 操作乱码+ os.environ["PYTHONIOENCODING"] = "utf-8"+ os.environ["PYTHONUTF8"] = "1"+ if os.name == "nt":+ # Windows 控制台 UTF-8 模式+ os.environ["PYTHONLEGACYWINDOWSSTDIO"] = "utf-8"+ try:+ ctypes.windll.kernel32.SetConsoleOutputCP(65001)+ ctypes.windll.kernel32.SetConsoleCP(65001)+ except Exception: # noqa: BLE001+ pass+# Windows: 防止 subprocess 弹出控制台窗口(console=False 编译时 git 等命令会弹出黑框)# Monkey-patch asyncio.create_subprocess_exec,自动添加 CREATE_NO_WINDOW 标志if os.name == "nt":@@ -39,10 +52,6 @@ if getattr(sys, "frozen", False):_DESKTOP_RUN_AGENT = "--desktop-run-agent"_DESKTOP_RUN_GATEWAY = "--desktop-run-gateway"-# 子进程 flag 集合,这些模式下需要将错误写入日志文件,-# 因为 console=False 的 PyInstaller exe 在 Windows 上无法通过 stderr 捕获错误。-_CHILD_FLAGS = {"--desktop-run-app", "--desktop-run-web", _DESKTOP_RUN_AGENT, _DESKTOP_RUN_GATEWAY}-# ── 单实例锁(在重量级 import 之前执行) ──────────────────────────_SINGLE_INSTANCE_LOCK_FD: int | None = None@@ -99,7 +108,6 @@ def _show_already_running_message() -> None:title = "JiuwenSwarm"try:if os.name == "nt":- import ctypesctypes.windll.user32.MessageBoxW(0, msg, title, 0x30)elif sys.platform == "darwin":import subprocess as _sp@@ -112,9 +120,6 @@ def _show_already_running_message() -> None:pass-def _is_child_mode() -> bool:- return any(flag in sys.argv for flag in _CHILD_FLAGS)-def _write_child_error(exc: BaseException) -> None:"""将子进程的未捕获异常写入日志文件。"""@@ -143,16 +148,18 @@ def _pop_flag(flag: str) -> bool:def main() -> None:- is_child = _is_child_mode()-try:_dispatch()- except BaseException as exc:- if is_child:- _write_child_error(exc)- # 子进程异常:写入日志后静默退出,不弹窗- raise SystemExit(1) from exc+ except SystemExit:+ # SystemExit 是正常的退出请求(如 sys.exit()),直接传递,不弹窗raise+ except KeyboardInterrupt as e:+ # Ctrl+C 也是正常退出+ raise SystemExit(0) from e+ except BaseException as exc:+ # 其他未捕获异常:记录日志后静默退出,避免 PyInstaller exe 弹窗+ _write_child_error(exc)+ raise SystemExit(1) from Nonedef _dispatch() -> None: