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
feat(web): 支持图片附件与多模态对话
fyfugoyfad87e428ca9e4
diff --git a/jiuwenswarm/agents/harness/common/prompt/user_prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/user_prompt_builder.pynew file mode 100644index 0000000000..146696e97c--- /dev/null+++ b/jiuwenswarm/agents/harness/common/prompt/user_prompt_builder.py@@ -0,0 +1,364 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""User prompt helpers for multimodal image attachments."""++from __future__ import annotations++import base64+import copy+import json+import mimetypes+from contextvars import ContextVar+from pathlib import Path+from typing import Any++IMAGE_CONTENT_OMITTED = (+ "[Image content omitted from chat-model context. Use the original image "+ "path or a vision tool when image analysis is required.]"+)++_IMAGE_CONTENT_TYPES = frozenset({"image", "image_url", "input_image"})+_VISION_INLINE_IMAGE_MIME_TYPES = frozenset({+ "image/png",+ "image/jpeg",+ "image/webp",+ "image/gif",+})+_MAX_VISION_INLINE_IMAGE_BYTES = 10 * 1024 * 1024+_MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR = "_jiuwenswarm_multimodal_image_window_mutator"+_CURRENT_MULTIMODAL_IMAGE_FILES: ContextVar[tuple[dict[str, Any], ...]] = ContextVar(+ "jiuwenswarm_current_multimodal_image_files",+ default=(),+)+++def is_image_content_block(part: Any) -> bool:+ if not isinstance(part, dict):+ return False+ block_type = str(part.get("type") or "").strip().lower()+ if block_type in _IMAGE_CONTENT_TYPES:+ return True+ return "image_url" in part or "image" in part+++def extract_multimodal_image_files(params: Any) -> list[dict[str, Any]]:+ """Return normalized image-file records from a request payload."""++ if not isinstance(params, dict):+ return []++ candidates: list[Any] = []+ raw_media_items = params.get("media_items")+ if isinstance(raw_media_items, list):+ candidates.extend(raw_media_items)++ files = params.get("files")+ if isinstance(files, dict):+ uploaded_images = files.get("uploaded_images")+ if isinstance(uploaded_images, list):+ candidates.extend(uploaded_images)++ normalized: list[dict[str, Any]] = []+ seen_paths: set[str] = set()+ for item in candidates:+ image = _normalize_image_file(item)+ if not image:+ continue+ path = image["path"]+ if path in seen_paths:+ continue+ seen_paths.add(path)+ normalized.append(image)+ return normalized+++def set_current_multimodal_image_files(image_files: list[dict[str, Any]]) -> Any:+ """Bind request image files to the current Core model-call task."""++ return _CURRENT_MULTIMODAL_IMAGE_FILES.set(tuple(_normalize_image_files(image_files)))+++def reset_current_multimodal_image_files(token: Any) -> None:+ _CURRENT_MULTIMODAL_IMAGE_FILES.reset(token)+++def current_multimodal_image_files() -> list[dict[str, Any]]:+ return list(_CURRENT_MULTIMODAL_IMAGE_FILES.get())+++def prepare_multimodal_image_messages(+ messages: list[Any],+ image_files: list[dict[str, Any]] | None = None,+) -> tuple[list[Any], int]:+ images = _normalize_image_files(image_files or current_multimodal_image_files())+ if not images:+ return messages, 0++ target_index = _latest_user_message_index(messages)+ if target_index < 0:+ return messages, 0++ message = messages[target_index]+ content = (+ message.get("content")+ if isinstance(message, dict)+ else getattr(message, "content", None)+ )+ updated_content, injected = _append_image_files_to_content(content, images)+ if not injected:+ return messages, 0++ updated_messages = list(messages)+ updated_messages[target_index] = _copy_message_with_content(message, updated_content)+ return updated_messages, injected+++def strip_image_content_blocks(content: Any) -> tuple[Any, int]:+ if not isinstance(content, list):+ return content, 0++ kept_parts: list[Any] = []+ removed = 0+ for part in content:+ if is_image_content_block(part):+ removed += 1+ continue+ kept_parts.append(part)++ if not removed:+ return content, 0+ if not kept_parts:+ return IMAGE_CONTENT_OMITTED, removed++ text_parts: list[str] = []+ for part in kept_parts:+ text = _text_from_content_part(part)+ if text is None:+ return kept_parts, removed+ if text:+ text_parts.append(text)+ return "\n".join(text_parts).strip() or IMAGE_CONTENT_OMITTED, removed+++def strip_image_content_from_model_context(context: Any) -> int:+ removed_total = 0+ for message in context.get_messages():+ sanitized_content, removed = strip_image_content_blocks(+ getattr(message, "content", None)+ )+ if not removed:+ continue+ message.content = sanitized_content+ removed_total += removed+ return removed_total+++def prepare_multimodal_image_context_window(+ window: Any,+ image_files: list[dict[str, Any]] | None = None,+) -> tuple[Any, int]:+ context_messages = list(getattr(window, "context_messages", []) or [])+ updated_messages, injected = prepare_multimodal_image_messages(+ context_messages,+ image_files,+ )+ if not injected:+ return window, 0++ model_copy = getattr(window, "model_copy", None)+ if callable(model_copy):+ return model_copy(update={"context_messages": updated_messages}), injected+ window.context_messages = updated_messages+ return window, injected+++def ensure_multimodal_image_window_mutator(+ context: Any,+ image_files: list[dict[str, Any]] | None = None,+) -> bool:+ mutators = getattr(context, "_window_mutators", None)+ if not isinstance(mutators, list):+ return False++ images = _normalize_image_files(+ image_files if image_files is not None else current_multimodal_image_files()+ )+ mutators[:] = [+ mutator+ for mutator in mutators+ if not bool(getattr(mutator, _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR, False))+ ]+ if not images:+ return False++ async def multimodal_image_window_mutator(_context: Any, window: Any) -> Any:+ return prepare_multimodal_image_context_window(window, images)[0]++ setattr(+ multimodal_image_window_mutator,+ _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR,+ True,+ )+ mutators.append(multimodal_image_window_mutator)+ return True+++def _normalize_image_files(image_files: list[dict[str, Any]] | tuple[Any, ...]) -> list[dict[str, Any]]:+ normalized: list[dict[str, Any]] = []+ seen_paths: set[str] = set()+ for item in image_files:+ image = _normalize_image_file(item)+ if not image:+ continue+ path = image["path"]+ if path in seen_paths:+ continue+ seen_paths.add(path)+ normalized.append(image)+ return normalized+++def _normalize_image_file(item: Any) -> dict[str, Any] | None:+ if not isinstance(item, dict):+ return None+ item_type = item.get("type")+ if item_type is not None and item_type != "image":+ return None++ path = str(item.get("path") or "").strip()+ if not path:+ return None++ mime_type = str(item.get("mime_type") or item.get("mimeType") or "").strip().lower()+ if not mime_type:+ mime_type = mimetypes.guess_type(path)[0] or ""+ if mime_type not in _VISION_INLINE_IMAGE_MIME_TYPES:+ return None++ filename = str(item.get("filename") or Path(path).name).strip() or Path(path).name+ image: dict[str, Any] = {+ "type": "image",+ "filename": filename,+ "path": path,+ "mime_type": mime_type,+ }+ size_bytes = item.get("size_bytes")+ if isinstance(size_bytes, int):+ image["size_bytes"] = size_bytes+ return image+++def _latest_user_message_index(messages: list[Any]) -> int:+ for index in range(len(messages) - 1, -1, -1):+ if _is_user_message(messages[index]):+ return index+ return -1+++def _is_user_message(message: Any) -> bool:+ role = (+ message.get("role")+ if isinstance(message, dict)+ else getattr(message, "role", None)+ )+ if str(role or "").lower() == "user":+ return True+ return message.__class__.__name__ == "UserMessage"+++def _append_image_files_to_content(+ content: Any,+ image_files: list[dict[str, Any]],+) -> tuple[Any, int]:+ image_url_parts: list[Any] = []+ injected_files: list[dict[str, Any]] = []+ for image_file in image_files:+ data_uri = _image_data_uri_from_path(image_file["path"], image_file["mime_type"])+ if _append_image_url_part(image_url_parts, data_uri):+ injected_files.append(image_file)+ if not injected_files:+ return content, 0++ parts: list[Any] = [{"type": "text", "text": _build_query_file_text(content, injected_files)}]+ parts.extend(image_url_parts)+ return parts, len(injected_files)+++def _build_query_file_text(content: Any, image_files: list[dict[str, Any]]) -> str:+ """Serialize the user query and attached images as a ``{query, file}`` JSON text block.++ The multimodal image content parts are appended separately; this text block gives the+ model both the original query and the image file paths in a single serialized payload.+ """++ payload = {+ "query": _content_to_query_text(content),+ "file": [+ {+ "filename": image_file["filename"],+ "path": image_file["path"],+ "mime_type": image_file["mime_type"],+ }+ for image_file in image_files+ ],+ }+ return json.dumps(payload, ensure_ascii=False)+++def _content_to_query_text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ texts: list[str] = []+ for part in content:+ text = _text_from_content_part(part)+ if text:+ texts.append(text)+ return "\n".join(texts)+ if content is None:+ return ""+ return str(content)+++def _text_from_content_part(part: Any) -> str | None:+ if isinstance(part, str):+ return part+ if isinstance(part, dict) and isinstance(part.get("text"), str):+ return part["text"]+ return None+++def _image_data_uri_from_path(path_text: str, mime_type: str) -> str:+ path = Path(path_text.strip())+ if not path.is_file():+ return ""+ if mime_type not in _VISION_INLINE_IMAGE_MIME_TYPES:+ return ""+ try:+ data = path.read_bytes()+ except OSError:+ return ""+ if not data or len(data) > _MAX_VISION_INLINE_IMAGE_BYTES:+ return ""+ encoded = base64.b64encode(data).decode("ascii")+ return f"data:{mime_type};base64,{encoded}"+++def _append_image_url_part(parts: list[Any], data_uri: str) -> bool:+ if not data_uri.startswith("data:image/"):+ return False+ parts.append({"type": "image_url", "image_url": {"url": data_uri}})+ return True+++def _copy_message_with_content(message: Any, content: Any) -> Any:+ if isinstance(message, dict):+ updated = dict(message)+ updated["content"] = content+ return updated+ model_copy = getattr(message, "model_copy", None)+ if callable(model_copy):+ return model_copy(update={"content": content})+ updated = copy.copy(message)+ updated.content = content+ return updateddiff --git a/jiuwenswarm/agents/harness/common/rails/__init__.py b/jiuwenswarm/agents/harness/common/rails/__init__.pyindex 1a744cfb4d..b58dac113b 100644--- a/jiuwenswarm/agents/harness/common/rails/__init__.py+++ b/jiuwenswarm/agents/harness/common/rails/__init__.py@@ -14,10 +14,12 @@ from jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail importMemberSkillToolkitRail,)from jiuwenswarm.agents.harness.common.rails.ask_user_rail import StructuredAskUserRail+from jiuwenswarm.agents.harness.common.rails.multimodal_image_rail import MultimodalImageRailfrom jiuwenswarm.agents.harness.common.rails.stream_event_rail import JiuSwarmStreamEventRail__all__ = ["JiuSwarmStreamEventRail",+ "MultimodalImageRail","PermissionInterruptRail","AvatarPromptRail","ProjectMemoryRail",diff --git a/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py b/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.pynew file mode 100644index 0000000000..ce18d68998--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py@@ -0,0 +1,63 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Multimodal image input adaptation for Core model calls."""++from __future__ import annotations++from typing import Any++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.base import DeepAgentRail++from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ current_multimodal_image_files,+ ensure_multimodal_image_window_mutator,+ strip_image_content_from_model_context,+)+from jiuwenswarm.common.utils import logger+++class MultimodalImageRail(DeepAgentRail):+ """Prepare image attachments for native multimodal model input."""++ priority = 75++ def __init__(self, enable_image_multimodal: bool | None = None) -> None:+ super().__init__()+ self._enable_image_multimodal = enable_image_multimodal+ self._deep_agent: Any | None = None++ def init(self, agent: Any) -> None:+ self._deep_agent = agent++ def _read_image_multimodal_enabled(self) -> bool:+ if self._enable_image_multimodal is not None:+ return self._enable_image_multimodal+ deep_config = (+ getattr(self._deep_agent, "deep_config", None)+ or getattr(self._deep_agent, "_deep_config", None)+ )+ return bool(getattr(deep_config, "enable_read_image_multimodal", False))++ async def before_model_call(self, ctx: AgentCallbackContext) -> None:+ if ctx.context is None:+ return+ if self._read_image_multimodal_enabled():+ image_files = current_multimodal_image_files()+ installed = ensure_multimodal_image_window_mutator(+ ctx.context,+ image_files,+ )+ if installed:+ logger.info(+ "Installed multimodal image context-window adapter for %d image attachment(s)",+ len(image_files),+ )+ return++ removed = strip_image_content_from_model_context(ctx.context)+ if removed:+ logger.info(+ "Removed %d image content block(s) from chat-model context",+ removed,+ )diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex d76f04b1ea..97024a806a 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -18,7 +18,6 @@ from openjiuwen.core.context_engine.context.context_utils import ContextUtilsfrom openjiuwen.core.foundation.llm import (AssistantMessage,ToolMessage,- UserMessage,)from openjiuwen.core.session.agent import Sessionfrom openjiuwen.core.session.stream import OutputSchema@@ -27,7 +26,6 @@ from openjiuwen.core.single_agent.rail.base import (InvokeInputs,ToolCallInputs,)-from openjiuwen.core.runner import Runnerfrom openjiuwen.harness.rails.base import DeepAgentRailfrom openjiuwen.harness.schema.task import TodoStatusfrom openjiuwen.harness.tools import TodoListTool@@ -36,14 +34,12 @@ from openjiuwen.harness.workspace.workspace import WorkspaceNodefrom jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (convert_interactions_to_ask_user_question,)+from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ strip_image_content_from_model_context,+)from jiuwenswarm.common.utils import logger_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify"])-_IMAGE_CONTENT_TYPES = frozenset({"image", "image_url", "input_image"})-_IMAGE_CONTENT_OMITTED = (- "[Image content omitted from chat-model context. Use the original image "- "path or a vision tool when image analysis is required.]"-)def _structured_tool_result_payload(result: Any) -> Any | None:@@ -105,50 +101,6 @@ def _parse_tool_call_arguments(tool_call: Any) -> dict[str, Any]:return {}-def _is_image_content_block(part: Any) -> bool:- if not isinstance(part, dict):- return False- block_type = str(part.get("type") or "").strip().lower()- if block_type in _IMAGE_CONTENT_TYPES:- return True- return "image_url" in part or "image" in part---def _text_from_content_part(part: Any) -> str | None:- if isinstance(part, str):- return part- if isinstance(part, dict) and isinstance(part.get("text"), str):- return part["text"]- return None---def _strip_image_content_blocks(content: Any) -> tuple[Any, int]:- if not isinstance(content, list):- return content, 0-- kept_parts: list[Any] = []- removed = 0- for part in content:- if _is_image_content_block(part):- removed += 1- continue- kept_parts.append(part)-- if not removed:- return content, 0- if not kept_parts:- return _IMAGE_CONTENT_OMITTED, removed-- text_parts: list[str] = []- for part in kept_parts:- text = _text_from_content_part(part)- if text is None:- return kept_parts, removed- if text:- text_parts.append(text)- return "\n".join(text_parts).strip() or _IMAGE_CONTENT_OMITTED, removed--def _extract_tool_interrupt(value: Any) -> Any | None:if value is None:return None@@ -342,6 +294,13 @@ class JiuSwarmStreamEventRail(DeepAgentRail):"language", None,) or "cn"+ def _read_image_multimodal_enabled(self) -> bool:+ deep_config = (+ getattr(self._deep_agent, "deep_config", None)+ or getattr(self._deep_agent, "_deep_config", None)+ )+ return bool(getattr(deep_config, "enable_read_image_multimodal", False))+def _tool_interrupted_message(self, tool_name: str) -> str:"""Build a language-aware tool interruption message."""if self._get_prompt_language() == "en":@@ -463,30 +422,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):return Falsereturn self._is_legacy_tool_interrupt_placeholder_text(content, tool_name)- def _read_image_multimodal_enabled(self) -> bool:- deep_config = (- getattr(self._deep_agent, "deep_config", None)- or getattr(self._deep_agent, "_deep_config", None)- )- return bool(getattr(deep_config, "enable_read_image_multimodal", False))-- @staticmethod- def _strip_image_content_from_model_context(context: Any) -> None:- removed_total = 0- for message in context.get_messages():- sanitized_content, removed = _strip_image_content_blocks(- getattr(message, "content", None)- )- if not removed:- continue- message.content = sanitized_content- removed_total += removed- if removed_total:- logger.info(- "Removed %d image content block(s) from chat-model context",- removed_total,- )-def _resolve_sid(self, ctx: AgentCallbackContext, session: Session | None = None) -> str:"""Resolve the per-session key used by this rail.@@ -688,9 +623,9 @@ class JiuSwarmStreamEventRail(DeepAgentRail):raise asyncio.CancelledError("Agent abort requested")if ctx.context is not None:- await self._fix_incomplete_tool_context(ctx)if not self._read_image_multimodal_enabled():- self._strip_image_content_from_model_context(ctx.context)+ strip_image_content_from_model_context(ctx.context)+ await self._fix_incomplete_tool_context(ctx)async def after_model_call(self, ctx: AgentCallbackContext) -> None:await self._emit_context_usage(diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex de0778bb19..3e233b1073 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -42,7 +42,7 @@ import {import { useWebSocket } from './hooks';import { webRequest } from './services/webClient';import { useTeamPanelState } from './features/teamPanelState';-import { AgentMode, UserAnswer, ModelEntry } from './types';+import { AgentMode, MediaItem, UserAnswer, ModelEntry } from './types';import { useSessionStore, useChatStore, useTodoStore, useHarnessStore } from './stores';import { useTranslation } from 'react-i18next';import {@@ -397,6 +397,7 @@ function AppContent() {const {isConnected,request,+ persistMedia,sendMessage,sendStructuredChatContent,pause,@@ -1151,13 +1152,21 @@ function AppContent() {void switchMode(sessionId, mode);}, [sessionId, switchMode]);- const handleSendMessage = useCallback((content: string) => {+ const handleSendMessage = useCallback((content: string, mediaItems?: MediaItem[]) => {const currentSessionId = sessionIdRef.current;if (!currentSessionId || currentSessionId === 'new') return;disposeInFlightHistoryHandles();- void sendMessage(content, currentSessionId);+ void sendMessage(content, currentSessionId, mediaItems);}, [disposeInFlightHistoryHandles, sendMessage]);+ const handlePersistMedia = useCallback((content: string, mediaItems: MediaItem[]) => {+ const currentSessionId = sessionIdRef.current;+ if (!currentSessionId || currentSessionId === 'new') {+ return Promise.reject(new Error('会话未就绪,请稍后重试'));+ }+ return persistMedia(content, currentSessionId, mediaItems);+ }, [persistMedia]);+useEffect(() => {return setA2UIActionHandler((message) => {const currentSessionId = sessionIdRef.current;@@ -1527,6 +1536,7 @@ function AppContent() {<div className={`flex-1 min-h-0 ${isTeamAreaExpanded ? 'card rounded-l-lg rounded-r-none' : ''}`}><ChatPanelonSendMessage={handleSendMessage}+ onPersistMedia={handlePersistMedia}onInterrupt={handleInterrupt}onCancel={handleCancel}onSwitchMode={handleSwitchMode}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.cssindex cea15a8207..17ffc262e9 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css@@ -45,6 +45,18 @@border-color: var(--danger) !important;}+.chat-input-container--dragging {+ border-color: var(--accent);+ box-shadow:+ var(--chat-composer-shadow),+ 0 0 0 2px color-mix(in srgb, var(--accent) 22%, transparent);+}++.chat-input-frame {+ position: relative;+ width: 100%;+}+.chat-active-team-group {width: calc(100% - 48px);margin: 0 auto -1px;@@ -568,6 +580,254 @@opacity: 1;}+.chat-input-attachment-panel {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 12px 14px 4px;+ border-bottom: 1px solid color-mix(in srgb, var(--border) 60%, transparent);+ background: color-mix(in srgb, var(--chat-composer-surface) 96%, var(--bg) 4%);+}++.chat-input-attachment-grid {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: 8px;+ max-height: 124px;+ overflow-y: auto;+ padding-right: 2px;+}++.chat-input-attachment-grid--menu-open {+ overflow: visible;+}++.chat-input-attachment-card {+ position: relative;+ display: grid;+ grid-template-columns: 36px minmax(0, 1fr);+ align-items: center;+ gap: 8px;+ min-width: 0;+ min-height: 48px;+ padding: 6px 28px 6px 6px;+ border: 1px solid color-mix(in srgb, var(--border) 84%, transparent);+ border-radius: 8px;+ background: var(--card);+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);+}++.chat-input-attachment-card--uploading {+ background: color-mix(in srgb, var(--accent) 4%, var(--card));+}++.chat-input-attachment-card--error {+ border-color: color-mix(in srgb, var(--danger) 40%, var(--border));+ background: color-mix(in srgb, var(--danger) 7%, var(--card));+}++.chat-input-attachment-preview {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 36px;+ height: 36px;+ border-radius: 7px;+ overflow: hidden;+ background: color-mix(in srgb, var(--accent) 8%, var(--secondary));+ color: var(--accent);+}++.chat-input-attachment-preview img {+ display: block;+ width: 100%;+ height: 100%;+ object-fit: cover;+}++.chat-input-attachment-main {+ min-width: 0;+}++.chat-input-attachment-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--text);+ font-size: 12px;+ font-weight: 500;+ line-height: 16px;+}++.chat-input-attachment-meta {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ color: var(--muted);+ font-size: 11px;+ line-height: 15px;+}++.chat-input-attachment-card--error .chat-input-attachment-meta {+ color: var(--danger);+ justify-content: space-between;+}++.chat-input-attachment-spin {+ flex: 0 0 auto;+ animation: harness-spin 0.9s linear infinite;+}++.chat-input-attachment-remove {+ position: absolute;+ display: flex;+ align-items: center;+ justify-content: center;+ border: 0;+ border-radius: var(--radius-full);+ cursor: pointer;+}++.chat-input-attachment-remove {+ right: -5px;+ top: -5px;+ width: 17px;+ height: 17px;+ background: color-mix(in srgb, var(--text) 15%, var(--card));+ color: var(--muted-strong);+ box-shadow: 0 1px 4px rgba(15, 23, 42, 0.14);+}++.chat-input-attachment-remove:hover {+ color: var(--text);+ background: color-mix(in srgb, var(--accent) 16%, var(--card));+}++.chat-input-attachment-status-error {+ color: var(--danger);+ font-weight: 500;+}++.chat-input-attachment-retry {+ display: inline-flex;+ align-items: center;+ flex: 0 0 auto;+ margin-left: auto;+ padding: 0;+ border: 0;+ background: transparent;+ color: var(--accent);+ cursor: pointer;+ font: inherit;+ font-weight: 500;+ line-height: inherit;+}++.chat-input-attachment-retry:hover {+ color: color-mix(in srgb, var(--accent) 76%, var(--text));+}++.chat-input-attachment-menu {+ position: absolute;+ right: -92px;+ top: 18px;+ z-index: 5;+ display: flex;+ flex-direction: column;+ gap: 4px;+ width: 92px;+ padding: 6px;+ border: 1px solid color-mix(in srgb, var(--border) 74%, transparent);+ border-radius: 8px;+ background: var(--card);+ box-shadow: 0 10px 28px rgba(15, 23, 42, 0.16);+}++.chat-input-attachment-menu button {+ display: flex;+ align-items: center;+ min-height: 32px;+ padding: 0 12px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--text);+ cursor: pointer;+ font-size: 13px;+ text-align: left;+}++.chat-input-attachment-menu button:hover {+ background: color-mix(in srgb, var(--accent) 9%, transparent);+}++.chat-input-local-alerts {+ position: absolute;+ left: 50%;+ bottom: calc(100% + 16px);+ z-index: 30;+ display: flex;+ flex-direction: column;+ gap: 10px;+ width: min(620px, calc(100vw - 64px));+ transform: translateX(-50%);+ pointer-events: none;+}++.chat-welcome__composer .chat-input-local-alerts {+ bottom: calc(100% + 104px);+}++.chat-input-local-alert {+ display: grid;+ grid-template-columns: 18px minmax(0, 1fr) 22px;+ align-items: center;+ gap: 12px;+ min-height: 52px;+ padding: 0 14px 0 18px;+ border: 1px solid color-mix(in srgb, var(--danger) 22%, transparent);+ border-radius: 10px;+ background: color-mix(in srgb, var(--danger) 13%, var(--card));+ color: var(--text);+ box-shadow: 0 12px 28px rgba(185, 28, 28, 0.12);+ pointer-events: auto;+}++.chat-input-local-alert svg {+ color: var(--danger);+}++.chat-input-local-alert span {+ min-width: 0;+ overflow: hidden;+ color: var(--text);+ font-size: 14px;+ font-weight: 500;+ line-height: 20px;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.chat-input-local-alert button {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ padding: 0;+ border: 0;+ border-radius: var(--radius-full);+ background: transparent;+ color: color-mix(in srgb, var(--muted-strong) 72%, var(--danger));+ cursor: pointer;+}++.chat-input-local-alert button:hover {+ background: color-mix(in srgb, var(--danger) 10%, transparent);+ color: var(--danger);+}+/* Action buttons */.chat-input-actions {display: flex;@@ -615,6 +875,20 @@cursor: not-allowed;}+.chat-input-btn--add-file {+ width: 30px;+ height: 30px;+ flex: 0 0 auto;+ border: 1px solid color-mix(in srgb, var(--border) 80%, transparent);+ border-radius: 6px;+ color: var(--muted-strong);+ background: color-mix(in srgb, var(--card) 88%, transparent);+}++.chat-input-btn--add-file:hover:not(:disabled) {+ border-color: color-mix(in srgb, var(--accent) 34%, var(--border));+}+.chat-input-btn--recording {background: var(--danger) !important;color: white !important;@@ -649,6 +923,39 @@box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 24%, transparent);}+.chat-model-inline {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ max-width: min(260px, 46cqi);+}++.chat-model-inline__name {+ min-width: 0;+ max-width: min(140px, 28cqi);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--muted-strong);+ font-size: 11px;+ line-height: 16px;+ padding: 0 2px;+}++.chat-model-inline__warning {+ max-width: min(128px, 24cqi);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--warning, #a16207);+ background: color-mix(in srgb, var(--warning, #ca8a04) 12%, transparent);+ border-radius: var(--radius-sm);+ font-size: 11px;+ line-height: 18px;+ padding: 0 6px;+}+.chat-input-btn--send {width: 32px;height: 32px;@@ -688,6 +995,15 @@padding-inline: 12px;}+ .chat-input-attachment-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ max-height: 172px;+ }++ .chat-input-attachment-footer {+ flex-direction: column;+ }+.chat-input-toolbar-left {flex: 0 1 auto;gap: 8px;@@ -706,6 +1022,10 @@.chat-model-selector {max-width: 72px;}++ .chat-model-inline__warning {+ display: none;+ }}.share-export-btn {diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsxindex cd0e3e9eb4..413eea98fb 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx@@ -1,18 +1,19 @@-import { useState, useRef, useCallback, KeyboardEvent, useEffect } from 'react';+import { useState, useRef, useCallback, KeyboardEvent, useEffect, ClipboardEvent, DragEvent, ChangeEvent, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { Square } from 'lucide-react';+import { CircleX, FileImage, Loader2, Plus, Square, X } from 'lucide-react';import { useSpeechRecognition } from '../../hooks';// import { stopAllTts } from '../../utils';import { useChatStore, useSessionStore } from '../../stores';-import { AgentMode } from '../../types';+import { AgentMode, MediaItem } from '../../types';import clsx from 'clsx';import { getEvolutionPillLabel } from './evolution-status';import sendIcon from '../../assets/send.svg';import sendActiveIcon from '../../assets/send_active.svg';interface InputAreaProps {- onSubmit: (content: string) => void;+ onSubmit: (content: string, mediaItems?: MediaItem[]) => void;+ onPersistMedia: (content: string, mediaItems: MediaItem[]) => Promise<PersistMediaResponse>;onInterrupt: (newInput?: string) => void;onCancel: () => void;onSwitchMode: (mode: AgentMode) => void;@@ -20,6 +21,124 @@ interface InputAreaProps {onNewSession: () => Promise<void>;}+const ACCEPTED_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);+const MAX_IMAGE_BYTES = 100 * 1024 * 1024;+const MAX_IMAGE_COUNT = 20;++type AttachmentStatus = 'uploading' | 'ready' | 'error';++interface AttachmentDraft {+ id: string;+ filename: string;+ mimeType: string;+ size: number;+ status: AttachmentStatus;+ base64Data?: string;+ previewUrl?: string;+ persistedMediaItem?: Record<string, unknown>;+ error?: string;+ file?: File;+}++interface AttachmentAlert {+ id: string;+ message: string;+}++interface PersistMediaResponse {+ content?: string;+ query?: string;+ media_items?: Record<string, unknown>[];+ files?: Record<string, unknown>;+}++function formatAttachmentSize(size: number): string {+ if (size < 1024) return `${size} B`;+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;+ return `${(size / 1024 / 1024).toFixed(1)} MB`;+}++function makeAttachmentId(file: File): string {+ const random = typeof crypto !== 'undefined' && 'randomUUID' in crypto+ ? crypto.randomUUID()+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`;+ return `${file.name || 'image'}-${file.size}-${random}`;+}++function attachmentToMediaItem(attachment: AttachmentDraft): MediaItem {+ const persisted = attachment.persistedMediaItem;+ const filename = pickString(persisted?.filename) || attachment.filename;+ const mimeType = pickString(persisted?.mime_type, persisted?.mimeType) || attachment.mimeType;+ const sizeBytes = pickNumber(persisted?.size_bytes, persisted?.sizeBytes) ?? attachment.size;+ return {+ type: 'image',+ mimeType,+ mime_type: mimeType,+ filename,+ base64Data: attachment.base64Data,+ path: pickString(persisted?.path),+ sizeBytes,+ size_bytes: sizeBytes,+ };+}++function buildUploadMediaItem(attachment: AttachmentDraft, payload: Pick<AttachmentDraft, 'base64Data'>): MediaItem {+ return {+ type: 'image',+ mimeType: attachment.mimeType,+ filename: attachment.filename,+ base64Data: payload.base64Data,+ };+}++function pickString(...values: unknown[]): string | undefined {+ for (const value of values) {+ if (typeof value === 'string' && value.trim()) {+ return value;+ }+ }+ return undefined;+}++function pickNumber(...values: unknown[]): number | undefined {+ for (const value of values) {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ }+ return undefined;+}++function getImageValidationError(file: File): string | null {+ if (!ACCEPTED_IMAGE_TYPES.has(file.type)) {+ return `文件类型不支持:${file.name || '未命名文件'}`;+ }+ if (file.size > MAX_IMAGE_BYTES) {+ return `文件大小超出限制:${file.name || '未命名文件'}(最大${formatAttachmentSize(MAX_IMAGE_BYTES)})`;+ }+ return null;+}++function readImageFile(file: File): Promise<Pick<AttachmentDraft, 'base64Data' | 'previewUrl'> | null> {+ if (getImageValidationError(file)) {+ return Promise.resolve(null);+ }+ return new Promise((resolve) => {+ const reader = new FileReader();+ reader.onload = () => {+ const result = typeof reader.result === 'string' ? reader.result : '';+ const base64Data = result.includes(',') ? result.split(',')[1] : '';+ if (!base64Data) {+ resolve(null);+ return;+ }+ resolve({ base64Data, previewUrl: result });+ };+ reader.onerror = () => resolve(null);+ reader.readAsDataURL(file);+ });+}+function ClusterIcon({ className }: { className?: string }) {return (<svg className={className} viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">@@ -33,6 +152,7 @@ function ClusterIcon({ className }: { className?: string }) {export function InputArea({onSubmit,+ onPersistMedia,onInterrupt,onCancel,onSwitchMode,@@ -43,9 +163,16 @@ export function InputArea({const [isModeMenuOpen, setIsModeMenuOpen] = useState(false);const [showModeSwitchModal, setShowModeSwitchModal] = useState(false);const [pendingMode, setPendingMode] = useState<AgentMode | null>(null);+ const [attachments, setAttachments] = useState<AttachmentDraft[]>([]);+ const [attachmentAlerts, setAttachmentAlerts] = useState<AttachmentAlert[]>([]);+ const [attachmentMenuId, setAttachmentMenuId] = useState<string | null>(null);+ const [isDraggingImage, setIsDraggingImage] = useState(false);const textareaRef = useRef<HTMLTextAreaElement>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);const modeMenuRef = useRef<HTMLDivElement>(null);const autoSendTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const attachmentMenuTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const attachmentMenuOpenedByLongPressRef = useRef(false);const isComposingRef = useRef(false);// const activePointerIdRef = useRef<number | null>(null);const isVoicePressingRef = useRef(false);@@ -112,6 +239,18 @@ export function InputArea({},});+ const imageInputDisabled = isListening || (isInterruptible && !isTeamMode);+ const readyAttachments = useMemo(+ () => attachments.filter((attachment) => attachment.status === 'ready' && attachment.base64Data),+ [attachments],+ );+ const hasUploadingAttachments = attachments.some((attachment) => attachment.status === 'uploading');+ const hasAttachmentErrors = attachments.some((attachment) => attachment.status === 'error');+ const readyMediaItems = useMemo(+ () => readyAttachments.map(attachmentToMediaItem),+ [readyAttachments],+ );+useEffect(() => {if (!isListening && pendingVoiceText) {const finalText = (inputValue + pendingVoiceText).trim();@@ -141,9 +280,155 @@ export function InputArea({if (autoSendTimeoutRef.current) {clearTimeout(autoSendTimeoutRef.current);}+ if (attachmentMenuTimerRef.current) {+ clearTimeout(attachmentMenuTimerRef.current);+ }};}, []);+ const pushAttachmentAlert = useCallback((message: string) => {+ const id = `${Date.now()}-${Math.random().toString(36).slice(2)}`;+ setAttachmentAlerts((prev) => [...prev, { id, message }].slice(-3));+ }, []);++ const dismissAttachmentAlert = useCallback((id: string) => {+ setAttachmentAlerts((prev) => prev.filter((item) => item.id !== id));+ }, []);++ const updateAttachment = useCallback((id: string, update: Partial<AttachmentDraft>) => {+ setAttachments((prev) => prev.map((item) => (+ item.id === id ? { ...item, ...update } : item+ )));+ }, []);++ const removeAttachment = useCallback((id: string) => {+ setAttachments((prev) => prev.filter((item) => item.id !== id));+ setAttachmentMenuId((current) => (current === id ? null : current));+ }, []);++ const clearAttachments = useCallback(() => {+ setAttachments([]);+ setAttachmentAlerts([]);+ setAttachmentMenuId(null);+ }, []);++ const stopAttachmentMenuTimer = useCallback(() => {+ if (attachmentMenuTimerRef.current) {+ clearTimeout(attachmentMenuTimerRef.current);+ attachmentMenuTimerRef.current = null;+ }+ }, []);++ const startAttachmentMenuTimer = useCallback((id: string) => {+ stopAttachmentMenuTimer();+ attachmentMenuOpenedByLongPressRef.current = false;+ attachmentMenuTimerRef.current = setTimeout(() => {+ attachmentMenuOpenedByLongPressRef.current = true;+ setAttachmentMenuId(id);+ }, 520);+ }, [stopAttachmentMenuTimer]);++ const handleAttachmentRemoveClick = useCallback((id: string) => {+ if (attachmentMenuOpenedByLongPressRef.current || attachmentMenuId === id) {+ attachmentMenuOpenedByLongPressRef.current = false;+ return;+ }+ removeAttachment(id);+ }, [attachmentMenuId, removeAttachment]);++ const uploadAttachment = useCallback((attachment: AttachmentDraft) => {+ if (!attachment.file) return;+ const validationError = getImageValidationError(attachment.file);+ if (validationError) {+ pushAttachmentAlert(validationError);+ updateAttachment(attachment.id, { status: 'error', error: validationError });+ return;+ }+ updateAttachment(attachment.id, { status: 'uploading', error: undefined });+ void readImageFile(attachment.file).then(async (payload) => {+ if (!payload) {+ updateAttachment(attachment.id, {+ status: 'error',+ error: '上传失败,请重试',+ });+ 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,+ persistedMediaItem,+ status: 'ready',+ error: undefined,+ });+ } catch (error) {+ console.error('图片上传失败:', error);+ updateAttachment(attachment.id, {+ ...payload,+ status: 'error',+ error: '上传失败,请重试',+ });+ }+ });+ }, [onPersistMedia, pushAttachmentAlert, updateAttachment]);++ const retryAttachment = useCallback((attachment: AttachmentDraft) => {+ uploadAttachment(attachment);+ }, [uploadAttachment]);++ const appendImageFiles = useCallback((files: FileList | File[]) => {+ const selectedFiles = Array.from(files);+ if (!selectedFiles.length) return;+ const remainingSlots = Math.max(0, MAX_IMAGE_COUNT - attachments.length);+ if (!remainingSlots) {+ pushAttachmentAlert(`单次对话最多上传${MAX_IMAGE_COUNT}个附件。`);+ return;+ }++ const acceptedFiles = selectedFiles.slice(0, remainingSlots);+ const overflow = selectedFiles.length - acceptedFiles.length;+ if (overflow > 0) {+ pushAttachmentAlert(`单次对话最多上传${MAX_IMAGE_COUNT}个附件。`);+ }++ const drafts = acceptedFiles.reduce<AttachmentDraft[]>((items, file) => {+ const base = {+ id: makeAttachmentId(file),+ filename: file.name || `image-${Date.now()}`,+ mimeType: file.type || 'application/octet-stream',+ size: file.size,+ file,+ };+ const validationError = getImageValidationError(file);+ if (validationError) {+ pushAttachmentAlert(validationError);+ items.push({+ ...base,+ status: 'error',+ error: validationError,+ });+ return items;+ }+ items.push({+ ...base,+ status: 'uploading',+ });+ return items;+ }, []);++ if (!drafts.length) return;++ setAttachments((prev) => [...prev, ...drafts].slice(0, MAX_IMAGE_COUNT));+ drafts.forEach((draft) => {+ if (draft.status !== 'uploading' || !draft.file) return;+ uploadAttachment(draft);+ });+ }, [attachments.length, pushAttachmentAlert, uploadAttachment]);+useEffect(() => {if (!isModeMenuOpen) return;@@ -160,37 +445,77 @@ export function InputArea({};}, [isModeMenuOpen]);+ useEffect(() => {+ if (!attachmentMenuId) return;++ const handlePointerDown = (event: PointerEvent) => {+ const target = event.target as Element | null;+ if (+ target?.closest('.chat-input-attachment-menu') ||+ target?.closest('.chat-input-attachment-remove')+ ) {+ return;+ }+ setAttachmentMenuId(null);+ };++ document.addEventListener('pointerdown', handlePointerDown);++ return () => {+ document.removeEventListener('pointerdown', handlePointerDown);+ };+ }, [attachmentMenuId]);+const handleSubmit = useCallback(() => {const trimmed = (inputValue + pendingVoiceText).trim();- if (!trimmed) return;+ if ((!trimmed && readyMediaItems.length === 0) || hasUploadingAttachments || hasAttachmentErrors) return;+ if (isInterruptible && !isTeamMode && readyMediaItems.length > 0) return;if (isListening) {stopListening();}if (isTeamMode) {- onSubmit(trimmed);+ onSubmit(trimmed, readyMediaItems);} else if (isInterruptible) {- if (isAgentMode) {+ if (isAgentMode && readyMediaItems.length === 0) {addToTaskQueue(trimmed);} else {onInterrupt(trimmed);}} else {- onSubmit(trimmed);+ onSubmit(trimmed, readyMediaItems);}setInputValue('');setPendingVoiceText('');+ setAttachments([]);+ setAttachmentAlerts([]);if (textareaRef.current) {textareaRef.current.style.height = 'auto';}- }, [inputValue, pendingVoiceText, isInterruptible, isListening, onSubmit, onInterrupt, stopListening, isAgentMode, isTeamMode, addToTaskQueue, setInputValue]);+ }, [+ inputValue,+ pendingVoiceText,+ readyMediaItems,+ hasUploadingAttachments,+ hasAttachmentErrors,+ isInterruptible,+ isListening,+ onSubmit,+ onInterrupt,+ stopListening,+ isAgentMode,+ isTeamMode,+ addToTaskQueue,+ setInputValue,+ ]);const trimmedDraft = (inputValue + pendingVoiceText).trim();- const hasDraft = trimmedDraft.length > 0 || isListening;+ const hasDraft = trimmedDraft.length > 0 || attachments.length > 0 || isListening;+ const isImageInterruptBlocked = isInterruptible && !isTeamMode && readyMediaItems.length > 0;const showStop = isProcessing && !isPaused && !hasDraft;- const canSubmit = hasDraft || showStop;+ const canSubmit = (hasDraft && !isImageInterruptBlocked && !hasUploadingAttachments && !hasAttachmentErrors) || showStop;const handleSendButtonClick = useCallback(() => {if (showStop) {@@ -218,6 +543,49 @@ export function InputArea({}}, []);+ const handleFileInputChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {+ const files = event.target.files;+ if (files) {+ void appendImageFiles(files);+ }+ event.target.value = '';+ }, [appendImageFiles]);++ const handlePaste = useCallback((event: ClipboardEvent<HTMLTextAreaElement>) => {+ const items = Array.from(event.clipboardData.items);+ const files = items+ .filter((item) => item.kind === 'file' && ACCEPTED_IMAGE_TYPES.has(item.type))+ .map((item) => item.getAsFile())+ .filter((file): file is File => Boolean(file));+ if (files.length) {+ event.preventDefault();+ void appendImageFiles(files);+ }+ }, [appendImageFiles]);++ const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {+ const hasImage = Array.from(event.dataTransfer.items).some(+ (item) => item.kind === 'file' && ACCEPTED_IMAGE_TYPES.has(item.type)+ );+ if (!hasImage) return;+ event.preventDefault();+ setIsDraggingImage(true);+ }, []);++ const handleDragLeave = useCallback((event: DragEvent<HTMLDivElement>) => {+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {+ setIsDraggingImage(false);+ }+ }, []);++ const handleDrop = useCallback((event: DragEvent<HTMLDivElement>) => {+ setIsDraggingImage(false);+ const files = Array.from(event.dataTransfer.files).filter((file) => ACCEPTED_IMAGE_TYPES.has(file.type));+ if (!files.length) return;+ event.preventDefault();+ void appendImageFiles(files);+ }, [appendImageFiles]);+// const handleVoiceStart = useCallback(() => {// if (isListening) return;// stopAllTts();@@ -274,6 +642,8 @@ export function InputArea({if (isListening || (isInterruptible && !isTeamMode)) return;setInputValue('');setPendingVoiceText('');+ setAttachments([]);+ setAttachmentAlerts([]);if (textareaRef.current) {textareaRef.current.style.height = 'auto';}@@ -324,13 +694,37 @@ export function InputArea({const evolutionLabel = getEvolutionPillLabel(mode, evolutionStatus, t);return (- <div- className={cx(- 'chat-input-container',- isModeMenuOpen && 'chat-input-container--menu-open',- isListening && 'chat-input-container--recording',- )}- >+ <>+ <div className="chat-input-frame">+ {attachmentAlerts.length > 0 && (+ <div className="chat-input-local-alerts" role="status" aria-live="polite">+ {attachmentAlerts.map((alert) => (+ <div className="chat-input-local-alert" key={alert.id}>+ <CircleX size={16} strokeWidth={2.2} />+ <span>{alert.message}</span>+ <button+ type="button"+ onClick={() => dismissAttachmentAlert(alert.id)}+ aria-label="关闭提示"+ >+ <X size={15} strokeWidth={2} />+ </button>+ </div>+ ))}+ </div>+ )}++ <div+ className={cx(+ 'chat-input-container',+ isModeMenuOpen && 'chat-input-container--menu-open',+ isListening && 'chat-input-container--recording',+ isDraggingImage && 'chat-input-container--dragging',+ )}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >{isListening && (<div className="chat-input-recording-bar"><span className="chat-input-recording-dot" />@@ -367,6 +761,108 @@ export function InputArea({</div>)}+ {attachments.length > 0 && (+ <div className="chat-input-attachment-panel">+ <div+ className={cx(+ 'chat-input-attachment-grid',+ attachmentMenuId && 'chat-input-attachment-grid--menu-open',+ )}+ >+ {attachments.map((attachment) => (+ <div+ className={cx(+ 'chat-input-attachment-card',+ attachment.status === 'error' && 'chat-input-attachment-card--error',+ attachment.status === 'uploading' && 'chat-input-attachment-card--uploading',+ )}+ key={attachment.id}+ >+ <div className="chat-input-attachment-preview" aria-hidden="true">+ {attachment.previewUrl ? (+ <img src={attachment.previewUrl} alt="" />+ ) : (+ <FileImage size={18} strokeWidth={1.8} />+ )}+ </div>+ <div className="chat-input-attachment-main">+ <div className="chat-input-attachment-name" title={attachment.filename}>+ {attachment.filename}+ </div>+ <div className="chat-input-attachment-meta">+ {attachment.status === 'uploading' ? (+ <>+ <Loader2 className="chat-input-attachment-spin" size={12} strokeWidth={2} />+ <span>上传中...</span>+ </>+ ) : attachment.status === 'error' ? (+ <>+ <span+ className="chat-input-attachment-status-error"+ title={attachment.error || '上传失败'}+ >+ 上传失败+ </span>+ {attachment.file && (+ <button+ type="button"+ className="chat-input-attachment-retry"+ onClick={() => retryAttachment(attachment)}+ >+ 重试+ </button>+ )}+ </>+ ) : (+ <>+ <span>{attachment.mimeType.split('/')[1]?.toUpperCase() || 'IMAGE'}</span>+ <span>{formatAttachmentSize(attachment.size)}</span>+ </>+ )}+ </div>+ </div>+ <button+ type="button"+ className="chat-input-attachment-remove"+ onPointerDown={() => startAttachmentMenuTimer(attachment.id)}+ onPointerUp={stopAttachmentMenuTimer}+ onPointerCancel={stopAttachmentMenuTimer}+ onPointerLeave={stopAttachmentMenuTimer}+ onContextMenu={(event) => {+ event.preventDefault();+ stopAttachmentMenuTimer();+ setAttachmentMenuId(attachment.id);+ }}+ onClick={() => handleAttachmentRemoveClick(attachment.id)}+ title="删除,长按显示更多操作"+ aria-label="删除附件"+ >+ <X size={12} strokeWidth={2} />+ </button>+ {attachmentMenuId === attachment.id && (+ <div className="chat-input-attachment-menu" role="menu">+ <button+ type="button"+ role="menuitem"+ onClick={() => removeAttachment(attachment.id)}+ >+ 删除+ </button>+ <button+ type="button"+ role="menuitem"+ onClick={clearAttachments}+ >+ 清空附件+ </button>+ </div>+ )}+ </div>+ ))}+ </div>+ </div>+ )}+<textarearef={textareaRef}value={displayValue}@@ -375,6 +871,7 @@ export function InputArea({onCompositionStart={() => { isComposingRef.current = true; }}onCompositionEnd={() => { isComposingRef.current = false; }}onInput={handleInput}+ onPaste={handlePaste}placeholder={isListening? t('chat.placeholderVoice')@@ -397,6 +894,27 @@ export function InputArea({<div className="chat-input-toolbar"><div className="chat-input-toolbar-left">+ <input+ ref={fileInputRef}+ type="file"+ accept="image/png,image/jpeg,image/webp,image/gif"+ multiple+ className="hidden"+ onChange={handleFileInputChange}+ />+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={imageInputDisabled}+ className={cx(+ 'chat-input-btn chat-input-btn--add-file',+ imageInputDisabled && 'chat-input-btn--disabled',+ )}+ title={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ aria-label={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ >+ <Plus className="chat-input-btn-icon" strokeWidth={1.8} />+ </button><divref={modeMenuRef}className={clsx(@@ -557,7 +1075,9 @@ export function InputArea({</div></div>)}- </div>+ </div>+ </div>+ </>);}@@ -569,29 +1089,33 @@ function ModelSelector() {if (chatAvailableModels.length === 1) {return (- <span- className="text-xs text-text-muted px-2 truncate max-w-[200px]"- title={chatAvailableModels[0].model_name}- >- {chatAvailableModels[0].alias || chatAvailableModels[0].model_name}+ <span className="chat-model-inline">+ <span+ className="chat-model-inline__name"+ title={chatAvailableModels[0].model_name}+ >+ {chatAvailableModels[0].alias || chatAvailableModels[0].model_name}+ </span></span>);}return (- <select- value={selectedModelName ?? ''}- onChange={(e) => setSelectedModelName(e.target.value)}- title={t('chat.modelSelector.tooltip')}- className="chat-model-selector"- data-testid="chat-model-selector"- >- {chatAvailableModels.map((m, idx) => (- <option key={`${m.model_name}-${idx}`} value={m.alias || m.model_name}>- {m.alias ? `${m.alias} (${m.model_name})` : m.model_name}- </option>- ))}- </select>+ <span className="chat-model-inline">+ <select+ value={selectedModelName ?? ''}+ onChange={(e) => setSelectedModelName(e.target.value)}+ title={t('chat.modelSelector.tooltip')}+ className="chat-model-selector"+ data-testid="chat-model-selector"+ >+ {chatAvailableModels.map((m, idx) => (+ <option key={`${m.model_name}-${idx}`} value={m.alias || m.model_name}>+ {m.alias ? `${m.alias} (${m.model_name})` : m.model_name}+ </option>+ ))}+ </select>+ </span>);}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex 2067717aeb..b607ab47d3 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -9,7 +9,7 @@ import { ArrowRight, LoaderCircle, Share2, Sparkles } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { useChatStore, useSessionStore, useTodoStore } from '../../stores';-import { AgentMode, Message, UserAnswer } from '../../types';+import { AgentMode, MediaItem, Message, UserAnswer } from '../../types';import { MessageList } from './MessageList';import { ContextCompressionLines } from './MessageItem';import { InputArea } from './InputArea';@@ -30,7 +30,13 @@ export interface ChatHistoryPagerProps {}interface ChatPanelProps {- onSendMessage: (content: string) => void;+ onSendMessage: (content: string, mediaItems?: MediaItem[]) => void;+ onPersistMedia: (content: string, mediaItems: MediaItem[]) => Promise<{+ content?: string;+ query?: string;+ media_items?: Record<string, unknown>[];+ files?: Record<string, unknown>;+ }>;onInterrupt: (newInput?: string) => void;onCancel: () => void;onSwitchMode: (mode: AgentMode) => void;@@ -188,6 +194,7 @@ function getShareExportTitle(export function ChatPanel({onSendMessage,+ onPersistMedia,onInterrupt,onCancel,onSwitchMode,@@ -301,9 +308,9 @@ export function ChatPanel({}, [historyPager, messages.length]);// 包装发送消息函数,添加滚动逻辑- const handleSendMessage = useCallback((content: string) => {+ const handleSendMessage = useCallback((content: string, mediaItems?: MediaItem[]) => {setIsSending(true);- onSendMessage(content);+ onSendMessage(content, mediaItems);}, [onSendMessage]);// 当发送消息时强制滚动到底部@@ -394,6 +401,7 @@ export function ChatPanel({<InterruptResultBubble /><InputAreaonSubmit={handleSendMessage}+ onPersistMedia={onPersistMedia}onInterrupt={onInterrupt}onCancel={onCancel}onSwitchMode={onSwitchMode}@@ -418,6 +426,7 @@ export function ChatPanel({<InterruptResultBubble /><InputAreaonSubmit={handleSendMessage}+ onPersistMedia={onPersistMedia}onInterrupt={onInterrupt}onCancel={onCancel}onSwitchMode={onSwitchMode}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 1fffa9e800..99de8006e8 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -296,7 +296,8 @@ interface UseWebSocketReturn {params?: Record<string, unknown>,options?: WebRequestOptions) => Promise<T>;- sendMessage: (content: string, sessionId: string) => Promise<void>;+ persistMedia: (content: string, sessionId: string, mediaItems: MediaItem[]) => Promise<PersistMediaResponse>;+ sendMessage: (content: string, sessionId: string, mediaItems?: MediaItem[]) => Promise<void>;sendStructuredChatContent: (content: unknown, sessionId: string) => Promise<void>;interrupt: (sessionId: string,@@ -324,6 +325,42 @@ interface UseWebSocketReturn {getInflightCount: () => number;}+interface PersistMediaResponse {+ content?: string;+ query?: string;+ media_items?: Record<string, unknown>[];+ files?: Record<string, unknown>;+}++function isPersistedMediaItem(item: MediaItem): boolean {+ return typeof item.path === 'string' && item.path.trim().length > 0;+}++function getMediaMimeType(item: MediaItem): string {+ return item.mime_type || item.mimeType;+}++function toPersistedMediaRecord(item: MediaItem): Record<string, unknown> {+ return {+ type: item.type,+ filename: item.filename,+ mime_type: getMediaMimeType(item),+ path: item.path,+ size_bytes: item.size_bytes ?? item.sizeBytes,+ };+}++function buildPersistedMediaFiles(mediaItems: MediaItem[]): Record<string, unknown> {+ return {+ uploaded_images: mediaItems.map((item) => ({+ filename: item.filename,+ path: item.path,+ mime_type: getMediaMimeType(item),+ size_bytes: item.size_bytes ?? item.sizeBytes,+ })),+ };+}+interface ContextCompressionStatePayload extends Record<string, unknown> {status?: string;summary?: string;@@ -857,10 +894,22 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {};}, [clearAllPendingTeamMemberContextCompressionStarts, clearPendingContextCompressionStart]);+ const persistMedia = useCallback(+ async (content: string, sessionId: string, mediaItems: MediaItem[]) => {+ return request<PersistMediaResponse>('media.persist', {+ session_id: sessionId,+ content,+ media_items: mediaItems as unknown as Record<string, unknown>[],+ });+ },+ [request],+ );+// 发送聊天消息const sendMessage = useCallback(- async (content: string, sessionId: string) => {- if (!content.trim()) return;+ async (content: string, sessionId: string, mediaItems: MediaItem[] = []) => {+ const hasMedia = mediaItems.length > 0;+ if (!content.trim() && !hasMedia) return;const currentMode = useSessionStore.getState().mode;const unsupportedEvolutionMode = unsupportedEvolutionModeMessage(content, currentMode);@@ -897,6 +946,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {id: `user-${Date.now()}`,role: 'user',content,+ mediaItems,timestamp: new Date().toISOString(),});@@ -918,9 +968,25 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {setPaused(false);}try {+ let outgoingContent = content;+ let outgoingMediaItems: Record<string, unknown>[] | undefined;+ let outgoingFiles: Record<string, unknown> | undefined;+ if (hasMedia) {+ if (mediaItems.every(isPersistedMediaItem)) {+ outgoingMediaItems = mediaItems.map(toPersistedMediaRecord);+ outgoingFiles = buildPersistedMediaFiles(mediaItems);+ } else {+ const persisted = await persistMedia(content, sessionId, mediaItems);+ outgoingContent = persisted.content ?? persisted.query ?? content;+ outgoingMediaItems = persisted.media_items;+ outgoingFiles = persisted.files;+ }+ }await request('chat.send', {session_id: sessionId,- content,+ content: outgoingContent,+ ...(outgoingMediaItems ? { media_items: outgoingMediaItems } : {}),+ ...(outgoingFiles ? { files: outgoingFiles } : {}),mode: currentMode,...(selectedModel ? { model_name: selectedModel } : {}),});@@ -941,6 +1007,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {},[addMessage,+ persistMedia,request,resetContextCompressionTurn,setContextCompressionStats,@@ -2795,6 +2862,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {isConnected,connectionState,request,+ persistMedia,sendMessage,sendStructuredChatContent,interrupt,diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 5ab2171ea2..05050378f0 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -236,6 +236,9 @@"waitingTasks": "Waiting tasks","waitingTasksCount": "Waiting tasks ({{count}})","removeTask": "Remove task",+ "addImage": "Add image",+ "addImageDisabled": "Cannot add images while processing or recording",+ "removeImage": "Remove image","holdToSpeak": "Hold to speak","send": "Send (Enter)","stop": "Stop",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 3012fa49d7..e34047bedb 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -236,6 +236,9 @@"waitingTasks": "等待任务","waitingTasksCount": "等待任务 ({{count}})","removeTask": "移除任务",+ "addImage": "添加图片",+ "addImageDisabled": "处理中或录音中不可添加图片",+ "removeImage": "移除图片","holdToSpeak": "按住说话","send": "发送 (Enter)","stop": "停止",diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex 65cc4d0437..7f685826f1 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -9,9 +9,14 @@ export type MessageRole = 'user' | 'assistant' | 'system' | 'tool';export interface MediaItem {type: 'image' | 'audio' | 'video' | 'document';mimeType: string;+ mime_type?: string;filename: string;base64Data?: string;+ base64_data?: string;url?: string;+ path?: string;+ sizeBytes?: number;+ size_bytes?: number;}export interface UsageSummary {diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex d25f65e77c..227f44a369 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -1673,6 +1673,9 @@ def is_package_installation() -> bool:# 统一敏感信息掩码值。_SENSITIVE_MASK = "******"+_DATA_IMAGE_PATTERN = re.compile(+ r"data:image/[A-Za-z0-9.+-]+;base64,[A-Za-z0-9+/=]+"+)# 匹配常见敏感字段键值对(不要求值必须带引号),用于覆盖:# - token=abc# - api_key: sk-xxx@@ -1725,6 +1728,7 @@ def _sanitize_log_text(text: str) -> str:return textmasked = text+ masked = _DATA_IMAGE_PATTERN.sub("data:image/*;base64,******", masked)masked = _KV_SENSITIVE_PATTERN.sub(r"\1\2" f"{_SENSITIVE_MASK}", masked)masked = _NAMED_SENSITIVE_KV_PATTERN.sub(r"\1\2" f"{_SENSITIVE_MASK}" r"\2", masked)masked = _BEARER_SENSITIVE_PATTERN.sub(r"\1" f"{_SENSITIVE_MASK}", masked)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 81884298d1..b87ac72a00 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -60,6 +60,7 @@ from jiuwenswarm.common.utils import (from jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessServicefrom jiuwenswarm.agents.harness.common.tools.web_file_download import build_file_download_infofrom jiuwenswarm.common.version import __version__+from jiuwenswarm.gateway.media_attachments import normalize_chat_media_attachmentsfrom jiuwenswarm.symphony.skill_retrieval.taxonomy_config import (coerce_root_categories_value,root_categories_to_text,@@ -896,7 +897,6 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if env_path.is_file():with open(env_path, "r", encoding="utf-8") as f:lines = f.readlines()- updated_keys = set(updates.keys())new_lines: list[str] = []for line in lines:stripped = line.strip()@@ -1730,7 +1730,6 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:mem = psutil.virtual_memory()total_mb = mem.total / (1024 * 1024)available_mb = mem.available / (1024 * 1024)- used_percent = mem.percentawait channel.send_response(ws, req_id, ok=True,payload={"rss_mb": rss_mb, "total_mb": total_mb,@@ -1744,6 +1743,24 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload={"accepted": True, "session_id": session_id},)+ async def _media_persist(ws, req_id, params, session_id):+ if not isinstance(params, dict):+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")+ return+ normalized = dict(params)+ try:+ normalize_chat_media_attachments(normalized, session_id)+ except Exception as exc:+ logger.exception("[media.persist] failed: %s", exc)+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")+ return+ payload = {+ key: normalized[key]+ for key in ("content", "query", "media_items", "files")+ if key in normalized+ }+ await channel.send_response(ws, req_id, ok=True, payload=payload)+async def _chat_resume(ws, req_id, params, session_id):await channel.send_response(ws,@@ -2586,6 +2603,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("hooks.list", _hooks_list)channel.register_method("chat.send", _chat_send)+ channel.register_method("media.persist", _media_persist)channel.register_method("chat.resume", _chat_resume)channel.register_method("chat.interrupt", _chat_interrupt)channel.register_method("chat.user_answer", _chat_user_answer)@@ -2777,21 +2795,12 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:async def _forward_harness_to_agent(ws, req_id, params, session_id, *, req_method):"""harness.*:优先经 E2A 转发到 AgentServer;Agent 未就绪时本地执行(无 agent 实例)。"""from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields- from jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethodif not isinstance(req_method, ReqMethod):await channel.send_response(ws, req_id, ok=False, error="invalid req_method", code="INTERNAL_ERROR")return- synthetic = AgentRequest(- request_id=str(req_id) if req_id else "",- channel_id="",- session_id=session_id,- req_method=req_method,- params=dict(params) if isinstance(params, dict) else {},- )-ac = _resolve(agent_client)if ac is None or not getattr(ac, "server_ready", False):# Agent 未就绪时本地处理(无 agent 实例可用)diff --git a/jiuwenswarm/gateway/media_attachments.py b/jiuwenswarm/gateway/media_attachments.pynew file mode 100644index 0000000000..ef92a14628--- /dev/null+++ b/jiuwenswarm/gateway/media_attachments.py@@ -0,0 +1,130 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Helpers for normalizing browser-uploaded media attachments."""++from __future__ import annotations++import base64+import binascii+import re+from contextlib import suppress+from pathlib import Path+from typing import Any++from jiuwenswarm.common.utils import get_agent_sessions_dir++_SAFE_FILENAME_RE = re.compile(r"[^A-Za-z0-9._-]+")+_SESSION_ID_RE = re.compile(r"[^A-Za-z0-9._-]+")++_SUPPORTED_IMAGE_MIME_TYPES = {+ "image/png": ".png",+ "image/jpeg": ".jpg",+ "image/webp": ".webp",+ "image/gif": ".gif",+}+_MAX_IMAGE_BYTES = 10 * 1024 * 1024+_MAX_IMAGE_COUNT = 8+++def normalize_chat_media_attachments(params: dict[str, Any], session_id: str | None) -> None:+ """Validate browser media_items, persist images, and enrich the chat params.++ The frontend sends images as base64 for cross-platform browser compatibility.+ The gateway stores images under the current session and returns structured+ image file records. Downstream multimodal rails can load images from these+ paths without sending long base64 payloads through normal text context.+ """++ raw_items = params.get("media_items")+ if not isinstance(raw_items, list) or not raw_items:+ return++ stored: list[dict[str, Any]] = []+ for index, item in enumerate(raw_items[:_MAX_IMAGE_COUNT]):+ if not isinstance(item, dict):+ continue+ if item.get("type") != "image":+ continue+ stored_item = _store_image_item(item, session_id=session_id, index=index)+ if stored_item:+ stored.append(stored_item)++ if not stored:+ params.pop("media_items", None)+ return++ params["media_items"] = stored+ files = params.get("files")+ if not isinstance(files, dict):+ files = {}+ files["uploaded_images"] = [+ {+ "filename": item.get("filename"),+ "path": item.get("path"),+ "mime_type": item.get("mime_type"),+ "size_bytes": item.get("size_bytes"),+ }+ for item in stored+ ]+ params["files"] = files+++def _store_image_item(item: dict[str, Any], *, session_id: str | None, index: int) -> dict[str, Any] | None:+ mime_type = str(item.get("mimeType") or item.get("mime_type") or "").lower().strip()+ suffix = _SUPPORTED_IMAGE_MIME_TYPES.get(mime_type)+ if suffix is None:+ return None++ raw_base64 = item.get("base64Data") or item.get("base64_data")+ if not isinstance(raw_base64, str) or not raw_base64.strip():+ return None+ data: bytes | None = None+ with suppress(binascii.Error):+ data = base64.b64decode(raw_base64, validate=True)+ if not data or len(data) > _MAX_IMAGE_BYTES:+ return None++ 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)++ filename = _safe_filename(+ str(item.get("filename") or f"image-{index + 1}{suffix}"),+ fallback=f"image-{index + 1}{suffix}",+ )+ if Path(filename).suffix.lower() not in set(_SUPPORTED_IMAGE_MIME_TYPES.values()):+ filename = f"{filename}{suffix}"+ path = _unique_path(upload_dir / filename)+ path.write_bytes(data)++ return {+ "type": "image",+ "filename": path.name,+ "mime_type": mime_type,+ "path": str(path),+ "size_bytes": len(data),+ }+++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_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex dbecc34f31..9d12369486 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -14,6 +14,7 @@ import jsonimport loggingimport osimport platform+import reimport subprocessimport timefrom collections import Counter@@ -122,6 +123,7 @@ from jiuwenswarm.agents.harness.common.tools.todo_compat import (from jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_promptfrom jiuwenswarm.agents.harness.common.rails import (JiuSwarmStreamEventRail,+ MultimodalImageRail,ResponsePromptRail,RuntimePromptRail,StructuredAskUserRail,@@ -270,7 +272,6 @@ from jiuwenswarm.common.utils import (get_agent_skills_dir,get_agent_workspace_dir,get_checkpoint_dir,- get_config_dir,get_env_file,get_prompt_attachment_dir,get_runtime_state_path,@@ -2204,6 +2205,43 @@ class JiuWenSwarmDeepAdapter:)return Model(model_client_config=ModelClientConfig(**mcc_fields), model_config=m_config)+ def _register_model_cache_entry(+ self,+ entry: dict[str, Any],+ name_counter: dict[str, int],+ ) -> None:+ """Register one model entry into the request-selectable model cache."""+ mcc = entry.get("model_client_config") or {}+ if not mcc.get("model_name"):+ return+ model_name = mcc["model_name"]+ idx = name_counter.get(model_name, 0)+ name_counter[model_name] = idx + 1+ cache_key = f"{model_name}#{idx}"+ try:+ model = self._build_model_from_entry(+ mcc,+ entry.get("model_config_obj") or {},+ )+ self._model_cache[cache_key] = model+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] 跳过无效模型条目 %s: %s",+ model_name, exc,+ )+ return+ if model_name not in self._model_name_to_keys:+ self._model_name_to_keys[model_name] = []+ self._model_name_to_keys[model_name].append(cache_key)++ # 同时用纯 model_name 作为 key 指向 is_default=true 的条目+ if entry.get("is_default") is True:+ self._model_cache[model_name] = self._model_cache[cache_key]++ alias = entry.get("alias") or ""+ if alias and alias != model_name and alias not in self._model_cache:+ self._model_cache[alias] = self._model_cache[cache_key]+def _build_model_cache_from_defaults(self, config: dict) -> None:"""从 models.defaults 列表构建模型缓存。@@ -2214,35 +2252,7 @@ class JiuWenSwarmDeepAdapter:name_counter: dict[str, int] = {}for entry in get_default_models(config):- mcc = entry.get("model_client_config") or {}- if not mcc.get("model_name"):- continue- model_name = mcc["model_name"]- idx = name_counter.get(model_name, 0)- name_counter[model_name] = idx + 1- cache_key = f"{model_name}#{idx}"- try:- self._model_cache[cache_key] = self._build_model_from_entry(- mcc,- entry.get("model_config_obj") or {},- )- except Exception as exc:- logger.warning(- "[JiuWenSwarmDeepAdapter] 跳过无效模型条目 %s: %s",- model_name, exc,- )- continue- if model_name not in self._model_name_to_keys:- self._model_name_to_keys[model_name] = []- self._model_name_to_keys[model_name].append(cache_key)-- # 同时用纯 model_name 作为 key 指向 is_default=true 的条目- if entry.get("is_default") is True:- self._model_cache[model_name] = self._model_cache[cache_key]-- alias = entry.get("alias", "")- if alias and alias != model_name and alias not in self._model_cache:- self._model_cache[alias] = self._model_cache[cache_key]+ self._register_model_cache_entry(entry, name_counter)def _build_model_cache_legacy(self, config: dict) -> None:"""回退到旧格式(models.default / react 段)构建单条目缓存。"""@@ -2330,6 +2340,34 @@ class JiuWenSwarmDeepAdapter:return self._model_cache[requested]return self._model+ @staticmethod+ def _prepare_multimodal_image_inputs(+ request: AgentRequest,+ inputs: dict[str, Any],+ ) -> dict[str, Any]:+ from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ extract_multimodal_image_files,+ )++ image_files = extract_multimodal_image_files(request.params)+ if not image_files:+ return inputs++ updated = dict(inputs)+ updated["_multimodal_image_files"] = image_files+ logger.info(+ "[JiuWenSwarmDeepAdapter] Prepared %d image attachment(s) "+ "for Core multimodal context-window injection",+ len(image_files),+ )+ return updated++ def _resolve_enable_read_image_multimodal(self, config: dict[str, Any]) -> bool:+ configured = config.get("enable_read_image_multimodal")+ if isinstance(configured, bool):+ return configured+ return self._vision_model_config is None+def _apply_model_to_react_agent(self, model: Model) -> None:"""将指定模型应用到 react_agent 实例(替换 _llm 和 _config 字段)。@@ -2984,6 +3022,21 @@ class JiuWenSwarmDeepAdapter:stream_event_rail = Nonereturn stream_event_rail+ @staticmethod+ def _build_multimodal_image_rail(+ enable_image_multimodal: bool | None = None,+ ) -> MultimodalImageRail | None:+ """Build MultimodalImageRail."""+ try:+ multimodal_image_rail = MultimodalImageRail(+ enable_image_multimodal=enable_image_multimodal,+ )+ logger.info("[JiuWenSwarmDeepAdapter] MultimodalImageRail create success")+ except Exception as exc:+ logger.warning("[JiuWenSwarmDeepAdapter] MultimodalImageRail create failed: %s", exc)+ multimodal_image_rail = None+ return multimodal_image_rail+@staticmethoddef _build_task_planning_rail() -> TaskPlanningRail | None:"""Build TaskPlanningRail."""@@ -3176,6 +3229,13 @@ class JiuWenSwarmDeepAdapter:rail_infos = [_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),+ _RailBuildInfo(+ "_multimodal_image_rail",+ self._build_multimodal_image_rail,+ {+ "enable_image_multimodal": self._resolve_enable_read_image_multimodal(config),+ },+ ),_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),_RailBuildInfo("_task_planning_rail", self._build_task_planning_rail),_RailBuildInfo("_security_rail", self._build_security_rail),@@ -3351,7 +3411,7 @@ class JiuWenSwarmDeepAdapter:rails=rails,vision_model_config=self._vision_model_config,audio_model_config=self._audio_model_config,- enable_read_image_multimodal=self._vision_model_config is None,+ enable_read_image_multimodal=self._resolve_enable_read_image_multimodal(config),completion_timeout=config.get("completion_timeout", 3600.0),)@@ -3734,7 +3794,7 @@ class JiuWenSwarmDeepAdapter:context_engine_config=_deep_agent_context_engine_config(config),vision_model_config=self._vision_model_config,audio_model_config=self._audio_model_config,- enable_read_image_multimodal=self._vision_model_config is None,+ enable_read_image_multimodal=self._resolve_enable_read_image_multimodal(config),enable_llm_retry_rail=((config_base.get("execution_guard") or {}).get("llm_retry_rail") or {}).get("enabled", False),@@ -5657,6 +5717,7 @@ class JiuWenSwarmDeepAdapter:self._register_session_agent_task(session_id)if self._stream_event_rail is not None:self._stream_event_rail.reset_abort(session_id)+ image_files_token = Nonetry:await self._update_runtime_config(self._RuntimeConfig(@@ -5672,7 +5733,18 @@ class JiuWenSwarmDeepAdapter:))inputs = dict(inputs)+ inputs = self._prepare_multimodal_image_inputs(+ request,+ inputs,+ )await self._sync_prompt_attachments_for_request(session_id)+ from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ set_current_multimodal_image_files,+ )++ image_files_token = set_current_multimodal_image_files(+ inputs.pop("_multimodal_image_files", []) or []+ )result = await Runner.run_agent(agent=self._instance, inputs=inputs)except asyncio.CancelledError:logger.info(@@ -5685,6 +5757,12 @@ class JiuWenSwarmDeepAdapter:logger.error("[JiuWenSwarmDeepAdapter] Agent 任务执行异常: %s", e)raisefinally:+ if image_files_token is not None:+ from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ reset_current_multimodal_image_files,+ )++ reset_current_multimodal_image_files(image_files_token)self._unregister_session_agent_task(session_id)TOOL_PERMISSION_CHANNEL_ID.reset(token_cid)cleanup_permission_context(token_perm)@@ -5898,6 +5976,7 @@ class JiuWenSwarmDeepAdapter:self._mark_session_active(session_id)self._register_session_agent_task(session_id)stream_consumer_cancelled = False+ image_files_token = Nonetry:await self._update_runtime_config(self._RuntimeConfig(@@ -5915,7 +5994,18 @@ class JiuWenSwarmDeepAdapter:if self._stream_event_rail is not None:self._stream_event_rail.reset_abort(session_id)inputs = dict(inputs)+ inputs = self._prepare_multimodal_image_inputs(+ request,+ inputs,+ )await self._sync_prompt_attachments_for_request(session_id)+ from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ set_current_multimodal_image_files,+ )++ image_files_token = set_current_multimodal_image_files(+ inputs.pop("_multimodal_image_files", []) or []+ )async for chunk in Runner.run_agent_streaming(self._instance, inputs):if not (hasattr(chunk, "type") and hasattr(chunk, "payload")):parsed = self._parse_stream_chunk(chunk)@@ -6139,6 +6229,12 @@ class JiuWenSwarmDeepAdapter:is_complete=False,)finally:+ if image_files_token is not None:+ from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (+ reset_current_multimodal_image_files,+ )++ reset_current_multimodal_image_files(image_files_token)self._unregister_session_agent_task(session_id)TOOL_PERMISSION_CHANNEL_ID.reset(token_cid)cleanup_permission_context(token_perm)@@ -7333,7 +7429,6 @@ class JiuWenSwarmDeepAdapter:return {"status": "failed", "error": "Model returned empty response"}# Strip <analysis> block to get clean summary- import recleaned = re.sub(r"<analysis>.*?</analysis>", "", summary, flags=re.DOTALL).strip()return {@@ -7359,7 +7454,6 @@ class JiuWenSwarmDeepAdapter:# skip tool call/result records — they contain JSON blobs, not useful for summaryif role == "user":# strip file-content blocks to save tokens- import recleaned = re.sub(r"<file-content[^>]*>.*?</file-content>", "", content, flags=re.DOTALL).strip()if cleaned:messages.append(UserMessage(content=cleaned))