Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: web端对话支持文件对象返回,例如ppt文件,并支持下载

haowenzhong1fd562107ceb2
diff --git a/jiuwenclaw/agents/harness/common/tools/send_file_to_user.py b/jiuwenclaw/agents/harness/common/tools/send_file_to_user.py
index 14ff2d4130..058e0e7946 100644
--- a/jiuwenclaw/agents/harness/common/tools/send_file_to_user.py
+++ b/jiuwenclaw/agents/harness/common/tools/send_file_to_user.py
@@ -107,13 +107,39 @@ class SendFileToolkit:
from jiuwenclaw.server.agent_ws_server import AgentWebSocketServer
server = AgentWebSocketServer.get_instance()
- files_payload = [
- {
- "path": file_path,
- "name": os.path.basename(file_path),
- }
- for file_path in valid_files
- ]
+
+ files_payload = []
+ try:
+ from jiuwenclaw.agents.harness.common.tools.web_file_download import (
+ build_file_download_info,
+ )
+
+ for file_path in valid_files:
+ base_name = os.path.basename(file_path)
+ download_info = build_file_download_info(
+ file_path, base_name, self.session_id
+ )
+ files_payload.append({
+ "path": file_path,
+ "name": base_name,
+ "size": download_info["size"],
+ "mime_type": download_info["mime_type"],
+ "download_url": download_info["download_url"],
+ "download_token": download_info["download_token"],
+ })
+ except Exception as download_err:
+ logger.warning(
+ "[SendFileToolkit] 生成下载信息失败,回退到基础模式: %s",
+ download_err,
+ )
+ files_payload = [
+ {
+ "path": file_path,
+ "name": os.path.basename(file_path),
+ }
+ for file_path in valid_files
+ ]
+
msg = {
"request_id": self.request_id,
"channel_id": self.channel_id,
@@ -175,12 +201,11 @@ class SendFileToolkit:
"type": "object",
"properties": {
"abs_file_path_list": {
- "type": ["array", "string"],
- "items": {"type": "string"},
+ "type": "string",
"description": (
"要发送的文件绝对路径。"
"可以是单个路径字符串如 '/path/to/file.pdf',"
- "或路径数组如 ['/path/file1.csv', '/path/file2.xlsx']。"
+ "或 JSON 数组字符串如 '[\"/path/file1.csv\", \"/path/file2.xlsx\"]'。"
"支持任意文件类型(pdf、xlsx、docx、png、zip等)。"
),
}
diff --git a/jiuwenclaw/agents/harness/common/tools/web_file_download.py b/jiuwenclaw/agents/harness/common/tools/web_file_download.py
new file mode 100644
index 0000000000..62be5c4bf0
--- /dev/null
+++ b/jiuwenclaw/agents/harness/common/tools/web_file_download.py
@@ -0,0 +1,183 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Web File Download Token Manager
+
+提供基于 HMAC 签名的文件下载令牌生成与验证,支持跨进程(AgentServer / Gateway / app_web.py)
+无需共享内存即可安全校验。
+
+协议:
+- 令牌格式: Base64URL(payload_json) + "." + Hex(HMAC-SHA256)
+- payload 包含: path, exp, session_id
+- 密钥来源: 环境变量 JIUWENCLAW_FILE_DOWNLOAD_SECRET 或自动生成并写入共享文件
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import logging
+import os
+import secrets
+import time
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_EXPIRES_SECONDS = 600
+_SECRET_ENV_KEY = "JIUWENCLAW_FILE_DOWNLOAD_SECRET"
+_SECRET_FILE_NAME = ".file_download_secret"
+
+
+def _get_secret_file_path() -> Path:
+ workspace = os.getenv("JIUWENCLAW_WORKSPACE")
+ if workspace:
+ return Path(workspace) / "config" / _SECRET_FILE_NAME
+ return Path.home() / ".jiuwenclaw" / "config" / _SECRET_FILE_NAME
+
+
+def _load_or_create_secret() -> str:
+ secret = os.getenv(_SECRET_ENV_KEY)
+ if secret and len(secret) >= 32:
+ return secret
+
+ secret_file = _get_secret_file_path()
+ try:
+ if secret_file.exists():
+ existing = secret_file.read_text(encoding="utf-8").strip()
+ if existing and len(existing) >= 32:
+ return existing
+ except Exception:
+ logger.debug("[WebFileDownload] 读取密钥文件失败,将重新生成")
+
+ new_secret = secrets.token_hex(32)
+ try:
+ secret_file.parent.mkdir(parents=True, exist_ok=True)
+ secret_file.write_text(new_secret, encoding="utf-8")
+ os.chmod(secret_file, 0o600)
+ except Exception:
+ logger.warning("[WebFileDownload] 写入密钥文件失败,使用内存密钥(重启后失效)")
+
+ return new_secret
+
+
+class WebFileDownloadManager:
+ """管理 Web 端文件下载令牌的生成与验证。
+
+ 使用 HMAC-SHA256 签名保证令牌不可伪造,
+ 密钥通过环境变量或共享文件在 AgentServer / Gateway / app_web.py 间共享。
+ """
+
+ _instance: WebFileDownloadManager | None = None
+
+ def __init__(self, secret: str | None = None) -> None:
+ self._secret = secret or _load_or_create_secret()
+
+ @classmethod
+ def get_instance(cls) -> WebFileDownloadManager:
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ @classmethod
+ def reset_instance(cls) -> None:
+ cls._instance = None
+
+ def generate_token(
+ self,
+ file_path: str,
+ session_id: str = "",
+ expires_in: int = _DEFAULT_EXPIRES_SECONDS,
+ ) -> str:
+ payload = {
+ "path": file_path,
+ "exp": int(time.time()) + expires_in,
+ "sid": session_id,
+ }
+ payload_json = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
+ payload_b64 = base64.urlsafe_b64encode(
+ payload_json.encode("utf-8")
+ ).decode("ascii")
+ signature = hmac.new(
+ self._secret.encode("utf-8"),
+ payload_b64.encode("ascii"),
+ hashlib.sha256,
+ ).hexdigest()
+ return f"{payload_b64}.{signature}"
+
+ def validate_token(self, token: str) -> dict[str, Any] | None:
+ try:
+ parts = token.split(".")
+ if len(parts) != 2:
+ return None
+ payload_b64, signature = parts
+ expected_sig = hmac.new(
+ self._secret.encode("utf-8"),
+ payload_b64.encode("ascii"),
+ hashlib.sha256,
+ ).hexdigest()
+ if not hmac.compare_digest(signature, expected_sig):
+ logger.warning("[WebFileDownload] 令牌签名校验失败")
+ return None
+ payload_json = base64.urlsafe_b64decode(payload_b64).decode("utf-8")
+ payload = json.loads(payload_json)
+ if not isinstance(payload, dict):
+ return None
+ if payload.get("exp", 0) < time.time():
+ logger.info("[WebFileDownload] 令牌已过期: path=%s", payload.get("path"))
+ return None
+ return payload
+ except Exception:
+ logger.debug("[WebFileDownload] 令牌解析异常", exc_info=True)
+ return None
+
+ @staticmethod
+ def generate_download_url(token: str) -> str:
+ return f"/file-api/download?token={token}"
+
+
+def generate_file_download_token(
+ file_path: str,
+ session_id: str = "",
+ expires_in: int = _DEFAULT_EXPIRES_SECONDS,
+) -> str:
+ return WebFileDownloadManager.get_instance().generate_token(
+ file_path, session_id, expires_in
+ )
+
+
+def validate_file_download_token(token: str) -> dict[str, Any] | None:
+ return WebFileDownloadManager.get_instance().validate_token(token)
+
+
+def build_file_download_info(
+ file_path: str,
+ file_name: str,
+ session_id: str = "",
+ expires_in: int = _DEFAULT_EXPIRES_SECONDS,
+) -> dict[str, Any]:
+ token = generate_file_download_token(file_path, session_id, expires_in)
+ download_url = WebFileDownloadManager.get_instance().generate_download_url(token)
+
+ file_size = 0
+ mime_type = "application/octet-stream"
+ try:
+ file_size = os.path.getsize(file_path)
+ except OSError:
+ pass
+
+ import mimetypes
+
+ guessed_type, _ = mimetypes.guess_type(file_name)
+ if guessed_type:
+ mime_type = guessed_type
+
+ return {
+ "name": file_name,
+ "size": file_size,
+ "mime_type": mime_type,
+ "download_url": download_url,
+ "download_token": token,
+ }
diff --git a/jiuwenclaw/channels/web/app_web.py b/jiuwenclaw/channels/web/app_web.py
index 2253423c2a..1458366243 100644
--- a/jiuwenclaw/channels/web/app_web.py
+++ b/jiuwenclaw/channels/web/app_web.py
@@ -611,6 +611,10 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
self.wfile.write(body)
return
+ if path == "/file-api/download":
+ self._handle_file_download(query)
+ return
+
if path == "/file-api/ws-debug-config":
self._write_json(
200,
@@ -622,6 +626,63 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
self._write_json(404, {"error": "not_found"})
+ def _handle_file_download(self, query: dict[str, str]) -> None:
+ token = query.get("token", "")
+ if not token:
+ self._write_json(400, {"error": "missing_token"})
+ return
+
+ try:
+ from jiuwenclaw.agents.harness.common.tools.web_file_download import (
+ validate_file_download_token,
+ )
+ except ImportError:
+ self._write_json(500, {"error": "download_module_unavailable"})
+ return
+
+ payload = validate_file_download_token(token)
+ if payload is None:
+ self._write_json(403, {"error": "invalid_or_expired_token"})
+ return
+
+ file_path = payload.get("path", "")
+ if not file_path or not os.path.isfile(file_path):
+ self._write_json(404, {"error": "file_not_found"})
+ return
+
+ try:
+ file_size = os.path.getsize(file_path)
+ file_name = os.path.basename(file_path)
+
+ mime_type, _ = mimetypes.guess_type(file_name)
+ if not mime_type:
+ mime_type = "application/octet-stream"
+
+ self.send_response(200)
+ self.send_header("Content-Type", mime_type)
+ self.send_header("Content-Length", str(file_size))
+ self.send_header(
+ "Content-Disposition",
+ f'attachment; filename="{file_name}"',
+ )
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+
+ if self.command != "HEAD":
+ with open(file_path, "rb") as f:
+ while True:
+ chunk = f.read(65536)
+ if not chunk:
+ break
+ self.wfile.write(chunk)
+ except Exception as exc:
+ self.log_error("file download error: %s", exc)
+ try:
+ self._write_json(500, {"error": "download_failed", "detail": str(exc)})
+ except Exception:
+ # Connection may already be closed or broken; nothing more we can do.
+ self.log_error("failed to send download error response")
+
def _handle_file_api_post(self, parsed) -> None:
if parsed.path == "/file-api/rebuild-agent-data":
try:
diff --git a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
index 8a429a88fd..331f1472bc 100644
--- a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
+++ b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
@@ -6,7 +6,7 @@
import { useState, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { Message } from '../../types';
+import { Message, FileDownloadItem } from '../../types';
import { StreamingContent } from './StreamingContent';
import { ToolCallDisplay } from './ToolCallDisplay';
import { MediaRenderer } from './MediaRenderer';
@@ -34,6 +34,7 @@ export function MessageItem({ message, autoSpeak = false }: MessageItemProps) {
audioBase64,
audioMime,
mediaItems,
+ fileItems,
} = message;
const [hasAutoSpoken, setHasAutoSpoken] = useState(false);
const [isAudioPlaying, setIsAudioPlaying] = useState(false);
@@ -416,6 +417,9 @@ export function MessageItem({ message, autoSpeak = false }: MessageItemProps) {
{mediaItems && mediaItems.length > 0 && (
<MediaRenderer items={mediaItems} />
)}
+ {fileItems && fileItems.length > 0 && (
+ <FileDownloadList files={fileItems} />
+ )}
</>
)}
</div>
@@ -486,3 +490,104 @@ export function MessageItem({ message, autoSpeak = false }: MessageItemProps) {
</div>
);
}
+
+function formatFileSize(bytes: number | undefined): string {
+ if (bytes === undefined || bytes === null || isNaN(bytes)) return '';
+ if (bytes === 0) return '0 B';
+ const units = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
+ const size = bytes / Math.pow(1024, i);
+ return `${size.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
+}
+
+function getFileExtension(name: string): string {
+ const parts = name.split('.');
+ if (parts.length < 2) return '';
+ return parts[parts.length - 1].toUpperCase();
+}
+
+function getFileTypeConfig(mimeType: string | undefined, name: string) {
+ const ext = name.split('.').pop()?.toLowerCase() || '';
+ const mt = mimeType || '';
+ if (mt.startsWith('image/') || ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp'].includes(ext))
+ return { label: 'IMG', bg: 'bg-[#3370ff]', icon: '🖼' };
+ if (mt.startsWith('audio/') || ['mp3', 'wav', 'aac', 'flac', 'ogg'].includes(ext))
+ return { label: 'AUDIO', bg: 'bg-[#7b67ee]', icon: '🎵' };
+ if (mt.startsWith('video/') || ['mp4', 'avi', 'mov', 'mkv', 'webm'].includes(ext))
+ return { label: 'VIDEO', bg: 'bg-[#f77234]', icon: '🎬' };
+ if (mt.includes('pdf') || ext === 'pdf')
+ return { label: 'PDF', bg: 'bg-[#f54a45]', icon: '📄' };
+ if (mt.includes('presentation') || mt.includes('ppt') || ['ppt', 'pptx'].includes(ext))
+ return { label: 'PPT', bg: '#FFFFFF', icon: (
+ <svg viewBox="0 0 1024 1024" className="w-7 h-7">
+ <path d="M145.6 0C100.8 0 64 36.8 64 81.6v860.8C64 987.2 100.8 1024 145.6 1024h732.8c44.8 0 81.6-36.8 81.6-81.6V324.8L657.6 0h-512z" fill="#E34221" />
+ <path d="M960 326.4v16H755.2s-100.8-20.8-99.2-108.8c0 0 4.8 92.8 97.6 92.8H960z" fill="#DC3119" />
+ <path d="M657.6 0v233.6c0 25.6 17.6 92.8 97.6 92.8H960L657.6 0z" fill="#FFFFFF" opacity=".5" />
+ <path d="M304 784h-54.4v67.2c0 6.4-4.8 11.2-11.2 11.2-6.4 0-12.8-4.8-12.8-11.2V686.4c0-9.6 8-17.6 17.6-17.6H304c38.4 0 59.2 25.6 59.2 57.6S340.8 784 304 784z m-3.2-94.4h-51.2v73.6h51.2c22.4 0 38.4-16 38.4-36.8 0-22.4-16-36.8-38.4-36.8zM480 784h-54.4v67.2c0 6.4-4.8 11.2-11.2 11.2-6.4 0-11.2-4.8-11.2-11.2V686.4c0-9.6 6.4-17.6 16-17.6H480c38.4 0 59.2 25.6 59.2 57.6S518.4 784 480 784z m-3.2-94.4h-49.6v73.6h49.6c22.4 0 38.4-16 38.4-36.8 0-22.4-16-36.8-38.4-36.8z m225.6 0h-52.8v161.6c0 6.4-4.8 11.2-11.2 11.2-6.4 0-12.8-4.8-12.8-11.2V689.6h-51.2c-6.4 0-11.2-4.8-11.2-11.2 0-4.8 4.8-9.6 11.2-9.6h128c6.4 0 11.2 4.8 11.2 11.2 0 4.8-4.8 9.6-11.2 9.6z" fill="#FFFFFF" />
+ </svg>
+ ) };
+ if (mt.includes('spreadsheet') || mt.includes('excel') || mt.includes('xlsx') || ['xls', 'xlsx', 'csv'].includes(ext))
+ return { label: 'XLS', bg: 'bg-[#2b9348]', icon: '📗' };
+ if (mt.includes('word') || mt.includes('document') || mt.includes('docx') || ['doc', 'docx'].includes(ext))
+ return { label: 'DOC', bg: 'bg-[#3370ff]', icon: '📝' };
+ if (mt.includes('zip') || mt.includes('compressed') || mt.includes('archive') || ['zip', 'rar', '7z', 'tar', 'gz'].includes(ext))
+ return { label: 'ZIP', bg: 'bg-[#8b5cf6]', icon: '📦' };
+ if (['txt', 'md', 'log'].includes(ext))
+ return { label: 'TXT', bg: 'bg-[#6b7280]', icon: '📃' };
+ if (['json', 'xml', 'yaml', 'yml', 'toml', 'ini', 'cfg'].includes(ext))
+ return { label: 'CFG', bg: 'bg-[#6b7280]', icon: '⚙' };
+ if (['py', 'js', 'ts', 'java', 'go', 'rs', 'cpp', 'c', 'h'].includes(ext))
+ return { label: 'CODE', bg: 'bg-[#6b7280]', icon: '�' };
+ return { label: 'FILE', bg: 'bg-[#6b7280]', icon: '��' };
+}
+
+function FileDownloadList({ files }: { files: FileDownloadItem[] }) {
+ const handleDownload = (file: FileDownloadItem) => {
+ const link = document.createElement('a');
+ link.href = file.download_url;
+ link.download = file.name || '';
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ };
+
+ return (
+ <div className="mt-2 space-y-2">
+ {files.map((file, index) => {
+ const typeConfig = getFileTypeConfig(file.mime_type, file.name);
+ const ext = getFileExtension(file.name);
+ return (
+ <div
+ key={`${file.name}-${index}`}
+ className="flex items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 hover:shadow-md hover:border-border-hover transition-all duration-fast cursor-pointer group"
+ onClick={() => handleDownload(file)}
+ >
+ <div className={`flex-shrink-0 w-10 h-10 rounded-lg ${typeConfig.bg} flex items-center justify-center`}>
+ {typeof typeConfig.icon === 'string' ? (
+ <span className="text-white text-base leading-none select-none">{typeConfig.icon}</span>
+ ) : (
+ typeConfig.icon
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-text leading-snug truncate">{file.name}</div>
+ <div className="flex items-center gap-1.5 mt-0.5">
+ <span className="inline-flex items-center px-1 py-px rounded text-[10px] font-mono font-medium text-text-muted bg-secondary leading-none">
+ {ext || typeConfig.label}
+ </span>
+ <span className="text-xs text-text-muted">{formatFileSize(file.size)}</span>
+ </div>
+ </div>
+ <div
+ className="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-text-muted group-hover:text-accent group-hover:bg-accent-subtle transition-colors duration-fast"
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
+ </svg>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts
index 7d9ec4fec9..770427587c 100644
--- a/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -23,6 +23,7 @@ import {
ToolResult,
ToolCall,
UsageSummary,
+ FileDownloadItem,
} from '../types';
import { useChatStore, useTodoStore, useSessionStore } from '../stores';
import { webClient } from '../services/webClient';
@@ -163,6 +164,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
clearMessages,
setPendingQuestion,
removeFromTaskQueue,
+ addFileItems,
} = useChatStore();
const { setTodos, clearTodos } = useTodoStore();
const {
@@ -748,6 +750,12 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
handleTtsPlayback(targetId, mediaPayload.content);
}
}),
+ webClient.on('chat.file', ({ payload }) => {
+ if (!shouldHandleSessionEvent(payload)) return;
+ const files = (payload.files ?? []) as FileDownloadItem[];
+ if (!files.length) return;
+ addFileItems(files);
+ }),
webClient.on('chat.tool_call', ({ payload }) => {
if (!shouldHandleSessionEvent(payload)) return;
if (shouldDropDuplicatedEvent('chat.tool_call', payload)) return;
diff --git a/jiuwenclaw/channels/web/frontend/src/services/webClient.ts b/jiuwenclaw/channels/web/frontend/src/services/webClient.ts
index 16fa9eb8c3..be95e2054d 100644
--- a/jiuwenclaw/channels/web/frontend/src/services/webClient.ts
+++ b/jiuwenclaw/channels/web/frontend/src/services/webClient.ts
@@ -28,6 +28,7 @@ const LEGACY_EVENT_MAP: Record<string, string> = {
content_chunk: 'chat.delta',
content: 'chat.final',
media_content: 'chat.media',
+ file_content: 'chat.file',
tool_call: 'chat.tool_call',
tool_result: 'chat.tool_result',
error: 'chat.error',
diff --git a/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts b/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts
index ee50ab1f1c..8aedc68772 100644
--- a/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts
+++ b/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts
@@ -14,6 +14,7 @@ import {
AskUserQuestionPayload,
EvolutionStatusPayload,
UsageSummary,
+ FileDownloadItem,
} from '../types';
import { useTodoStore } from './todoStore';
@@ -107,6 +108,8 @@ interface ChatState {
setInputValue: (value: string) => void;
// Usage summary
setUsageSummary: (messageId: string, usage: UsageSummary) => void;
+ // File download items
+ addFileItems: (files: FileDownloadItem[]) => void;
}
export const useChatStore = create<ChatState>((set, get) => ({
@@ -578,4 +581,34 @@ export const useChatStore = create<ChatState>((set, get) => ({
),
}));
},
+
+ addFileItems: (files) => {
+ const { currentStreamId, messages } = get();
+ let targetId =
+ currentStreamId ??
+ [...messages].reverse().find((msg) => msg.role === 'assistant')?.id;
+ if (!targetId) {
+ const msgId = `file-${Date.now()}`;
+ set((state) => ({
+ messages: [
+ ...state.messages,
+ {
+ id: msgId,
+ role: 'assistant',
+ content: '',
+ timestamp: new Date().toISOString(),
+ fileItems: files,
+ },
+ ],
+ }));
+ return;
+ }
+ set((state) => ({
+ messages: state.messages.map((msg) =>
+ msg.id === targetId
+ ? { ...msg, fileItems: [...(msg.fileItems || []), ...files] }
+ : msg
+ ),
+ }));
+ },
}));
diff --git a/jiuwenclaw/channels/web/frontend/src/types/message.ts b/jiuwenclaw/channels/web/frontend/src/types/message.ts
index 6e42a4dd8e..2e9b307496 100644
--- a/jiuwenclaw/channels/web/frontend/src/types/message.ts
+++ b/jiuwenclaw/channels/web/frontend/src/types/message.ts
@@ -21,6 +21,14 @@ export interface UsageSummary {
total_cost?: number;
}
+export interface FileDownloadItem {
+ name: string;
+ size: number;
+ mime_type: string;
+ download_url: string;
+ download_token: string;
+}
+
export interface Message {
id: string;
role: MessageRole;
@@ -29,6 +37,7 @@ export interface Message {
audioBase64?: string;
audioMime?: string;
mediaItems?: MediaItem[];
+ fileItems?: FileDownloadItem[];
// 工具调用相关
toolCall?: ToolCall;
toolResult?: ToolResult;
diff --git a/jiuwenclaw/gateway/channel_manager/web/web_connect.py b/jiuwenclaw/gateway/channel_manager/web/web_connect.py
index f018aacda4..4feba95c7e 100644
--- a/jiuwenclaw/gateway/channel_manager/web/web_connect.py
+++ b/jiuwenclaw/gateway/channel_manager/web/web_connect.py
@@ -357,7 +357,7 @@ class WebChannel(BaseChannel):
"context.compressed", "chat.ask_user_question", "chat.subtask_update",
"history.message",
"chat.session_result", "chat.usage_metadata",
- "chat.usage_summary") or event_name.startswith("team."):
+ "chat.usage_summary", "chat.file") or event_name.startswith("team."):
# 传递完整 payload,保留所有字段
payload = {**msg.payload}
# 确保包含 session_id
diff --git a/jiuwenclaw/resources/config.team.distributed.leader.yaml b/jiuwenclaw/resources/config.team.distributed.leader.yaml
index 7794121886..00192554b8 100644
--- a/jiuwenclaw/resources/config.team.distributed.leader.yaml
+++ b/jiuwenclaw/resources/config.team.distributed.leader.yaml
@@ -317,6 +317,8 @@ heartbeat:
end: 22:00
channels:
+ web:
+ send_file_allowed: true
feishu:
# 飞书应用配置
app_id:
diff --git a/jiuwenclaw/resources/config.team.distributed.teammate.yaml b/jiuwenclaw/resources/config.team.distributed.teammate.yaml
index d447bf5f67..002fc6ae3d 100644
--- a/jiuwenclaw/resources/config.team.distributed.teammate.yaml
+++ b/jiuwenclaw/resources/config.team.distributed.teammate.yaml
@@ -317,6 +317,8 @@ heartbeat:
end: 22:00
channels:
+ web:
+ send_file_allowed: true
feishu:
# 飞书应用配置
app_id:
diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yaml
index 71993dd6d7..9c21d29540 100644
--- a/jiuwenclaw/resources/config.yaml
+++ b/jiuwenclaw/resources/config.yaml
@@ -320,6 +320,8 @@ heartbeat:
end: 22:00
channels:
+ web:
+ send_file_allowed: true
feishu:
# 飞书应用配置
app_id: