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: 【回合】优化文件上传功能
w110162753318e2e45d63be
diff --git a/jiuwenswarm/channels/desktop/desktop_app.py b/jiuwenswarm/channels/desktop/desktop_app.pyindex 95f6a276fe..b3940186bf 100644--- a/jiuwenswarm/channels/desktop/desktop_app.py+++ b/jiuwenswarm/channels/desktop/desktop_app.py@@ -3,8 +3,11 @@ from __future__ import annotationsimport argparseimport base64import binascii+import ctypesimport http.client+import jsonimport logging+import mimetypesimport osimport shleximport shutil@@ -15,7 +18,10 @@ import sysimport tempfileimport threadingimport time+from ctypes import wintypes+from dataclasses import dataclassfrom pathlib import Path+from typing import Anyfrom logging.handlers import RotatingFileHandler@@ -42,6 +48,117 @@ STARTUP_TIMEOUT_SECONDS = 45.0PNG_DATA_URL_PREFIX = "data:image/png;base64,"PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"DesktopSaveResult = dict[str, bool]+IMAGE_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".gif", ".jfif"})+MAX_IMAGE_BYTES = 10 * 1024 * 1024+# Keep in sync with frontend/document_attachments forbidden list.+FORBIDDEN_DOCUMENT_EXTENSIONS = frozenset(+ {+ ".exe",+ ".dll",+ ".msi",+ ".scr",+ ".bat",+ ".cmd",+ ".ps1",+ ".vbs",+ ".wsf",+ ".hta",+ ".jar",+ ".lnk",+ ".bin",+ ".so",+ ".dylib",+ ".app",+ ".dmg",+ ".pkg",+ ".command",+ ".scpt",+ ".scptd",+ ".workflow",+ ".xpc",+ ".bundle",+ ".framework",+ ".kext",+ ".prefpane",+ ".saver",+ ".component",+ }+)+# Dialog allow-list (UI filter only). Keep in sync with InputArea ATTACHMENT_ACCEPT.+# Intentionally omits FORBIDDEN_DOCUMENT_EXTENSIONS and does NOT include *.* so+# Windows/macOS pickers hide blacklist types the same way the browser accept= does.+ATTACHMENT_DIALOG_EXTENSIONS: tuple[str, ...] = (+ ".png",+ ".jpg",+ ".jpeg",+ ".webp",+ ".gif",+ ".bmp",+ ".svg",+ ".ico",+ ".jfif",+ ".pdf",+ ".doc",+ ".docx",+ ".xls",+ ".xlsx",+ ".ppt",+ ".pptx",+ ".txt",+ ".md",+ ".markdown",+ ".csv",+ ".tsv",+ ".rtf",+ ".odt",+ ".ods",+ ".odp",+ ".json",+ ".xml",+ ".yaml",+ ".yml",+ ".html",+ ".htm",+ ".css",+ ".js",+ ".ts",+ ".tsx",+ ".jsx",+ ".py",+ ".java",+ ".c",+ ".cpp",+ ".h",+ ".go",+ ".rs",+ ".rb",+ ".php",+ ".sql",+ ".ipynb",+ ".toml",+ ".ini",+ ".log",+ ".zip",+ ".rar",+ ".7z",+ ".tar",+ ".gz",+ # audio/* / video/* from browser accept=+ ".mp3",+ ".wav",+ ".flac",+ ".aac",+ ".ogg",+ ".m4a",+ ".wma",+ ".mp4",+ ".avi",+ ".mov",+ ".mkv",+ ".webm",+ ".wmv",+ ".flv",+)UPDATE_CLEANUP_PATTERNS = ("JiuwenSwarm-setup-*.exe","JiuwenSwarm-*.dmg",@@ -90,6 +207,16 @@ def _setup_logger() -> logging.Logger:logger = _setup_logger()+def attachment_open_file_types() -> tuple[str, ...]:+ """pywebview OPEN dialog filters that hide blacklist extensions.++ Format must be ``Description (*.ext1;*.ext2)``. Do not append+ ``All files (*.*)`` — that would re-expose ``.exe`` etc.+ """+ patterns = ";".join(f"*{ext}" for ext in ATTACHMENT_DIALOG_EXTENSIONS)+ return (f"Allowed files ({patterns})",)++def _format_ports_for_log(ports: dict[str, int]) -> str:return ", ".join(f"{name}={ports.get(name, 0)}" for name in PORT_TYPES)@@ -413,6 +540,105 @@ class _WindowApi:"""打开系统目录选择器,返回用户选择的项目目录绝对路径。"""return self._runtime.select_project_directory()+ def select_local_files(+ self,+ allow_multiple: bool = True,+ initial_dir: str | None = None,+ ) -> list[dict[str, Any]]:+ """打开系统文件选择器,返回本地绝对路径及附件元数据。++ WebView2 / pywebview 的 ``<input type="file">`` 不会暴露 Electron 式+ ``File.path``,文档上传必须走原生对话框拿绝对路径。+ 默认打开上次成功选择文件所在目录(无则用户主目录)。+ """+ return self._runtime.select_local_files(+ allow_multiple=bool(allow_multiple),+ initial_dir=initial_dir,+ )++ def describe_local_files(self, paths: list[str] | None = None) -> list[dict[str, Any]]:+ """根据本机绝对路径返回与 select_local_files 同形的附件元数据。"""+ return self._runtime.describe_local_files(paths or [])++ def get_clipboard_files(self) -> list[dict[str, Any]]:+ """读取系统剪贴板中的文件路径并描述为附件元数据。"""+ return self._runtime.get_clipboard_files()+++def _clipboard_file_paths_windows() -> list[str]:+ """Read CF_HDROP file paths from the Windows clipboard."""+ # Win32 clipboard format CF_HDROP == 15+ cf_hdrop = 15+ user32 = ctypes.windll.user32+ shell32 = ctypes.windll.shell32++ user32.OpenClipboard.argtypes = [wintypes.HWND]+ user32.OpenClipboard.restype = wintypes.BOOL+ user32.CloseClipboard.argtypes = []+ user32.CloseClipboard.restype = wintypes.BOOL+ user32.IsClipboardFormatAvailable.argtypes = [wintypes.UINT]+ user32.IsClipboardFormatAvailable.restype = wintypes.BOOL+ user32.GetClipboardData.argtypes = [wintypes.UINT]+ user32.GetClipboardData.restype = wintypes.HANDLE+ shell32.DragQueryFileW.argtypes = [+ wintypes.HANDLE,+ wintypes.UINT,+ wintypes.LPWSTR,+ wintypes.UINT,+ ]+ shell32.DragQueryFileW.restype = wintypes.UINT++ if not user32.OpenClipboard(None):+ return []+ try:+ if not user32.IsClipboardFormatAvailable(cf_hdrop):+ return []+ h_drop = user32.GetClipboardData(cf_hdrop)+ if not h_drop:+ return []+ count = shell32.DragQueryFileW(h_drop, 0xFFFFFFFF, None, 0)+ paths: list[str] = []+ for index in range(count):+ length = shell32.DragQueryFileW(h_drop, index, None, 0)+ if length <= 0:+ continue+ buffer = ctypes.create_unicode_buffer(length + 1)+ shell32.DragQueryFileW(h_drop, index, buffer, length + 1)+ value = buffer.value.strip()+ if value:+ paths.append(value)+ return paths+ finally:+ user32.CloseClipboard()+++def _clipboard_file_paths_macos() -> list[str]:+ """Read file paths from the macOS general pasteboard."""+ try:+ from AppKit import NSPasteboard # type: ignore[import-not-found]+ except Exception: # noqa: BLE001+ return []++ try:+ pasteboard = NSPasteboard.generalPasteboard()+ items = pasteboard.propertyListForType_("NSFilenamesPboardType")+ if not items:+ return []+ return [str(item).strip() for item in items if str(item).strip()]+ except Exception: # noqa: BLE001+ return []+++def _clipboard_file_paths() -> list[str]:+ try:+ if os.name == "nt":+ return _clipboard_file_paths_windows()+ if sys.platform == "darwin":+ return _clipboard_file_paths_macos()+ except Exception as exc: # noqa: BLE001+ logger.warning("[desktop] clipboard file path read failed: %s", exc)+ return []+class DesktopRuntime:def __init__(@@ -426,6 +652,7 @@ class DesktopRuntime:self.window = Noneself._lock = threading.Lock()self._is_shutting_down = False+ self._desktop_dnd_bound = False@propertydef frontend_url(self) -> str:@@ -589,6 +816,336 @@ class DesktopRuntime:except Exception: # noqa: BLE001return str(Path(selected_path).expanduser())+ def select_local_files(+ self,+ allow_multiple: bool = True,+ initial_dir: str | None = None,+ ) -> list[dict[str, Any]]:+ if self.window is None or not hasattr(self.window, "create_file_dialog"):+ logger.error("[desktop] local file picker unavailable")+ return []++ from jiuwenswarm.channels.web.file_picker import (+ remember_file_picker_dir,+ resolve_file_picker_initial_dir,+ )++ start_dir = resolve_file_picker_initial_dir(initial_dir)+ try:+ selected_paths = self.window.create_file_dialog(+ webview.FileDialog.OPEN,+ directory=start_dir,+ allow_multiple=bool(allow_multiple),+ file_types=attachment_open_file_types(),+ )+ except Exception as exc: # noqa: BLE001+ logger.error("[desktop] local file picker failed: %s", exc)+ return []++ if not selected_paths:+ return []++ if isinstance(selected_paths, (str, Path)):+ path_list = [selected_paths]+ else:+ path_list = list(selected_paths)++ results: list[dict[str, Any]] = []+ for raw in path_list:+ item = self._describe_local_file(raw)+ if item is not None:+ results.append(item)+ if results:+ remember_file_picker_dir(results[0].get("path") or path_list[0])+ return results++ @staticmethod+ def _describe_local_file(raw_path: str | Path) -> dict[str, Any] | None:+ try:+ path = Path(raw_path).expanduser().resolve()+ except Exception: # noqa: BLE001+ path = Path(raw_path).expanduser()++ if not path.is_file():+ logger.warning("[desktop] selected path is not a file: %s", path)+ return None++ filename = path.name+ ext = path.suffix.lower()+ try:+ size = path.stat().st_size+ except OSError as exc:+ logger.warning("[desktop] failed to stat selected file %s: %s", path, exc)+ return None++ mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"+ absolute = str(path)+ if ext in IMAGE_EXTENSIONS:+ if size > MAX_IMAGE_BYTES:+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "image",+ "error": "image_too_large",+ }+ try:+ payload = base64.b64encode(path.read_bytes()).decode("ascii")+ except OSError as exc:+ logger.warning("[desktop] failed to read image %s: %s", path, exc)+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "image",+ "error": "read_failed",+ }+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "image",+ "base64": payload,+ }++ if ext in FORBIDDEN_DOCUMENT_EXTENSIONS:+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "document",+ "error": "forbidden",+ }++ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "document",+ }++ def describe_local_files(self, paths: list[str] | Any) -> list[dict[str, Any]]:+ if isinstance(paths, (str, Path)):+ path_list = [paths]+ elif paths:+ path_list = list(paths)+ else:+ return []++ results: list[dict[str, Any]] = []+ for raw in path_list:+ if raw is None:+ continue+ item = self._describe_local_file(str(raw))+ if item is not None:+ results.append(item)+ return results++ def get_clipboard_files(self) -> list[dict[str, Any]]:+ return self.describe_local_files(_clipboard_file_paths())++ def _evaluate_js(self, script: str) -> None:+ if self.window is None:+ return+ try:+ self.window.evaluate_js(script)+ except Exception as exc: # noqa: BLE001+ logger.warning("[desktop] evaluate_js failed: %s", exc)++ def _run_js(self, script: str) -> Any:+ """Run JS without pywebview's eval()/escape_string wrapping."""+ if self.window is None:+ return None+ try:+ run_js = getattr(self.window, "run_js", None)+ if callable(run_js):+ return run_js(script)+ return self.window.evaluate_js(script)+ except Exception as exc: # noqa: BLE001+ logger.warning("[desktop] run_js failed: %s", exc)+ return None++ def _mark_desktop_shell(self) -> None:+ """Mark desktop shell and force the page to accept OS file drags.++ React may set ``dropEffect='none'`` during bubble; a window-level bubble+ listener runs afterwards and restores ``copy`` so the forbidden cursor+ does not appear inside the desktop webview. OS file drags into WebView2+ require ``copy`` — ``move``/``none`` are rejected and show the forbidden+ cursor.+ """+ self._run_js(+ """+(function () {+ window.__JIUWEN_DESKTOP__ = true;+ window.__JIUWEN_DROP_QUEUE__ = window.__JIUWEN_DROP_QUEUE__ || [];+ // Durable stub: never leave Python without a callable ingest hook.+ if (typeof window.__JIUWEN_INGEST_LOCAL_FILES__ !== 'function') {+ window.__JIUWEN_INGEST_LOCAL_FILES__ = function (detail) {+ try { window.__JIUWEN_DROP_QUEUE__.push(detail); } catch (err) {}+ window.dispatchEvent(new CustomEvent('jiuwen-desktop-local-files', { detail: detail }));+ };+ }+ window.dispatchEvent(new CustomEvent('jiuwen-desktop-ready'));+ if (window.__JIUWEN_DESKTOP_DND__) return;+ window.__JIUWEN_DESKTOP_DND__ = true;+ function hasFiles(dt) {+ if (!dt || !dt.types) return false;+ try {+ return Array.from(dt.types).indexOf('Files') !== -1;+ } catch (err) {+ return false;+ }+ }+ function accept(e) {+ if (!hasFiles(e.dataTransfer)) return;+ e.preventDefault();+ try { e.dataTransfer.dropEffect = 'copy'; } catch (err) {}+ window.dispatchEvent(new CustomEvent('jiuwen-desktop-file-drag', {detail:{active:true}}));+ }+ function endDrag() {+ window.dispatchEvent(new CustomEvent('jiuwen-desktop-file-drag', {detail:{active:false}}));+ }+ // Capture: ensure preventDefault early. Bubble on window: win over React dropEffect=none.+ window.addEventListener('dragenter', accept, true);+ window.addEventListener('dragover', accept, true);+ window.addEventListener('dragenter', accept, false);+ window.addEventListener('dragover', accept, false);+ window.addEventListener('drop', function (e) {+ if (!hasFiles(e.dataTransfer)) return;+ e.preventDefault();+ endDrag();+ }, true);+})();+"""+ )++ def _dispatch_local_files_event(+ self,+ source: str,+ files: list[dict[str, Any]],+ *,+ client_x: float | int | None = None,+ client_y: float | int | None = None,+ ) -> None:+ if self.window is None or not files:+ return+ payload: dict[str, Any] = {+ "source": source,+ "files": files,+ "trusted": True,+ "dropId": f"{time.time_ns()}",+ }+ if isinstance(client_x, (int, float)):+ payload["clientX"] = client_x+ if isinstance(client_y, (int, float)):+ payload["clientY"] = client_y+ try:+ detail = json.dumps(payload, ensure_ascii=False)+ # Single JS round-trip per drop: end the drag overlay, then hand the+ # files to the durable ingest bridge (frontend or the injected stub).+ # Do not issue multiple concurrent evaluate_js calls here — racing JS+ # calls from pywebview's DOMEventHandler thread can deadlock the+ # WebView2 UI thread.+ script = f"""+(function () {{+ var detail = {detail};+ window.dispatchEvent(new CustomEvent('jiuwen-desktop-file-drag', {{ detail: {{ active: false }} }}));+ if (typeof window.__JIUWEN_INGEST_LOCAL_FILES__ === 'function') {{+ window.__JIUWEN_INGEST_LOCAL_FILES__(detail);+ }} else {{+ window.dispatchEvent(new CustomEvent('jiuwen-desktop-local-files', {{ detail: detail }}));+ }}+}})();+"""+ self._run_js(script)+ logger.info(+ "[desktop] dispatched %d local file(s) from %s", len(files), source+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("[desktop] failed to dispatch local files event: %s", exc)++ @staticmethod+ def _on_desktop_drag(_event: Any) -> None:+ # Overlay / cursor feedback is driven by the injected JS accept handlers.+ return None++ def _on_desktop_drop(self, event: Any) -> None:+ # No standalone run_js here: the drag-end overlay event is folded into the+ # dispatch script, and the page-side drop listener already ends the+ # overlay. Extra concurrent JS calls at drop time can deadlock the UI thread.+ try:+ payload = event or {}+ data_transfer = payload.get("dataTransfer") or {}+ raw_files = data_transfer.get("files") or []+ except Exception: # noqa: BLE001+ return+ if not raw_files:+ logger.info("[desktop] drop event without files")+ return++ paths: list[str] = []+ for item in raw_files:+ if not isinstance(item, dict):+ continue+ path = item.get("pywebviewFullPath")+ if isinstance(path, str) and path.strip():+ paths.append(path.strip())+ if not paths:+ logger.warning("[desktop] drop files missing pywebviewFullPath: %s", raw_files)+ return+ described = self.describe_local_files(paths)+ if described:+ logger.info("[desktop] dispatching %d dropped file(s)", len(described))+ self._dispatch_local_files_event(+ "drop",+ described,+ client_x=payload.get("clientX"),+ client_y=payload.get("clientY"),+ )++ def _bind_desktop_file_dnd(self) -> None:+ if self.window is None or self._desktop_dnd_bound:+ return+ try:+ from webview.dom import DOMEventHandler++ document = self.window.dom.document+ # preventDefault so WebView2 accepts the drop and exposes full paths.+ # Do not stopPropagation on dragenter/dragover — React needs those for+ # the chat drop overlay; the injected window listeners fix the cursor.+ document.events.dragenter += DOMEventHandler(self._on_desktop_drag, True, False)+ document.events.dragover += DOMEventHandler(+ self._on_desktop_drag, True, False, debounce=500+ )+ document.events.drop += DOMEventHandler(self._on_desktop_drop, True, True)+ self._desktop_dnd_bound = True+ logger.info("[desktop] file drag-and-drop handlers bound")+ except Exception as exc: # noqa: BLE001+ logger.warning("[desktop] failed to bind file drag-and-drop handlers: %s", exc)++ def _schedule_desktop_file_dnd_bind(self) -> None:+ self._mark_desktop_shell()+ self._desktop_dnd_bound = False+ self._bind_desktop_file_dnd()+ if self._desktop_dnd_bound:+ return++ def _retry() -> None:+ try:+ self._mark_desktop_shell()+ self._bind_desktop_file_dnd()+ except Exception as exc: # noqa: BLE001+ logger.warning("[desktop] retry bind file drag-and-drop failed: %s", exc)++ threading.Timer(1.0, _retry).start()+ threading.Timer(3.0, _retry).start()+def save_data_url(self, data_url: str, filename: str) -> DesktopSaveResult:"""选择保存位置并保存 PNG data URL。"""if not isinstance(data_url, str) or not data_url.startswith(PNG_DATA_URL_PREFIX):@@ -623,7 +1180,6 @@ class DesktopRuntime:"""下载完成后提醒用户并打开文件所在文件夹。"""try:if os.name == "nt":- import ctypes# Windows: 弹窗询问是否打开文件夹result = ctypes.windll.user32.MessageBoxW(0,@@ -1115,9 +1671,20 @@ setInterval(showTip,3500);self.window.maximize()self.window.events.loaded -= self._on_loaded_firstself.window.events.loaded += self._on_loaded+ # loading HTML → load_url(frontend) 与 handler 切换存在竞态:+ # 若真实前端的 loaded 落在 _on_loaded_first 上,会只 maximize/换 handler,+ # 永远不绑定拖拽。延迟再绑一次,覆盖该竞态(_schedule 会重置 bound 标志)。+ threading.Timer(1.5, self._schedule_desktop_file_dnd_bind).start()+ threading.Timer(4.0, self._schedule_desktop_file_dnd_bind).start()def _on_loaded(self) -> None:- pass+ # Frontend navigation completed; bind OS file drop path bridge for the new document.+ # Note: never touch the WebView2 controller (window.native.*) from this+ # thread — pywebview fires `loaded` on a background thread and WebView2+ # controller members are UI-thread-only. A cross-apartment COM call from+ # here intermittently deadlocks the UI thread (window "not responding").+ # AllowExternalDrop defaults to true, so no controller access is needed.+ self._schedule_desktop_file_dnd_bind()def _on_closed(self) -> None:self.shutdown()diff --git a/jiuwenswarm/channels/web/directory_picker.py b/jiuwenswarm/channels/web/directory_picker.pynew file mode 100644index 0000000000..5c9b0c73a7--- /dev/null+++ b/jiuwenswarm/channels/web/directory_picker.py@@ -0,0 +1,295 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""浏览器 / Web 通道使用的本机目录选择器(非 pywebview)。++策略:+- Windows:沿用 tkinter 文件夹对话框(当前实现)+- macOS:osascript(独立进程)+- Linux:zenity → kdialog → yad → tkinter 子进程(均在独立进程,+ 避免 ``asyncio.to_thread`` 工作线程里创建 ``Tk()``)+- 均不可用时抛出 ``RuntimeError``,由前端回落到「手填绝对路径」+"""++from __future__ import annotations++import logging+import os+import shutil+import subprocess+import sys+from collections.abc import Callable+from pathlib import Path++logger = logging.getLogger(__name__)++_DIALOG_TITLE = "选择项目目录"+++def _resolve_initial_dir(initial_dir: str | None) -> str:+ if initial_dir:+ candidate = Path(initial_dir).expanduser()+ if candidate.is_dir():+ try:+ return str(candidate.resolve())+ except Exception: # noqa: BLE001+ return str(candidate)+ return str(Path.home())+++def _normalize_selected(selected: str | None) -> str | None:+ if not selected:+ return None+ path = Path(str(selected).strip()).expanduser()+ if not str(path):+ return None+ try:+ return str(path.resolve())+ except Exception: # noqa: BLE001+ return str(path)+++def _run_capture(command: list[str], *, timeout: float = 600.0) -> subprocess.CompletedProcess[str]:+ return subprocess.run( # noqa: S603+ command,+ check=False,+ capture_output=True,+ text=True,+ timeout=timeout,+ )+++def _select_directory_windows_tk(initial_dir: str) -> str | None:+ """Windows:保留 tkinter 实现。"""+ try:+ import tkinter as tk+ from tkinter import filedialog+ except Exception as exc: # noqa: BLE001+ raise RuntimeError(f"directory picker unavailable: {exc}") from exc++ root = tk.Tk()+ root.withdraw()+ try:+ try:+ root.attributes("-topmost", True)+ except Exception: # noqa: BLE001+ pass+ try:+ root.lift()+ root.focus_force()+ except Exception: # noqa: BLE001+ pass++ selected = filedialog.askdirectory(+ parent=root,+ initialdir=initial_dir,+ mustexist=True,+ title=_DIALOG_TITLE,+ )+ finally:+ try:+ root.destroy()+ except Exception: # noqa: BLE001+ pass++ return _normalize_selected(selected)+++def _select_directory_macos(initial_dir: str) -> str | None:+ """macOS:AppleScript choose folder(独立进程,可在工作线程调用)。"""+ script_with_default = (+ f'set defaultFolder to POSIX file "{initial_dir}"\n'+ f'set chosenFolder to choose folder with prompt "{_DIALOG_TITLE}" default location defaultFolder\n'+ "POSIX path of chosenFolder"+ )+ script_plain = (+ f'set chosenFolder to choose folder with prompt "{_DIALOG_TITLE}"\n'+ "POSIX path of chosenFolder"+ )+ for script in (script_with_default, script_plain):+ try:+ completed = _run_capture(["osascript", "-e", script])+ except FileNotFoundError as exc:+ raise RuntimeError("directory picker unavailable: osascript not found") from exc+ except subprocess.TimeoutExpired as exc:+ raise RuntimeError("directory picker timed out") from exc++ if completed.returncode == 0:+ return _normalize_selected(completed.stdout)+ stderr = (completed.stderr or "").strip()+ if "User canceled" in stderr or "-128" in stderr:+ return None+ if script is script_with_default:+ continue+ raise RuntimeError(f"directory picker unavailable: {stderr or 'osascript failed'}")+ return None+++def _try_zenity(initial_dir: str) -> str | None:+ completed = _run_capture(+ [+ "zenity",+ "--file-selection",+ "--directory",+ f"--title={_DIALOG_TITLE}",+ f"--filename={initial_dir.rstrip(os.sep) + os.sep}",+ ],+ )+ # zenity: 0=ok, 1=cancel, 其他=错误+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "zenity failed")+ return _normalize_selected(completed.stdout)+++def _try_kdialog(initial_dir: str) -> str | None:+ completed = _run_capture(+ ["kdialog", "--getexistingdirectory", initial_dir, "--title", _DIALOG_TITLE],+ )+ # kdialog: 0=ok, 1=cancel+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "kdialog failed")+ return _normalize_selected(completed.stdout)+++def _try_yad(initial_dir: str) -> str | None:+ completed = _run_capture(+ [+ "yad",+ "--file",+ "--directory",+ f"--title={_DIALOG_TITLE}",+ f"--filename={initial_dir.rstrip(os.sep) + os.sep}",+ ],+ )+ # yad 与 zenity 类似:0=ok, 1=cancel+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "yad failed")+ return _normalize_selected(completed.stdout)+++def _try_tkinter_subprocess(initial_dir: str) -> str | None:+ """在独立子进程中跑 tkinter,保证 Tk 位于该进程主线程。++ 可安全从 ``asyncio.to_thread`` 工作线程调用,适用于 Ubuntu 等未安装+ zenity/kdialog、但已安装 ``python3-tk`` 的桌面环境。+ """+ env = os.environ.copy()+ env["JIUWEN_DIR_PICKER_INITIAL"] = initial_dir+ env["JIUWEN_DIR_PICKER_TITLE"] = _DIALOG_TITLE+ script = r"""+import os, sys+try:+ import tkinter as tk+ from tkinter import filedialog+except Exception as exc:+ sys.stderr.write(f"tkinter unavailable: {exc}\n")+ sys.exit(2)++initial = os.environ.get("JIUWEN_DIR_PICKER_INITIAL") or str(os.path.expanduser("~"))+title = os.environ.get("JIUWEN_DIR_PICKER_TITLE") or "Select Directory"+root = tk.Tk()+root.withdraw()+try:+ try:+ root.attributes("-topmost", True)+ except Exception:+ pass+ try:+ root.lift()+ root.focus_force()+ except Exception:+ pass+ selected = filedialog.askdirectory(+ parent=root,+ initialdir=initial,+ mustexist=True,+ title=title,+ )+finally:+ try:+ root.destroy()+ except Exception:+ pass++if selected:+ sys.stdout.write(selected)+ sys.exit(0)+sys.exit(1)+"""+ completed = subprocess.run( # noqa: S603+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ text=True,+ timeout=600.0,+ env=env,+ )+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "tkinter subprocess failed")+ return _normalize_selected(completed.stdout)+++def _select_directory_linux(initial_dir: str) -> str | None:+ """Linux:依次尝试 zenity / kdialog / yad / tkinter 子进程。"""+ backends: list[tuple[str, Callable[[str], str | None]]] = []+ if shutil.which("zenity"):+ backends.append(("zenity", _try_zenity))+ if shutil.which("kdialog"):+ backends.append(("kdialog", _try_kdialog))+ if shutil.which("yad"):+ backends.append(("yad", _try_yad))+ # Ubuntu 桌面通常有 python3-tk;即使没有 zenity 也可弹窗+ backends.append(("tkinter", _try_tkinter_subprocess))++ errors: list[str] = []+ for name, fn in backends:+ try:+ return fn(initial_dir)+ except subprocess.TimeoutExpired as exc:+ raise RuntimeError("directory picker timed out") from exc+ except Exception as exc: # noqa: BLE001+ msg = f"{name}: {exc}"+ logger.warning("[directory_picker] linux backend failed: %s", msg)+ errors.append(msg)+ continue++ detail = "; ".join(errors) if errors else "no backend available"+ raise RuntimeError(+ f"directory picker unavailable on Linux: {detail}; "+ "fallback to typing an absolute path in the UI"+ )+++def select_directory_native(*, initial_dir: str | None = None) -> str | None:+ """打开本机系统文件夹对话框,返回选中目录的绝对路径。++ - Windows:tkinter+ - macOS:osascript+ - Linux:zenity / kdialog / yad / tkinter 子进程+ - 其它平台或工具缺失:抛 ``RuntimeError``,前端回落手填绝对路径++ 用户取消时返回 ``None``。+ """+ start_dir = _resolve_initial_dir(initial_dir)++ if sys.platform == "win32":+ return _select_directory_windows_tk(start_dir)+ if sys.platform == "darwin":+ return _select_directory_macos(start_dir)+ if sys.platform.startswith("linux"):+ return _select_directory_linux(start_dir)++ raise RuntimeError(+ f"directory picker unavailable on platform {sys.platform!r}; "+ "fallback to typing an absolute path in the UI"+ )diff --git a/jiuwenswarm/channels/web/file_picker.py b/jiuwenswarm/channels/web/file_picker.pynew file mode 100644index 0000000000..0d658b1db9--- /dev/null+++ b/jiuwenswarm/channels/web/file_picker.py@@ -0,0 +1,642 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""浏览器 / Web 通道使用的本机文件选择器(非 pywebview)。++对齐 ``directory_picker.py``(commit 87cdbaf3):+- Windows:进程内 tkinter 文件对话框(与选目录一致;不可用 ``sys.executable -c``,+ 冻结 exe 下 ``sys.executable`` 不是 Python 解释器)+- macOS:osascript(独立进程)+- Linux:zenity → kdialog → yad → tkinter 子进程+- 均不可用时抛出 ``RuntimeError``++对话框过滤器故意省略黑名单扩展名(与浏览器 accept= / 桌面端白名单一致),+选中后仍通过 ``describe_local_file`` 做二次校验。+"""++from __future__ import annotations++import base64+import logging+import mimetypes+import os+import shutil+import subprocess+import sys+from collections.abc import Callable+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)++_DIALOG_TITLE = "选择文件"+# Persist last successful picker directory under the user workspace so the next+# open starts where the user left off (desktop + path.select_files share this).+_LAST_DIR_FILENAME = "last_file_picker_dir.txt"+IMAGE_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".gif", ".jfif"})+MAX_IMAGE_BYTES = 10 * 1024 * 1024+FORBIDDEN_DOCUMENT_EXTENSIONS = frozenset(+ {+ ".exe",+ ".dll",+ ".msi",+ ".scr",+ ".bat",+ ".cmd",+ ".ps1",+ ".vbs",+ ".wsf",+ ".hta",+ ".jar",+ ".lnk",+ ".bin",+ ".so",+ ".dylib",+ ".app",+ ".dmg",+ ".pkg",+ ".command",+ ".scpt",+ ".scptd",+ ".workflow",+ ".xpc",+ ".bundle",+ ".framework",+ ".kext",+ ".prefpane",+ ".saver",+ ".component",+ }+)+# Keep in sync with InputArea ATTACHMENT_ACCEPT / desktop ATTACHMENT_DIALOG_EXTENSIONS.+# Intentionally omits FORBIDDEN_DOCUMENT_EXTENSIONS (no *.* either).+ATTACHMENT_DIALOG_EXTENSIONS: tuple[str, ...] = (+ ".png",+ ".jpg",+ ".jpeg",+ ".webp",+ ".gif",+ ".bmp",+ ".svg",+ ".ico",+ ".jfif",+ ".pdf",+ ".doc",+ ".docx",+ ".xls",+ ".xlsx",+ ".ppt",+ ".pptx",+ ".txt",+ ".md",+ ".markdown",+ ".csv",+ ".tsv",+ ".rtf",+ ".odt",+ ".ods",+ ".odp",+ ".json",+ ".xml",+ ".yaml",+ ".yml",+ ".html",+ ".htm",+ ".css",+ ".js",+ ".ts",+ ".tsx",+ ".jsx",+ ".py",+ ".java",+ ".c",+ ".cpp",+ ".h",+ ".go",+ ".rs",+ ".rb",+ ".php",+ ".sql",+ ".ipynb",+ ".toml",+ ".ini",+ ".log",+ ".zip",+ ".rar",+ ".7z",+ ".tar",+ ".gz",+ ".mp3",+ ".wav",+ ".flac",+ ".aac",+ ".ogg",+ ".m4a",+ ".wma",+ ".mp4",+ ".avi",+ ".mov",+ ".mkv",+ ".webm",+ ".wmv",+ ".flv",+)+++def _last_dir_state_path() -> Path:+ try:+ from jiuwenswarm.common.utils import get_user_workspace_dir++ base = get_user_workspace_dir()+ except Exception: # noqa: BLE001+ base = Path.home() / ".jiuwenswarm"+ return base / _LAST_DIR_FILENAME+++def get_last_file_picker_dir() -> str | None:+ """Return the last remembered picker directory if it still exists."""+ try:+ raw = _last_dir_state_path().read_text(encoding="utf-8").strip()+ except OSError:+ return None+ if not raw:+ return None+ candidate = Path(raw).expanduser()+ if not candidate.is_dir():+ return None+ try:+ return str(candidate.resolve())+ except Exception: # noqa: BLE001+ return str(candidate)+++def remember_file_picker_dir(path: str | Path | None) -> None:+ """Remember a directory (or the parent of a selected file) for the next open."""+ if path is None:+ return+ try:+ candidate = Path(path).expanduser()+ directory = candidate if candidate.is_dir() else candidate.parent+ if not directory.is_dir():+ return+ try:+ stored = str(directory.resolve())+ except Exception: # noqa: BLE001+ stored = str(directory)+ state_path = _last_dir_state_path()+ state_path.parent.mkdir(parents=True, exist_ok=True)+ state_path.write_text(stored + "\n", encoding="utf-8")+ except Exception as exc: # noqa: BLE001+ logger.debug("[file_picker] failed to remember directory: %s", exc)+++def resolve_file_picker_initial_dir(initial_dir: str | None = None) -> str:+ """Resolve dialog start directory: explicit → last remembered → home."""+ for raw in (initial_dir, get_last_file_picker_dir()):+ if not raw:+ continue+ candidate = Path(raw).expanduser()+ if candidate.is_dir():+ try:+ return str(candidate.resolve())+ except Exception: # noqa: BLE001+ return str(candidate)+ return str(Path.home())+++def _resolve_initial_dir(initial_dir: str | None) -> str:+ return resolve_file_picker_initial_dir(initial_dir)+++def _normalize_selected_path(selected: str | None) -> str | None:+ if not selected:+ return None+ path = Path(str(selected).strip().strip('"')).expanduser()+ if not str(path):+ return None+ try:+ return str(path.resolve())+ except Exception: # noqa: BLE001+ return str(path)+++def _normalize_selected_paths(raw_paths: list[str] | tuple[str, ...] | str | None) -> list[str]:+ if raw_paths is None:+ return []+ if isinstance(raw_paths, str):+ candidates = [raw_paths]+ else:+ candidates = list(raw_paths)+ results: list[str] = []+ for item in candidates:+ normalized = _normalize_selected_path(item)+ if normalized:+ results.append(normalized)+ return results+++def _tk_filetypes() -> list[tuple[str, str]]:+ patterns = " ".join(f"*{ext}" for ext in ATTACHMENT_DIALOG_EXTENSIONS)+ return [("Allowed files", patterns)]+++def _run_capture(command: list[str], *, timeout: float = 600.0) -> subprocess.CompletedProcess[str]:+ return subprocess.run( # noqa: S603+ command,+ check=False,+ capture_output=True,+ text=True,+ timeout=timeout,+ )+++def describe_local_file(raw_path: str | Path) -> dict[str, Any] | None:+ """把本机路径描述成前端 ``LocalFilePick`` 同形字典。"""+ try:+ path = Path(raw_path).expanduser().resolve()+ except Exception: # noqa: BLE001+ path = Path(raw_path).expanduser()++ if not path.is_file():+ logger.warning("[file_picker] selected path is not a file: %s", path)+ return None++ filename = path.name+ ext = path.suffix.lower()+ try:+ size = path.stat().st_size+ except OSError as exc:+ logger.warning("[file_picker] failed to stat selected file %s: %s", path, exc)+ return None++ mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"+ absolute = str(path)+ if ext in IMAGE_EXTENSIONS:+ if size > MAX_IMAGE_BYTES:+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "image",+ "error": "image_too_large",+ }+ try:+ payload = base64.b64encode(path.read_bytes()).decode("ascii")+ except OSError as exc:+ logger.warning("[file_picker] failed to read image %s: %s", path, exc)+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "image",+ "error": "read_failed",+ }+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "image",+ "base64": payload,+ }++ if ext in FORBIDDEN_DOCUMENT_EXTENSIONS:+ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "document",+ "error": "forbidden",+ }++ return {+ "path": absolute,+ "filename": filename,+ "size": size,+ "mime_type": mime_type,+ "kind": "document",+ }+++def describe_local_files(paths: list[str]) -> list[dict[str, Any]]:+ results: list[dict[str, Any]] = []+ for raw in paths:+ item = describe_local_file(raw)+ if item is not None:+ results.append(item)+ return results+++def _select_files_windows_tk(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ try:+ import tkinter as tk+ from tkinter import filedialog+ except Exception as exc: # noqa: BLE001+ raise RuntimeError(f"file picker unavailable: {exc}") from exc++ root = tk.Tk()+ root.withdraw()+ try:+ try:+ root.attributes("-topmost", True)+ except Exception: # noqa: BLE001+ pass+ try:+ root.lift()+ root.focus_force()+ except Exception: # noqa: BLE001+ pass++ kwargs = {+ "parent": root,+ "initialdir": initial_dir,+ "title": _DIALOG_TITLE,+ "filetypes": _tk_filetypes(),+ }+ if allow_multiple:+ selected = filedialog.askopenfilenames(**kwargs)+ else:+ selected = filedialog.askopenfilename(**kwargs)+ finally:+ try:+ root.destroy()+ except Exception: # noqa: BLE001+ pass++ if not selected:+ return None+ paths = _normalize_selected_paths(selected)+ return paths or None+++def _select_files_macos(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ multi = " with multiple selections allowed" if allow_multiple else ""+ # Handle both single alias and list return values from `choose file`.+ body = (+ "set posixList to {}\n"+ "if class of chosen is list then\n"+ "repeat with f in chosen\n"+ "set end of posixList to POSIX path of f\n"+ "end repeat\n"+ "else\n"+ "set end of posixList to POSIX path of chosen\n"+ "end if\n"+ "set AppleScript's text item delimiters to linefeed\n"+ "return posixList as text"+ )+ script_with_default = (+ f'set defaultFolder to POSIX file "{initial_dir}"\n'+ f'set chosen to choose file with prompt "{_DIALOG_TITLE}" '+ f"default location defaultFolder{multi}\n"+ f"{body}"+ )+ script_plain = (+ f'set chosen to choose file with prompt "{_DIALOG_TITLE}"{multi}\n'+ f"{body}"+ )++ for script in (script_with_default, script_plain):+ try:+ completed = _run_capture(["osascript", "-e", script])+ except FileNotFoundError as exc:+ raise RuntimeError("file picker unavailable: osascript not found") from exc+ except subprocess.TimeoutExpired as exc:+ raise RuntimeError("file picker timed out") from exc++ if completed.returncode == 0:+ lines = [line for line in (completed.stdout or "").splitlines() if line.strip()]+ paths = _normalize_selected_paths(lines)+ return paths or None+ stderr = (completed.stderr or "").strip()+ if "User canceled" in stderr or "-128" in stderr:+ return None+ if script is script_with_default:+ continue+ raise RuntimeError(f"file picker unavailable: {stderr or 'osascript failed'}")+ return None+++def _zenity_file_filter() -> str:+ patterns = " ".join(f"*{ext}" for ext in ATTACHMENT_DIALOG_EXTENSIONS)+ return f"Allowed files | {patterns}"+++def _try_zenity_files(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ command = [+ "zenity",+ "--file-selection",+ f"--title={_DIALOG_TITLE}",+ f"--filename={initial_dir.rstrip(os.sep) + os.sep}",+ f"--file-filter={_zenity_file_filter()}",+ ]+ if allow_multiple:+ command.append("--multiple")+ command.append("--separator=\n")+ completed = _run_capture(command)+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "zenity failed")+ lines = [line for line in (completed.stdout or "").splitlines() if line.strip()]+ paths = _normalize_selected_paths(lines)+ return paths or None+++def _try_kdialog_files(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ command = ["kdialog", "--getopenfilename", initial_dir, "--title", _DIALOG_TITLE]+ if allow_multiple:+ command.append("--multiple")+ # Filter string: '*.txt *.md|Allowed files'+ patterns = " ".join(f"*{ext}" for ext in ATTACHMENT_DIALOG_EXTENSIONS)+ command.append(f"{patterns}|Allowed files")+ completed = _run_capture(command)+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "kdialog failed")+ # kdialog --multiple separates with spaces that may break paths; prefer newline if present.+ raw = (completed.stdout or "").strip()+ if "\n" in raw:+ candidates = raw.splitlines()+ else:+ candidates = [raw] if raw else []+ paths = _normalize_selected_paths(candidates)+ return paths or None+++def _try_yad_files(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ command = [+ "yad",+ "--file",+ f"--title={_DIALOG_TITLE}",+ f"--filename={initial_dir.rstrip(os.sep) + os.sep}",+ f"--file-filter={_zenity_file_filter()}",+ ]+ if allow_multiple:+ command.append("--multiple")+ completed = _run_capture(command)+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "yad failed")+ lines = [line for line in (completed.stdout or "").splitlines() if line.strip()]+ # yad may separate with |+ if len(lines) == 1 and "|" in lines[0]:+ lines = [part for part in lines[0].split("|") if part.strip()]+ paths = _normalize_selected_paths(lines)+ return paths or None+++def _try_tkinter_subprocess_files(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ # Frozen builds (PyInstaller etc.): sys.executable is the app binary, not CPython.+ if getattr(sys, "frozen", False):+ if sys.platform == "win32":+ return _select_files_windows_tk(+ initial_dir=initial_dir,+ allow_multiple=allow_multiple,+ )+ raise RuntimeError(+ "file picker subprocess unavailable in frozen build "+ f"(sys.executable={sys.executable!r})"+ )++ env = os.environ.copy()+ env["JIUWEN_FILE_PICKER_INITIAL"] = initial_dir+ env["JIUWEN_FILE_PICKER_TITLE"] = _DIALOG_TITLE+ env["JIUWEN_FILE_PICKER_MULTIPLE"] = "1" if allow_multiple else "0"+ env["JIUWEN_FILE_PICKER_PATTERNS"] = " ".join(f"*{ext}" for ext in ATTACHMENT_DIALOG_EXTENSIONS)+ script = r"""+import os, sys+try:+ import tkinter as tk+ from tkinter import filedialog+except Exception as exc:+ sys.stderr.write(f"tkinter unavailable: {exc}\n")+ sys.exit(2)++initial = os.environ.get("JIUWEN_FILE_PICKER_INITIAL") or str(os.path.expanduser("~"))+title = os.environ.get("JIUWEN_FILE_PICKER_TITLE") or "Select File"+multiple = os.environ.get("JIUWEN_FILE_PICKER_MULTIPLE") == "1"+patterns = os.environ.get("JIUWEN_FILE_PICKER_PATTERNS") or "*.*"+filetypes = [("Allowed files", patterns)]+root = tk.Tk()+root.withdraw()+try:+ try:+ root.attributes("-topmost", True)+ except Exception:+ pass+ try:+ root.lift()+ root.focus_force()+ except Exception:+ pass+ kwargs = dict(parent=root, initialdir=initial, title=title, filetypes=filetypes)+ selected = filedialog.askopenfilenames(**kwargs) if multiple else filedialog.askopenfilename(**kwargs)+finally:+ try:+ root.destroy()+ except Exception:+ pass++if not selected:+ sys.exit(1)+if isinstance(selected, str):+ sys.stdout.write(selected)+else:+ sys.stdout.write("\n".join(selected))+sys.exit(0)+"""+ completed = subprocess.run( # noqa: S603+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ text=True,+ timeout=600.0,+ env=env,+ )+ if completed.returncode == 1:+ return None+ if completed.returncode != 0:+ stderr = (completed.stderr or "").strip()+ raise RuntimeError(stderr or "tkinter subprocess failed")+ lines = [line for line in (completed.stdout or "").splitlines() if line.strip()]+ paths = _normalize_selected_paths(lines)+ return paths or None+++def _select_files_linux(*, initial_dir: str, allow_multiple: bool) -> list[str] | None:+ backends: list[tuple[str, Callable[..., list[str] | None]]] = []+ if shutil.which("zenity"):+ backends.append(("zenity", _try_zenity_files))+ if shutil.which("kdialog"):+ backends.append(("kdialog", _try_kdialog_files))+ if shutil.which("yad"):+ backends.append(("yad", _try_yad_files))+ backends.append(("tkinter", _try_tkinter_subprocess_files))++ errors: list[str] = []+ for name, fn in backends:+ try:+ return fn(initial_dir=initial_dir, allow_multiple=allow_multiple)+ except subprocess.TimeoutExpired as exc:+ raise RuntimeError("file picker timed out") from exc+ except Exception as exc: # noqa: BLE001+ msg = f"{name}: {exc}"+ logger.warning("[file_picker] linux backend failed: %s", msg)+ errors.append(msg)+ continue++ detail = "; ".join(errors) if errors else "no backend available"+ raise RuntimeError(+ f"file picker unavailable on Linux: {detail}; "+ "fallback to HTML file input"+ )+++def select_files_native(+ *,+ allow_multiple: bool = True,+ initial_dir: str | None = None,+) -> list[str] | None:+ """打开本机系统文件对话框,返回选中文件的绝对路径列表。++ 用户取消时返回 ``None``。+ """+ start_dir = _resolve_initial_dir(initial_dir)++ if sys.platform == "win32":+ # 与 directory_picker 一致:Windows 上在 asyncio.to_thread 里用进程内 Tk。+ # 旧实现用 subprocess([sys.executable, "-c", ...]),在 jiuwenswarm.exe+ # 冻结包下会失败(executable 不是 Python),表现为浏览器「添加文件」无弹窗。+ return _select_files_windows_tk(+ initial_dir=start_dir,+ allow_multiple=allow_multiple,+ )+ if sys.platform == "darwin":+ return _select_files_macos(initial_dir=start_dir, allow_multiple=allow_multiple)+ if sys.platform.startswith("linux"):+ return _select_files_linux(initial_dir=start_dir, allow_multiple=allow_multiple)++ raise RuntimeError(+ f"file picker unavailable on platform {sys.platform!r}; "+ "fallback to HTML file input"+ )+++def select_and_describe_files(+ *,+ allow_multiple: bool = True,+ initial_dir: str | None = None,+) -> list[dict[str, Any]] | None:+ """弹窗选文件并返回前端可用的元数据列表;取消返回 ``None``。"""+ selected = select_files_native(allow_multiple=allow_multiple, initial_dir=initial_dir)+ if selected is None:+ return None+ if selected:+ remember_file_picker_dir(selected[0])+ return describe_local_files(selected)diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex a5ddc80c43..28c802ebd9 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -64,6 +64,7 @@ import {registerCreatedConversation,resetNewConversationRuntime,} from './multi-session/state/newConversationLifecycle';+import { toDisplaySessionTitle } from './utils/documentMessage';import { createConversationSession } from './multi-session/state/createConversationSession';import { useTranslation } from 'react-i18next';import {@@ -442,7 +443,8 @@ function AppContent() {const session = currentSession?.session_id === sessionId? currentSession: sessions.find((s) => s.session_id === sessionId);- return session?.title?.trim() ?? '';+ const raw = session?.title?.trim() ?? '';+ return toDisplaySessionTitle(raw);}, [currentSession, sessions, sessionId]);const sessionProjectName = useMemo(() => {const session = currentSession?.session_id === sessionIddiff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.cssindex 8cb8fc9c59..c16b45fdb3 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css@@ -3,6 +3,14 @@--chat-input-textarea-min-height: 96px;}+/* ===========================+ ChatPanel - Desktop file drop+ =========================== */++.chat-panel-shell {+ position: relative;+}+/* ===========================ChatPanel - Input Area=========================== */@@ -2568,12 +2576,12 @@ overflow: hidden;.chat-msg-file-card {display: grid;- grid-template-columns: 28px minmax(0, 1fr);+ grid-template-columns: 28px minmax(0, max-content);align-items: center;gap: 8px;box-sizing: border-box;- width: 168px;- max-width: 46%;+ width: max-content;+ max-width: min(100%, 480px);min-height: 48px;padding: 8px 10px;border: 1px solid rgba(var(--color-border-default-rgb), 0.9);@@ -2609,9 +2617,11 @@ overflow: hidden;}.chat-msg-file-card__name {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;+ overflow: visible;+ text-overflow: clip;+ white-space: normal;+ word-break: break-word;+ overflow-wrap: anywhere;color: var(--color-text-primary);font-size: 13px;font-weight: 600;@@ -2693,9 +2703,11 @@ overflow: hidden;}.chat-msg-file-more__name {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;+ overflow: visible;+ text-overflow: clip;+ white-space: normal;+ word-break: break-word;+ overflow-wrap: anywhere;font-size: 13px;line-height: 18px;}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsxindex 6e94e9b579..d77e6d50c3 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsx@@ -4,11 +4,19 @@ export type FileTypeIconKey =| 'pdf'| 'docx'| 'sheet'+ | 'ppt'| 'html'+ | 'css'| 'json'| 'ipynb'| 'md'| 'text'+ | 'python'+ | 'code'+ | 'config'+ | 'archive'+ | 'audio'+ | 'video'| 'image'| 'file'| 'unknown';@@ -19,9 +27,17 @@ const ICON_COLORS: Record<FileTypeIconKey, { base: string; light: string; fold:md: { base: '#0D9488', light: '#2DD4BF', fold: '#0F766E' },text: { base: '#64748B', light: '#94A3B8', fold: '#475569' },sheet: { base: '#1FA971', light: '#3FBF88', fold: '#178A5B' },- html: { base: '#F08A24', light: '#F5A24D', fold: '#D47312' },- json: { base: '#6B7C93', light: '#8796A8', fold: '#556578' },- ipynb: { base: '#7B61FF', light: '#9580FF', fold: '#6349E0' },+ ppt: { base: '#D97706', light: '#F59E0B', fold: '#B45309' },+ html: { base: '#E44D26', light: '#F16529', fold: '#C13B1A' },+ css: { base: '#264DE4', light: '#2965F1', fold: '#1C3DB0' },+ json: { base: '#CA8A04', light: '#EAB308', fold: '#A16207' },+ ipynb: { base: '#F37726', light: '#F59A56', fold: '#D45F12' },+ python: { base: '#3776AB', light: '#4B8BBE', fold: '#2A5A8A' },+ code: { base: '#7C3AED', light: '#8B5CF6', fold: '#6D28D9' },+ config: { base: '#0E7490', light: '#06B6D4', fold: '#155E75' },+ archive: { base: '#92400E', light: '#B45309', fold: '#78350F' },+ audio: { base: '#DB2777', light: '#EC4899', fold: '#BE185D' },+ video: { base: '#4F46E5', light: '#6366F1', fold: '#3730A3' },image: { base: '#E45CA8', light: '#F07BC0', fold: '#C9448F' },file: { base: '#3B82F6', light: '#60A5FA', fold: '#2563EB' },unknown: { base: '#9AA3AF', light: '#B0B8C2', fold: '#7F8894' },@@ -85,7 +101,6 @@ function GlyphLines() {);}-/** Markdown: hash headings style */function GlyphMd() {return (<>@@ -107,7 +122,6 @@ function GlyphMd() {);}-/** Plain text: letter T */function GlyphTxt() {return (<path@@ -133,12 +147,45 @@ function GlyphSheet() {);}-function GlyphPie() {+/** Presentation: slide + triangle play mark */+function GlyphPpt() {return (<>- <circle cx="24" cy="26" r="7.5" fill="white" fillOpacity="0.35" />- <path d="M24 18.5V26H31.5A7.5 7.5 0 0 0 24 18.5Z" fill="white" />- <path d="M24 26V33.5A7.5 7.5 0 0 0 30.8 29.2L24 26Z" fill="white" fillOpacity="0.85" />+ <rect x="14.5" y="19.5" width="19" height="13" rx="2" fill="white" fillOpacity="0.95" />+ <path d="M21.5 23L28 26L21.5 29V23Z" fill="#D97706" />+ </>+ );+}++/** HTML: angle brackets */+function GlyphHtml() {+ return (+ <path+ d="M20 21.5L15.5 26L20 30.5M28 21.5L32.5 26L28 30.5"+ stroke="white"+ strokeWidth="2.4"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ );+}++/** CSS: hash / braces */+function GlyphCss() {+ return (+ <>+ <path+ d="M19 21V32M24 21V32M17.5 24.5H25.5M17.5 28.5H25.5"+ stroke="white"+ strokeWidth="2.2"+ strokeLinecap="round"+ />+ <path+ d="M29 22.5C30.5 22.5 31.5 23.4 31.5 24.8C31.5 26.8 29.2 27.2 29.2 28.8V30.5"+ stroke="white"+ strokeWidth="2.1"+ strokeLinecap="round"+ /></>);}@@ -155,6 +202,69 @@ function GlyphCode() {);}+/** Python: stylized "Py" */+function GlyphPython() {+ return (+ <text+ x="24"+ y="30.5"+ textAnchor="middle"+ fill="white"+ fontSize="13"+ fontWeight="700"+ fontFamily="Arial, Helvetica, sans-serif"+ >+ Py+ </text>+ );+}++function GlyphConfig() {+ return (+ <>+ <circle cx="24" cy="26" r="6.5" stroke="white" strokeWidth="2.2" fill="none" />+ <path+ d="M24 17.5V19.2M24 32.8V34.5M15.5 26H17.2M30.8 26H32.5M18.2 20.2L19.4 21.4M28.6 30.6L29.8 31.8M29.8 20.2L28.6 21.4M19.4 30.6L18.2 31.8"+ stroke="white"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </>+ );+}++function GlyphArchive() {+ return (+ <>+ <rect x="16" y="18.5" width="16" height="15" rx="1.5" fill="white" fillOpacity="0.95" />+ <rect x="21.5" y="18.5" width="5" height="15" fill="#92400E" fillOpacity="0.85" />+ <rect x="22.2" y="24" width="3.6" height="3.2" rx="0.6" fill="white" />+ </>+ );+}++function GlyphAudio() {+ return (+ <>+ <path+ d="M20 22V30M24 20V32M28 23.5V28.5"+ stroke="white"+ strokeWidth="2.6"+ strokeLinecap="round"+ />+ </>+ );+}++function GlyphVideo() {+ return (+ <>+ <rect x="14.5" y="19.5" width="14" height="13" rx="2" fill="white" fillOpacity="0.95" />+ <path d="M29.5 23L35 26.5L29.5 30V23Z" fill="white" />+ </>+ );+}+function GlyphImage() {return (<>@@ -193,11 +303,28 @@ function glyphFor(typeKey: FileTypeIconKey): ReactNode {return <GlyphTxt />;case 'sheet':return <GlyphSheet />;+ case 'ppt':+ return <GlyphPpt />;case 'html':- return <GlyphPie />;+ return <GlyphHtml />;+ case 'css':+ return <GlyphCss />;case 'json':+ return <GlyphCode />;case 'ipynb':return <GlyphCode />;+ case 'python':+ return <GlyphPython />;+ case 'code':+ return <GlyphCode />;+ case 'config':+ return <GlyphConfig />;+ case 'archive':+ return <GlyphArchive />;+ case 'audio':+ return <GlyphAudio />;+ case 'video':+ return <GlyphVideo />;case 'image':return <GlyphImage />;case 'unknown':@@ -209,19 +336,103 @@ function glyphFor(typeKey: FileTypeIconKey): ReactNode {}}+const CODE_EXTENSIONS = new Set([+ '.js',+ '.jsx',+ '.ts',+ '.tsx',+ '.java',+ '.c',+ '.cpp',+ '.h',+ '.hpp',+ '.go',+ '.rs',+ '.rb',+ '.php',+ '.sql',+ '.sh',+ '.bash',+ '.ps1',+]);++const CONFIG_EXTENSIONS = new Set([+ '.xml',+ '.yaml',+ '.yml',+ '.toml',+ '.ini',+ '.cfg',+ '.conf',+ '.env',+]);++const ARCHIVE_EXTENSIONS = new Set([+ '.zip',+ '.rar',+ '.7z',+ '.tar',+ '.gz',+ '.tgz',+ '.bz2',+]);++const AUDIO_EXTENSIONS = new Set([+ '.mp3',+ '.wav',+ '.flac',+ '.aac',+ '.ogg',+ '.m4a',+ '.wma',+]);++const VIDEO_EXTENSIONS = new Set([+ '.mp4',+ '.avi',+ '.mov',+ '.mkv',+ '.webm',+ '.wmv',+ '.flv',+]);++const IMAGE_EXTENSIONS = new Set([+ '.png',+ '.jpg',+ '.jpeg',+ '.gif',+ '.webp',+ '.bmp',+ '.svg',+ '.ico',+ '.jfif',+]);+export function getFileTypeIconKeyFromFilename(filename: string, kind?: string): FileTypeIconKey {if (kind === 'image') return 'image';const idx = filename.lastIndexOf('.');const ext = idx >= 0 ? filename.slice(idx).toLowerCase() : '';+if (ext === '.pdf') return 'pdf';- if (ext === '.docx' || ext === '.doc') return 'docx';- if (ext === '.xlsx' || ext === '.xls' || ext === '.csv' || ext === '.tsv') return 'sheet';- if (ext === '.html' || ext === '.htm' || ext === '.css') return 'html';+ if (ext === '.docx' || ext === '.doc' || ext === '.rtf' || ext === '.odt') return 'docx';+ if (ext === '.xlsx' || ext === '.xls' || ext === '.csv' || ext === '.tsv' || ext === '.ods') {+ return 'sheet';+ }+ if (ext === '.ppt' || ext === '.pptx' || ext === '.odp') return 'ppt';+ if (ext === '.html' || ext === '.htm') return 'html';+ if (ext === '.css') return 'css';if (ext === '.json') return 'json';if (ext === '.ipynb') return 'ipynb';if (ext === '.md' || ext === '.markdown') return 'md';- if (ext === '.txt') return 'text';- if (['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg'].includes(ext)) return 'image';+ if (ext === '.txt' || ext === '.log') return 'text';+ if (ext === '.py') return 'python';+ if (CODE_EXTENSIONS.has(ext)) return 'code';+ if (CONFIG_EXTENSIONS.has(ext)) return 'config';+ if (ARCHIVE_EXTENSIONS.has(ext)) return 'archive';+ if (AUDIO_EXTENSIONS.has(ext)) return 'audio';+ if (VIDEO_EXTENSIONS.has(ext)) return 'video';+ if (IMAGE_EXTENSIONS.has(ext)) return 'image';if (!ext) return 'file';return 'unknown';}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsxindex 655115f8b3..8cfcdd3c29 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx@@ -1,4 +1,16 @@-import { useState, useRef, useCallback, KeyboardEvent, useEffect, ClipboardEvent, DragEvent, ChangeEvent, useMemo } from 'react';+import {+ useState,+ useRef,+ useCallback,+ KeyboardEvent,+ useEffect,+ ClipboardEvent,+ DragEvent,+ ChangeEvent,+ useMemo,+ forwardRef,+ useImperativeHandle,+} from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { AtSign, CircleX, FileText, Loader2, Plus, Square, Target, X } from 'lucide-react';@@ -18,11 +30,20 @@ import { ModelProviderIcon } from '../ModelProviderIcon';import { getEvolutionPillLabel } from './evolution-status';import { webRequest } from '../../services/webClient';import { getSkillAvatar } from '../../utils/skillAvatar';+import { withUploadDocumentBlock } from '../../utils/documentMessage';import {isLikelyAbsolutePath,isProjectDirectoryPickerSupported,selectProjectDirectory,} from '../../features/workspace/projectDirectoryPicker';+import {+ getClipboardFilePicks,+ isDesktopLocalFilePicker,+ isDesktopShell,+ selectLocalFiles,+ type LocalFilePick,+} from '../../features/workspace/localFilePicker';+import { useDesktopLocalFilePickerReady } from '../../hooks';import { getInputProjectOptions, isDefaultInputProject } from './projectSelection';import sendIcon from '../../assets/send.svg';import sendActiveIcon from '../../assets/send_active.svg';@@ -30,6 +51,7 @@ import { TeamMemberAvatar } from '../TeamMemberAvatar';import { CodeBranchSelector } from '../../features/code-mode/CodeBranchSelector';import { generateUuidV4 } from '../../utils/uuid';+/** 输入栏下拉所需的最小技能数据结构(与 SkillPanel 中的 SkillItem 保持一致) */type InputAreaSkillItem = {name: string;@@ -125,46 +147,120 @@ interface InputAreaProps {onDrainTaskQueueIfIdle?: (sessionId: string) => void;}+export type InputAreaHandle = {+ appendLocalFilePicks: (picks: LocalFilePick[]) => void;+};++function clipboardHasFileItems(clipboardData: DataTransfer | null | undefined): boolean {+ if (!clipboardData) return false;+ if (Array.from(clipboardData.items || []).some((item) => item.kind === 'file')) return true;+ return Array.from(clipboardData.types || []).includes('Files');+}+const ACCEPTED_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);-const ACCEPTED_DOCUMENT_EXTENSIONS = new Set([+/**+ * Keep in sync with jiuwenswarm/gateway/document_attachments.py+ * FORBIDDEN_DOCUMENT_EXTENSIONS.+ */+const FORBIDDEN_DOCUMENT_EXTENSIONS = new Set([+ '.exe',+ '.dll',+ '.msi',+ '.scr',+ '.bat',+ '.cmd',+ '.ps1',+ '.vbs',+ '.wsf',+ '.hta',+ '.jar',+ '.lnk',+ '.bin',+ '.so',+ '.dylib',+ '.app',+ '.dmg',+ '.pkg',+ '.command',+ '.scpt',+ '.scptd',+ '.workflow',+ '.xpc',+ '.bundle',+ '.framework',+ '.kext',+ '.prefpane',+ '.saver',+ '.component',+]);+/**+ * Dialog filter only (not a security boundary). Intentionally omits blacklist+ * extensions. Do NOT append star-slash-star (all MIME); Windows then collapses+ * to image-only. Final allow/deny still uses FORBIDDEN_DOCUMENT_EXTENSIONS in JS.+ */+const ATTACHMENT_ACCEPT = [+ 'image/*',+ '.png',+ '.jpg',+ '.jpeg',+ '.webp',+ '.gif',+ '.bmp',+ '.svg',+ '.ico','.pdf',+ '.doc','.docx',+ '.xls','.xlsx',- '.csv',- '.tsv',+ '.ppt',+ '.pptx','.txt','.md','.markdown',+ '.csv',+ '.tsv',+ '.rtf',+ '.odt',+ '.ods',+ '.odp',+ '.json',+ '.xml',+ '.yaml',+ '.yml','.html','.htm',- '.json',+ '.css',+ '.js',+ '.ts',+ '.tsx',+ '.jsx',+ '.py',+ '.java',+ '.c',+ '.cpp',+ '.h',+ '.go',+ '.rs',+ '.rb',+ '.php',+ '.sql','.ipynb',-]);-const ACCEPTED_DOCUMENT_MIME_TYPES = new Set([- 'application/pdf',- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',- 'text/csv',- 'application/csv',- 'text/tab-separated-values',- 'text/plain',- 'text/markdown',- 'text/x-markdown',- 'text/html',- 'application/xhtml+xml',- 'application/json',- 'application/x-ipynb+json',- 'application/jupyter',- 'application/vnd.jupyter',-]);-const DOCUMENT_ACCEPT =- '.pdf,.docx,.xlsx,.csv,.tsv,.txt,.md,.markdown,.html,.htm,.json,.ipynb,application/pdf,text/plain,text/markdown,text/html,application/json';-const IMAGE_ACCEPT = 'image/png,image/jpeg,image/webp,image/gif,.png,.jpg,.jpeg,.webp,.gif';-const ATTACHMENT_ACCEPT = `${IMAGE_ACCEPT},${DOCUMENT_ACCEPT}`;+ '.toml',+ '.ini',+ '.log',+ '.zip',+ '.rar',+ '.7z',+ '.tar',+ '.gz',+ 'audio/*',+ 'video/*',+]+ .filter((item) => !FORBIDDEN_DOCUMENT_EXTENSIONS.has(item.toLowerCase()))+ .join(',');const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);const MAX_IMAGE_BYTES = 10 * 1024 * 1024;-const MAX_DOCUMENT_BYTES = 30 * 1024 * 1024;-const MAX_ATTACHMENT_COUNT = 20;const ATTACHMENT_ALERT_DURATION_MS = 3000;type AttachmentKind = 'image' | 'document';@@ -182,6 +278,8 @@ interface AttachmentDraft {persistedMediaItem?: Record<string, unknown>;error?: string;file?: File;+ /** Absolute local path from desktop native picker (WebView2 has no File.path). */+ localPath?: string;}interface AttachmentAlert {@@ -270,18 +368,34 @@ function isImageFile(file: File): boolean {return IMAGE_EXTENSIONS.has(getFileExtension(file.name || ''));}-function isDocumentFile(file: File): boolean {+function isForbiddenDocumentFile(file: File): boolean {const ext = getFileExtension(file.name || '');- const mimeOk = Boolean(file.type) && ACCEPTED_DOCUMENT_MIME_TYPES.has(file.type);- const extOk = ACCEPTED_DOCUMENT_EXTENSIONS.has(ext);- return mimeOk || extOk;+ return Boolean(ext) && FORBIDDEN_DOCUMENT_EXTENSIONS.has(ext);+}++function isDocumentFile(file: File): boolean {+ if (isImageFile(file)) return false;+ return !isForbiddenDocumentFile(file);+}++/** Local absolute path when available (desktop native picker / Electron File.path). */+function getLocalFilePath(file: File | undefined, explicitPath?: string): string | undefined {+ if (typeof explicitPath === 'string' && explicitPath.trim()) {+ return explicitPath.trim();+ }+ if (!file) return undefined;+ const maybePath = (file as File & { path?: string }).path;+ if (typeof maybePath === 'string' && maybePath.trim()) {+ return maybePath.trim();+ }+ return undefined;}/** Classify a picked file for routing to media.persist vs document.persist. */function resolveAttachmentKind(file: File): AttachmentKind | null {if (isImageFile(file)) return 'image';- if (isDocumentFile(file)) return 'document';- return null;+ if (isForbiddenDocumentFile(file)) return null;+ return 'document';}function getImageValidationError(file: File): string | null {@@ -299,12 +413,19 @@ function clearAttachmentAlertTimers(timers: Map<string, number>): void {timers.clear();}-function getDocumentValidationError(file: File): string | null {- if (!isDocumentFile(file)) {- return `文件类型不支持:${file.name || '未命名文件'}`;+function getDocumentValidationError(+ file: File | undefined,+ options?: { filename?: string; localPath?: string },+): string | null {+ const filename = options?.filename || file?.name || '未命名文件';+ if (file && isForbiddenDocumentFile(file)) {+ return `禁止上传该文件类型:${filename}`;}- if (file.size > MAX_DOCUMENT_BYTES) {- return `文件大小超出限制:${file.name || '未命名文件'}(最大${formatAttachmentSize(MAX_DOCUMENT_BYTES)})`;+ if (file && !isDocumentFile(file)) {+ return `文件类型不支持:${filename}`;+ }+ if (!getLocalFilePath(file, options?.localPath)) {+ return `无法获取本地文件路径:${filename}(请使用桌面端选择文件)`;}return null;}@@ -341,30 +462,38 @@ function buildSubmitContent(text: string, attachments: AttachmentDraft[]): strinif (!docs.length) {return text;}- // Agent-facing hint only (stripped from chat bubble). List every file; no 说明 line.- const lines = docs.map((doc) => {- const path = pickString(doc.persistedMediaItem?.path) || '';- return path ? `- ${doc.filename}: ${path}` : `- ${doc.filename}`;- });- return [text, '【上传文档】', ...lines].filter(Boolean).join('\n');+ // Agent-facing @path refs only (stripped from chat bubble). No parse / no sidecar.+ // Paths may be missing on a brand-new session before persist; useWebSocket+ // rewrites this block after document.persist returns real paths.+ return withUploadDocumentBlock(+ text,+ docs.map((doc) => ({+ filename: doc.filename,+ path: pickString(doc.persistedMediaItem?.path),+ originalPath: pickString(doc.persistedMediaItem?.original_path, doc.persistedMediaItem?.path),+ })),+ );}-export function InputArea({- onSubmit,- onPersistMedia,- onPersistDocuments,- onInterrupt,- onCancel,- onSwitchMode,- isProcessing,- autoFocusKey = null,- onNavigateToSkills,- permissionsEnabled,- onSavePermission,- onSetGoal,- onClearGoal,- onDrainTaskQueueIfIdle,-}: InputAreaProps) {+export const InputArea = forwardRef<InputAreaHandle, InputAreaProps>(function InputArea(+ {+ onSubmit,+ onPersistMedia,+ onPersistDocuments,+ onInterrupt,+ onCancel,+ onSwitchMode,+ isProcessing,+ autoFocusKey = null,+ onNavigateToSkills,+ permissionsEnabled,+ onSavePermission,+ onSetGoal,+ onClearGoal,+ onDrainTaskQueueIfIdle,+ },+ ref,+) {const [pendingVoiceText, setPendingVoiceText] = useState('');const [isModeMenuOpen, setIsModeMenuOpen] = useState(false);const [attachments, setAttachments] = useState<AttachmentDraft[]>([]);@@ -556,6 +685,7 @@ export function InputArea({});const imageInputDisabled = isListening || (isInterruptible && !isTeamMode);+ const isDesktopBridgeReady = useDesktopLocalFilePickerReady();// "+" 触发按钮本身不跟图片/目标的可用性挂钩:菜单以后可能挂其他跟图片/目标无关的功能,// 触发按钮只要不在录音就该能点开;具体某一项能不能选,交给菜单里每一项各自的禁用态处理。const attachTriggerDisabled = isListening;@@ -688,22 +818,127 @@ export function InputArea({}, [attachmentMenuId, removeAttachment]);const uploadAttachment = useCallback((attachment: AttachmentDraft) => {- if (!attachment.file) return;const validationError =attachment.kind === 'document'- ? getDocumentValidationError(attachment.file)- : getImageValidationError(attachment.file);+ ? getDocumentValidationError(attachment.file, {+ filename: attachment.filename,+ localPath: attachment.localPath,+ })+ : attachment.file+ ? getImageValidationError(attachment.file)+ : (attachment.base64Data ? null : `文件类型不支持:${attachment.filename || '未命名文件'}`);if (validationError) {pushAttachmentAlert(validationError);updateAttachment(attachment.id, { status: 'error', error: validationError });return;}updateAttachment(attachment.id, { status: 'uploading', error: undefined });- const reader =- attachment.kind === 'document'- ? readBinaryFileAsBase64(attachment.file)- : readImageFile(attachment.file);- void reader.then(async (payload) => {++ // Documents: validate local path only — no base64 transfer / no disk persist / no parse.+ if (attachment.kind === 'document') {+ const localPath = getLocalFilePath(attachment.file, attachment.localPath);+ if (!localPath) {+ const error = `无法获取本地文件路径:${attachment.filename || '未命名文件'}`;+ pushAttachmentAlert(error);+ updateAttachment(attachment.id, { status: 'error', error });+ return;+ }+ void (async () => {+ if (!canPersistAttachments) {+ updateAttachment(attachment.id, {+ persistedMediaItem: {+ type: 'document',+ filename: attachment.filename,+ mime_type: attachment.mimeType,+ path: localPath,+ original_path: localPath,+ size_bytes: attachment.size,+ },+ status: 'ready',+ error: undefined,+ });+ return;+ }+ try {+ const persisted = await onPersistDocuments('', [+ {+ type: 'document',+ mimeType: attachment.mimeType,+ filename: attachment.filename,+ path: localPath,+ sizeBytes: attachment.size,+ size_bytes: attachment.size,+ },+ ]);+ const persistedMediaItem = persisted.media_items?.[0];+ if (!persistedMediaItem || !pickString(persistedMediaItem.path)) {+ throw new Error('document.persist did not return document path');+ }+ updateAttachment(attachment.id, {+ base64Data: undefined,+ persistedMediaItem,+ status: 'ready',+ error: undefined,+ });+ } catch (error) {+ console.error('文档上传失败:', error);+ updateAttachment(attachment.id, {+ status: 'error',+ error: '上传失败,请重试',+ });+ }+ })();+ return;+ }++ // Desktop native picker may already include base64 for images.+ if (attachment.base64Data) {+ void (async () => {+ const payload = {+ base64Data: attachment.base64Data,+ previewUrl: attachment.previewUrl,+ };+ if (!canPersistAttachments) {+ updateAttachment(attachment.id, {+ ...payload,+ status: 'ready',+ error: undefined,+ });+ return;+ }+ try {+ const persisted = await onPersistMedia('', [buildUploadMediaItem(attachment, payload)]);+ const persistedMediaItem = persisted.media_items?.[0];+ if (!persistedMediaItem || !pickString(persistedMediaItem.path)) {+ throw new Error('media.persist did not return image path');+ }+ updateAttachment(attachment.id, {+ ...payload,+ base64Data: undefined,+ persistedMediaItem,+ status: 'ready',+ error: undefined,+ });+ } catch (error) {+ console.error('图片上传失败:', error);+ updateAttachment(attachment.id, {+ ...payload,+ status: 'error',+ error: '上传失败,请重试',+ });+ }+ })();+ return;+ }++ if (!attachment.file) {+ const error = '上传失败,请重试';+ pushAttachmentAlert(error);+ updateAttachment(attachment.id, { status: 'error', error });+ return;+ }++ void readImageFile(attachment.file).then(async (payload) => {if (!payload) {updateAttachment(attachment.id, {status: 'error',@@ -720,15 +955,10 @@ export function InputArea({return;}try {- const persistFn = attachment.kind === 'document' ? onPersistDocuments : onPersistMedia;- const persisted = await persistFn('', [buildUploadMediaItem(attachment, payload)]);+ const persisted = await onPersistMedia('', [buildUploadMediaItem(attachment, payload)]);const persistedMediaItem = persisted.media_items?.[0];if (!persistedMediaItem || !pickString(persistedMediaItem.path)) {- throw new Error(- attachment.kind === 'document'- ? 'document.persist did not return document path'- : 'media.persist did not return image path',- );+ throw new Error('media.persist did not return image path');}updateAttachment(attachment.id, {...payload,@@ -738,7 +968,7 @@ export function InputArea({error: undefined,});} catch (error) {- console.error(attachment.kind === 'document' ? '文档上传失败:' : '图片上传失败:', error);+ console.error('图片上传失败:', error);updateAttachment(attachment.id, {...payload,status: 'error',@@ -755,24 +985,17 @@ export function InputArea({const appendAttachmentFiles = useCallback((files: FileList | File[]) => {const selectedFiles = Array.from(files);if (!selectedFiles.length) return;- const remainingSlots = Math.max(0, MAX_ATTACHMENT_COUNT - attachments.length);- if (!remainingSlots) {- pushAttachmentAlert(`单次对话最多上传${MAX_ATTACHMENT_COUNT}个附件。`);- return;- }- const acceptedFiles = selectedFiles.slice(0, remainingSlots);- const overflow = selectedFiles.length - acceptedFiles.length;- if (overflow > 0) {- pushAttachmentAlert(`单次对话最多上传${MAX_ATTACHMENT_COUNT}个附件。`);- }-- const drafts = acceptedFiles.reduce<AttachmentDraft[]>((items, file) => {+ const drafts = selectedFiles.reduce<AttachmentDraft[]>((items, file) => {const kind = resolveAttachmentKind(file);if (!kind) {- pushAttachmentAlert(`文件类型不支持:${file.name || '未命名文件'}`);+ const message = isForbiddenDocumentFile(file)+ ? `禁止上传该文件类型:${file.name || '未命名文件'}`+ : `文件类型不支持:${file.name || '未命名文件'}`;+ pushAttachmentAlert(message);return items;}+ const localPath = getLocalFilePath(file);const base = {id: makeAttachmentId(file),kind,@@ -780,9 +1003,12 @@ export function InputArea({mimeType: file.type || 'application/octet-stream',size: file.size,file,+ ...(localPath ? { localPath } : {}),};const validationError =- kind === 'document' ? getDocumentValidationError(file) : getImageValidationError(file);+ kind === 'document'+ ? getDocumentValidationError(file, { filename: base.filename, localPath })+ : getImageValidationError(file);if (validationError) {pushAttachmentAlert(validationError);items.push({@@ -801,12 +1027,102 @@ export function InputArea({if (!drafts.length) return;- setAttachments((prev) => [...prev, ...drafts].slice(0, MAX_ATTACHMENT_COUNT));+ setAttachments((prev) => [...prev, ...drafts]);drafts.forEach((draft) => {- if (draft.status !== 'uploading' || !draft.file) return;+ if (draft.status !== 'uploading') return;uploadAttachment(draft);});- }, [attachments.length, pushAttachmentAlert, uploadAttachment]);+ }, [pushAttachmentAlert, uploadAttachment]);++ const appendLocalFilePicks = useCallback((picks: LocalFilePick[]) => {+ if (!picks.length) return;++ const drafts = picks.reduce<AttachmentDraft[]>((items, pick) => {+ if (pick.error === 'forbidden') {+ pushAttachmentAlert(`禁止上传该文件类型:${pick.filename}`);+ return items;+ }+ if (pick.error === 'image_too_large') {+ pushAttachmentAlert(+ `文件大小超出限制:${pick.filename}(最大${formatAttachmentSize(MAX_IMAGE_BYTES)})`,+ );+ return items;+ }+ if (pick.error === 'read_failed') {+ pushAttachmentAlert(`读取文件失败:${pick.filename}`);+ return items;+ }+ if (pick.kind === 'image' && !pick.base64) {+ pushAttachmentAlert(`读取图片失败:${pick.filename}`);+ return items;+ }++ const draft: AttachmentDraft = {+ id: `${pick.filename}-${pick.size}-${generateUuidV4()}`,+ kind: pick.kind,+ filename: pick.filename,+ mimeType: pick.mime_type || 'application/octet-stream',+ size: pick.size,+ localPath: pick.path,+ status: 'uploading',+ ...(pick.kind === 'image' && pick.base64+ ? {+ base64Data: pick.base64,+ previewUrl: `data:${pick.mime_type || 'application/octet-stream'};base64,${pick.base64}`,+ }+ : {}),+ };+ items.push(draft);+ return items;+ }, []);++ if (!drafts.length) return;+ setAttachments((prev) => [...prev, ...drafts]);+ drafts.forEach((draft) => {+ uploadAttachment(draft);+ });+ }, [pushAttachmentAlert, uploadAttachment]);++ const openAttachmentPicker = useCallback(async () => {+ if (imageInputDisabled) return;+ setAttachMenuOpen(false);+ // 文档上传依赖本机绝对路径:桌面 pywebview 或浏览器后端 path.select_files。+ // 不要回落 HTML <input type="file">,浏览器拿不到 File.path,只会得到+ // 「无法获取本地文件路径」的假失败。+ const result = await selectLocalFiles(true);+ if (result.ok) {+ appendLocalFilePicks(result.files);+ return;+ }+ if (result.reason === 'cancelled') {+ return;+ }+ const hint =+ result.reason === 'unsupported'+ ? '当前环境无法打开本机文件选择器(请确认 jiuwenswarm 在本机运行且已重启加载最新后端)'+ : (result.message || '打开文件选择器失败');+ pushAttachmentAlert(hint);+ }, [appendLocalFilePicks, imageInputDisabled, pushAttachmentAlert]);++ const acceptExternalLocalFilePicks = useCallback(+ (picks: LocalFilePick[]) => {+ if (!picks.length) return;+ if (imageInputDisabled) {+ pushAttachmentAlert(t('chat.addFileDisabled'));+ return;+ }+ appendLocalFilePicks(picks);+ },+ [appendLocalFilePicks, imageInputDisabled, pushAttachmentAlert, t],+ );++ useImperativeHandle(+ ref,+ () => ({+ appendLocalFilePicks: acceptExternalLocalFilePicks,+ }),+ [acceptExternalLocalFilePicks],+ );useEffect(() => {if (!isModeMenuOpen) return;@@ -982,8 +1298,12 @@ export function InputArea({(Boolean(pickString(attachment.persistedMediaItem?.path)) || Boolean(attachment.base64Data)),);const trimmed = buildSubmitContent(trimmedBase, readyDrafts);- if ((!trimmed && readyMediaItems.length === 0) || hasUploadingAttachments || hasAttachmentErrors) return;- if (isInterruptible && !isTeamMode && readyMediaItems.length > 0) return;+ // Require typed/voice text — attachments alone must not enable send.+ if (!trimmedBase || hasUploadingAttachments || hasAttachmentErrors) return;+ // In agent mode attachments queue with the task (taskQueue carries mediaItems).+ // Other non-team modes still go through the text-only onInterrupt channel where+ // attachments would be lost, so keep blocking there.+ if (isInterruptible && !isTeamMode && !isAgentMode && readyMediaItems.length > 0) return;if (isListening) {stopListening();@@ -1067,12 +1387,19 @@ export function InputArea({t,]);- const trimmedDraft = (inputValue + pendingVoiceText).trim();- const hasDraft = trimmedDraft.length > 0 || attachments.length > 0 || isListening;- const isImageInterruptBlocked = isInterruptible && !isTeamMode && readyMediaItems.length > 0;+ // Prefer live contenteditable text so a stale store inputValue cannot keep Send+ // enabled while the editor is empty (attachments alone must not enable Send).+ const liveEditorText = inputRef.current ? extractPlainText() : inputValue;+ const trimmedDraft = (liveEditorText + pendingVoiceText).trim();+ const hasTextDraft = trimmedDraft.length > 0;+ // Attachments / listening still count as "composer busy" so Stop stays hidden+ // while the user is preparing a follow-up, but they do not enable Send.+ const hasDraft = hasTextDraft || attachments.length > 0 || isListening;+ const isImageInterruptBlocked =+ isInterruptible && !isTeamMode && !isAgentMode && readyMediaItems.length > 0;const showStop = isProcessing && !isPaused && !hasDraft;const canSubmit = showStop || (- hasDraft &&+ hasTextDraft &&!isLoadingHistory &&!isImageInterruptBlocked &&!hasUploadingAttachments &&@@ -1302,21 +1629,95 @@ export function InputArea({event.target.value = '';}, [appendAttachmentFiles]);- const handlePaste = useCallback((event: ClipboardEvent<HTMLDivElement>) => {- if (Array.from(event.clipboardData.items).some((item) => item.kind === 'file')) {- event.preventDefault();- }- }, []);+ const handleDesktopFilePaste = useCallback(+ (event: ClipboardEvent | globalThis.ClipboardEvent) => {+ if (!isDesktopBridgeReady && !isDesktopLocalFilePicker()) return false;++ const target = event.target as Node | null;+ const shell = inputRef.current?.closest('.chat-panel-shell');+ if (!shell || !target || !shell.contains(target)) return false;++ const hasBrowserFiles = clipboardHasFileItems(event.clipboardData);+ // Capture File blobs before any await; clipboardData can become unavailable.+ const imageFiles = hasBrowserFiles+ ? Array.from(event.clipboardData?.items || [])+ .filter((item) => item.kind === 'file')+ .map((item) => item.getAsFile())+ .filter((file): file is File => Boolean(file && isImageFile(file)))+ : [];++ if (hasBrowserFiles) {+ event.preventDefault();+ if (imageInputDisabled) return true;+ void (async () => {+ const clipboardPicks = await getClipboardFilePicks();+ if (clipboardPicks.length) {+ appendLocalFilePicks(clipboardPicks);+ return;+ }+ if (imageFiles.length) {+ appendAttachmentFiles(imageFiles);+ }+ })();+ return true;+ }++ // Explorer-copied files may only expose CF_HDROP to the native bridge.+ // Do not block text paste; append native file picks if any are found.+ if (!imageInputDisabled) {+ void (async () => {+ const clipboardPicks = await getClipboardFilePicks();+ if (clipboardPicks.length) {+ appendLocalFilePicks(clipboardPicks);+ }+ })();+ }+ return false;+ },+ [appendAttachmentFiles, appendLocalFilePicks, imageInputDisabled, isDesktopBridgeReady],+ );++ const handlePaste = useCallback(+ (event: ClipboardEvent<HTMLDivElement>) => {+ if (handleDesktopFilePaste(event)) return;+ if (clipboardHasFileItems(event.clipboardData)) {+ event.preventDefault();+ }+ },+ [handleDesktopFilePaste],+ );++ useEffect(() => {+ if (!isDesktopBridgeReady) return undefined;++ const onDocumentPaste = (event: globalThis.ClipboardEvent) => {+ // contenteditable onPaste already covers the composer; this covers the rest of the shell.+ if (inputRef.current?.contains(event.target as Node)) return;+ handleDesktopFilePaste(event);+ };++ document.addEventListener('paste', onDocumentPaste);+ return () => document.removeEventListener('paste', onDocumentPaste);+ }, [handleDesktopFilePaste, isDesktopBridgeReady]);const handleFileDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {if (!Array.from(event.dataTransfer.types).includes('Files')) return;event.preventDefault();+ // Never set dropEffect='none'/'move' inside the desktop shell — WebView2+ // rejects those for Explorer file drags and shows the forbidden cursor.+ const desktop = isDesktopBridgeReady || isDesktopShell() || isDesktopLocalFilePicker();+ if (desktop) {+ event.dataTransfer.dropEffect = 'copy';+ return;+ }+ // Browser / whl: reject OS file drops (no absolute path bridge).event.dataTransfer.dropEffect = 'none';- }, []);+ }, [isDesktopBridgeReady]);const handleFileDrop = useCallback((event: DragEvent<HTMLDivElement>) => {if (!Array.from(event.dataTransfer.types).includes('Files')) return;event.preventDefault();+ // Desktop paths arrive via jiuwen-desktop-local-files from pywebview.}, []);/** 在光标处插入技能 chip(不可编辑原子节点) */@@ -1795,9 +2196,7 @@ export function InputArea({disabled={imageInputDisabled}title={imageInputDisabled ? t('chat.addFileDisabled') : undefined}onClick={() => {- if (imageInputDisabled) return;- setAttachMenuOpen(false);- fileInputRef.current?.click();+ void openAttachmentPicker();}}><span className="chat-mode-select__option-main">@@ -2193,7 +2592,7 @@ export function InputArea({</div></>);-}+});function ProjectAddSubmenu({ onCreate }: { onCreate: (mode: ProjectCreateMode) => void }) {const { t } = useTranslation();diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsxindex bf8de10778..285155878c 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx@@ -37,13 +37,16 @@ function mediaSrc(item: MediaItem): string | undefined {return `data:${mimeType};base64,${base64Data}`;}if (item.url) return item.url;- if (item.path) return `/file-api/raw-file?path=${encodeURIComponent(item.path)}`;+ // Documents keep local absolute paths for agent @path refs; raw-file is project-scoped.+ if (item.path && isImageItem(item)) {+ return `/file-api/raw-file?path=${encodeURIComponent(item.path)}`;+ }return undefined;}function FileCard({ item }: { item: MediaItem }) {const filename = item.filename || 'file';- const { stem, extLabel } = splitFilenameParts(filename);+ const { extLabel } = splitFilenameParts(filename);const typeKey = getFileTypeIconKeyFromFilename(filename, item.type);const src = mediaSrc(item);const showThumb = isImageItem(item) && Boolean(src);@@ -59,7 +62,7 @@ function FileCard({ item }: { item: MediaItem }) {</span><span className="chat-msg-file-card__meta"><span className="chat-msg-file-card__name" title={filename}>- {stem}+ {filename}</span>{extLabel ? <span className="chat-msg-file-card__ext">{extLabel}</span> : null}</span>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex 50baeb3cd4..ea4fc164ee 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -14,7 +14,7 @@ import { AgentMode, MediaItem, Message, UserAnswer, type ProjectInfo, type UserAimport type { HumanShareCommand } from '../../stores/sessionStore';import { MessageList } from './MessageList';import { ContextCompressionLines } from './MessageItem';-import { InputArea } from './InputArea';+import { InputArea, type InputAreaHandle } from './InputArea';import chatIcon from '../../assets/chat.svg';import expandIcon from '../../assets/expand.svg';import lineUpIcon from '../../assets/lineUp.svg';@@ -41,6 +41,16 @@ import {canLoadOlderHistory,shouldShowHistoryRetry,} from '../../features/historyPagination';+import {+ DESKTOP_FILE_DRAG_EVENT,+ DESKTOP_LOCAL_FILES_EVENT,+ isDesktopShell,+ normalizePicks,+ registerDesktopLocalFilesConsumer,+ type DesktopLocalFilesEventDetail,+ type LocalFilePick,+} from '../../features/workspace/localFilePicker';+import { useDesktopLocalFilePickerReady } from '../../hooks';export interface ChatHistoryPagerProps {loadedPages: number;@@ -701,6 +711,9 @@ export function ChatPanel({));const teamHumanShareCommands = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.teamHumanShareCommands ?? []);const scrollContainerRef = useRef<HTMLDivElement>(null);+ const inputAreaRef = useRef<InputAreaHandle>(null);+ const desktopFileDropAcceptUntilRef = useRef(0);+ const lastConsumedDesktopDropIdRef = useRef<string | null>(null);const historyLayoutSnapshotRef = useRef<{sessionId: string;loadedPages: number;@@ -710,6 +723,7 @@ export function ChatPanel({const suppressNextScrollToEndRef = useRef(false);const stickToBottomUntilStableRef = useRef(false);const [isSending, setIsSending] = React.useState(false);+ const isDesktopAttachmentDropEnabled = useDesktopLocalFilePickerReady();const hasTimelineContent = messages.length > 0 || toolExecutionOrder.length > 0;const hasConversation = Boolean(isHistoryRestoring || historyPager || hasTimelineContent);const historyLoadedPages = historyPager?.loadedPages ?? 0;@@ -1002,8 +1016,131 @@ export function ChatPanel({(text: string) => handleSendMessage(text),[handleSendMessage],);++ const markDesktopFileDropZoneActive = useCallback(() => {+ desktopFileDropAcceptUntilRef.current = Date.now() + 1200;+ }, []);++ const clearDesktopFileDropZone = useCallback(() => {+ desktopFileDropAcceptUntilRef.current = 0;+ }, []);++ const canAcceptDesktopFileDrag = useCallback(() => {+ return isDesktopAttachmentDropEnabled || isDesktopShell();+ }, [isDesktopAttachmentDropEnabled]);++ const handleDesktopFileDragEnter = useCallback(+ (event: React.DragEvent<HTMLDivElement>) => {+ if (!canAcceptDesktopFileDrag()) return;+ if (!Array.from(event.dataTransfer.types).includes('Files')) return;+ event.preventDefault();+ // OS file drags require copy; move/none show the forbidden cursor in WebView2.+ event.dataTransfer.dropEffect = 'copy';+ markDesktopFileDropZoneActive();+ },+ [canAcceptDesktopFileDrag, markDesktopFileDropZoneActive],+ );++ const handleDesktopFileDragOver = useCallback(+ (event: React.DragEvent<HTMLDivElement>) => {+ if (!canAcceptDesktopFileDrag()) return;+ if (!Array.from(event.dataTransfer.types).includes('Files')) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ markDesktopFileDropZoneActive();+ },+ [canAcceptDesktopFileDrag, markDesktopFileDropZoneActive],+ );++ const ingestDesktopLocalFiles = useCallback(+ (detail: DesktopLocalFilesEventDetail | null | undefined, files: LocalFilePick[]) => {+ if (detail?.source && detail.source !== 'drop') return;+ if (!files.length) {+ clearDesktopFileDropZone();+ return;+ }++ const dropId = typeof detail?.dropId === 'string' ? detail.dropId : null;+ if (dropId && lastConsumedDesktopDropIdRef.current === dropId) {+ clearDesktopFileDropZone();+ return;+ }++ const acceptByTime = Date.now() <= desktopFileDropAcceptUntilRef.current;+ const clientX = detail?.clientX;+ const clientY = detail?.clientY;+ const hasCoords = typeof clientX === 'number' && typeof clientY === 'number';+ let inZone = false;+ if (hasCoords) {+ const hit = document.elementFromPoint(clientX, clientY);+ inZone = Boolean(+ hit?.closest('.chat-panel-shell') || hit?.closest('.chat-layout__surface'),+ );+ }+ // Native bridge trusted=true always accepts (coords from WebView2 are often wrong).+ const trusted = detail?.trusted === true;+ if (!trusted && !acceptByTime && !inZone) {+ clearDesktopFileDropZone();+ return;+ }++ if (dropId) lastConsumedDesktopDropIdRef.current = dropId;+ inputAreaRef.current?.appendLocalFilePicks(files);+ clearDesktopFileDropZone();+ },+ [clearDesktopFileDropZone],+ );++ const handleDesktopFileDrop = useCallback(+ (event: React.DragEvent<HTMLDivElement>) => {+ if (!canAcceptDesktopFileDrag()) return;+ if (!Array.from(event.dataTransfer.types).includes('Files')) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ markDesktopFileDropZoneActive();+ // Files arrive via the durable ingest bridge invoked by desktop_app run_js.+ // Do NOT call pywebview APIs here: a JS->Python call racing the Python-side+ // drop handler's run_js deadlocks the UI thread (window freezes).+ },+ [canAcceptDesktopFileDrag, markDesktopFileDropZoneActive],+ );++ useEffect(() => {+ // Durable bridge lives in localFilePicker; ChatPanel only registers a consumer.+ // Never delete window.__JIUWEN_INGEST_LOCAL_FILES__ — Python run_js requires it.+ const unregister = registerDesktopLocalFilesConsumer((detail, files) => {+ ingestDesktopLocalFiles(detail, files);+ });++ const onDesktopLocalFiles = (event: Event) => {+ const detail = (event as CustomEvent<DesktopLocalFilesEventDetail>).detail;+ ingestDesktopLocalFiles(detail, normalizePicks(detail?.files));+ };++ const onDesktopFileDrag = (event: Event) => {+ const active = Boolean((event as CustomEvent<{ active?: boolean }>).detail?.active);+ if (active) {+ markDesktopFileDropZoneActive();+ }+ };++ window.addEventListener(DESKTOP_LOCAL_FILES_EVENT, onDesktopLocalFiles as EventListener);+ window.addEventListener(DESKTOP_FILE_DRAG_EVENT, onDesktopFileDrag as EventListener);+ return () => {+ unregister();+ window.removeEventListener(DESKTOP_LOCAL_FILES_EVENT, onDesktopLocalFiles as EventListener);+ window.removeEventListener(DESKTOP_FILE_DRAG_EVENT, onDesktopFileDrag as EventListener);+ };+ }, [ingestDesktopLocalFiles, markDesktopFileDropZoneActive]);+return (- <div className="chat-panel-shell flex flex-col h-full" data-testid="chat-panel">+ <div+ className="chat-panel-shell flex flex-col h-full"+ data-testid="chat-panel"+ onDragEnter={handleDesktopFileDragEnter}+ onDragOver={handleDesktopFileDragOver}+ onDrop={handleDesktopFileDrop}+ >{shouldShowChatHeader && (<div className="chat-panel-header"><div className="chat-panel-header__meta">@@ -1129,6 +1266,7 @@ export function ChatPanel({<InterruptResultBubble /><InteractionSlot onSubmit={onUserAnswer} /><InputArea+ ref={inputAreaRef}onSubmit={handleSendMessage}onPersistMedia={onPersistMedia}onPersistDocuments={onPersistDocuments}@@ -1170,6 +1308,7 @@ export function ChatPanel({/>)}<InputArea+ ref={inputAreaRef}onSubmit={handleSendMessage}onPersistMedia={onPersistMedia}onPersistDocuments={onPersistDocuments}diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionItem.tsxindex 8993f0dfc2..eff5c8b0ec 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/SessionItem.tsx@@ -7,6 +7,7 @@import { useState } from 'react';import { useTranslation } from 'react-i18next';import { Session } from '../../types';+import { toDisplaySessionTitle } from '../../utils/documentMessage';import clsx from 'clsx';interface SessionItemProps {@@ -54,8 +55,9 @@ export function SessionItem({ session, isActive, onClick, onDelete }: SessionIteconst { t, i18n } = useTranslation();const [showDelete, setShowDelete] = useState(false);- // 优先展示会话标题,缺失时回退到会话 ID 片段- const preview = session.title?.trim() || session.session_id.slice(0, 8);+ // 优先展示会话标题,缺失时回退到会话 ID 片段;隐藏【上传文档】后缀+ const preview =+ toDisplaySessionTitle(session.title || '') || session.session_id.slice(0, 8);const handleDelete = (e: React.MouseEvent) => {e.stopPropagation();diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsxindex 3318793ae0..5ae5753336 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx@@ -6,6 +6,7 @@ import { containsIgnoredDirectory } from '../../features/fileTreeFilters';import { isHistoryPreviewFile } from '../../features/historyFilePreview';import { webRequest } from '../../services/webClient';import { useChatStore } from '../../stores/chatStore';+import { toDisplaySessionTitle } from '../../utils/documentMessage';function SessionErrorIndicator({ sessionId }: { sessionId: string }) {const error = useChatStore((state) => state.runtimes[sessionId]?.error);@@ -545,10 +546,10 @@ export function SessionsPanel({setSelectedSessionId(session.session_id);void loadSessionFilesForSession(session.session_id);}}- title={session.title || parseSessionDisplayLabel(session.session_id, t)}+ title={toDisplaySessionTitle(session.title || '') || parseSessionDisplayLabel(session.session_id, t)}><span className="flex items-center gap-2">- <span className="truncate block flex-1">{session.title || parseSessionDisplayLabel(session.session_id, t)}</span>+ <span className="truncate block flex-1">{toDisplaySessionTitle(session.title || '') || parseSessionDisplayLabel(session.session_id, t)}</span><SessionErrorIndicator sessionId={session.session_id} /></span>{session.mode === 'team' && session.team_name ? (diff --git a/jiuwenswarm/channels/web/frontend/src/features/workspace/localFilePicker.ts b/jiuwenswarm/channels/web/frontend/src/features/workspace/localFilePicker.tsnew file mode 100644index 0000000000..df4225302d--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/workspace/localFilePicker.ts@@ -0,0 +1,364 @@+export type LocalFilePick = {+ path: string;+ filename: string;+ size: number;+ mime_type: string;+ kind: 'image' | 'document';+ base64?: string;+ error?: string;+};++export type LocalFilePickResult =+ | { ok: true; files: LocalFilePick[] }+ | { ok: false; reason: 'unsupported' | 'cancelled' | 'failed'; message?: string };++export const DESKTOP_LOCAL_FILES_EVENT = 'jiuwen-desktop-local-files';+export const DESKTOP_READY_EVENT = 'jiuwen-desktop-ready';+export const DESKTOP_FILE_DRAG_EVENT = 'jiuwen-desktop-file-drag';++export type DesktopLocalFilesEventDetail = {+ source?: 'drop' | 'paste' | string;+ files?: unknown;+ clientX?: number;+ clientY?: number;+ /** Set by desktop_app.py when the event comes from the native drop bridge. */+ trusted?: boolean;+ /** Unique id so the ingest bridge + CustomEvent paths do not double-ingest. */+ dropId?: string;+};++export type DesktopLocalFilesConsumer = (+ detail: DesktopLocalFilesEventDetail,+ files: LocalFilePick[],+) => void;++type DesktopWindowMarker = Window & {+ __JIUWEN_DESKTOP__?: boolean;+ __JIUWEN_DESKTOP_DND__?: boolean;+ /** Frontend override that forces dropEffect=copy so OS file drags are accepted. */+ __JIUWEN_DESKTOP_DND_COPY_OVERRIDE__?: boolean;+ __JIUWEN_DROP_QUEUE__?: DesktopLocalFilesEventDetail[];+};++/** Survives ChatPanel mount/unmount — Python run_js must always find a function. */+let desktopLocalFilesConsumer: DesktopLocalFilesConsumer | null = null;+let durableBridgeInstalled = false;++function getDropQueue(): DesktopLocalFilesEventDetail[] {+ const marker = window as DesktopWindowMarker;+ if (!Array.isArray(marker.__JIUWEN_DROP_QUEUE__)) {+ marker.__JIUWEN_DROP_QUEUE__ = [];+ }+ return marker.__JIUWEN_DROP_QUEUE__;+}++/**+ * Install a durable window.__JIUWEN_INGEST_LOCAL_FILES__ that never gets deleted+ * by React effect cleanup. ChatPanel registers a consumer to drain/receive drops.+ */+export function installDesktopLocalFilesBridge(): void {+ if (typeof window === 'undefined' || durableBridgeInstalled) return;+ durableBridgeInstalled = true;++ window.__JIUWEN_INGEST_LOCAL_FILES__ = (raw) => {+ const detail = (raw || {}) as DesktopLocalFilesEventDetail;+ const files = normalizePicks(detail.files);+ // No pywebview API call here: this function runs inside Python-side run_js,+ // and a concurrent JS->Python call deadlocks the WebView2 UI thread.+ if (desktopLocalFilesConsumer) {+ desktopLocalFilesConsumer(detail, files);+ } else {+ getDropQueue().push(detail);+ }+ window.dispatchEvent(new CustomEvent(DESKTOP_LOCAL_FILES_EVENT, { detail }));+ };+}++/** Register ChatPanel (or other UI) as the active consumer; drains queued drops. */+export function registerDesktopLocalFilesConsumer(+ consumer: DesktopLocalFilesConsumer,+): () => void {+ installDesktopLocalFilesBridge();+ desktopLocalFilesConsumer = consumer;+ const queue = getDropQueue();+ const queued = queue.splice(0, queue.length);+ for (const detail of queued) {+ consumer(detail, normalizePicks(detail.files));+ }+ return () => {+ if (desktopLocalFilesConsumer === consumer) {+ desktopLocalFilesConsumer = null;+ }+ // Keep window.__JIUWEN_INGEST_LOCAL_FILES__ — Python must always find it.+ };+}++/** Desktop webview shell marker and/or pywebview bridge (not browser / whl). */+export function isDesktopShell(): boolean {+ if (typeof window === 'undefined') return false;+ const marker = window as DesktopWindowMarker;+ if (marker.__JIUWEN_DESKTOP__ === true || marker.__JIUWEN_DESKTOP_DND__ === true) return true;+ if (typeof window.pywebview?.api?.select_local_files === 'function') return true;+ return 'pywebview' in window;+}++function dataTransferHasFiles(dt: DataTransfer | null): boolean {+ if (!dt?.types) return false;+ try {+ return Array.from(dt.types).includes('Files');+ } catch {+ return false;+ }+}++/**+ * Install window-level file-drag accept handlers inside the desktop webview.+ * Must run in the page itself (not only via Python evaluate_js) so a frontend+ * hot-update can fix the forbidden cursor without waiting for a full exe rebuild.+ * Window bubble listeners run after React and override dropEffect='none'.+ * OS file drags into Chromium/WebView2 must use dropEffect='copy':+ * ``none`` shows the forbidden cursor, and ``move`` is often rejected by the+ * browser for Explorer file drags (also ends up as the forbidden cursor).+ */+export function installDesktopFileDragAccept(): boolean {+ if (typeof window === 'undefined') return false;+ if (!isDesktopShell()) return false;+ installDesktopLocalFilesBridge();+ const marker = window as DesktopWindowMarker;+ marker.__JIUWEN_DESKTOP__ = true;++ // Bubble-phase override always wins over React paths that set dropEffect='none'+ // (forbidden cursor). Safe to install even when DND handlers already exist.+ if (!marker.__JIUWEN_DESKTOP_DND_COPY_OVERRIDE__) {+ marker.__JIUWEN_DESKTOP_DND_COPY_OVERRIDE__ = true;+ const forceCopy = (event: DragEvent) => {+ if (!dataTransferHasFiles(event.dataTransfer)) return;+ event.preventDefault();+ try {+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';+ } catch {+ // ignore+ }+ };+ window.addEventListener('dragenter', forceCopy, false);+ window.addEventListener('dragover', forceCopy, false);+ }++ if (marker.__JIUWEN_DESKTOP_DND__ === true) return true;+ marker.__JIUWEN_DESKTOP_DND__ = true;++ const accept = (event: DragEvent) => {+ if (!dataTransferHasFiles(event.dataTransfer)) return;+ event.preventDefault();+ try {+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';+ } catch {+ // ignore+ }+ window.dispatchEvent(+ new CustomEvent(DESKTOP_FILE_DRAG_EVENT, { detail: { active: true } }),+ );+ };+ const endDrag = () => {+ window.dispatchEvent(+ new CustomEvent(DESKTOP_FILE_DRAG_EVENT, { detail: { active: false } }),+ );+ };++ window.addEventListener('dragenter', accept, true);+ window.addEventListener('dragover', accept, true);+ window.addEventListener('dragenter', accept, false);+ window.addEventListener('dragover', accept, false);+ window.addEventListener(+ 'drop',+ (event: DragEvent) => {+ if (!dataTransferHasFiles(event.dataTransfer)) return;+ event.preventDefault();+ endDrag();+ },+ true,+ );+ return true;+}++const FILE_PICKER_TIMEOUT_MS = 10 * 60 * 1000;+const LAST_DIR_STORAGE_KEY = 'jiuwenswarm:last-file-picker-dir';++function getLocalFilePickerApi() {+ if (typeof window === 'undefined') return undefined;+ return window.pywebview?.api?.select_local_files;+}++/** True when the native pywebview file picker bridge is available. */+export function isDesktopLocalFilePicker(): boolean {+ return typeof getLocalFilePickerApi() === 'function';+}++export function isLocalFilePickerSupported(): boolean {+ // 桌面端走 pywebview;浏览器 / whl 走后端 path.select_files(对齐 path.select_directory)+ return isDesktopLocalFilePicker() || typeof window !== 'undefined';+}++function parentDirectoryOf(path: string): string | undefined {+ const trimmed = path.trim().replace(/[\\/]+$/, '');+ if (!trimmed) return undefined;+ const idx = Math.max(trimmed.lastIndexOf('\\'), trimmed.lastIndexOf('/'));+ if (idx <= 0) return undefined;+ return trimmed.slice(0, idx);+}++function readLastPickerDir(): string | undefined {+ if (typeof window === 'undefined') return undefined;+ try {+ const raw = window.localStorage.getItem(LAST_DIR_STORAGE_KEY)?.trim();+ return raw || undefined;+ } catch {+ return undefined;+ }+}++function rememberLastPickerDir(files: LocalFilePick[]): void {+ const dir = parentDirectoryOf(files[0]?.path || '');+ if (!dir || typeof window === 'undefined') return;+ try {+ window.localStorage.setItem(LAST_DIR_STORAGE_KEY, dir);+ } catch {+ // private mode / quota — ignore+ }+}++function normalizePick(raw: unknown): LocalFilePick | null {+ if (!raw || typeof raw !== 'object') return null;+ const item = raw as Record<string, unknown>;+ const path = typeof item.path === 'string' ? item.path.trim() : '';+ const filename = typeof item.filename === 'string' ? item.filename.trim() : '';+ if (!path || !filename) return null;+ const kind = item.kind === 'image' ? 'image' : 'document';+ const size = typeof item.size === 'number' && Number.isFinite(item.size) ? item.size : 0;+ const mimeType =+ typeof item.mime_type === 'string' && item.mime_type.trim()+ ? item.mime_type.trim()+ : 'application/octet-stream';+ const base64 = typeof item.base64 === 'string' && item.base64 ? item.base64 : undefined;+ const error = typeof item.error === 'string' && item.error ? item.error : undefined;+ return {+ path,+ filename,+ size,+ mime_type: mimeType,+ kind,+ ...(base64 ? { base64 } : {}),+ ...(error ? { error } : {}),+ };+}++export function normalizePicks(rawFiles: unknown): LocalFilePick[] {+ if (!Array.isArray(rawFiles)) return [];+ return rawFiles+ .map((item) => normalizePick(item))+ .filter((item): item is LocalFilePick => item !== null);+}++async function selectLocalFilesViaBackend(+ allowMultiple: boolean,+ initialDir?: string,+): Promise<LocalFilePickResult> {+ try {+ const { webRequest } = await import('../../services/webClient');+ const payload = await webRequest<{+ files?: Array<Record<string, unknown>>;+ cancelled?: boolean;+ }>(+ 'path.select_files',+ {+ allow_multiple: allowMultiple,+ ...(initialDir ? { initial_dir: initialDir } : {}),+ },+ { timeoutMs: FILE_PICKER_TIMEOUT_MS },+ );+ if (payload?.cancelled) {+ return { ok: false, reason: 'cancelled' };+ }+ const files = normalizePicks(payload?.files);+ if (!files.length) {+ return { ok: false, reason: 'cancelled' };+ }+ rememberLastPickerDir(files);+ return { ok: true, files };+ } catch (error) {+ const code =+ error && typeof error === 'object' && 'code' in error+ ? String((error as { code?: unknown }).code || '')+ : '';+ if (code === 'UNSUPPORTED') {+ return {+ ok: false,+ reason: 'unsupported',+ message: error instanceof Error ? error.message : String(error),+ };+ }+ if (code === 'METHOD_NOT_FOUND') {+ return {+ ok: false,+ reason: 'unsupported',+ message: '后端未注册 path.select_files,请重启 jiuwenswarm-start 后再试',+ };+ }+ return {+ ok: false,+ reason: 'failed',+ message: error instanceof Error ? error.message : String(error),+ };+ }+}++export async function selectLocalFiles(+ allowMultiple = true,+): Promise<LocalFilePickResult> {+ const initialDir = readLastPickerDir();+ const pickFiles = getLocalFilePickerApi();+ if (typeof pickFiles === 'function') {+ try {+ const selected = initialDir+ ? await pickFiles(allowMultiple, initialDir)+ : await pickFiles(allowMultiple);+ const files = normalizePicks(selected);+ if (!files.length) {+ return { ok: false, reason: 'cancelled' };+ }+ rememberLastPickerDir(files);+ return { ok: true, files };+ } catch (error) {+ return {+ ok: false,+ reason: 'failed',+ message: error instanceof Error ? error.message : String(error),+ };+ }+ }++ return selectLocalFilesViaBackend(allowMultiple, initialDir);+}++export async function describeLocalFiles(paths: string[]): Promise<LocalFilePick[]> {+ if (!isDesktopLocalFilePicker() || !paths.length) return [];+ const api = window.pywebview?.api?.describe_local_files;+ if (typeof api !== 'function') return [];+ try {+ return normalizePicks(await api(paths));+ } catch {+ return [];+ }+}++export async function getClipboardFilePicks(): Promise<LocalFilePick[]> {+ // Prefer the dedicated clipboard bridge; fall back once api is present even if+ // select_local_files was not yet enumerated on the proxy object.+ const api = window.pywebview?.api?.get_clipboard_files;+ if (typeof api !== 'function') return [];+ try {+ return normalizePicks(await api());+ } catch {+ return [];+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts b/jiuwenswarm/channels/web/frontend/src/hooks/index.tsindex 65737d0c2e..90c5e809ab 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/index.ts@@ -4,3 +4,4 @@export { useWebSocket, mergePersistedGoalCompletionMessages, stampGoalObjectiveMessages } from './useWebSocket';export { useSpeechRecognition, useSpeechSynthesis } from './useSpeech';+export { useDesktopLocalFilePickerReady } from './useDesktopLocalFilePickerReady';diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useDesktopLocalFilePickerReady.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useDesktopLocalFilePickerReady.tsnew file mode 100644index 0000000000..4c12733500--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useDesktopLocalFilePickerReady.ts@@ -0,0 +1,53 @@+import { useEffect, useState } from 'react';+import {+ DESKTOP_READY_EVENT,+ installDesktopFileDragAccept,+ isDesktopLocalFilePicker,+ isDesktopShell,+} from '../features/workspace/localFilePicker';++/**+ * Desktop drop/paste must not wait solely on `window.pywebview.api`.+ * `desktop_app.py` sets `window.__JIUWEN_DESKTOP__` and dispatches+ * `jiuwen-desktop-ready` as soon as the webview page finishes loading.+ */+export function useDesktopLocalFilePickerReady(): boolean {+ const [ready, setReady] = useState(() => isDesktopShell() || isDesktopLocalFilePicker());++ useEffect(() => {+ const markReady = () => {+ if (isDesktopShell() || isDesktopLocalFilePicker()) {+ installDesktopFileDragAccept();+ setReady(true);+ return true;+ }+ return false;+ };++ markReady();++ const onReady = () => {+ markReady();+ };+ window.addEventListener('pywebviewready', onReady);+ window.addEventListener(DESKTOP_READY_EVENT, onReady);++ const intervalId = window.setInterval(() => {+ if (markReady()) {+ window.clearInterval(intervalId);+ }+ }, 200);+ const timeoutId = window.setTimeout(() => {+ window.clearInterval(intervalId);+ }, 30000);++ return () => {+ window.removeEventListener('pywebviewready', onReady);+ window.removeEventListener(DESKTOP_READY_EVENT, onReady);+ window.clearInterval(intervalId);+ window.clearTimeout(timeoutId);+ };+ }, []);++ return ready;+}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 242032b6d3..6a68c94e40 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -74,7 +74,11 @@ import {findActiveTeamLeaderMessage as findActiveTeamLeaderMessageInTurn,} from '../features/teamLeaderMessages';import { buildGoalCompletedContent } from '../components/GoalBar/goalCompletedMessage';-import { stripUploadDocumentBlocks } from '../utils/documentMessage';+import {+ stripUploadDocumentBlocks,+ toUploadDocumentHints,+ withUploadDocumentBlock,+} from '../utils/documentMessage';const WS_RECONNECT_EVENT = 'jiuwenclaw:ws-reconnect-request';@@ -1179,16 +1183,22 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const persistDocuments = useCallback(async (content: string, sessionId: string, mediaItems: MediaItem[]) => {- return request<PersistMediaResponse>('document.persist', {- session_id: sessionId,- content,- parse: true,- documents: mediaItems.map((item) => ({- filename: item.filename,- mime_type: getMediaMimeType(item),- base64_data: item.base64_data || item.base64Data,- })),- });+ return request<PersistMediaResponse>(+ 'document.persist',+ {+ session_id: sessionId,+ content,+ documents: mediaItems.map((item) => ({+ filename: item.filename,+ mime_type: getMediaMimeType(item),+ path: item.path,+ original_path: item.path,+ size_bytes: item.size_bytes ?? item.sizeBytes,+ })),+ },+ // Path validation only — no base64 transfer / parse+ { timeoutMs: 30_000 },+ );},[request],);@@ -1314,7 +1324,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const sendMessage = useCallback(async (content: string, sessionId: string, mediaItems: MediaItem[] = []): Promise<boolean> => {const hasMedia = mediaItems.length > 0;- if (!content.trim() && !hasMedia) return false;+ // User-visible text is required; attachment-only / 【上传文档】-only payloads+ // must not send (matches InputArea canSubmit / handleSubmit).+ if (!stripUploadDocumentBlocks(content).trim()) return false;const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;const unsupportedEvolutionMode = unsupportedEvolutionModeMessage(content, currentMode ?? 'agent');@@ -1422,6 +1434,14 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (persistedDocs.files && typeof persistedDocs.files === 'object') {Object.assign(mergedFiles, persistedDocs.files);}+ // The composer could not persist these documents before send (a+ // brand-new session has no id yet), so its hint block carries+ // filenames without paths. Rewrite it now that paths exist —+ // team mode reads paths from the message text only.+ const documentHints = toUploadDocumentHints(persistedDocs.media_items);+ if (documentHints.length) {+ outgoingContent = withUploadDocumentBlock(outgoingContent, documentHints);+ }}outgoingMediaItems = mergedItems.length ? slimPersistedMediaRecords(mergedItems) : undefined;outgoingFiles = Object.keys(mergedFiles).length ? mergedFiles : undefined;diff --git a/jiuwenswarm/channels/web/frontend/src/main.tsx b/jiuwenswarm/channels/web/frontend/src/main.tsxindex 453fc45445..cf4003b9f7 100644--- a/jiuwenswarm/channels/web/frontend/src/main.tsx+++ b/jiuwenswarm/channels/web/frontend/src/main.tsx@@ -5,11 +5,15 @@ import type { A2UIClientEventMessage } from '@a2ui/react';import { injectStyles } from '@a2ui/react/styles';import App from './App.tsx'import { dispatchA2UIAction } from './features/a2ui/actionBridge';+import { installDesktopLocalFilesBridge } from './features/workspace/localFilePicker';import './styles/foundation.css'import './styles/themes/default/light.css'import './index.css'import './features/a2ui/a2ui.css'+// Durable desktop drop bridge — must exist before ChatPanel mounts / effect cleanup.+installDesktopLocalFilesBridge();+function flagA2UIIconFontAvailability() {if (typeof document === 'undefined' || !('fonts' in document)) {returndiff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsxindex 89b844a680..429f1b4968 100644--- a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx@@ -32,6 +32,7 @@ import {isProjectDirectoryPickerSupported,selectProjectDirectory,} from '../../features/workspace/projectDirectoryPicker';+import { toDisplaySessionTitle } from '../../utils/documentMessage';import './ConversationSidebar.css';import '../dialogs/dialogs.css';import AddProjectIcon from '../../assets/work-mode/add-project.svg?react';@@ -122,7 +123,8 @@ export function formatRelativeTime(}function getSessionTitle(session: Session, fallback: string): string {- return session.display_title?.trim() || session.title?.trim() || fallback;+ const raw = session.display_title?.trim() || session.title?.trim() || fallback;+ return toDisplaySessionTitle(raw) || fallback;}const menuIconByAction: Record<SidebarMenuAction, React.ComponentType<React.SVGProps<SVGSVGElement>>> = {diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts b/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.tsindex fca3dc8d39..0ab7243dba 100644--- a/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts@@ -7,6 +7,7 @@ import {useTodoStore,} from '../../stores';import type { AgentMode, Session } from '../../types';+import { toDisplaySessionTitle } from '../../utils/documentMessage';export const NEW_CONVERSATION_ID = 'new';@@ -19,7 +20,7 @@ interface ConversationRuntimeSettings {const locallyCreatedConversations = new Map<string, Session>();export function createConversationTitle(content: string): string {- return content.replace(/\{\{skill:[^}]+\}\}/g, '').trim().replace(/\n/g, ' ');+ return toDisplaySessionTitle(content.replace(/\{\{skill:[^}]+\}\}/g, ''));}function applyRuntimeSettings(diff --git a/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.ts b/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.tsindex 58d09f921e..b0bb2db6ed 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.ts@@ -1,13 +1,87 @@+/** Agent-facing hint block listing this turn's uploaded documents. */+export const UPLOAD_DOCUMENT_BLOCK_HEADER = '【上传文档】';++export interface UploadDocumentHint {+ filename: string;+ path?: string;+ /**+ * Preferred absolute path for `@path` refs. When set and different from+ * `path`, this wins (legacy sidecar cases); otherwise equals `path`.+ */+ originalPath?: string;+}++/** Quote `@path` when the path contains whitespace. */+export function formatAtPath(path: string): string {+ return /\s/.test(path) ? `@"${path}"` : `@${path}`;+}+/** Strip agent document-hint blocks from user-visible bubble text. */export function stripUploadDocumentBlocks(content: string): string {if (!content || !content.includes('【上传文档')) {return content;}+ // Document hints are always appended after the user query — drop from the+ // marker through the end so titles / bubbles only keep the query text.return content- // New compact form: 【上传文档】 plus following "- name: path" lines.- .replace(/(?:^|\n+)【上传文档】(?:\n-[^\n]*)*/g, '')- // Legacy per-file blocks: 【上传文档: name】 / 路径 / 说明- .replace(/(?:^|\n+)【上传文档[::][^\n]*(?:\n(?!【)[^\n]*)*/g, '')+ .replace(/【上传文档】[\s\S]*$/u, '')+ .replace(/【上传文档[::][\s\S]*$/u, '').replace(/\n{3,}/g, '\n\n').trim();}++/** Session / header title: strip document hints and collapse whitespace. */+export function toDisplaySessionTitle(title: string): string {+ return stripUploadDocumentBlocks(title).replace(/\s+/g, ' ').trim();+}++/**+ * Append the agent-facing document hint block to `text`.+ *+ * Format:+ * 【上传文档】+ * @/abs/path+ *+ * Any block already present is stripped first, so calling this again with+ * freshly persisted records replaces incomplete lines with real `@path` refs.+ * Entries without a path are skipped.+ */+export function withUploadDocumentBlock(text: string, docs: UploadDocumentHint[]): string {+ const base = stripUploadDocumentBlocks(text);+ if (!docs.length) {+ return base;+ }+ const lines = docs+ .map((doc) => {+ const path = (doc.originalPath || doc.path || '').trim();+ return path ? formatAtPath(path) : '';+ })+ .filter(Boolean);+ if (!lines.length) {+ return base;+ }+ return [base, UPLOAD_DOCUMENT_BLOCK_HEADER, ...lines].filter(Boolean).join('\n');+}++function readString(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim() ? value : undefined;+}++/** Extract document hints from persisted `media_items` returned by document.persist. */+export function toUploadDocumentHints(mediaItems: unknown): UploadDocumentHint[] {+ if (!Array.isArray(mediaItems)) {+ return [];+ }+ const hints: UploadDocumentHint[] = [];+ for (const item of mediaItems) {+ if (!item || typeof item !== 'object') continue;+ const record = item as Record<string, unknown>;+ if (record.type !== 'document') continue;+ const path = readString(record.path);+ const originalPath = readString(record.original_path) || path;+ const filename = readString(record.filename) || (path ? path.split(/[\\/]/).pop() : undefined);+ if (!filename) continue;+ hints.push({ filename, path, originalPath });+ }+ return hints;+}diff --git a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts b/jiuwenswarm/channels/web/frontend/src/vite-env.d.tsindex 80a7bad29c..8a7f4382bd 100644--- a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts+++ b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts@@ -16,12 +16,28 @@ type DesktopSaveResult = {};interface Window {+ /** Set by desktop_app.py after the webview page loads. */+ __JIUWEN_DESKTOP__?: boolean;+ /** Set by desktop_app.py when OS file-drag accept handlers are injected. */+ __JIUWEN_DESKTOP_DND__?: boolean;pywebview?: {api?: {download_file?: (url: string, filename: string) => Promise<DesktopSaveResult> | DesktopSaveResult;install_update?: (path: string) => Promise<boolean> | boolean;save_data_url?: (dataUrl: string, filename: string) => Promise<DesktopSaveResult> | DesktopSaveResult;select_project_directory?: () => Promise<string | null> | string | null;+ select_local_files?: (+ allowMultiple?: boolean,+ initialDir?: string | null,+ ) => Promise<Array<Record<string, unknown>>> | Array<Record<string, unknown>>;+ describe_local_files?: (+ paths: string[],+ ) => Promise<Array<Record<string, unknown>>> | Array<Record<string, unknown>>;+ get_clipboard_files?: () =>+ | Promise<Array<Record<string, unknown>>>+ | Array<Record<string, unknown>>;};};+ /** Durable ingest hook invoked by desktop_app.py run_js on native file drops. */+ __JIUWEN_INGEST_LOCAL_FILES__?: (detail: unknown) => void;}diff --git a/jiuwenswarm/common/document_parser.py b/jiuwenswarm/common/document_parser.pydeleted file mode 100644index 4bea313b3d..0000000000--- a/jiuwenswarm/common/document_parser.py+++ /dev/null@@ -1,219 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Shared document parsing helpers for Web upload and Agent tools.--Wraps openjiuwen ``AutoFileParser`` and adds ``.ipynb`` support (not registered-in AutoFileParser by default).-"""--from __future__ import annotations--import json-import logging-from pathlib import Path-from typing import Any--logger = logging.getLogger(__name__)--DEFAULT_MAX_CHARS = 50_000-_IPYNB_REGISTERED = False--# Formats accepted by the Web document upload/parse API.-SUPPORTED_DOCUMENT_EXTENSIONS: frozenset[str] = frozenset(- {- ".pdf",- ".docx",- ".xlsx",- ".csv",- ".tsv",- ".txt",- ".md",- ".markdown",- ".html",- ".htm",- ".json",- ".ipynb",- }-)--SUPPORTED_DOCUMENT_MIME_TYPES: dict[str, str] = {- "application/pdf": ".pdf",- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",- "text/csv": ".csv",- "application/csv": ".csv",- "text/tab-separated-values": ".tsv",- "text/plain": ".txt",- "text/markdown": ".md",- "text/x-markdown": ".md",- "text/html": ".html",- "application/xhtml+xml": ".html",- "application/json": ".json",- "application/x-ipynb+json": ".ipynb",- "application/jupyter": ".ipynb",- "application/vnd.jupyter": ".ipynb",-}---def resolve_document_suffix(*, filename: str | None, mime_type: str | None) -> str | None:- """Resolve a supported document suffix from filename and/or MIME type."""- mime = (mime_type or "").lower().strip()- if mime in SUPPORTED_DOCUMENT_MIME_TYPES:- return SUPPORTED_DOCUMENT_MIME_TYPES[mime]-- name = Path(str(filename or "")).name- suffix = Path(name).suffix.lower()- if suffix in SUPPORTED_DOCUMENT_EXTENSIONS:- return suffix- return None---def is_supported_document(*, filename: str | None = None, mime_type: str | None = None) -> bool:- return resolve_document_suffix(filename=filename, mime_type=mime_type) is not None---def _ensure_ipynb_parser_registered() -> None:- """Register a lightweight IpynbParser into AutoFileParser once."""- global _IPYNB_REGISTERED- if _IPYNB_REGISTERED:- return-- from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import (- AutoFileParser,- _PARSER_REGISTRY,- )- from openjiuwen.core.retrieval.indexing.processor.parser.base import Parser-- if ".ipynb" in _PARSER_REGISTRY:- _IPYNB_REGISTERED = True- return-- class IpynbParser(Parser):- """Parse Jupyter notebook cells into readable Markdown-ish text."""-- async def _parse(self, file_path: str, *args, **kwargs) -> str | None:- path = Path(file_path)- raw = path.read_text(encoding="utf-8", errors="replace")- notebook = json.loads(raw)- cells = notebook.get("cells") or []- blocks: list[str] = []- for idx, cell in enumerate(cells, 1):- if not isinstance(cell, dict):- continue- cell_type = str(cell.get("cell_type") or "unknown")- source = cell.get("source") or []- if isinstance(source, list):- source_text = "".join(str(part) for part in source)- else:- source_text = str(source)- blocks.append(f"## Cell {idx} [{cell_type}]")- if source_text.strip():- blocks.append(source_text.rstrip("\n"))- outputs = cell.get("outputs") or []- if not isinstance(outputs, list) or not outputs:- continue- blocks.append("### Outputs")- for out in outputs:- if not isinstance(out, dict):- continue- text = ""- if "text" in out:- text_val = out.get("text")- text = "".join(text_val) if isinstance(text_val, list) else str(text_val or "")- elif isinstance(out.get("data"), dict):- plain = out["data"].get("text/plain")- if isinstance(plain, list):- text = "".join(str(part) for part in plain)- elif isinstance(plain, str):- text = plain- elif "ename" in out and "evalue" in out:- text = f"{out.get('ename')}: {out.get('evalue')}"- if text:- blocks.append(text.rstrip("\n"))- return "\n".join(blocks).strip() or None-- AutoFileParser.register_new_parser(".ipynb", IpynbParser)- _IPYNB_REGISTERED = True---async def parse_document_file(- file_path: str | Path,- *,- max_chars: int | None = DEFAULT_MAX_CHARS,- doc_id: str = "",-) -> dict[str, Any]:- """Parse a local document and return text plus metadata.-- Args:- max_chars: Truncate returned text to this many characters. Pass ``None``- to keep the full parsed text (used when writing ``.txt`` sidecars).-- Returns:- dict with keys: text, truncated, parser, file_ext, char_count, documents_count- """- path = Path(file_path)- if not path.is_file():- raise FileNotFoundError(f"File not found: {path}")-- suffix = path.suffix.lower()- if suffix not in SUPPORTED_DOCUMENT_EXTENSIONS:- raise ValueError(- f"Unsupported format: {suffix}. Supported: {sorted(SUPPORTED_DOCUMENT_EXTENSIONS)}"- )-- _ensure_ipynb_parser_registered()-- from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import AutoFileParser-- parser = AutoFileParser()- output_dir = str(path.parent / ".parsed_images")- docs = await parser.parse(- str(path),- doc_id=doc_id or path.stem,- file_name=path.name,- output_dir=output_dir,- )- if not docs:- return {- "text": "",- "truncated": False,- "parser": "AutoFileParser",- "file_ext": suffix,- "char_count": 0,- "documents_count": 0,- }-- # Prefer the concrete parser name from registry when available.- from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import (- _PARSER_REGISTRY,- )-- concrete = _PARSER_REGISTRY.get(suffix)- parser_name = concrete().__class__.__name__ if concrete else "AutoFileParser"-- parts: list[str] = []- for doc in docs:- text = getattr(doc, "text", None)- if text:- parts.append(str(text))- joined = "\n\n".join(parts).strip()- full_len = len(joined)- truncated = False- if max_chars is not None:- limit = max(1, int(max_chars))- if full_len > limit:- joined = joined[:limit] + f"\n\n[内容过长已截断,完整约 {full_len} 字符]"- truncated = True-- return {- "text": joined,- "truncated": truncated,- "parser": parser_name,- "file_ext": suffix,- "char_count": full_len,- "documents_count": len(docs),- }---def supported_formats() -> list[str]:- """Return sorted list of supported extensions (including .ipynb)."""- return sorted(SUPPORTED_DOCUMENT_EXTENSIONS)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex e94d8115ea..f57967061f 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -115,11 +115,9 @@ from jiuwenswarm.common.local_env_config import (from jiuwenswarm.extensions.extension_config_sync import update_extensions_in_configfrom jiuwenswarm.gateway.media_attachments import normalize_chat_media_attachmentsfrom jiuwenswarm.gateway.document_attachments import (- coerce_document_parse_flag,- parse_existing_document,+ forbidden_formats,persist_and_parse_documents,)-from jiuwenswarm.common.document_parser import DEFAULT_MAX_CHARS, supported_formatsfrom jiuwenswarm.server.runtime.session import project_storefrom jiuwenswarm.symphony.skill_retrieval.taxonomy_config import (coerce_root_categories_value,@@ -4744,6 +4742,90 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path, "headless": headless})+ async def _path_select_directory(ws, req_id, params, session_id):+ """在服务端本机弹出系统文件夹对话框(浏览器 / whl 包回退方案)。++ 桌面端 pywebview 已提供 ``select_project_directory``;本方法覆盖无该桥接时的+ 纯浏览器访问场景。++ - Windows:tkinter+ - macOS:osascript;+ - Linux:zenity/kdialog/yad/tkinter+ - 不可用时返回 ``UNSUPPORTED``,前端回落到手填绝对路径+ """+ if not isinstance(params, dict):+ params = {}+ initial_dir = params.get("initial_dir")+ if initial_dir is not None and not isinstance(initial_dir, str):+ await channel.send_response(+ ws, req_id, ok=False, error="initial_dir must be string", code="BAD_REQUEST",+ )+ return++ from jiuwenswarm.channels.web.directory_picker import select_directory_native++ try:+ selected = await asyncio.to_thread(+ select_directory_native,+ initial_dir=initial_dir.strip() if isinstance(initial_dir, str) else None,+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("[path.select_directory] picker unavailable: %s", exc)+ await channel.send_response(+ ws, req_id, ok=False, error=str(exc), code="UNSUPPORTED",+ )+ return++ if not selected:+ await channel.send_response(ws, req_id, ok=True, payload={"path": None, "cancelled": True})+ return+ await channel.send_response(ws, req_id, ok=True, payload={"path": selected, "cancelled": False})++ async def _path_select_files(ws, req_id, params, session_id):+ """在服务端本机弹出系统文件对话框(浏览器 / whl 包回退方案)。++ 桌面端 pywebview 已提供 ``select_local_files``;本方法覆盖无该桥接时的+ 纯浏览器访问场景,返回带绝对路径的文件元数据(与桌面端同形)。+ """+ if not isinstance(params, dict):+ params = {}+ initial_dir = params.get("initial_dir")+ if initial_dir is not None and not isinstance(initial_dir, str):+ await channel.send_response(+ ws, req_id, ok=False, error="initial_dir must be string", code="BAD_REQUEST",+ )+ return+ allow_multiple = params.get("allow_multiple", True)+ if not isinstance(allow_multiple, bool):+ await channel.send_response(+ ws, req_id, ok=False, error="allow_multiple must be boolean", code="BAD_REQUEST",+ )+ return++ from jiuwenswarm.channels.web.file_picker import select_and_describe_files++ try:+ selected = await asyncio.to_thread(+ select_and_describe_files,+ allow_multiple=allow_multiple,+ initial_dir=initial_dir.strip() if isinstance(initial_dir, str) else None,+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("[path.select_files] picker unavailable: %s", exc)+ await channel.send_response(+ ws, req_id, ok=False, error=str(exc), code="UNSUPPORTED",+ )+ return++ if selected is None:+ await channel.send_response(+ ws, req_id, ok=True, payload={"files": [], "cancelled": True},+ )+ return+ await channel.send_response(+ ws, req_id, ok=True, payload={"files": selected, "cancelled": False},+ )+async def _memory_compute(ws, req_id, params, session_id):if _HAS_PSUTIL:process = _psutil.Process() # type: ignore[union-attribute]@@ -4786,25 +4868,13 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await channel.send_response(ws, req_id, ok=True, payload=payload)async def _document_persist(ws, req_id, params, session_id):- """Upload documents (PDF/DOCX/XLSX/ipynb/...) and parse via AutoFileParser."""+ """Validate local document paths (blacklist); do not persist or parse content."""if not isinstance(params, dict):await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")returnnormalized = dict(params)- parse = coerce_document_parse_flag(normalized.get("parse", True), default=True)- max_chars_raw = normalized.get("max_chars", DEFAULT_MAX_CHARS)- try:- max_chars = int(max_chars_raw)- except (TypeError, ValueError):- max_chars = DEFAULT_MAX_CHARS- max_chars = max(1, min(max_chars, 500_000))try:- await persist_and_parse_documents(- normalized,- session_id,- parse=parse,- max_chars=max_chars,- )+ await persist_and_parse_documents(normalized)except Exception as exc:logger.exception("[document.persist] failed: %s", exc)await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")@@ -4818,56 +4888,20 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:"files","documents","document_errors",- "supported_formats",+ "forbidden_formats",):if key in normalized:payload[key] = normalized[key]- if "supported_formats" not in payload:- payload["supported_formats"] = supported_formats()+ if "forbidden_formats" not in payload:+ payload["forbidden_formats"] = forbidden_formats()await channel.send_response(ws, req_id, ok=True, payload=payload)- async def _document_parse(ws, req_id, params, session_id):- """Parse an already-uploaded document path with AutoFileParser (+ ipynb)."""- if not isinstance(params, dict):- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")- return- path = str(params.get("path") or "").strip()- if not path:- await channel.send_response(ws, req_id, ok=False, error="path is required", code="BAD_REQUEST")- return- max_chars_raw = params.get("max_chars", DEFAULT_MAX_CHARS)- try:- max_chars = int(max_chars_raw)- except (TypeError, ValueError):- max_chars = DEFAULT_MAX_CHARS- max_chars = max(1, min(max_chars, 500_000))- try:- result = await parse_existing_document(- path,- session_id=session_id,- max_chars=max_chars,- )- except FileNotFoundError as exc:- await channel.send_response(ws, req_id, ok=False, error=str(exc), code="NOT_FOUND")- return- except PermissionError as exc:- await channel.send_response(ws, req_id, ok=False, error=str(exc), code="FORBIDDEN")- return- except ValueError as exc:- await channel.send_response(ws, req_id, ok=False, error=str(exc), code="BAD_REQUEST")- return- except Exception as exc:- logger.exception("[document.parse] failed: %s", exc)- await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")- return- await channel.send_response(ws, req_id, ok=True, payload=result)-async def _document_formats(ws, req_id, params, session_id):await channel.send_response(ws,req_id,ok=True,- payload={"supported_formats": supported_formats()},+ payload={"forbidden_formats": forbidden_formats()},)async def _chat_resume(ws, req_id, params, session_id):@@ -6016,6 +6050,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("path.get", _path_get)channel.register_method("path.set", _path_set)+ channel.register_method("path.select_directory", _path_select_directory)+ channel.register_method("path.select_files", _path_select_files)async def _hooks_list(ws, req_id, params, session_id):from jiuwenswarm.common.hooks_config import load_hooks_config@@ -6038,7 +6074,6 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("chat.send", _chat_send)channel.register_method("media.persist", _media_persist)channel.register_method("document.persist", _document_persist)- channel.register_method("document.parse", _document_parse)channel.register_method("document.formats", _document_formats)channel.register_method("chat.resume", _chat_resume)channel.register_method("chat.interrupt", _chat_interrupt)diff --git a/jiuwenswarm/gateway/document_attachments.py b/jiuwenswarm/gateway/document_attachments.pyindex a26a433152..fe29d3f5f9 100644--- a/jiuwenswarm/gateway/document_attachments.py+++ b/jiuwenswarm/gateway/document_attachments.py@@ -1,74 +1,91 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Helpers for normalizing browser-uploaded document attachments."""+"""Helpers for normalizing browser document attachments.++Documents are not persisted or parsed: the client supplies a local absolute+path, which is validated against the extension blacklist and returned for the+main chat as an ``@path`` reference.+"""from __future__ import annotations-import base64-import binasciiimport logging-import re-from contextlib import suppressfrom pathlib import Pathfrom typing import Any-from jiuwenswarm.common.document_parser import (- DEFAULT_MAX_CHARS,- SUPPORTED_DOCUMENT_EXTENSIONS,- is_supported_document,- parse_document_file,- resolve_document_suffix,- supported_formats,+logger = logging.getLogger(__name__)++# Executable / script / package types rejected by document upload.+FORBIDDEN_DOCUMENT_EXTENSIONS: frozenset[str] = frozenset(+ {+ ".exe",+ ".dll",+ ".msi",+ ".scr",+ ".bat",+ ".cmd",+ ".ps1",+ ".vbs",+ ".wsf",+ ".hta",+ ".jar",+ ".lnk",+ ".bin",+ ".so",+ ".dylib",+ ".app",+ ".dmg",+ ".pkg",+ ".command",+ ".scpt",+ ".scptd",+ ".workflow",+ ".xpc",+ ".bundle",+ ".framework",+ ".kext",+ ".prefpane",+ ".saver",+ ".component",+ })-from jiuwenswarm.common.utils import get_agent_sessions_dir-logger = logging.getLogger(__name__)-_SAFE_FILENAME_RE = re.compile(r"[^A-Za-z0-9._-]+")-_SESSION_ID_RE = re.compile(r"[^A-Za-z0-9._-]+")+def forbidden_formats() -> list[str]:+ """Return sorted list of forbidden upload extensions."""+ return sorted(FORBIDDEN_DOCUMENT_EXTENSIONS)-_MAX_DOCUMENT_BYTES = 30 * 1024 * 1024-_MAX_DOCUMENT_COUNT = 20-# Office binaries that read_file cannot open directly — persist a .txt sidecar.-_OFFICE_TEXT_SIDECAR_SUFFIXES = frozenset({".docx", ".xlsx"})-_TRUE_STRINGS = frozenset({"true", "1", "yes"})-_FALSE_STRINGS = frozenset({"false", "0", "no"})+def _document_suffix(filename: str | None) -> str:+ name = Path(str(filename or "")).name+ return Path(name).suffix.lower()-def coerce_document_parse_flag(value: Any, *, default: bool = True) -> bool:- """Normalize document.persist ``parse`` flag without ``bool("false")`` pitfalls.+def is_forbidden_document(*, filename: str | None = None, suffix: str | None = None) -> bool:+ """Return True when the file extension is on the upload blacklist."""+ ext = (suffix or _document_suffix(filename) or "").lower()+ if not ext.startswith(".") and ext:+ ext = f".{ext}"+ return ext in FORBIDDEN_DOCUMENT_EXTENSIONS+++def is_supported_document(*, filename: str | None = None) -> bool:+ """Return True when the filename is allowed for document upload (not blacklisted)."""+ name = Path(str(filename or "")).name.strip()+ if not name or name in {".", ".."}:+ return False+ return not is_forbidden_document(filename=name)- - bool is returned as-is- - strings ``true``/``false``/``1``/``0``/``yes``/``no`` (case-insensitive) are mapped- - any other type/value falls back to ``default``- """- if isinstance(value, bool):- return value- if isinstance(value, str):- normalized = value.strip().lower()- if normalized in _TRUE_STRINGS:- return True- if normalized in _FALSE_STRINGS:- return False- return default- return default---async def persist_and_parse_documents(- params: dict[str, Any],- session_id: str | None,- *,- parse: bool = True,- max_chars: int = DEFAULT_MAX_CHARS,-) -> dict[str, Any]:- """Validate browser document items, persist files, optionally parse, enrich params.++async def persist_and_parse_documents(params: dict[str, Any]) -> dict[str, Any]:+ """Validate document items by local path; do not write or parse content.Accepts either ``params["documents"]`` or ``params["media_items"]`` entries with- ``type == "document"``. Each item must provide base64 payload plus filename/mime.+ ``type == "document"``. Each item must provide an existing local ``path``+ (absolute or expandable) plus filename/mime metadata.Mutates and returns ``params`` with:- - ``media_items``: stored document records (path + optional parsed text)+ - ``media_items``: document records pointing at the original local path- ``files.uploaded_documents``: lightweight path metadata for chat.send"""raw_items = _collect_document_items(params)@@ -78,43 +95,22 @@ async def persist_and_parse_documents(stored: list[dict[str, Any]] = []errors: list[dict[str, Any]] = []- accepted_items = raw_items[:_MAX_DOCUMENT_COUNT]- overflow_items = raw_items[_MAX_DOCUMENT_COUNT:]- if overflow_items:- overflow_count = len(overflow_items)- logger.warning(- "[document.persist] dropping %s document(s) over limit=%s session_id=%s",- overflow_count,- _MAX_DOCUMENT_COUNT,- session_id,- )- for index, item in enumerate(overflow_items, start=_MAX_DOCUMENT_COUNT):- filename = ""- if isinstance(item, dict):- filename = str(item.get("filename") or item.get("name") or "")++ for index, item in enumerate(raw_items):+ try:+ stored_item = _resolve_document_item(item, index=index)+ if stored_item:+ stored.append(stored_item)+ except (ValueError, OSError) as exc:+ # FileNotFoundError is an OSError subclass — do not list both (G.ERR.09).+ logger.warning("[document.persist] rejected item %s: %s", index, exc)errors.append({"index": index,- "filename": filename,- "error": (- f"Document count exceeds limit ({_MAX_DOCUMENT_COUNT}); "- "this item was ignored"- ),- "code": "DOCUMENT_COUNT_LIMIT",+ "filename": str(item.get("filename") or item.get("name") or ""),+ "error": str(exc),})-- for index, item in enumerate(accepted_items):- try:- stored_item = await _store_and_maybe_parse_item(- item,- session_id=session_id,- index=index,- parse=parse,- max_chars=max_chars,- )- if stored_item:- stored.append(stored_item)except Exception as exc:logger.exception("[document.persist] failed for item %s: %s", index, exc)errors.append(@@ -141,12 +137,9 @@ async def persist_and_parse_documents({"filename": item.get("filename"),"path": item.get("path"),- "original_path": item.get("original_path"),- "text_path": item.get("text_path"),+ "original_path": item.get("original_path") or item.get("path"),"mime_type": item.get("mime_type"),"size_bytes": item.get("size_bytes"),- "parser": item.get("parser"),- "text_truncated": item.get("text_truncated"),}for item in stored]@@ -156,64 +149,10 @@ async def persist_and_parse_documents(if errors:params["document_errors"] = errors- params["supported_formats"] = supported_formats()+ params["forbidden_formats"] = forbidden_formats()return params-async def parse_existing_document(- path: str,- *,- session_id: str | None,- max_chars: int = DEFAULT_MAX_CHARS,-) -> dict[str, Any]:- """Parse an already-persisted document path under the session uploads dir."""- safe_path = resolve_session_upload_path(path, session_id=session_id)- result = await parse_document_file(safe_path, max_chars=max_chars)- return {- "type": "document",- "path": str(safe_path),- "filename": safe_path.name,- "text": result["text"],- "text_truncated": result["truncated"],- "parser": result["parser"],- "file_ext": result["file_ext"],- "char_count": result["char_count"],- "documents_count": result["documents_count"],- }---def session_uploads_dir(session_id: str | None) -> Path:- """Return the canonical uploads directory for a session."""- return (get_agent_sessions_dir() / _safe_session_id(session_id) / "uploads").resolve()---def resolve_session_upload_path(path: str | Path, *, session_id: str | None) -> Path:- """Resolve ``path`` and require it to stay under the session uploads directory.-- Prevents path traversal via ``../`` and symlink/junction escapes outside uploads.- """- text = str(path or "").strip()- if not text:- raise ValueError("path is required")-- upload_root = session_uploads_dir(session_id)- try:- resolved = Path(text).expanduser().resolve(strict=False)- except OSError as exc:- raise ValueError(f"Invalid path: {text}") from exc-- try:- resolved.relative_to(upload_root)- except ValueError as exc:- raise PermissionError(- f"path must be under session uploads directory: {upload_root}"- ) from exc-- if not resolved.is_file():- raise FileNotFoundError(f"File not found: {resolved}")- return resolved--def _collect_document_items(params: dict[str, Any]) -> list[dict[str, Any]]:items: list[dict[str, Any]] = []documents = params.get("documents")@@ -231,195 +170,46 @@ def _collect_document_items(params: dict[str, Any]) -> list[dict[str, Any]]:if item_type == "document" or (item_type is Noneand is_supported_document(- filename=str(item.get("filename") or item.get("name") or ""),- mime_type=str(item.get("mimeType") or item.get("mime_type") or ""),+ filename=str(item.get("filename") or item.get("name") or item.get("path") or ""),)):items.append(item)return items-async def _store_and_maybe_parse_item(- item: dict[str, Any],- *,- session_id: str | None,- index: int,- parse: bool,- max_chars: int,-) -> dict[str, Any] | None:+def _resolve_document_item(item: dict[str, Any], *, index: int) -> dict[str, Any] | None:filename_hint = str(item.get("filename") or item.get("name") or "")mime_type = str(item.get("mimeType") or item.get("mime_type") or "").lower().strip()- suffix = resolve_document_suffix(filename=filename_hint, mime_type=mime_type)- if suffix is None:+ raw_path = str(+ item.get("path") or item.get("original_path") or item.get("originalPath") or ""+ ).strip()+ if not raw_path:raise ValueError(- f"Unsupported document type: filename={filename_hint!r} mime={mime_type!r}. "- f"Supported: {supported_formats()}"+ "Missing local path for document upload; base64 persist is no longer supported")- raw_base64 = item.get("base64Data") or item.get("base64_data")- if not isinstance(raw_base64, str) or not raw_base64.strip():- # Allow re-parse of already-persisted path without base64.- existing_path = str(item.get("path") or "").strip()- if existing_path:- path = resolve_session_upload_path(existing_path, session_id=session_id)- data_size = path.stat().st_size- stored = {- "type": "document",- "filename": path.name,- "mime_type": mime_type or _mime_from_suffix(suffix),- "path": str(path),- "size_bytes": data_size,- }- # Office re-parse / sidecar: always materialize .txt for read_file.- need_office_txt = path.suffix.lower() in _OFFICE_TEXT_SIDECAR_SUFFIXES- if parse or need_office_txt:- await _attach_parse_and_office_txt(- stored,- original_path=path,- parse_meta=parse,- max_chars=max_chars,- )- return stored- raise ValueError("Missing base64Data / base64_data for document upload")-- data: bytes | None = None- with suppress(binascii.Error):- data = base64.b64decode(raw_base64, validate=True)- if not data:- raise ValueError("Invalid base64 document payload")- if len(data) > _MAX_DOCUMENT_BYTES:+ try:+ path = Path(raw_path).expanduser().resolve(strict=False)+ except OSError as exc:+ raise ValueError(f"Invalid path: {raw_path}") from exc++ if not path.is_file():+ raise FileNotFoundError(f"File not found: {path}")++ filename = filename_hint or path.name or f"document-{index + 1}"+ if is_forbidden_document(filename=filename) or is_forbidden_document(filename=path.name):raise ValueError(- f"Document exceeds size limit ({_MAX_DOCUMENT_BYTES // (1024 * 1024)}MB): "- f"{filename_hint or f'document-{index + 1}'}"+ f"Forbidden document type: filename={filename!r} path={path.name!r}. "+ f"Forbidden: {forbidden_formats()}")- safe_session_id = _safe_session_id(session_id)- upload_dir = get_agent_sessions_dir() / safe_session_id / "uploads"- upload_dir.mkdir(parents=True, exist_ok=True)-- fallback = f"document-{index + 1}{suffix}"- filename = _safe_filename(filename_hint or fallback, fallback=fallback)- if Path(filename).suffix.lower() not in SUPPORTED_DOCUMENT_EXTENSIONS:- filename = f"{filename}{suffix}"- path = _unique_path(upload_dir / filename)- path.write_bytes(data)+ data_size = path.stat().st_size- stored = {+ return {"type": "document",- "filename": path.name,- "mime_type": mime_type or _mime_from_suffix(suffix),+ "filename": Path(filename).name,+ "mime_type": mime_type or "application/octet-stream","path": str(path),- "size_bytes": len(data),+ "original_path": str(path),+ "size_bytes": data_size,}- need_office_txt = path.suffix.lower() in _OFFICE_TEXT_SIDECAR_SUFFIXES- if parse or need_office_txt:- await _attach_parse_and_office_txt(- stored,- original_path=path,- parse_meta=parse,- max_chars=max_chars,- )- return stored---async def _attach_parse_and_office_txt(- stored: dict[str, Any],- *,- original_path: Path,- parse_meta: bool,- max_chars: int,-) -> None:- """Parse ``original_path``; for docx/xlsx also write a full ``.txt`` sidecar.-- After a successful sidecar write, ``stored["path"]`` points at the ``.txt``- so Agent ``read_file`` can open it. ``original_path`` / ``text_path`` keep both.- """- suffix = original_path.suffix.lower()- write_sidecar = suffix in _OFFICE_TEXT_SIDECAR_SUFFIXES-- if write_sidecar:- # Full text on disk for read_file (no truncation).- parsed_full = await parse_document_file(original_path, max_chars=None)- text_path = _write_office_text_sidecar(original_path, parsed_full.get("text") or "")- stored["original_path"] = str(original_path)- stored["text_path"] = str(text_path)- # Prefer .txt for downstream read_file / chat path hints.- stored["path"] = str(text_path)- stored["parser"] = parsed_full.get("parser")- stored["char_count"] = parsed_full.get("char_count")- stored["documents_count"] = parsed_full.get("documents_count")- if parse_meta:- full_len = int(parsed_full.get("char_count") or 0)- stored["text_truncated"] = full_len > max(1, int(max_chars))- return-- if not parse_meta:- return-- parsed = await parse_document_file(original_path, max_chars=max_chars)- stored.update(- {- "text_truncated": parsed["truncated"],- "parser": parsed["parser"],- "char_count": parsed["char_count"],- "documents_count": parsed["documents_count"],- }- )---def _write_office_text_sidecar(original_path: Path, text: str) -> Path:- """Write parsed office content next to the original as ``stem.txt``."""- candidate = original_path.with_suffix(".txt")- txt_path = _unique_path(candidate)- txt_path.write_text(text if isinstance(text, str) else str(text or ""), encoding="utf-8")- logger.info(- "[document.persist] wrote office text sidecar original=%s text=%s chars=%s",- original_path.name,- txt_path.name,- len(text or ""),- )- return txt_path---_SUFFIX_TO_MIME: dict[str, str] = {- ".pdf": "application/pdf",- ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",- ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- ".csv": "text/csv",- ".tsv": "text/tab-separated-values",- ".txt": "text/plain",- ".md": "text/markdown",- ".markdown": "text/markdown",- ".html": "text/html",- ".htm": "text/html",- ".json": "application/json",- ".ipynb": "application/x-ipynb+json",-}---def _mime_from_suffix(suffix: str) -> str:- return _SUFFIX_TO_MIME.get(suffix.lower(), "application/octet-stream")---def _safe_session_id(session_id: str | None) -> str:- text = str(session_id or "default").strip() or "default"- return _SESSION_ID_RE.sub("_", text)[:120]---def _safe_filename(filename: str, *, fallback: str) -> str:- name = Path(filename).name.strip()- if not name or name in {".", ".."}:- name = fallback- return _SAFE_FILENAME_RE.sub("_", name)[:180]---def _unique_path(path: Path) -> Path:- if not path.exists():- return path- stem = path.stem- suffix = path.suffix- for idx in range(1, 1000):- candidate = path.with_name(f"{stem}-{idx}{suffix}")- if not candidate.exists():- return candidate- return path.with_name(f"{stem}-overflow{suffix}")diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 8b63e524a3..8c6d297628 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -32,9 +32,11 @@ from jiuwenswarm.server.runtime.agent_adapter.agent_adapters import (resolve_sdk_choice,)from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_auto_memory_enabled, is_memory_enabled+from jiuwenswarm.agents.harness.code.prompt import plan_approval as _plan_approvalfrom jiuwenswarm.server.runtime.session.session_history import (append_compact_history_records,append_history_record,+ collapse_file_content_blocks,)from jiuwenswarm.server.runtime.session.session_manager import SessionManagerfrom jiuwenswarm.server.runtime.session.permission_response_ledger import (@@ -69,6 +71,12 @@ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers importis_interrupt_resume_payload,)+PLAN_REMINDER_ORIGINAL_QUERY_KEY = getattr(+ _plan_approval,+ "PLAN_REMINDER_ORIGINAL_QUERY_KEY",+ "_plan_reminder_original_query",+)+class _TeamPlanApprovalPayloadError(ValueError):"""Raised when a structured team.plan approval payload is malformed."""@@ -133,12 +141,29 @@ def _history_user_content(params: Any, query: Any) -> Any:追加补充/调整请求时,``query`` 是包装后的提示词模板,会把模型提示词暴露到历史记录里。这里优先使用原始用户输入 ``supplement_input`` 作为展示内容。++ 进入 plan 的那一轮同理:``query`` 前面被拼了一段 <system-reminder>,历史里+ 要还原成用户原文,否则重新加载会话会把提示词当成用户提问显示出来。++ Gateway 可能已把 ``@path`` 展开成 ``<file-content>`` 正文;历史只保留 ``@path``,+ 避免 transcript 膨胀,也不影响当轮已发给模型的内联内容。"""- if isinstance(params, dict) and params.get("is_supplement"):+ content: Any+ if not isinstance(params, dict):+ content = query+ elif params.get("is_supplement"):supplement_input = params.get("supplement_input")if isinstance(supplement_input, str) and supplement_input.strip():- return supplement_input- return query+ content = supplement_input+ else:+ content = query+ else:+ original_query = params.get(PLAN_REMINDER_ORIGINAL_QUERY_KEY)+ content = original_query if isinstance(original_query, str) else query++ if isinstance(content, str):+ return collapse_file_content_blocks(content)+ return contentdef _should_record_user_history(params: Any) -> bool:diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex bd7840af98..026281b60e 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -6,6 +6,7 @@ import loggingimport jsonimport osimport queue+import reimport threadingimport timefrom collections import OrderedDict@@ -25,6 +26,42 @@ _LEGACY_HISTORY_FILENAME = "history.json"_JSONL_HISTORY_FILENAME = "history.jsonl"_LEGACY_HISTORY_ENV = "JIUWENSWARM_USE_LEGACY_HISTORY_JSON"_HEARTBEAT_OK = "HEARTBEAT_OK"+_VALID_SESSION_ID = re.compile(+ r"^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,78}[A-Za-z0-9])?$"+)+# Gateway may inline @path as <file-content>...</file-content> before chat.send.+# History should keep the short @path form so jsonl rows stay one physical line+# and refresh UI does not load megabytes of file body.+_FILE_CONTENT_BLOCK_RE = re.compile(+ r"\n?<file-content\s+path=\"([^\"]*)\">.*?</file-content>\n?",+ re.DOTALL,+)+++def collapse_file_content_blocks(content: str) -> str:+ """Replace inlined ``<file-content>`` bodies with ``@path`` references.++ Used when persisting / serving user history so the agent-facing inline+ expansion is not stored as the user-visible transcript.+ """+ if not content or "<file-content" not in content:+ return content++ def _replacer(match: re.Match[str]) -> str:+ path = match.group(1) or ""+ if not path:+ return "\n"+ ref = f'@"{path}"' if any(ch.isspace() for ch in path) else f"@{path}"+ return f"\n{ref}\n"++ collapsed = _FILE_CONTENT_BLOCK_RE.sub(_replacer, content)+ return re.sub(r"\n{3,}", "\n\n", collapsed).strip()+++def is_valid_session_id(session_id: str) -> bool:+ """Return whether a session id is safe to use as one path component."""++ return _VALID_SESSION_ID.fullmatch(session_id) is not None# 缓冲层分两组:普通缓冲层(_session_buffer,合并后批量写)与暂留层(_session_pending,# tool_calls.delta 等对应 chat.tool_call 命中后再决定丢弃/落盘)。@@ -412,8 +449,13 @@ def _read_history_jsonl(path: Path) -> list[dict[str, Any]]:records: list[dict[str, Any]] = []try:- for lineno, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):- line = raw_line.strip()+ # JSONL records are delimited by "\n" only. Do NOT use str.splitlines():+ # inlined file bodies may contain Unicode line separators (U+2028 etc.)+ # that splitlines() treats as breaks, corrupting a single JSON object+ # into fragments and dropping the user turn on refresh.+ text = path.read_text(encoding="utf-8")+ for lineno, raw_line in enumerate(text.split("\n"), start=1):+ line = raw_line.rstrip("\r").strip()if not line:continuetry:@@ -422,6 +464,14 @@ def _read_history_jsonl(path: Path) -> list[dict[str, Any]]:logger.warning("读取 history.jsonl 第 %d 行失败,已跳过: %s", lineno, exc)continueif isinstance(item, dict):+ content = item.get("content")+ if (+ item.get("role") in {"user", "human"}+ and isinstance(content, str)+ and "<file-content" in content+ ):+ item = dict(item)+ item["content"] = collapse_file_content_blocks(content)records.append(item)else:logger.warning(diff --git a/scripts/build-exe.ps1 b/scripts/build-exe.ps1index ef03e7a5da..d2da0bcea8 100644--- a/scripts/build-exe.ps1+++ b/scripts/build-exe.ps1@@ -256,7 +256,11 @@ if (-not $Iscc) {& $Iscc "$ProjectRoot\scripts\installer.iss"if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }-$InstallerPath = (Get-ChildItem "$ProjectRoot\dist\JiuwenSwarm-setup-*.exe" | Select-Object -First 1).FullName+$InstallerPath = (+ Get-ChildItem "$ProjectRoot\dist\JiuwenSwarm-setup-*.exe" |+ Sort-Object LastWriteTime -Descending |+ Select-Object -First 1+).FullNameWrite-Host "`n=== Build complete ===" -ForegroundColor GreenWrite-Host "Installer: $InstallerPath" -ForegroundColor Greendiff --git a/tests/unit_tests/channels/web/test_file_picker.py b/tests/unit_tests/channels/web/test_file_picker.pynew file mode 100644index 0000000000..6c62c332dc--- /dev/null+++ b/tests/unit_tests/channels/web/test_file_picker.py@@ -0,0 +1,73 @@+from pathlib import Path++from jiuwenswarm.channels.web import file_picker+++def test_remember_and_resolve_last_file_picker_dir(tmp_path: Path, monkeypatch):+ monkeypatch.setattr(file_picker, "_last_dir_state_path", lambda: tmp_path / "last_file_picker_dir.txt")+ target = tmp_path / "uploads"+ target.mkdir()+ nested = target / "notes.txt"+ nested.write_text("x", encoding="utf-8")++ file_picker.remember_file_picker_dir(nested)+ assert file_picker.get_last_file_picker_dir() == str(target.resolve())+ assert file_picker.resolve_file_picker_initial_dir(None) == str(target.resolve())+ override = tmp_path / "other"+ override.mkdir()+ assert file_picker.resolve_file_picker_initial_dir(str(override)) == str(override.resolve())+++def test_describe_local_file_document(tmp_path: Path):+ path = tmp_path / "notes.txt"+ path.write_text("hello", encoding="utf-8")++ item = file_picker.describe_local_file(path)++ assert item is not None+ assert item["kind"] == "document"+ assert item["filename"] == "notes.txt"+ assert item["path"] == str(path.resolve())+ assert item["size"] == 5+ assert "base64" not in item+ assert "error" not in item+++def test_describe_local_file_image_includes_base64(tmp_path: Path):+ path = tmp_path / "pic.png"+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 16)++ item = file_picker.describe_local_file(path)++ assert item is not None+ assert item["kind"] == "image"+ assert item["filename"] == "pic.png"+ assert item["base64"]+ assert "error" not in item+++def test_describe_local_file_forbidden_extension(tmp_path: Path):+ path = tmp_path / "setup.exe"+ path.write_bytes(b"MZ")++ item = file_picker.describe_local_file(path)++ assert item is not None+ assert item["kind"] == "document"+ assert item["error"] == "forbidden"+++def test_attachment_dialog_extensions_exclude_blacklist():+ for ext in (".exe", ".dll", ".msi", ".bat", ".ps1", ".dmg", ".app"):+ assert ext not in file_picker.ATTACHMENT_DIALOG_EXTENSIONS+ assert ".txt" in file_picker.ATTACHMENT_DIALOG_EXTENSIONS+ assert ".png" in file_picker.ATTACHMENT_DIALOG_EXTENSIONS+++def test_tk_filetypes_omit_all_files_mask():+ filetypes = file_picker._tk_filetypes()+ assert len(filetypes) == 1+ assert filetypes[0][0] == "Allowed files"+ assert "*.*" not in filetypes[0][1]+ assert "*.txt" in filetypes[0][1]+ assert "*.exe" not in filetypes[0][1]diff --git a/tests/unit_tests/gateway/test_document_attachments.py b/tests/unit_tests/gateway/test_document_attachments.pyindex 3cc2626214..01e9b18a94 100644--- a/tests/unit_tests/gateway/test_document_attachments.py+++ b/tests/unit_tests/gateway/test_document_attachments.py@@ -2,284 +2,119 @@from __future__ import annotations-import base64-import jsonfrom pathlib import Pathimport pytest-from jiuwenswarm.common.document_parser import (- is_supported_document,- parse_document_file,- resolve_document_suffix,- supported_formats,-)from jiuwenswarm.gateway.document_attachments import (- coerce_document_parse_flag,- parse_existing_document,+ FORBIDDEN_DOCUMENT_EXTENSIONS,+ forbidden_formats,+ is_forbidden_document,+ is_supported_document,persist_and_parse_documents,- resolve_session_upload_path,)@pytest.mark.asyncio-async def test_persist_and_parse_documents_reports_count_limit(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-):- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",- lambda: tmp_path,- )- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments._MAX_DOCUMENT_COUNT",- 2,- )+async def test_persist_accepts_many_documents_without_count_limit(tmp_path: Path):documents = []- for idx in range(4):- content = f"# doc {idx}"+ for idx in range(25):+ doc = tmp_path / f"doc-{idx}.md"+ doc.write_text(f"# doc {idx}", encoding="utf-8")documents.append({- "filename": f"doc-{idx}.md",+ "filename": doc.name,"mime_type": "text/markdown",- "base64_data": base64.b64encode(content.encode("utf-8")).decode("ascii"),+ "path": str(doc),})- result = await persist_and_parse_documents(- {"documents": documents},- "sess_limit",- parse=True,- max_chars=1000,- )- items = result.get("media_items") or []- assert len(items) == 2- errors = result.get("document_errors") or []- assert len(errors) == 2- assert errors[0]["index"] == 2- assert errors[0]["code"] == "DOCUMENT_COUNT_LIMIT"- assert "limit" in errors[0]["error"].lower()- assert errors[1]["filename"] == "doc-3.md"-+ result = await persist_and_parse_documents({"documents": documents})-def test_coerce_document_parse_flag():- assert coerce_document_parse_flag(True) is True- assert coerce_document_parse_flag(False) is False- assert coerce_document_parse_flag("false") is False- assert coerce_document_parse_flag("FALSE") is False- assert coerce_document_parse_flag("0") is False- assert coerce_document_parse_flag("true") is True- assert coerce_document_parse_flag("yes") is True- # 非空但无法识别的字符串 / 其它类型:回退默认 True- assert coerce_document_parse_flag("maybe") is True- assert coerce_document_parse_flag(1) is True- assert coerce_document_parse_flag(0, default=True) is True- assert coerce_document_parse_flag(None, default=True) is True- assert coerce_document_parse_flag("", default=False) is False+ items = result.get("media_items") or []+ assert len(items) == 25+ assert not result.get("document_errors")-def test_supported_formats_include_ipynb_and_office():- formats = set(supported_formats())- assert ".ipynb" in formats- assert ".pdf" in formats- assert ".docx" in formats- assert ".xlsx" in formats- assert ".md" in formats+def test_forbidden_formats_include_executables():+ formats = set(forbidden_formats())+ assert formats == set(FORBIDDEN_DOCUMENT_EXTENSIONS)+ assert ".exe" in formats+ assert ".dll" in formats+ assert ".ps1" in formats+ assert ".dmg" in formats+ assert ".pdf" not in formats-def test_resolve_document_suffix_from_mime_and_filename():- assert resolve_document_suffix(filename="a.PDF", mime_type="") == ".pdf"- assert (- resolve_document_suffix(- filename="x.bin",- mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",- )- == ".docx"- )+def test_document_blacklist_helpers():assert is_supported_document(filename="note.ipynb")+ assert is_supported_document(filename="report.docx")assert not is_supported_document(filename="a.exe")+ assert is_forbidden_document(filename="malware.bin")+ assert is_forbidden_document(suffix=".ps1")+ assert not is_forbidden_document(filename="readme.md")@pytest.mark.asyncio-async def test_parse_ipynb_and_markdown(tmp_path: Path):- nb = {- "cells": [- {"cell_type": "markdown", "source": ["# Title\n"]},- {- "cell_type": "code",- "source": ["print(1)\n"],- "outputs": [{"text": ["1\n"]}],- },- ],- "metadata": {},- "nbformat": 4,- "nbformat_minor": 5,- }- ipynb_path = tmp_path / "demo.ipynb"- ipynb_path.write_text(json.dumps(nb), encoding="utf-8")- parsed_nb = await parse_document_file(ipynb_path, max_chars=5000)- assert "Cell 1" in parsed_nb["text"]- assert "print(1)" in parsed_nb["text"]- assert parsed_nb["parser"] == "IpynbParser"-- md_path = tmp_path / "note.md"- md_path.write_text("# Hello\n\nworld", encoding="utf-8")- parsed_md = await parse_document_file(md_path, max_chars=5000)- assert "Hello" in parsed_md["text"]- assert parsed_md["file_ext"] == ".md"---async def test_persist_and_parse_documents(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",- lambda: tmp_path,- )+async def test_persist_documents_returns_original_path_without_writing(tmp_path: Path):content = "# uploaded doc\n\ncontent"+ source = tmp_path / "readme.md"+ source.write_text(content, encoding="utf-8")+payload = {"documents": [{"filename": "readme.md","mime_type": "text/markdown",- "base64_data": base64.b64encode(content.encode("utf-8")).decode("ascii"),+ "path": str(source),}]}- result = await persist_and_parse_documents(payload, "sess_test", parse=True, max_chars=1000)+ result = await persist_and_parse_documents(payload)+items = result.get("media_items") or []assert len(items) == 1assert items[0]["type"] == "document"- assert Path(items[0]["path"]).is_file()- assert items[0]["text_truncated"] is False+ assert Path(items[0]["path"]) == source.resolve()+ assert items[0]["original_path"] == items[0]["path"]assert "text" not in items[0]+ assert "parser" not in items[0]assert result["files"]["uploaded_documents"][0]["path"] == items[0]["path"]@pytest.mark.asyncio-async def test_persist_docx_writes_txt_sidecar(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",- lambda: tmp_path,- )-- async def fake_parse(file_path, *, max_chars=None, doc_id=""):- return {- "text": "parsed office body",- "truncated": False,- "parser": "FakeDocxParser",- "file_ext": Path(file_path).suffix.lower(),- "char_count": len("parsed office body"),- "documents_count": 1,+async def test_persist_rejects_forbidden_extension(tmp_path: Path):+ exe = tmp_path / "setup.exe"+ exe.write_bytes(b"MZ")+ result = await persist_and_parse_documents(+ {+ "documents": [+ {+ "filename": "setup.exe",+ "path": str(exe),+ }+ ]}-- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.parse_document_file",- fake_parse,)-- # Minimal non-empty payload; content is not really a docx — parser is mocked.- payload = {- "documents": [- {- "filename": "report.docx",- "mime_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",- "base64_data": base64.b64encode(b"fake-docx-bytes").decode("ascii"),- }- ]- }- result = await persist_and_parse_documents(payload, "sess_office", parse=True, max_chars=1000)- items = result.get("media_items") or []- assert len(items) == 1- item = items[0]- assert item["filename"] == "report.docx"- assert Path(item["original_path"]).suffix == ".docx"- assert Path(item["original_path"]).is_file()- assert Path(item["text_path"]).suffix == ".txt"- assert Path(item["text_path"]).is_file()- assert item["path"] == item["text_path"]- assert Path(item["path"]).read_text(encoding="utf-8") == "parsed office body"- assert result["files"]["uploaded_documents"][0]["path"] == item["text_path"]- assert result["files"]["uploaded_documents"][0]["original_path"] == item["original_path"]+ assert not result.get("media_items")+ errors = result.get("document_errors") or []+ assert len(errors) == 1+ assert "forbidden" in errors[0]["error"].lower()@pytest.mark.asyncio-async def test_persist_xlsx_writes_txt_sidecar_even_when_parse_false(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-):- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",- lambda: tmp_path,- )-- async def fake_parse(file_path, *, max_chars=None, doc_id=""):- return {- "text": "sheet A1 value",- "truncated": False,- "parser": "FakeXlsxParser",- "file_ext": ".xlsx",- "char_count": 14,- "documents_count": 1,+async def test_persist_rejects_missing_path():+ result = await persist_and_parse_documents(+ {+ "documents": [+ {+ "filename": "readme.md",+ "mime_type": "text/markdown",+ "base64_data": "YWJj",+ }+ ]}-- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.parse_document_file",- fake_parse,- )-- payload = {- "documents": [- {- "filename": "data.xlsx",- "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- "base64_data": base64.b64encode(b"fake-xlsx-bytes").decode("ascii"),- }- ]- }- result = await persist_and_parse_documents(payload, "sess_xlsx", parse=False, max_chars=1000)- item = (result.get("media_items") or [])[0]- assert Path(item["original_path"]).suffix == ".xlsx"- assert Path(item["path"]).suffix == ".txt"- assert Path(item["path"]).read_text(encoding="utf-8") == "sheet A1 value"---def test_resolve_session_upload_path_blocks_traversal(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-):- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",- lambda: tmp_path,)- upload_dir = tmp_path / "sess_test" / "uploads"- upload_dir.mkdir(parents=True)- safe_file = upload_dir / "note.md"- safe_file.write_text("hello", encoding="utf-8")-- outside = tmp_path / "secret.json"- outside.write_text('{"token":"x"}', encoding="utf-8")-- resolved = resolve_session_upload_path(str(safe_file), session_id="sess_test")- assert resolved == safe_file.resolve()-- with pytest.raises(PermissionError):- resolve_session_upload_path(str(outside), session_id="sess_test")-- with pytest.raises(PermissionError):- resolve_session_upload_path(- str(upload_dir / ".." / ".." / "secret.json"),- session_id="sess_test",- )-- with pytest.raises(PermissionError):- resolve_session_upload_path("../../../secret.json", session_id="sess_test")---async def test_parse_existing_document_rejects_outside_uploads(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-):- monkeypatch.setattr(- "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",- lambda: tmp_path,- )- outside = tmp_path / "leak.md"- outside.write_text("# secret", encoding="utf-8")- with pytest.raises(PermissionError):- await parse_existing_document(str(outside), session_id="sess_test", max_chars=1000)+ assert not result.get("media_items")+ errors = result.get("document_errors") or []+ assert len(errors) == 1+ assert "path" in errors[0]["error"].lower()diff --git a/tests/unit_tests/test_desktop_local_file_picker.py b/tests/unit_tests/test_desktop_local_file_picker.pynew file mode 100644index 0000000000..a7f0fcb577--- /dev/null+++ b/tests/unit_tests/test_desktop_local_file_picker.py@@ -0,0 +1,120 @@+from pathlib import Path++from jiuwenswarm.channels.desktop import desktop_app+++def _runtime() -> desktop_app.DesktopRuntime:+ return desktop_app.DesktopRuntime(+ frontend_host="127.0.0.1",+ ports={+ "app": 19001,+ "web": 19000,+ "frontend": 5173,+ "tui": 19002,+ "third_party": 19003,+ },+ )+++def test_describe_local_file_document(tmp_path: Path):+ path = tmp_path / "notes.txt"+ path.write_text("hello", encoding="utf-8")++ item = desktop_app.DesktopRuntime._describe_local_file(path)++ assert item is not None+ assert item["kind"] == "document"+ assert item["filename"] == "notes.txt"+ assert item["path"] == str(path.resolve())+ assert item["size"] == 5+ assert "base64" not in item+ assert "error" not in item+++def test_describe_local_file_image_includes_base64(tmp_path: Path):+ path = tmp_path / "pic.png"+ # Minimal valid-enough bytes for base64 packaging (not a real PNG decode check).+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 16)++ item = desktop_app.DesktopRuntime._describe_local_file(path)++ assert item is not None+ assert item["kind"] == "image"+ assert item["filename"] == "pic.png"+ assert item["base64"]+ assert "error" not in item+++def test_describe_local_file_forbidden_extension(tmp_path: Path):+ path = tmp_path / "setup.exe"+ path.write_bytes(b"MZ")++ item = desktop_app.DesktopRuntime._describe_local_file(path)++ assert item is not None+ assert item["kind"] == "document"+ assert item["error"] == "forbidden"+++def test_attachment_open_file_types_excludes_blacklist():+ file_types = desktop_app.attachment_open_file_types()+ assert len(file_types) == 1+ filter_text = file_types[0]+ assert filter_text.startswith("Allowed files (")+ assert "*.*" not in filter_text+ assert "*.txt" in filter_text+ assert "*.png" in filter_text+ for ext in (".exe", ".dll", ".msi", ".bat", ".ps1", ".dmg", ".app"):+ assert f"*{ext}" not in filter_text+ for ext in desktop_app.FORBIDDEN_DOCUMENT_EXTENSIONS:+ assert f"*{ext}" not in filter_text+++def test_select_local_files_uses_allowed_file_types(monkeypatch, tmp_path: Path):+ from jiuwenswarm.channels.web import file_picker++ runtime = _runtime()+ doc = tmp_path / "a.md"+ doc.write_text("# hi", encoding="utf-8")+ captured: dict[str, object] = {}+ monkeypatch.setattr(file_picker, "_last_dir_state_path", lambda: tmp_path / "last_file_picker_dir.txt")++ class FakeWindow:+ def create_file_dialog(self, *args, **kwargs):+ captured["file_types"] = kwargs.get("file_types")+ captured["directory"] = kwargs.get("directory")+ return [str(doc)]++ runtime.window = FakeWindow()+ results = runtime.select_local_files(allow_multiple=True)++ assert len(results) == 1+ assert results[0]["filename"] == "a.md"+ assert captured["file_types"] == desktop_app.attachment_open_file_types()+ # First open with no memory → user home; selection remembers the file's parent.+ assert captured["directory"] == str(Path.home())+ assert file_picker.get_last_file_picker_dir() == str(tmp_path.resolve())++ # Next open should start in the remembered directory.+ captured.clear()+ runtime.select_local_files(allow_multiple=True)+ assert captured["directory"] == str(tmp_path.resolve())+++def test_window_api_select_local_files_delegates(monkeypatch, tmp_path: Path):+ runtime = _runtime()+ called = {}++ def fake_select(allow_multiple: bool = True, initial_dir: str | None = None):+ called["allow_multiple"] = allow_multiple+ called["initial_dir"] = initial_dir+ return [{"path": str(tmp_path / "x.txt"), "filename": "x.txt", "kind": "document"}]++ monkeypatch.setattr(runtime, "select_local_files", fake_select)+ api = desktop_app._WindowApi(runtime)++ out = api.select_local_files(False)++ assert called["allow_multiple"] is False+ assert called["initial_dir"] is None+ assert out[0]["filename"] == "x.txt"diff --git a/tests/unit_tests/test_session_history_jsonl_read.py b/tests/unit_tests/test_session_history_jsonl_read.pynew file mode 100644index 0000000000..32e5e75390--- /dev/null+++ b/tests/unit_tests/test_session_history_jsonl_read.py@@ -0,0 +1,66 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import json+from pathlib import Path++from jiuwenswarm.server.runtime.agent_adapter.interface import _history_user_content+from jiuwenswarm.server.runtime.session.session_history import (+ collapse_file_content_blocks,+ _read_history_jsonl,+)+++def test_collapse_file_content_blocks_restores_at_path():+ raw = (+ "how many files\n"+ "[upload]\n\n"+ '<file-content path="C:\\Users\\a\\file.txt">\n'+ "line1\nline2\n"+ "</file-content>\n"+ )+ collapsed = collapse_file_content_blocks(raw)+ assert "file-content" not in collapsed+ assert collapsed.startswith("how many files")+ assert "@C:\\Users\\a\\file.txt" in collapsed+++def test_collapse_file_content_quotes_paths_with_spaces():+ raw = '<file-content path="D:\\docs\\my file.txt">hello</file-content>'+ assert collapse_file_content_blocks(raw) == '@"D:\\docs\\my file.txt"'+++def test_history_user_content_strips_inlined_file_body():+ query = (+ "summarize\n[upload]\n"+ '<file-content path="D:\\a.txt">huge body</file-content>'+ )+ got = _history_user_content({"mode": "agent"}, query)+ assert "file-content" not in got+ assert got.startswith("summarize")+ assert "@D:\\a.txt" in got+++def test_read_history_jsonl_keeps_user_row_with_unicode_line_separator(tmp_path: Path):+ """Inlined bodies may contain U+2028; splitlines() must not break the JSONL row."""+ body = "hello\u2028world"+ content = (+ f"ask me\n[upload]\n"+ f'<file-content path="C:\\t.txt">{body}</file-content>'+ )+ record = {+ "id": "r1:user",+ "role": "user",+ "content": content,+ "timestamp": 1.0,+ }+ path = tmp_path / "history.jsonl"+ path.write_text(json.dumps(record, ensure_ascii=False) + "\n", encoding="utf-8")++ rows = _read_history_jsonl(path)+ assert len(rows) == 1+ assert rows[0]["role"] == "user"+ assert "ask me" in rows[0]["content"]+ assert "<file-content" not in rows[0]["content"]+ assert "@C:\\t.txt" in rows[0]["content"]