Skip to content

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

Python

fix: 增加文档上传和解析功能

w110162753359b87ca3becd
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 8da98bfa9c..44033b61cf 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -595,6 +595,7 @@ function AppContent() {
isConnected,
request,
persistMedia,
+ persistDocuments,
sendMessage,
sendStructuredChatContent,
pause,
@@ -1708,6 +1709,14 @@ function AppContent() {
return persistMedia(content, currentSessionId, mediaItems);
}, [persistMedia]);
+ const handlePersistDocuments = useCallback((content: string, mediaItems: MediaItem[]) => {
+ const currentSessionId = sessionIdRef.current;
+ if (!currentSessionId || currentSessionId === NEW_CONVERSATION_ID) {
+ return Promise.reject(new Error('会话未就绪,请稍后重试'));
+ }
+ return persistDocuments(content, currentSessionId, mediaItems);
+ }, [persistDocuments]);
+
useEffect(() => {
return setA2UIActionHandler((message) => {
const currentSessionId = sessionIdRef.current;
@@ -2178,6 +2187,7 @@ function AppContent() {
<ChatPanel
onSendMessage={handleSendMessage}
onPersistMedia={handlePersistMedia}
+ onPersistDocuments={handlePersistDocuments}
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.css
index 5f5ed6a110..8cb8fc9c59 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css
@@ -2451,14 +2451,14 @@ overflow: hidden;
height: 36px;
border-radius: 7px;
overflow: hidden;
- background-color: var(--color-action-secondary);
- background-image: linear-gradient(
- rgba(var(--color-action-primary-rgb), 0.08),
- rgba(var(--color-action-primary-rgb), 0.08)
- );
+ background: transparent;
color: var(--color-action-primary);
}
+.chat-input-attachment-preview--image {
+ background-color: var(--color-action-secondary);
+}
+
.chat-input-attachment-preview img {
display: block;
width: 100%;
@@ -2538,6 +2538,199 @@ overflow: hidden;
font-weight: 500;
}
+/* Uploaded files in chat message (above bubble) */
+.chat-msg-attachments {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+}
+
+.chat-msg-attachments--above {
+ margin-bottom: 8px;
+}
+
+.chat-msg-file-row {
+ display: flex;
+ flex-wrap: nowrap;
+ align-items: stretch;
+ gap: 8px;
+ min-width: 0;
+}
+
+.chat-msg-file-row--end {
+ justify-content: flex-end;
+}
+
+.chat-msg-file-row--start {
+ justify-content: flex-start;
+}
+
+.chat-msg-file-card {
+ display: grid;
+ grid-template-columns: 28px minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+ box-sizing: border-box;
+ width: 168px;
+ max-width: 46%;
+ min-height: 48px;
+ padding: 8px 10px;
+ border: 1px solid rgba(var(--color-border-default-rgb), 0.9);
+ border-radius: 10px;
+ background: var(--color-surface-card);
+ box-shadow: var(--effect-chat-toolbar-shadow);
+ text-decoration: none;
+ color: inherit;
+}
+
+.chat-msg-file-card__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ overflow: hidden;
+ border-radius: 5px;
+}
+
+.chat-msg-file-card__thumb {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.chat-msg-file-card__meta {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.chat-msg-file-card__name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--color-text-primary);
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 18px;
+}
+
+.chat-msg-file-card__ext {
+ color: var(--color-text-secondary);
+ font-size: 12px;
+ line-height: 16px;
+ text-transform: lowercase;
+}
+
+.chat-msg-file-more {
+ position: relative;
+ flex: 0 0 auto;
+}
+
+.chat-msg-file-more__btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 48px;
+ height: 48px;
+ padding: 0 10px;
+ border: 1px solid rgba(var(--color-border-default-rgb), 0.9);
+ border-radius: 10px;
+ background: var(--color-surface-card);
+ box-shadow: var(--effect-chat-toolbar-shadow);
+ color: var(--color-text-primary);
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1;
+ cursor: pointer;
+}
+
+.chat-msg-file-more__btn:hover {
+ background-image: linear-gradient(
+ rgba(var(--color-action-primary-rgb), 0.06),
+ rgba(var(--color-action-primary-rgb), 0.06)
+ );
+}
+
+.chat-msg-file-more__menu {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ z-index: 30;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 220px;
+ max-width: min(320px, 70vw);
+ max-height: 240px;
+ overflow-y: auto;
+ padding: 6px;
+ border: 1px solid rgba(var(--color-border-default-rgb), 0.9);
+ border-radius: 10px;
+ background: var(--color-surface-card);
+ box-shadow: var(--effect-chat-menu-shadow);
+}
+
+.chat-msg-file-more__item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 8px 10px;
+ border-radius: 8px;
+ color: var(--color-text-primary);
+ text-decoration: none;
+}
+
+.chat-msg-file-more__item:hover {
+ background-image: linear-gradient(
+ rgba(var(--color-action-primary-rgb), 0.08),
+ rgba(var(--color-action-primary-rgb), 0.08)
+ );
+}
+
+.chat-msg-file-more__name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 13px;
+ line-height: 18px;
+}
+
+.chat-msg-file-more__thumb {
+ display: block;
+ width: 20px;
+ height: 20px;
+ flex-shrink: 0;
+ border-radius: 4px;
+ object-fit: cover;
+}
+
+.chat-msg-media-rich {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+}
+
+.chat-msg-media-rich--end {
+ align-items: flex-end;
+}
+
+.chat-msg-media-rich--start {
+ align-items: flex-start;
+}
+
+.chat-msg-media-image {
+ display: block;
+ max-width: 100%;
+ border-radius: 10px;
+ border: 1px solid rgba(var(--color-border-default-rgb), 0.84);
+}
+
.chat-input-attachment-retry {
display: inline-flex;
align-items: center;
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsx
new file mode 100644
index 0000000000..6e94e9b579
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/FileTypeIcon.tsx
@@ -0,0 +1,254 @@
+import { useId, type CSSProperties, type ReactNode } from 'react';
+
+export type FileTypeIconKey =
+ | 'pdf'
+ | 'docx'
+ | 'sheet'
+ | 'html'
+ | 'json'
+ | 'ipynb'
+ | 'md'
+ | 'text'
+ | 'image'
+ | 'file'
+ | 'unknown';
+
+const ICON_COLORS: Record<FileTypeIconKey, { base: string; light: string; fold: string }> = {
+ pdf: { base: '#E24B4A', light: '#F06A5F', fold: '#C53A3A' },
+ docx: { base: '#2F6FED', light: '#5B8FF5', fold: '#2459C7' },
+ md: { base: '#0D9488', light: '#2DD4BF', fold: '#0F766E' },
+ text: { base: '#64748B', light: '#94A3B8', fold: '#475569' },
+ sheet: { base: '#1FA971', light: '#3FBF88', fold: '#178A5B' },
+ html: { base: '#F08A24', light: '#F5A24D', fold: '#D47312' },
+ json: { base: '#6B7C93', light: '#8796A8', fold: '#556578' },
+ ipynb: { base: '#7B61FF', light: '#9580FF', fold: '#6349E0' },
+ image: { base: '#E45CA8', light: '#F07BC0', fold: '#C9448F' },
+ file: { base: '#3B82F6', light: '#60A5FA', fold: '#2563EB' },
+ unknown: { base: '#9AA3AF', light: '#B0B8C2', fold: '#7F8894' },
+};
+
+function DocumentShell({
+ typeKey,
+ children,
+ size,
+ gradientId,
+}: {
+ typeKey: FileTypeIconKey;
+ children?: ReactNode;
+ size: number;
+ gradientId: string;
+}) {
+ const colors = ICON_COLORS[typeKey];
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 48 48"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ aria-hidden="true"
+ style={{ display: 'block', flexShrink: 0 } as CSSProperties}
+ >
+ <defs>
+ <linearGradient id={gradientId} x1="24" y1="2" x2="24" y2="46" gradientUnits="userSpaceOnUse">
+ <stop stopColor={colors.light} />
+ <stop offset="1" stopColor={colors.base} />
+ </linearGradient>
+ </defs>
+ <path
+ d="M10 4C8.34315 4 7 5.34315 7 7V41C7 42.6569 8.34315 44 10 44H38C39.6569 44 41 42.6569 41 41V16L31 4H10Z"
+ fill={`url(#${gradientId})`}
+ />
+ <path d="M31 4V12C31 14.2091 32.7909 16 35 16H41L31 4Z" fill={colors.fold} />
+ <path d="M31 4L41 16H35C32.7909 16 31 14.2091 31 12V4Z" fill="rgba(255,255,255,0.28)" />
+ {children}
+ </svg>
+ );
+}
+
+function GlyphPdf() {
+ return (
+ <path
+ fill="white"
+ d="M17.8 31.8c.4-3.8 1.9-7.6 4.4-10.5 2.2-2.5 5-4.1 8.2-3.6 1.7.3 2.9 1.6 2.7 3.2-.3 2.2-2.3 3.4-4.4 4.1-2.6.8-5.3.7-7.9 1.5-2.1.7-3.4 2.2-3 5.3zm4.6-1.8c1.6-1.8 4.4-2.1 6.8-2.7 2-.5 3.5-1.3 3.7-2.8.1-.8-.5-1.4-1.4-1.5-2.1-.3-4.1.8-5.7 2.4-1.8 1.9-3 4.3-3.4 6.8.1-.7.1-1.5 0-2.2z"
+ />
+ );
+}
+
+function GlyphLines() {
+ return (
+ <>
+ <rect x="15" y="20" width="18" height="2.6" rx="1.3" fill="white" />
+ <rect x="15" y="25.2" width="14" height="2.6" rx="1.3" fill="white" />
+ <rect x="15" y="30.4" width="16" height="2.6" rx="1.3" fill="white" />
+ </>
+ );
+}
+
+/** Markdown: hash headings style */
+function GlyphMd() {
+ return (
+ <>
+ <path
+ d="M18 19V33M22.5 19V33"
+ stroke="white"
+ strokeWidth="2.4"
+ strokeLinecap="round"
+ />
+ <path
+ d="M16.5 24.5H24"
+ stroke="white"
+ strokeWidth="2.4"
+ strokeLinecap="round"
+ />
+ <rect x="27" y="22" width="5.5" height="2.2" rx="1.1" fill="white" />
+ <rect x="27" y="27" width="8" height="2.2" rx="1.1" fill="white" />
+ </>
+ );
+}
+
+/** Plain text: letter T */
+function GlyphTxt() {
+ return (
+ <path
+ d="M17 20H31M24 20V33"
+ stroke="white"
+ strokeWidth="2.6"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ );
+}
+
+function GlyphSheet() {
+ return (
+ <>
+ <rect x="15" y="19.5" width="5.8" height="5.8" rx="1.1" fill="white" />
+ <rect x="22.6" y="19.5" width="5.8" height="5.8" rx="1.1" fill="white" />
+ <rect x="30.2" y="19.5" width="2.4" height="5.8" rx="1" fill="white" fillOpacity="0.9" />
+ <rect x="15" y="27.2" width="5.8" height="5.8" rx="1.1" fill="white" />
+ <rect x="22.6" y="27.2" width="5.8" height="5.8" rx="1.1" fill="white" />
+ <rect x="30.2" y="27.2" width="2.4" height="5.8" rx="1" fill="white" fillOpacity="0.9" />
+ </>
+ );
+}
+
+function GlyphPie() {
+ return (
+ <>
+ <circle cx="24" cy="26" r="7.5" fill="white" fillOpacity="0.35" />
+ <path d="M24 18.5V26H31.5A7.5 7.5 0 0 0 24 18.5Z" fill="white" />
+ <path d="M24 26V33.5A7.5 7.5 0 0 0 30.8 29.2L24 26Z" fill="white" fillOpacity="0.85" />
+ </>
+ );
+}
+
+function GlyphCode() {
+ return (
+ <path
+ d="M20.2 22.2L17 25.2L20.2 28.2M27.8 22.2L31 25.2L27.8 28.2M25.2 20.5L22.8 30"
+ stroke="white"
+ strokeWidth="2.2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ );
+}
+
+function GlyphImage() {
+ return (
+ <>
+ <rect x="14.5" y="19" width="19" height="14" rx="2.2" fill="white" fillOpacity="0.95" />
+ <circle cx="19.5" cy="23.5" r="1.8" fill="#E45CA8" />
+ <path d="M15.5 30.5L21 26L25 29L28.5 25.5L32.5 30.5H15.5Z" fill="#E45CA8" />
+ </>
+ );
+}
+
+function GlyphQuestion() {
+ return (
+ <text
+ x="24"
+ y="31.5"
+ textAnchor="middle"
+ fill="white"
+ fontSize="18"
+ fontWeight="700"
+ fontFamily="Arial, Helvetica, sans-serif"
+ >
+ ?
+ </text>
+ );
+}
+
+function glyphFor(typeKey: FileTypeIconKey): ReactNode {
+ switch (typeKey) {
+ case 'pdf':
+ return <GlyphPdf />;
+ case 'docx':
+ return <GlyphLines />;
+ case 'md':
+ return <GlyphMd />;
+ case 'text':
+ return <GlyphTxt />;
+ case 'sheet':
+ return <GlyphSheet />;
+ case 'html':
+ return <GlyphPie />;
+ case 'json':
+ case 'ipynb':
+ return <GlyphCode />;
+ case 'image':
+ return <GlyphImage />;
+ case 'unknown':
+ return <GlyphQuestion />;
+ case 'file':
+ return null;
+ default:
+ return <GlyphQuestion />;
+ }
+}
+
+export function getFileTypeIconKeyFromFilename(filename: string, kind?: string): FileTypeIconKey {
+ if (kind === 'image') return 'image';
+ const idx = filename.lastIndexOf('.');
+ const ext = idx >= 0 ? filename.slice(idx).toLowerCase() : '';
+ if (ext === '.pdf') return 'pdf';
+ if (ext === '.docx' || ext === '.doc') return 'docx';
+ if (ext === '.xlsx' || ext === '.xls' || ext === '.csv' || ext === '.tsv') return 'sheet';
+ if (ext === '.html' || ext === '.htm' || ext === '.css') return 'html';
+ if (ext === '.json') return 'json';
+ if (ext === '.ipynb') return 'ipynb';
+ if (ext === '.md' || ext === '.markdown') return 'md';
+ if (ext === '.txt') return 'text';
+ if (['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg'].includes(ext)) return 'image';
+ if (!ext) return 'file';
+ return 'unknown';
+}
+
+export function splitFilenameParts(filename: string): { stem: string; extLabel: string } {
+ const idx = filename.lastIndexOf('.');
+ if (idx <= 0 || idx === filename.length - 1) {
+ return { stem: filename || 'file', extLabel: '' };
+ }
+ return {
+ stem: filename.slice(0, idx),
+ extLabel: filename.slice(idx + 1).toLowerCase(),
+ };
+}
+
+export function FileTypeIcon({
+ typeKey,
+ size = 32,
+}: {
+ typeKey: FileTypeIconKey;
+ size?: number;
+}) {
+ const reactId = useId().replace(/:/g, '');
+ const key: FileTypeIconKey = ICON_COLORS[typeKey] ? typeKey : 'unknown';
+ return (
+ <DocumentShell typeKey={key} size={size} gradientId={`fti-${key}-${reactId}`}>
+ {glyphFor(key)}
+ </DocumentShell>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx
index 34f612277d..655115f8b3 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx
@@ -1,7 +1,8 @@
import { useState, useRef, useCallback, KeyboardEvent, useEffect, ClipboardEvent, DragEvent, ChangeEvent, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
-import { AtSign, CircleX, FileImage, Loader2, Plus, Square, Target, X } from 'lucide-react';
+import { AtSign, CircleX, FileText, Loader2, Plus, Square, Target, X } from 'lucide-react';
+import { FileTypeIcon, getFileTypeIconKeyFromFilename, type FileTypeIconKey } from './FileTypeIcon';
import { useSpeechRecognition } from '../../hooks';
// import { stopAllTts } from '../../utils';
@@ -101,6 +102,7 @@ function isDefaultProject(project: ProjectInfo): boolean {
interface InputAreaProps {
onSubmit: (content: string, mediaItems?: MediaItem[]) => void;
onPersistMedia: (content: string, mediaItems: MediaItem[]) => Promise<PersistMediaResponse>;
+ onPersistDocuments: (content: string, mediaItems: MediaItem[]) => Promise<PersistMediaResponse>;
onInterrupt: (newInput?: string) => void;
onCancel: () => void;
onSwitchMode: (mode: AgentMode) => void;
@@ -124,14 +126,53 @@ interface InputAreaProps {
}
const ACCEPTED_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
+const ACCEPTED_DOCUMENT_EXTENSIONS = new Set([
+ '.pdf',
+ '.docx',
+ '.xlsx',
+ '.csv',
+ '.tsv',
+ '.txt',
+ '.md',
+ '.markdown',
+ '.html',
+ '.htm',
+ '.json',
+ '.ipynb',
+]);
+const ACCEPTED_DOCUMENT_MIME_TYPES = new Set([
+ 'application/pdf',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'text/csv',
+ 'application/csv',
+ 'text/tab-separated-values',
+ 'text/plain',
+ 'text/markdown',
+ 'text/x-markdown',
+ 'text/html',
+ 'application/xhtml+xml',
+ 'application/json',
+ 'application/x-ipynb+json',
+ 'application/jupyter',
+ 'application/vnd.jupyter',
+]);
+const DOCUMENT_ACCEPT =
+ '.pdf,.docx,.xlsx,.csv,.tsv,.txt,.md,.markdown,.html,.htm,.json,.ipynb,application/pdf,text/plain,text/markdown,text/html,application/json';
+const IMAGE_ACCEPT = 'image/png,image/jpeg,image/webp,image/gif,.png,.jpg,.jpeg,.webp,.gif';
+const ATTACHMENT_ACCEPT = `${IMAGE_ACCEPT},${DOCUMENT_ACCEPT}`;
+const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
-const MAX_IMAGE_COUNT = 20;
+const MAX_DOCUMENT_BYTES = 30 * 1024 * 1024;
+const MAX_ATTACHMENT_COUNT = 20;
const ATTACHMENT_ALERT_DURATION_MS = 3000;
+type AttachmentKind = 'image' | 'document';
type AttachmentStatus = 'uploading' | 'ready' | 'error';
interface AttachmentDraft {
id: string;
+ kind: AttachmentKind;
filename: string;
mimeType: string;
size: number;
@@ -162,7 +203,21 @@ function formatAttachmentSize(size: number): string {
}
function makeAttachmentId(file: File): string {
- return `${file.name || 'image'}-${file.size}-${generateUuidV4()}`;
+ return `${file.name || 'attachment'}-${file.size}-${generateUuidV4()}`;
+}
+
+function getFileExtension(filename: string): string {
+ const idx = filename.lastIndexOf('.');
+ if (idx < 0) return '';
+ return filename.slice(idx).toLowerCase();
+}
+
+function getAttachmentTypeKey(attachment: AttachmentDraft): FileTypeIconKey {
+ return getFileTypeIconKeyFromFilename(attachment.filename, attachment.kind);
+}
+
+function AttachmentTypeIcon({ attachment }: { attachment: AttachmentDraft }) {
+ return <FileTypeIcon typeKey={getAttachmentTypeKey(attachment)} size={32} />;
}
function attachmentToMediaItem(attachment: AttachmentDraft): MediaItem {
@@ -170,13 +225,14 @@ function attachmentToMediaItem(attachment: AttachmentDraft): MediaItem {
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;
+ const path = pickString(persisted?.path);
+ // After persist, only send path metadata — never re-send base64 on chat.send.
return {
- type: 'image',
+ type: attachment.kind,
mimeType,
mime_type: mimeType,
filename,
- base64Data: attachment.base64Data,
- path: pickString(persisted?.path),
+ ...(path ? { path } : { base64Data: attachment.base64Data }),
sizeBytes,
size_bytes: sizeBytes,
};
@@ -184,7 +240,7 @@ function attachmentToMediaItem(attachment: AttachmentDraft): MediaItem {
function buildUploadMediaItem(attachment: AttachmentDraft, payload: Pick<AttachmentDraft, 'base64Data'>): MediaItem {
return {
- type: 'image',
+ type: attachment.kind,
mimeType: attachment.mimeType,
filename: attachment.filename,
base64Data: payload.base64Data,
@@ -209,8 +265,27 @@ function pickNumber(...values: unknown[]): number | undefined {
return undefined;
}
+function isImageFile(file: File): boolean {
+ if (ACCEPTED_IMAGE_TYPES.has(file.type)) return true;
+ return IMAGE_EXTENSIONS.has(getFileExtension(file.name || ''));
+}
+
+function isDocumentFile(file: File): boolean {
+ const ext = getFileExtension(file.name || '');
+ const mimeOk = Boolean(file.type) && ACCEPTED_DOCUMENT_MIME_TYPES.has(file.type);
+ const extOk = ACCEPTED_DOCUMENT_EXTENSIONS.has(ext);
+ return mimeOk || extOk;
+}
+
+/** Classify a picked file for routing to media.persist vs document.persist. */
+function resolveAttachmentKind(file: File): AttachmentKind | null {
+ if (isImageFile(file)) return 'image';
+ if (isDocumentFile(file)) return 'document';
+ return null;
+}
+
function getImageValidationError(file: File): string | null {
- if (!ACCEPTED_IMAGE_TYPES.has(file.type)) {
+ if (!isImageFile(file)) {
return `文件类型不支持:${file.name || '未命名文件'}`;
}
if (file.size > MAX_IMAGE_BYTES) {
@@ -224,10 +299,17 @@ function clearAttachmentAlertTimers(timers: Map<string, number>): void {
timers.clear();
}
-function readImageFile(file: File): Promise<Pick<AttachmentDraft, 'base64Data' | 'previewUrl'> | null> {
- if (getImageValidationError(file)) {
- return Promise.resolve(null);
+function getDocumentValidationError(file: File): string | null {
+ if (!isDocumentFile(file)) {
+ return `文件类型不支持:${file.name || '未命名文件'}`;
+ }
+ if (file.size > MAX_DOCUMENT_BYTES) {
+ return `文件大小超出限制:${file.name || '未命名文件'}(最大${formatAttachmentSize(MAX_DOCUMENT_BYTES)})`;
}
+ return null;
+}
+
+function readBinaryFileAsBase64(file: File): Promise<Pick<AttachmentDraft, 'base64Data' | 'previewUrl'> | null> {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => {
@@ -237,16 +319,40 @@ function readImageFile(file: File): Promise<Pick<AttachmentDraft, 'base64Data' |
resolve(null);
return;
}
- resolve({ base64Data, previewUrl: result });
+ resolve({
+ base64Data,
+ previewUrl: ACCEPTED_IMAGE_TYPES.has(file.type) ? result : undefined,
+ });
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(file);
});
}
+function readImageFile(file: File): Promise<Pick<AttachmentDraft, 'base64Data' | 'previewUrl'> | null> {
+ if (getImageValidationError(file)) {
+ return Promise.resolve(null);
+ }
+ return readBinaryFileAsBase64(file);
+}
+
+function buildSubmitContent(text: string, attachments: AttachmentDraft[]): string {
+ const docs = attachments.filter((item) => item.kind === 'document' && item.status === 'ready');
+ if (!docs.length) {
+ return text;
+ }
+ // Agent-facing hint only (stripped from chat bubble). List every file; no 说明 line.
+ const lines = docs.map((doc) => {
+ const path = pickString(doc.persistedMediaItem?.path) || '';
+ return path ? `- ${doc.filename}: ${path}` : `- ${doc.filename}`;
+ });
+ return [text, '【上传文档】', ...lines].filter(Boolean).join('\n');
+}
+
export function InputArea({
onSubmit,
onPersistMedia,
+ onPersistDocuments,
onInterrupt,
onCancel,
onSwitchMode,
@@ -454,7 +560,12 @@ export function InputArea({
// 触发按钮只要不在录音就该能点开;具体某一项能不能选,交给菜单里每一项各自的禁用态处理。
const attachTriggerDisabled = isListening;
const readyAttachments = useMemo(
- () => attachments.filter((attachment) => attachment.status === 'ready' && attachment.base64Data),
+ () =>
+ attachments.filter(
+ (attachment) =>
+ attachment.status === 'ready' &&
+ (Boolean(pickString(attachment.persistedMediaItem?.path)) || Boolean(attachment.base64Data)),
+ ),
[attachments],
);
const hasUploadingAttachments = attachments.some((attachment) => attachment.status === 'uploading');
@@ -578,14 +689,21 @@ export function InputArea({
const uploadAttachment = useCallback((attachment: AttachmentDraft) => {
if (!attachment.file) return;
- const validationError = getImageValidationError(attachment.file);
+ const validationError =
+ attachment.kind === 'document'
+ ? getDocumentValidationError(attachment.file)
+ : 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) => {
+ const reader =
+ attachment.kind === 'document'
+ ? readBinaryFileAsBase64(attachment.file)
+ : readImageFile(attachment.file);
+ void reader.then(async (payload) => {
if (!payload) {
updateAttachment(attachment.id, {
status: 'error',
@@ -602,19 +720,25 @@ export function InputArea({
return;
}
try {
- const persisted = await onPersistMedia('', [buildUploadMediaItem(attachment, payload)]);
+ const persistFn = attachment.kind === 'document' ? onPersistDocuments : onPersistMedia;
+ const persisted = await persistFn('', [buildUploadMediaItem(attachment, payload)]);
const persistedMediaItem = persisted.media_items?.[0];
if (!persistedMediaItem || !pickString(persistedMediaItem.path)) {
- throw new Error('media.persist did not return image path');
+ throw new Error(
+ attachment.kind === 'document'
+ ? 'document.persist did not return document path'
+ : 'media.persist did not return image path',
+ );
}
updateAttachment(attachment.id, {
...payload,
+ base64Data: undefined,
persistedMediaItem,
status: 'ready',
error: undefined,
});
} catch (error) {
- console.error('图片上传失败:', error);
+ console.error(attachment.kind === 'document' ? '文档上传失败:' : '图片上传失败:', error);
updateAttachment(attachment.id, {
...payload,
status: 'error',
@@ -622,36 +746,43 @@ export function InputArea({
});
}
});
- }, [canPersistAttachments, onPersistMedia, pushAttachmentAlert, updateAttachment]);
+ }, [canPersistAttachments, onPersistDocuments, onPersistMedia, pushAttachmentAlert, updateAttachment]);
const retryAttachment = useCallback((attachment: AttachmentDraft) => {
uploadAttachment(attachment);
}, [uploadAttachment]);
- const appendImageFiles = useCallback((files: FileList | File[]) => {
+ const appendAttachmentFiles = useCallback((files: FileList | File[]) => {
const selectedFiles = Array.from(files);
if (!selectedFiles.length) return;
- const remainingSlots = Math.max(0, MAX_IMAGE_COUNT - attachments.length);
+ const remainingSlots = Math.max(0, MAX_ATTACHMENT_COUNT - attachments.length);
if (!remainingSlots) {
- pushAttachmentAlert(`单次对话最多上传${MAX_IMAGE_COUNT}个附件。`);
+ pushAttachmentAlert(`单次对话最多上传${MAX_ATTACHMENT_COUNT}个附件。`);
return;
}
const acceptedFiles = selectedFiles.slice(0, remainingSlots);
const overflow = selectedFiles.length - acceptedFiles.length;
if (overflow > 0) {
- pushAttachmentAlert(`单次对话最多上传${MAX_IMAGE_COUNT}个附件。`);
+ pushAttachmentAlert(`单次对话最多上传${MAX_ATTACHMENT_COUNT}个附件。`);
}
const drafts = acceptedFiles.reduce<AttachmentDraft[]>((items, file) => {
+ const kind = resolveAttachmentKind(file);
+ if (!kind) {
+ pushAttachmentAlert(`文件类型不支持:${file.name || '未命名文件'}`);
+ return items;
+ }
const base = {
id: makeAttachmentId(file),
- filename: file.name || `image-${Date.now()}`,
+ kind,
+ filename: file.name || (kind === 'document' ? `document-${Date.now()}` : `image-${Date.now()}`),
mimeType: file.type || 'application/octet-stream',
size: file.size,
file,
};
- const validationError = getImageValidationError(file);
+ const validationError =
+ kind === 'document' ? getDocumentValidationError(file) : getImageValidationError(file);
if (validationError) {
pushAttachmentAlert(validationError);
items.push({
@@ -670,7 +801,7 @@ export function InputArea({
if (!drafts.length) return;
- setAttachments((prev) => [...prev, ...drafts].slice(0, MAX_IMAGE_COUNT));
+ setAttachments((prev) => [...prev, ...drafts].slice(0, MAX_ATTACHMENT_COUNT));
drafts.forEach((draft) => {
if (draft.status !== 'uploading' || !draft.file) return;
uploadAttachment(draft);
@@ -844,7 +975,13 @@ export function InputArea({
const handleSubmit = useCallback(() => {
// 用富文本(含 chip 标记)作为发送内容,气泡可交织渲染技能
const richContent = extractRichContent();
- const trimmed = (richContent + pendingVoiceText).trim();
+ const trimmedBase = (richContent + pendingVoiceText).trim();
+ const readyDrafts = attachments.filter(
+ (attachment) =>
+ attachment.status === 'ready' &&
+ (Boolean(pickString(attachment.persistedMediaItem?.path)) || Boolean(attachment.base64Data)),
+ );
+ const trimmed = buildSubmitContent(trimmedBase, readyDrafts);
if ((!trimmed && readyMediaItems.length === 0) || hasUploadingAttachments || hasAttachmentErrors) return;
if (isInterruptible && !isTeamMode && readyMediaItems.length > 0) return;
@@ -853,19 +990,19 @@ export function InputArea({
}
const sid = useChatStore.getState().activeSessionId;
- if (goalArmed && trimmed && sid && onSetGoal && sid !== NEW_CONVERSATION_ID) {
+ if (goalArmed && trimmedBase && sid && onSetGoal && sid !== NEW_CONVERSATION_ID) {
// command.goal 是独立控制信令,不受聊天排队影响,跳过 team/queue/interrupt 判断;
// 消息仍要本地落进 chatStore 才能在气泡上显示"设为目标"徽章(见 MessageItem.tsx)
useChatStore.getState().addMessage(sid, {
id: `user-${Date.now()}`,
role: 'user',
- content: trimmed,
+ content: trimmedBase,
timestamp: new Date().toISOString(),
isGoalObjectiveMessage: true,
});
useGoalStore.getState().setArmed(sid, false);
- onSetGoal(sid, trimmed);
- } else if (goalArmed && trimmed && sid === NEW_CONVERSATION_ID) {
+ onSetGoal(sid, trimmedBase);
+ } else if (goalArmed && trimmedBase && sid === NEW_CONVERSATION_ID) {
// 欢迎页尚无真实 session,armed 状态先保留,交给 App.tsx 的 handleSendMessage
// 在 session.create 成功、拿到真实 session id 后再落地消息 + 调 onSetGoal
onSubmit(trimmed, readyMediaItems);
@@ -910,6 +1047,7 @@ export function InputArea({
}
setComposerSuggestion(null);
}, [
+ attachments,
extractRichContent,
pendingVoiceText,
readyMediaItems,
@@ -1159,10 +1297,10 @@ export function InputArea({
const handleFileInputChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
if (files) {
- void appendImageFiles(files);
+ void appendAttachmentFiles(files);
}
event.target.value = '';
- }, [appendImageFiles]);
+ }, [appendAttachmentFiles]);
const handlePaste = useCallback((event: ClipboardEvent<HTMLDivElement>) => {
if (Array.from(event.clipboardData.items).some((item) => item.kind === 'file')) {
@@ -1473,11 +1611,17 @@ export function InputArea({
)}
key={attachment.id}
>
- <div className="chat-input-attachment-preview" aria-hidden="true">
+ <div
+ className={cx(
+ 'chat-input-attachment-preview',
+ `chat-input-attachment-preview--${getAttachmentTypeKey(attachment)}`,
+ )}
+ aria-hidden="true"
+ >
{attachment.previewUrl ? (
<img src={attachment.previewUrl} alt="" />
) : (
- <FileImage size={18} strokeWidth={1.8} />
+ <AttachmentTypeIcon attachment={attachment} />
)}
</div>
<div className="chat-input-attachment-main">
@@ -1510,7 +1654,11 @@ export function InputArea({
</>
) : (
<>
- <span>{attachment.mimeType.split('/')[1]?.toUpperCase() || 'IMAGE'}</span>
+ <span>
+ {attachment.kind === 'document'
+ ? (getFileExtension(attachment.filename).replace('.', '').toUpperCase() || 'FILE')
+ : (attachment.mimeType.split('/')[1]?.toUpperCase() || 'IMAGE')}
+ </span>
<span>{formatAttachmentSize(attachment.size)}</span>
</>
)}
@@ -1601,52 +1749,34 @@ export function InputArea({
<input
ref={fileInputRef}
type="file"
- accept="image/png,image/jpeg,image/webp,image/gif"
+ accept={ATTACHMENT_ACCEPT}
multiple
className="hidden"
onChange={handleFileInputChange}
/>
<div ref={attachMenuRef} className="chat-input-attach-menu-anchor">
- {canUseGoalMenu ? (
- <button
- type="button"
- onClick={() => {
- if (attachTriggerDisabled) return;
- if (!attachMenuOpen && attachMenuRef.current) {
- setAttachMenuAnchor(attachMenuRef.current.getBoundingClientRect());
- }
- setAttachMenuOpen((open) => !open);
- }}
- disabled={attachTriggerDisabled}
- className={cx(
- 'chat-input-btn chat-input-btn--add-file',
- attachTriggerDisabled && 'chat-input-btn--disabled',
- )}
- title={attachTriggerDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}
- aria-label={attachTriggerDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}
- aria-haspopup="menu"
- aria-expanded={attachMenuOpen}
- >
- <Plus className="chat-input-btn-icon" strokeWidth={1.8} />
- </button>
- ) : (
- // 没有 onSetGoal(如欢迎页新会话尚未创建)时,Goal 入口本来就不适用——
- // 保持原来"+"直接打开文件选择器的单击行为,不额外套一层菜单
- <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>
- )}
- {canUseGoalMenu && attachMenuOpen && attachMenuAnchor && createPortal(
+ <button
+ type="button"
+ onClick={() => {
+ if (attachTriggerDisabled) return;
+ if (!attachMenuOpen && attachMenuRef.current) {
+ setAttachMenuAnchor(attachMenuRef.current.getBoundingClientRect());
+ }
+ setAttachMenuOpen((open) => !open);
+ }}
+ disabled={attachTriggerDisabled}
+ className={cx(
+ 'chat-input-btn chat-input-btn--add-file',
+ attachTriggerDisabled && 'chat-input-btn--disabled',
+ )}
+ title={attachTriggerDisabled ? t('chat.addFileDisabled') : t('chat.addFile')}
+ aria-label={attachTriggerDisabled ? t('chat.addFileDisabled') : t('chat.addFile')}
+ aria-haspopup="menu"
+ aria-expanded={attachMenuOpen}
+ >
+ <Plus className="chat-input-btn-icon" strokeWidth={1.8} />
+ </button>
+ {attachMenuOpen && attachMenuAnchor && createPortal(
<div
ref={attachMenuPortalRef}
className="chat-mode-select__menu"
@@ -1663,7 +1793,7 @@ export function InputArea({
className="chat-mode-select__option"
role="menuitem"
disabled={imageInputDisabled}
- title={imageInputDisabled ? t('chat.addImageDisabled') : undefined}
+ title={imageInputDisabled ? t('chat.addFileDisabled') : undefined}
onClick={() => {
if (imageInputDisabled) return;
setAttachMenuOpen(false);
@@ -1672,12 +1802,12 @@ export function InputArea({
>
<span className="chat-mode-select__option-main">
<span className="chat-mode-select__icon" aria-hidden="true">
- <FileImage className="w-4 h-4" />
+ <FileText className="w-4 h-4" />
</span>
- <span className="chat-mode-select__label">{t('chat.addImage')}</span>
+ <span className="chat-mode-select__label">{t('chat.addFile')}</span>
</span>
</button>
- {isAgentMode && onSetGoal && (
+ {canUseGoalMenu && (
<button
type="button"
className="chat-mode-select__option"
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx
index 34c4bf2552..bf8de10778 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MediaRenderer.tsx
@@ -1,43 +1,199 @@
+import { useEffect, useRef, useState } from 'react';
import { MediaItem } from '../../types';
+import {
+ FileTypeIcon,
+ getFileTypeIconKeyFromFilename,
+ splitFilenameParts,
+} from './FileTypeIcon';
+import { stripUploadDocumentBlocks } from '../../utils/documentMessage';
+
+export { stripUploadDocumentBlocks };
interface MediaRendererProps {
items: MediaItem[];
+ /** Align file cards to the end for user messages */
+ align?: 'start' | 'end';
+ /** Place attachments above the bubble (chat message layout) */
+ variant?: 'inline' | 'above';
}
-export function MediaRenderer({ items }: MediaRendererProps) {
- if (!items.length) {
- return null;
+const VISIBLE_FILE_COUNT = 2;
+
+function isImageItem(item: MediaItem): boolean {
+ if (item.type === 'image') return true;
+ const mime = (item.mimeType || item.mime_type || '').toLowerCase();
+ return mime.startsWith('image/');
+}
+
+function isCardItem(item: MediaItem): boolean {
+ // Images + documents share the same card row / overflow menu.
+ return item.type !== 'audio' && item.type !== 'video';
+}
+
+function mediaSrc(item: MediaItem): string | undefined {
+ const mimeType = item.mimeType || item.mime_type || 'application/octet-stream';
+ const base64Data = item.base64Data || item.base64_data;
+ if (base64Data) {
+ return `data:${mimeType};base64,${base64Data}`;
}
+ if (item.url) return item.url;
+ if (item.path) return `/file-api/raw-file?path=${encodeURIComponent(item.path)}`;
+ return undefined;
+}
+
+function FileCard({ item }: { item: MediaItem }) {
+ const filename = item.filename || 'file';
+ const { stem, extLabel } = splitFilenameParts(filename);
+ const typeKey = getFileTypeIconKeyFromFilename(filename, item.type);
+ const src = mediaSrc(item);
+ const showThumb = isImageItem(item) && Boolean(src);
+
+ const body = (
+ <>
+ <span className="chat-msg-file-card__icon">
+ {showThumb ? (
+ <img src={src} alt="" className="chat-msg-file-card__thumb" />
+ ) : (
+ <FileTypeIcon typeKey={typeKey} size={28} />
+ )}
+ </span>
+ <span className="chat-msg-file-card__meta">
+ <span className="chat-msg-file-card__name" title={filename}>
+ {stem}
+ </span>
+ {extLabel ? <span className="chat-msg-file-card__ext">{extLabel}</span> : null}
+ </span>
+ </>
+ );
+
+ if (src) {
+ return (
+ <a
+ className="chat-msg-file-card"
+ href={src}
+ download={filename}
+ title={filename}
+ >
+ {body}
+ </a>
+ );
+ }
+
+ return (
+ <div className="chat-msg-file-card" title={filename}>
+ {body}
+ </div>
+ );
+}
+
+function OverflowMenu({ items }: { items: MediaItem[] }) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const onPointerDown = (event: MouseEvent) => {
+ if (!rootRef.current?.contains(event.target as Node)) {
+ setOpen(false);
+ }
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') setOpen(false);
+ };
+ document.addEventListener('mousedown', onPointerDown);
+ document.addEventListener('keydown', onKeyDown);
+ return () => {
+ document.removeEventListener('mousedown', onPointerDown);
+ document.removeEventListener('keydown', onKeyDown);
+ };
+ }, [open]);
return (
- <div className="mt-2 space-y-2">
- {items.map((item, index) => (
- <MediaItemView key={`${item.filename}-${index}`} item={item} />
+ <div className="chat-msg-file-more" ref={rootRef}>
+ <button
+ type="button"
+ className="chat-msg-file-more__btn"
+ aria-expanded={open}
+ aria-haspopup="menu"
+ onClick={() => setOpen((prev) => !prev)}
+ >
+ +{items.length}
+ </button>
+ {open && (
+ <div className="chat-msg-file-more__menu" role="menu">
+ {items.map((item, index) => {
+ const filename = item.filename || 'file';
+ const typeKey = getFileTypeIconKeyFromFilename(filename, item.type);
+ const src = mediaSrc(item);
+ const showThumb = isImageItem(item) && Boolean(src);
+ const content = (
+ <>
+ {showThumb ? (
+ <img src={src} alt="" className="chat-msg-file-more__thumb" />
+ ) : (
+ <FileTypeIcon typeKey={typeKey} size={20} />
+ )}
+ <span className="chat-msg-file-more__name" title={filename}>
+ {filename}
+ </span>
+ </>
+ );
+ if (src) {
+ return (
+ <a
+ key={`${filename}-${index}`}
+ className="chat-msg-file-more__item"
+ href={src}
+ download={filename}
+ role="menuitem"
+ onClick={() => setOpen(false)}
+ >
+ {content}
+ </a>
+ );
+ }
+ return (
+ <div key={`${filename}-${index}`} className="chat-msg-file-more__item" role="menuitem">
+ {content}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function FileAttachmentBar({
+ items,
+ align = 'end',
+}: {
+ items: MediaItem[];
+ align?: 'start' | 'end';
+}) {
+ if (!items.length) return null;
+ const visible = items.slice(0, VISIBLE_FILE_COUNT);
+ const overflow = items.slice(VISIBLE_FILE_COUNT);
+
+ return (
+ <div className={`chat-msg-file-row chat-msg-file-row--${align}`}>
+ {visible.map((item, index) => (
+ <FileCard key={`${item.filename}-${index}`} item={item} />
))}
+ {overflow.length > 0 ? <OverflowMenu items={overflow} /> : null}
</div>
);
}
function MediaItemView({ item }: { item: MediaItem }) {
const mimeType = item.mimeType || item.mime_type || 'application/octet-stream';
- const base64Data = item.base64Data || item.base64_data;
- const src = base64Data
- ? `data:${mimeType};base64,${base64Data}`
- : item.url || (item.path ? `/file-api/raw-file?path=${encodeURIComponent(item.path)}` : undefined);
+ const src = mediaSrc(item);
if (!src) {
return null;
}
switch (item.type) {
- case 'image':
- return (
- <img
- src={src}
- alt={item.filename}
- className="max-w-full rounded-lg border border-border"
- />
- );
case 'audio':
return (
<audio controls className="w-full">
@@ -46,20 +202,33 @@ function MediaItemView({ item }: { item: MediaItem }) {
);
case 'video':
return (
- <video controls className="max-w-full rounded-lg border border-border">
+ <video controls className="chat-msg-media-image">
<source src={src} type={mimeType} />
</video>
);
- case 'document':
default:
- return (
- <a
- href={src}
- download={item.filename}
- className="inline-flex items-center gap-2 rounded-md border border-border bg-secondary px-3 py-2 text-sm text-text-strong hover:bg-secondary/80"
- >
- <span className="truncate max-w-[240px]">{item.filename}</span>
- </a>
- );
+ return null;
+ }
+}
+
+export function MediaRenderer({ items, align = 'end', variant = 'inline' }: MediaRendererProps) {
+ if (!items.length) {
+ return null;
}
+
+ const cardItems = items.filter(isCardItem);
+ const richItems = items.filter((item) => !isCardItem(item));
+
+ return (
+ <div className={variant === 'above' ? 'chat-msg-attachments chat-msg-attachments--above' : 'chat-msg-attachments'}>
+ {cardItems.length > 0 && <FileAttachmentBar items={cardItems} align={align} />}
+ {richItems.length > 0 && (
+ <div className={`chat-msg-media-rich chat-msg-media-rich--${align}`}>
+ {richItems.map((item, index) => (
+ <MediaItemView key={`${item.filename}-${index}`} item={item} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
index e0328c186c..fbe44ab255 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
@@ -23,7 +23,7 @@ import {
} from '../../types';
import { StreamingContent } from './StreamingContent';
import { ToolCallDisplay } from './ToolCallDisplay';
-import { MediaRenderer } from './MediaRenderer';
+import { MediaRenderer, stripUploadDocumentBlocks } from './MediaRenderer';
import { A2UIMessageContent } from '../../features/a2ui/A2UIMessageContent';
import { QaSummaryCard } from '../InteractionSlot/QaSummaryCard';
import { isQaSummaryContent } from '../InteractionSlot/qaSummary';
@@ -322,7 +322,9 @@ export const MessageItem = memo(function MessageItem({
const handleCopy = useCallback(async () => {
if (!content) return;
- const copyContent = a2uiContentToText(content) || content;
+ const raw = role === 'user' ? stripUploadDocumentBlocks(content) : content;
+ if (!raw) return;
+ const copyContent = a2uiContentToText(raw) || raw;
try {
await navigator.clipboard.writeText(copyContent);
} catch {
@@ -337,7 +339,7 @@ export const MessageItem = memo(function MessageItem({
}
setCopied(true);
window.setTimeout(() => setCopied(false), 2000);
- }, [content]);
+ }, [content, role]);
// 自动朗读新消息(仅助手消息,由父组件通过 autoSpeak 控制)
useEffect(() => {
@@ -541,15 +543,18 @@ export const MessageItem = memo(function MessageItem({
// 用户/助手消息
const isUser = role === 'user';
+ const displayContent = isUser ? stripUploadDocumentBlocks(content) : content;
const showTTS = Boolean(
!isUser && !isStreaming && content && (ttsSupported || audioBase64)
);
- const showCopy = Boolean(content) && !isStreaming;
+ const showCopy = Boolean(isUser ? displayContent : content) && !isStreaming;
const isPlaying = audioBase64 ? isAudioPlaying : isSpeaking;
const visibleMediaItems = mediaItems?.length ? mediaItems : null;
const visibleFileItems = fileItems?.length ? fileItems : null;
- const hasBubbleContent =
- isUser || Boolean(content) || Boolean(visibleMediaItems) || Boolean(visibleFileItems);
+ const hasDisplayText = Boolean(displayContent);
+ const hasBubbleContent = isUser
+ ? hasDisplayText || isStreaming
+ : Boolean(content) || Boolean(visibleMediaItems) || Boolean(visibleFileItems);
const withAssistantAvatar = !isUser && enableAssistantAvatar;
@@ -569,6 +574,10 @@ export const MessageItem = memo(function MessageItem({
<div className="hidden" data-testid="thinking-summary" aria-hidden="true" />
)}
+ {isUser && visibleMediaItems && (
+ <MediaRenderer items={visibleMediaItems} align="end" variant="above" />
+ )}
+
{hasBubbleContent && (
<div
className={clsx(
@@ -581,7 +590,7 @@ export const MessageItem = memo(function MessageItem({
>
{isStreaming ? (
isUser ? (
- <StreamingContent content={content} />
+ <StreamingContent content={displayContent} />
) : (
<A2UIMessageContent
key={`${id}-streaming`}
@@ -595,9 +604,11 @@ export const MessageItem = memo(function MessageItem({
) : (
<>
{isUser ? (
- <div className="chat-text">
- <span className="whitespace-pre-wrap">{renderRichContent(content)}</span>
- </div>
+ hasDisplayText ? (
+ <div className="chat-text">
+ <span className="whitespace-pre-wrap">{renderRichContent(displayContent)}</span>
+ </div>
+ ) : null
) : (
<A2UIMessageContent
key={`${id}-final`}
@@ -607,8 +618,8 @@ export const MessageItem = memo(function MessageItem({
testId="thinking-body"
/>
)}
- {visibleMediaItems && (
- <MediaRenderer items={visibleMediaItems} />
+ {!isUser && visibleMediaItems && (
+ <MediaRenderer items={visibleMediaItems} align="start" />
)}
{visibleFileItems && (
<FileDownloadList files={visibleFileItems} />
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
index 920afbbde6..e8ef75138c 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
@@ -55,6 +55,12 @@ interface ChatPanelProps {
media_items?: Record<string, unknown>[];
files?: Record<string, unknown>;
}>;
+ onPersistDocuments: (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;
@@ -646,6 +652,7 @@ function scrollToBottom(el: HTMLDivElement): void {
export function ChatPanel({
onSendMessage,
onPersistMedia,
+ onPersistDocuments,
onInterrupt,
onCancel,
onSwitchMode,
@@ -1109,6 +1116,7 @@ export function ChatPanel({
<InputArea
onSubmit={handleSendMessage}
onPersistMedia={onPersistMedia}
+ onPersistDocuments={onPersistDocuments}
onInterrupt={onInterrupt}
onCancel={onCancel}
onSwitchMode={onSwitchMode}
@@ -1149,6 +1157,7 @@ export function ChatPanel({
<InputArea
onSubmit={handleSendMessage}
onPersistMedia={onPersistMedia}
+ onPersistDocuments={onPersistDocuments}
onInterrupt={onInterrupt}
onCancel={onCancel}
onSwitchMode={onSwitchMode}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
index 295fb2ec39..5ab29a33b7 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
@@ -285,21 +285,12 @@ function normalizeHistoryMediaItem(value: unknown): MediaItem | null {
return null;
}
- const rawType = typeof value.type === 'string' ? value.type.trim().toLowerCase() : 'image';
- if (rawType && rawType !== 'image') {
- return null;
- }
-
const path = pickFirstString(value, ['path', 'url']);
if (!path) {
return null;
}
- const mimeType = pickFirstString(value, ['mime_type', 'mimeType']) ?? 'image/png';
- if (!mimeType.startsWith('image/')) {
- return null;
- }
-
+ const mimeType = pickFirstString(value, ['mime_type', 'mimeType']) ?? 'application/octet-stream';
const filename = pickFirstString(value, ['filename', 'name']) ?? filenameFromPath(path);
const size = typeof value.size_bytes === 'number'
? value.size_bytes
@@ -307,8 +298,27 @@ function normalizeHistoryMediaItem(value: unknown): MediaItem | null {
? value.sizeBytes
: undefined;
+ const rawType = typeof value.type === 'string' ? value.type.trim().toLowerCase() : '';
+ let type: MediaItem['type'];
+ if (rawType === 'image' || rawType === 'audio' || rawType === 'video' || rawType === 'document') {
+ type = rawType;
+ } else if (mimeType.startsWith('image/')) {
+ type = 'image';
+ } else if (mimeType.startsWith('audio/')) {
+ type = 'audio';
+ } else if (mimeType.startsWith('video/')) {
+ type = 'video';
+ } else {
+ type = 'document';
+ }
+
+ // Keep legacy image-only filtering for ambiguous image records without type.
+ if (type === 'image' && !mimeType.startsWith('image/') && rawType !== 'image') {
+ return null;
+ }
+
return {
- type: 'image',
+ type,
filename,
path,
mime_type: mimeType,
@@ -348,11 +358,13 @@ function extractHistoryMediaItems(record: Record<string, unknown>): MediaItem[]
if (isRecord(record.files)) {
appendHistoryMediaItems(mediaItems, seenKeys, record.files.uploaded_images);
+ appendHistoryMediaItems(mediaItems, seenKeys, record.files.uploaded_documents);
}
if (isRecord(record.event_payload)) {
appendHistoryMediaItems(mediaItems, seenKeys, record.event_payload.media_items);
if (isRecord(record.event_payload.files)) {
appendHistoryMediaItems(mediaItems, seenKeys, record.event_payload.files.uploaded_images);
+ appendHistoryMediaItems(mediaItems, seenKeys, record.event_payload.files.uploaded_documents);
}
}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index 2724d9030a..1713df090a 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -73,6 +73,7 @@ import {
findActiveTeamLeaderMessage as findActiveTeamLeaderMessageInTurn,
} from '../features/teamLeaderMessages';
import { buildGoalCompletedContent } from '../components/GoalBar/goalCompletedMessage';
+import { stripUploadDocumentBlocks } from '../utils/documentMessage';
const WS_RECONNECT_EVENT = 'jiuwenclaw:ws-reconnect-request';
@@ -504,6 +505,7 @@ interface UseWebSocketReturn {
options?: WebRequestOptions
) => Promise<T>;
persistMedia: (content: string, sessionId: string, mediaItems: MediaItem[]) => Promise<PersistMediaResponse>;
+ persistDocuments: (content: string, sessionId: string, mediaItems: MediaItem[]) => Promise<PersistMediaResponse>;
sendMessage: (content: string, sessionId: string, mediaItems?: MediaItem[]) => Promise<boolean>;
sendStructuredChatContent: (content: unknown, sessionId: string) => Promise<void>;
interrupt: (
@@ -563,15 +565,37 @@ function toPersistedMediaRecord(item: MediaItem): Record<string, unknown> {
};
}
+function slimPersistedMediaRecords(items: Record<string, unknown>[]): Record<string, unknown>[] {
+ return items.map((item) => ({
+ type: item.type,
+ filename: item.filename,
+ mime_type: item.mime_type ?? item.mimeType,
+ path: item.path,
+ size_bytes: item.size_bytes ?? item.sizeBytes,
+ }));
+}
+
function buildPersistedMediaFiles(mediaItems: MediaItem[]): Record<string, unknown> {
- return {
- uploaded_images: mediaItems.map((item) => ({
+ const files: Record<string, unknown> = {};
+ const images = mediaItems.filter((item) => item.type === 'image');
+ const documents = mediaItems.filter((item) => item.type === 'document');
+ if (images.length) {
+ files.uploaded_images = images.map((item) => ({
filename: item.filename,
path: item.path,
mime_type: getMediaMimeType(item),
size_bytes: item.size_bytes ?? item.sizeBytes,
- })),
- };
+ }));
+ }
+ if (documents.length) {
+ files.uploaded_documents = documents.map((item) => ({
+ filename: item.filename,
+ path: item.path,
+ mime_type: getMediaMimeType(item),
+ size_bytes: item.size_bytes ?? item.sizeBytes,
+ }));
+ }
+ return files;
}
function getSessionWorkContext(sessionId: string): Record<string, unknown> {
@@ -1151,6 +1175,22 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
[request],
);
+ const persistDocuments = useCallback(
+ async (content: string, sessionId: string, mediaItems: MediaItem[]) => {
+ return request<PersistMediaResponse>('document.persist', {
+ session_id: sessionId,
+ content,
+ parse: true,
+ documents: mediaItems.map((item) => ({
+ filename: item.filename,
+ mime_type: getMediaMimeType(item),
+ base64_data: item.base64_data || item.base64Data,
+ })),
+ });
+ },
+ [request],
+ );
+
// Goal(持续目标)控制:get/set/pause/resume/clear 共用一套 loading + 错误处理。
// get/pause/clear 走非流式一次性响应,真的会有 res,用 requestGoalAction() 正常等待;
// set/resume 走流式、正常路径上永远不会有 res(见 backend-requests.md #4),改用
@@ -1310,11 +1350,12 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
}
// 添加用户消息(附带输入栏选中的技能)
+ // 气泡只展示用户原文;路径提示仅随 chat.send 发给 Agent。
const selectedSkills = useSessionStore.getState().getRuntime(sessionId)?.selectedSkills ?? [];
useChatStore.getState().addMessage(sessionId, {
id: `user-${Date.now()}`,
role: 'user',
- content,
+ content: stripUploadDocumentBlocks(content) || content.replace(/\n*【上传文档[\s\S]*$/, '').trim() || content,
mediaItems,
timestamp: new Date().toISOString(),
...(selectedSkills.length > 0 ? { skills: selectedSkills } : {}),
@@ -1354,10 +1395,31 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
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;
+ const imageItems = mediaItems.filter((item) => item.type !== 'document');
+ const documentItems = mediaItems.filter((item) => item.type === 'document');
+ const mergedItems: Record<string, unknown>[] = [];
+ const mergedFiles: Record<string, unknown> = {};
+ if (imageItems.length) {
+ const persisted = await persistMedia(content, sessionId, imageItems);
+ outgoingContent = persisted.content ?? persisted.query ?? content;
+ if (Array.isArray(persisted.media_items)) {
+ mergedItems.push(...persisted.media_items);
+ }
+ if (persisted.files && typeof persisted.files === 'object') {
+ Object.assign(mergedFiles, persisted.files);
+ }
+ }
+ if (documentItems.length) {
+ const persistedDocs = await persistDocuments(content, sessionId, documentItems);
+ if (Array.isArray(persistedDocs.media_items)) {
+ mergedItems.push(...persistedDocs.media_items);
+ }
+ if (persistedDocs.files && typeof persistedDocs.files === 'object') {
+ Object.assign(mergedFiles, persistedDocs.files);
+ }
+ }
+ outgoingMediaItems = mergedItems.length ? slimPersistedMediaRecords(mergedItems) : undefined;
+ outgoingFiles = Object.keys(mergedFiles).length ? mergedFiles : undefined;
}
}
// Goal 处于 active 时,普通输入按文档 §5.1 作为补充约束插入当前 Goal,而不是覆盖它
@@ -1393,6 +1455,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
}
},
[
+ persistDocuments,
persistMedia,
request,
resetContextCompressionTurn,
@@ -3823,6 +3886,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
connectionState,
request,
persistMedia,
+ persistDocuments,
sendMessage,
sendStructuredChatContent,
interrupt,
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 8da5c39a1b..5c0d4e1671 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -259,6 +259,9 @@
"removeTask": "Remove task",
"addImage": "Add image",
"addImageDisabled": "Cannot add images while processing or recording",
+ "addFile": "Add file",
+ "addFileDisabled": "Cannot add files while processing or recording",
+ "addAttachment": "Add attachment",
"removeImage": "Remove image",
"sendTask": "Send message without interrupting model",
"editTask": "Edit",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 847fab8649..5ca291edac 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -260,6 +260,9 @@
"removeTask": "移除任务",
"addImage": "添加图片",
"addImageDisabled": "处理中或录音中不可添加图片",
+ "addFile": "添加文件",
+ "addFileDisabled": "处理中或录音中不可添加文件",
+ "addAttachment": "添加附件",
"removeImage": "移除图片",
"sendTask": "发送消息,但不打断模型运行",
"editTask": "编辑",
diff --git a/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.ts b/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.ts
new file mode 100644
index 0000000000..58d09f921e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/utils/documentMessage.ts
@@ -0,0 +1,13 @@
+/** Strip agent document-hint blocks from user-visible bubble text. */
+export function stripUploadDocumentBlocks(content: string): string {
+ if (!content || !content.includes('【上传文档')) {
+ return content;
+ }
+ return content
+ // New compact form: 【上传文档】 plus following "- name: path" lines.
+ .replace(/(?:^|\n+)【上传文档】(?:\n-[^\n]*)*/g, '')
+ // Legacy per-file blocks: 【上传文档: name】 / 路径 / 说明
+ .replace(/(?:^|\n+)【上传文档[::][^\n]*(?:\n(?!【)[^\n]*)*/g, '')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
diff --git a/jiuwenswarm/common/document_parser.py b/jiuwenswarm/common/document_parser.py
new file mode 100644
index 0000000000..4bea313b3d
--- /dev/null
+++ b/jiuwenswarm/common/document_parser.py
@@ -0,0 +1,219 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Shared document parsing helpers for Web upload and Agent tools.
+
+Wraps openjiuwen ``AutoFileParser`` and adds ``.ipynb`` support (not registered
+in AutoFileParser by default).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_MAX_CHARS = 50_000
+_IPYNB_REGISTERED = False
+
+# Formats accepted by the Web document upload/parse API.
+SUPPORTED_DOCUMENT_EXTENSIONS: frozenset[str] = frozenset(
+ {
+ ".pdf",
+ ".docx",
+ ".xlsx",
+ ".csv",
+ ".tsv",
+ ".txt",
+ ".md",
+ ".markdown",
+ ".html",
+ ".htm",
+ ".json",
+ ".ipynb",
+ }
+)
+
+SUPPORTED_DOCUMENT_MIME_TYPES: dict[str, str] = {
+ "application/pdf": ".pdf",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
+ "text/csv": ".csv",
+ "application/csv": ".csv",
+ "text/tab-separated-values": ".tsv",
+ "text/plain": ".txt",
+ "text/markdown": ".md",
+ "text/x-markdown": ".md",
+ "text/html": ".html",
+ "application/xhtml+xml": ".html",
+ "application/json": ".json",
+ "application/x-ipynb+json": ".ipynb",
+ "application/jupyter": ".ipynb",
+ "application/vnd.jupyter": ".ipynb",
+}
+
+
+def resolve_document_suffix(*, filename: str | None, mime_type: str | None) -> str | None:
+ """Resolve a supported document suffix from filename and/or MIME type."""
+ mime = (mime_type or "").lower().strip()
+ if mime in SUPPORTED_DOCUMENT_MIME_TYPES:
+ return SUPPORTED_DOCUMENT_MIME_TYPES[mime]
+
+ name = Path(str(filename or "")).name
+ suffix = Path(name).suffix.lower()
+ if suffix in SUPPORTED_DOCUMENT_EXTENSIONS:
+ return suffix
+ return None
+
+
+def is_supported_document(*, filename: str | None = None, mime_type: str | None = None) -> bool:
+ return resolve_document_suffix(filename=filename, mime_type=mime_type) is not None
+
+
+def _ensure_ipynb_parser_registered() -> None:
+ """Register a lightweight IpynbParser into AutoFileParser once."""
+ global _IPYNB_REGISTERED
+ if _IPYNB_REGISTERED:
+ return
+
+ from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import (
+ AutoFileParser,
+ _PARSER_REGISTRY,
+ )
+ from openjiuwen.core.retrieval.indexing.processor.parser.base import Parser
+
+ if ".ipynb" in _PARSER_REGISTRY:
+ _IPYNB_REGISTERED = True
+ return
+
+ class IpynbParser(Parser):
+ """Parse Jupyter notebook cells into readable Markdown-ish text."""
+
+ async def _parse(self, file_path: str, *args, **kwargs) -> str | None:
+ path = Path(file_path)
+ raw = path.read_text(encoding="utf-8", errors="replace")
+ notebook = json.loads(raw)
+ cells = notebook.get("cells") or []
+ blocks: list[str] = []
+ for idx, cell in enumerate(cells, 1):
+ if not isinstance(cell, dict):
+ continue
+ cell_type = str(cell.get("cell_type") or "unknown")
+ source = cell.get("source") or []
+ if isinstance(source, list):
+ source_text = "".join(str(part) for part in source)
+ else:
+ source_text = str(source)
+ blocks.append(f"## Cell {idx} [{cell_type}]")
+ if source_text.strip():
+ blocks.append(source_text.rstrip("\n"))
+ outputs = cell.get("outputs") or []
+ if not isinstance(outputs, list) or not outputs:
+ continue
+ blocks.append("### Outputs")
+ for out in outputs:
+ if not isinstance(out, dict):
+ continue
+ text = ""
+ if "text" in out:
+ text_val = out.get("text")
+ text = "".join(text_val) if isinstance(text_val, list) else str(text_val or "")
+ elif isinstance(out.get("data"), dict):
+ plain = out["data"].get("text/plain")
+ if isinstance(plain, list):
+ text = "".join(str(part) for part in plain)
+ elif isinstance(plain, str):
+ text = plain
+ elif "ename" in out and "evalue" in out:
+ text = f"{out.get('ename')}: {out.get('evalue')}"
+ if text:
+ blocks.append(text.rstrip("\n"))
+ return "\n".join(blocks).strip() or None
+
+ AutoFileParser.register_new_parser(".ipynb", IpynbParser)
+ _IPYNB_REGISTERED = True
+
+
+async def parse_document_file(
+ file_path: str | Path,
+ *,
+ max_chars: int | None = DEFAULT_MAX_CHARS,
+ doc_id: str = "",
+) -> dict[str, Any]:
+ """Parse a local document and return text plus metadata.
+
+ Args:
+ max_chars: Truncate returned text to this many characters. Pass ``None``
+ to keep the full parsed text (used when writing ``.txt`` sidecars).
+
+ Returns:
+ dict with keys: text, truncated, parser, file_ext, char_count, documents_count
+ """
+ path = Path(file_path)
+ if not path.is_file():
+ raise FileNotFoundError(f"File not found: {path}")
+
+ suffix = path.suffix.lower()
+ if suffix not in SUPPORTED_DOCUMENT_EXTENSIONS:
+ raise ValueError(
+ f"Unsupported format: {suffix}. Supported: {sorted(SUPPORTED_DOCUMENT_EXTENSIONS)}"
+ )
+
+ _ensure_ipynb_parser_registered()
+
+ from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import AutoFileParser
+
+ parser = AutoFileParser()
+ output_dir = str(path.parent / ".parsed_images")
+ docs = await parser.parse(
+ str(path),
+ doc_id=doc_id or path.stem,
+ file_name=path.name,
+ output_dir=output_dir,
+ )
+ if not docs:
+ return {
+ "text": "",
+ "truncated": False,
+ "parser": "AutoFileParser",
+ "file_ext": suffix,
+ "char_count": 0,
+ "documents_count": 0,
+ }
+
+ # Prefer the concrete parser name from registry when available.
+ from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import (
+ _PARSER_REGISTRY,
+ )
+
+ concrete = _PARSER_REGISTRY.get(suffix)
+ parser_name = concrete().__class__.__name__ if concrete else "AutoFileParser"
+
+ parts: list[str] = []
+ for doc in docs:
+ text = getattr(doc, "text", None)
+ if text:
+ parts.append(str(text))
+ joined = "\n\n".join(parts).strip()
+ full_len = len(joined)
+ truncated = False
+ if max_chars is not None:
+ limit = max(1, int(max_chars))
+ if full_len > limit:
+ joined = joined[:limit] + f"\n\n[内容过长已截断,完整约 {full_len} 字符]"
+ truncated = True
+
+ return {
+ "text": joined,
+ "truncated": truncated,
+ "parser": parser_name,
+ "file_ext": suffix,
+ "char_count": full_len,
+ "documents_count": len(docs),
+ }
+
+
+def supported_formats() -> list[str]:
+ """Return sorted list of supported extensions (including .ipynb)."""
+ return sorted(SUPPORTED_DOCUMENT_EXTENSIONS)
diff --git a/jiuwenswarm/common/ws_limits.py b/jiuwenswarm/common/ws_limits.py
index 840433761e..6ab7b98736 100644
--- a/jiuwenswarm/common/ws_limits.py
+++ b/jiuwenswarm/common/ws_limits.py
@@ -1,6 +1,11 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-"""Shared WebSocket payload limits for the Gateway-AgentServer link."""
+"""Shared WebSocket payload limits for Gateway and AgentServer links."""
+# Gateway ↔ AgentServer internal link (streaming events, no large file base64).
AGENT_WS_MAX_MESSAGE_BYTES = 8 * 2**20
AGENT_WS_SEND_BUDGET_BYTES = 6 * 2**20
+
+# Browser ↔ WebChannel: document.persist may carry large base64 payloads.
+# Keep headroom above the document size limit for base64 + JSON overhead.
+WEB_WS_MAX_MESSAGE_BYTES = 100 * 2**20
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 696e133f87..5d0889b638 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -103,6 +103,12 @@ from jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessService
from jiuwenswarm.agents.harness.common.tools.web_file_download import build_file_download_info
from jiuwenswarm.common.version import __version__
from jiuwenswarm.gateway.media_attachments import normalize_chat_media_attachments
+from jiuwenswarm.gateway.document_attachments import (
+ coerce_document_parse_flag,
+ parse_existing_document,
+ persist_and_parse_documents,
+)
+from jiuwenswarm.common.document_parser import DEFAULT_MAX_CHARS, supported_formats
from jiuwenswarm.server.runtime.session import project_store
from jiuwenswarm.symphony.skill_retrieval.taxonomy_config import (
coerce_root_categories_value,
@@ -4738,13 +4744,98 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
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
- }
+ # G.EXP.04: 多 key + 条件过滤不用推导式,改为显式循环。
+ payload = {}
+ for key in ("content", "query", "media_items", "files"):
+ if key in normalized:
+ payload[key] = normalized[key]
await channel.send_response(ws, req_id, ok=True, payload=payload)
+ async def _document_persist(ws, req_id, params, session_id):
+ """Upload documents (PDF/DOCX/XLSX/ipynb/...) and parse via AutoFileParser."""
+ 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)
+ parse = coerce_document_parse_flag(normalized.get("parse", True), default=True)
+ max_chars_raw = normalized.get("max_chars", DEFAULT_MAX_CHARS)
+ try:
+ max_chars = int(max_chars_raw)
+ except (TypeError, ValueError):
+ max_chars = DEFAULT_MAX_CHARS
+ max_chars = max(1, min(max_chars, 500_000))
+ try:
+ await persist_and_parse_documents(
+ normalized,
+ session_id,
+ parse=parse,
+ max_chars=max_chars,
+ )
+ except Exception as exc:
+ logger.exception("[document.persist] failed: %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+ return
+ # G.EXP.04: 多 key + 条件过滤不用推导式,改为显式循环。
+ payload = {}
+ for key in (
+ "content",
+ "query",
+ "media_items",
+ "files",
+ "documents",
+ "document_errors",
+ "supported_formats",
+ ):
+ if key in normalized:
+ payload[key] = normalized[key]
+ if "supported_formats" not in payload:
+ payload["supported_formats"] = supported_formats()
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _document_parse(ws, req_id, params, session_id):
+ """Parse an already-uploaded document path with AutoFileParser (+ ipynb)."""
+ if not isinstance(params, dict):
+ await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
+ return
+ path = str(params.get("path") or "").strip()
+ if not path:
+ await channel.send_response(ws, req_id, ok=False, error="path is required", code="BAD_REQUEST")
+ return
+ max_chars_raw = params.get("max_chars", DEFAULT_MAX_CHARS)
+ try:
+ max_chars = int(max_chars_raw)
+ except (TypeError, ValueError):
+ max_chars = DEFAULT_MAX_CHARS
+ max_chars = max(1, min(max_chars, 500_000))
+ try:
+ result = await parse_existing_document(
+ path,
+ session_id=session_id,
+ max_chars=max_chars,
+ )
+ except FileNotFoundError as exc:
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="NOT_FOUND")
+ return
+ except PermissionError as exc:
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="FORBIDDEN")
+ return
+ except ValueError as exc:
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="BAD_REQUEST")
+ return
+ except Exception as exc:
+ logger.exception("[document.parse] failed: %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+ return
+ await channel.send_response(ws, req_id, ok=True, payload=result)
+
+ async def _document_formats(ws, req_id, params, session_id):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=True,
+ payload={"supported_formats": supported_formats()},
+ )
+
async def _chat_resume(ws, req_id, params, session_id):
await channel.send_response(
ws,
@@ -5842,6 +5933,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
channel.register_method("chat.send", _chat_send)
channel.register_method("media.persist", _media_persist)
+ channel.register_method("document.persist", _document_persist)
+ channel.register_method("document.parse", _document_parse)
+ channel.register_method("document.formats", _document_formats)
channel.register_method("chat.resume", _chat_resume)
channel.register_method("chat.interrupt", _chat_interrupt)
channel.register_method("chat.user_answer", _chat_user_answer)
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
index 237ba39d03..6e4fccce05 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
@@ -547,7 +547,7 @@ class WebChannel(BaseWsChannel):
ws_serve = websockets.serve
- ws_max_size = 8 * 2**20 # 8 MB — matches AgentServer link
+ from jiuwenswarm.common.ws_limits import WEB_WS_MAX_MESSAGE_BYTES
self._server = await ws_serve(
self._connection_handler,
@@ -556,7 +556,7 @@ class WebChannel(BaseWsChannel):
process_request=self._process_request,
ping_interval=20,
ping_timeout=60,
- max_size=ws_max_size,
+ max_size=WEB_WS_MAX_MESSAGE_BYTES,
)
self._running = True
logger.info(
diff --git a/jiuwenswarm/gateway/document_attachments.py b/jiuwenswarm/gateway/document_attachments.py
new file mode 100644
index 0000000000..a26a433152
--- /dev/null
+++ b/jiuwenswarm/gateway/document_attachments.py
@@ -0,0 +1,425 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Helpers for normalizing browser-uploaded document attachments."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import logging
+import re
+from contextlib import suppress
+from pathlib import Path
+from typing import Any
+
+from jiuwenswarm.common.document_parser import (
+ DEFAULT_MAX_CHARS,
+ SUPPORTED_DOCUMENT_EXTENSIONS,
+ is_supported_document,
+ parse_document_file,
+ resolve_document_suffix,
+ supported_formats,
+)
+from jiuwenswarm.common.utils import get_agent_sessions_dir
+
+logger = logging.getLogger(__name__)
+
+_SAFE_FILENAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
+_SESSION_ID_RE = re.compile(r"[^A-Za-z0-9._-]+")
+
+_MAX_DOCUMENT_BYTES = 30 * 1024 * 1024
+_MAX_DOCUMENT_COUNT = 20
+# Office binaries that read_file cannot open directly — persist a .txt sidecar.
+_OFFICE_TEXT_SIDECAR_SUFFIXES = frozenset({".docx", ".xlsx"})
+
+_TRUE_STRINGS = frozenset({"true", "1", "yes"})
+_FALSE_STRINGS = frozenset({"false", "0", "no"})
+
+
+def coerce_document_parse_flag(value: Any, *, default: bool = True) -> bool:
+ """Normalize document.persist ``parse`` flag without ``bool("false")`` pitfalls.
+
+ - bool is returned as-is
+ - strings ``true``/``false``/``1``/``0``/``yes``/``no`` (case-insensitive) are mapped
+ - any other type/value falls back to ``default``
+ """
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in _TRUE_STRINGS:
+ return True
+ if normalized in _FALSE_STRINGS:
+ return False
+ return default
+ return default
+
+
+async def persist_and_parse_documents(
+ params: dict[str, Any],
+ session_id: str | None,
+ *,
+ parse: bool = True,
+ max_chars: int = DEFAULT_MAX_CHARS,
+) -> dict[str, Any]:
+ """Validate browser document items, persist files, optionally parse, enrich params.
+
+ Accepts either ``params["documents"]`` or ``params["media_items"]`` entries with
+ ``type == "document"``. Each item must provide base64 payload plus filename/mime.
+
+ Mutates and returns ``params`` with:
+ - ``media_items``: stored document records (path + optional parsed text)
+ - ``files.uploaded_documents``: lightweight path metadata for chat.send
+ """
+ raw_items = _collect_document_items(params)
+ if not raw_items:
+ params.pop("documents", None)
+ return params
+
+ stored: list[dict[str, Any]] = []
+ errors: list[dict[str, Any]] = []
+ accepted_items = raw_items[:_MAX_DOCUMENT_COUNT]
+ overflow_items = raw_items[_MAX_DOCUMENT_COUNT:]
+ if overflow_items:
+ overflow_count = len(overflow_items)
+ logger.warning(
+ "[document.persist] dropping %s document(s) over limit=%s session_id=%s",
+ overflow_count,
+ _MAX_DOCUMENT_COUNT,
+ session_id,
+ )
+ for index, item in enumerate(overflow_items, start=_MAX_DOCUMENT_COUNT):
+ filename = ""
+ if isinstance(item, dict):
+ filename = str(item.get("filename") or item.get("name") or "")
+ errors.append(
+ {
+ "index": index,
+ "filename": filename,
+ "error": (
+ f"Document count exceeds limit ({_MAX_DOCUMENT_COUNT}); "
+ "this item was ignored"
+ ),
+ "code": "DOCUMENT_COUNT_LIMIT",
+ }
+ )
+
+ for index, item in enumerate(accepted_items):
+ try:
+ stored_item = await _store_and_maybe_parse_item(
+ item,
+ session_id=session_id,
+ index=index,
+ parse=parse,
+ max_chars=max_chars,
+ )
+ if stored_item:
+ stored.append(stored_item)
+ except Exception as exc:
+ logger.exception("[document.persist] failed for item %s: %s", index, exc)
+ errors.append(
+ {
+ "index": index,
+ "filename": str(item.get("filename") or item.get("name") or ""),
+ "error": str(exc),
+ }
+ )
+
+ if stored:
+ # Keep previously persisted images if caller mixed them in; only replace documents.
+ existing_media = params.get("media_items")
+ kept_images: list[dict[str, Any]] = []
+ if isinstance(existing_media, list):
+ for entry in existing_media:
+ if isinstance(entry, dict) and entry.get("type") == "image" and entry.get("path"):
+ kept_images.append(entry)
+ params["media_items"] = kept_images + stored
+ files = params.get("files")
+ if not isinstance(files, dict):
+ files = {}
+ files["uploaded_documents"] = [
+ {
+ "filename": item.get("filename"),
+ "path": item.get("path"),
+ "original_path": item.get("original_path"),
+ "text_path": item.get("text_path"),
+ "mime_type": item.get("mime_type"),
+ "size_bytes": item.get("size_bytes"),
+ "parser": item.get("parser"),
+ "text_truncated": item.get("text_truncated"),
+ }
+ for item in stored
+ ]
+ params["files"] = files
+ else:
+ params.pop("documents", None)
+
+ if errors:
+ params["document_errors"] = errors
+ params["supported_formats"] = supported_formats()
+ return params
+
+
+async def parse_existing_document(
+ path: str,
+ *,
+ session_id: str | None,
+ max_chars: int = DEFAULT_MAX_CHARS,
+) -> dict[str, Any]:
+ """Parse an already-persisted document path under the session uploads dir."""
+ safe_path = resolve_session_upload_path(path, session_id=session_id)
+ result = await parse_document_file(safe_path, max_chars=max_chars)
+ return {
+ "type": "document",
+ "path": str(safe_path),
+ "filename": safe_path.name,
+ "text": result["text"],
+ "text_truncated": result["truncated"],
+ "parser": result["parser"],
+ "file_ext": result["file_ext"],
+ "char_count": result["char_count"],
+ "documents_count": result["documents_count"],
+ }
+
+
+def session_uploads_dir(session_id: str | None) -> Path:
+ """Return the canonical uploads directory for a session."""
+ return (get_agent_sessions_dir() / _safe_session_id(session_id) / "uploads").resolve()
+
+
+def resolve_session_upload_path(path: str | Path, *, session_id: str | None) -> Path:
+ """Resolve ``path`` and require it to stay under the session uploads directory.
+
+ Prevents path traversal via ``../`` and symlink/junction escapes outside uploads.
+ """
+ text = str(path or "").strip()
+ if not text:
+ raise ValueError("path is required")
+
+ upload_root = session_uploads_dir(session_id)
+ try:
+ resolved = Path(text).expanduser().resolve(strict=False)
+ except OSError as exc:
+ raise ValueError(f"Invalid path: {text}") from exc
+
+ try:
+ resolved.relative_to(upload_root)
+ except ValueError as exc:
+ raise PermissionError(
+ f"path must be under session uploads directory: {upload_root}"
+ ) from exc
+
+ if not resolved.is_file():
+ raise FileNotFoundError(f"File not found: {resolved}")
+ return resolved
+
+
+def _collect_document_items(params: dict[str, Any]) -> list[dict[str, Any]]:
+ items: list[dict[str, Any]] = []
+ documents = params.get("documents")
+ if isinstance(documents, list):
+ for item in documents:
+ if isinstance(item, dict):
+ items.append(item)
+
+ media_items = params.get("media_items")
+ if isinstance(media_items, list):
+ for item in media_items:
+ if not isinstance(item, dict):
+ continue
+ item_type = item.get("type")
+ if item_type == "document" or (
+ item_type is None
+ and is_supported_document(
+ filename=str(item.get("filename") or item.get("name") or ""),
+ mime_type=str(item.get("mimeType") or item.get("mime_type") or ""),
+ )
+ ):
+ items.append(item)
+ return items
+
+
+async def _store_and_maybe_parse_item(
+ item: dict[str, Any],
+ *,
+ session_id: str | None,
+ index: int,
+ parse: bool,
+ max_chars: int,
+) -> dict[str, Any] | None:
+ filename_hint = str(item.get("filename") or item.get("name") or "")
+ mime_type = str(item.get("mimeType") or item.get("mime_type") or "").lower().strip()
+ suffix = resolve_document_suffix(filename=filename_hint, mime_type=mime_type)
+ if suffix is None:
+ raise ValueError(
+ f"Unsupported document type: filename={filename_hint!r} mime={mime_type!r}. "
+ f"Supported: {supported_formats()}"
+ )
+
+ raw_base64 = item.get("base64Data") or item.get("base64_data")
+ if not isinstance(raw_base64, str) or not raw_base64.strip():
+ # Allow re-parse of already-persisted path without base64.
+ existing_path = str(item.get("path") or "").strip()
+ if existing_path:
+ path = resolve_session_upload_path(existing_path, session_id=session_id)
+ data_size = path.stat().st_size
+ stored = {
+ "type": "document",
+ "filename": path.name,
+ "mime_type": mime_type or _mime_from_suffix(suffix),
+ "path": str(path),
+ "size_bytes": data_size,
+ }
+ # Office re-parse / sidecar: always materialize .txt for read_file.
+ need_office_txt = path.suffix.lower() in _OFFICE_TEXT_SIDECAR_SUFFIXES
+ if parse or need_office_txt:
+ await _attach_parse_and_office_txt(
+ stored,
+ original_path=path,
+ parse_meta=parse,
+ max_chars=max_chars,
+ )
+ return stored
+ raise ValueError("Missing base64Data / base64_data for document upload")
+
+ data: bytes | None = None
+ with suppress(binascii.Error):
+ data = base64.b64decode(raw_base64, validate=True)
+ if not data:
+ raise ValueError("Invalid base64 document payload")
+ if len(data) > _MAX_DOCUMENT_BYTES:
+ raise ValueError(
+ f"Document exceeds size limit ({_MAX_DOCUMENT_BYTES // (1024 * 1024)}MB): "
+ f"{filename_hint or f'document-{index + 1}'}"
+ )
+
+ safe_session_id = _safe_session_id(session_id)
+ upload_dir = get_agent_sessions_dir() / safe_session_id / "uploads"
+ upload_dir.mkdir(parents=True, exist_ok=True)
+
+ fallback = f"document-{index + 1}{suffix}"
+ filename = _safe_filename(filename_hint or fallback, fallback=fallback)
+ if Path(filename).suffix.lower() not in SUPPORTED_DOCUMENT_EXTENSIONS:
+ filename = f"{filename}{suffix}"
+ path = _unique_path(upload_dir / filename)
+ path.write_bytes(data)
+
+ stored = {
+ "type": "document",
+ "filename": path.name,
+ "mime_type": mime_type or _mime_from_suffix(suffix),
+ "path": str(path),
+ "size_bytes": len(data),
+ }
+ need_office_txt = path.suffix.lower() in _OFFICE_TEXT_SIDECAR_SUFFIXES
+ if parse or need_office_txt:
+ await _attach_parse_and_office_txt(
+ stored,
+ original_path=path,
+ parse_meta=parse,
+ max_chars=max_chars,
+ )
+ return stored
+
+
+async def _attach_parse_and_office_txt(
+ stored: dict[str, Any],
+ *,
+ original_path: Path,
+ parse_meta: bool,
+ max_chars: int,
+) -> None:
+ """Parse ``original_path``; for docx/xlsx also write a full ``.txt`` sidecar.
+
+ After a successful sidecar write, ``stored["path"]`` points at the ``.txt``
+ so Agent ``read_file`` can open it. ``original_path`` / ``text_path`` keep both.
+ """
+ suffix = original_path.suffix.lower()
+ write_sidecar = suffix in _OFFICE_TEXT_SIDECAR_SUFFIXES
+
+ if write_sidecar:
+ # Full text on disk for read_file (no truncation).
+ parsed_full = await parse_document_file(original_path, max_chars=None)
+ text_path = _write_office_text_sidecar(original_path, parsed_full.get("text") or "")
+ stored["original_path"] = str(original_path)
+ stored["text_path"] = str(text_path)
+ # Prefer .txt for downstream read_file / chat path hints.
+ stored["path"] = str(text_path)
+ stored["parser"] = parsed_full.get("parser")
+ stored["char_count"] = parsed_full.get("char_count")
+ stored["documents_count"] = parsed_full.get("documents_count")
+ if parse_meta:
+ full_len = int(parsed_full.get("char_count") or 0)
+ stored["text_truncated"] = full_len > max(1, int(max_chars))
+ return
+
+ if not parse_meta:
+ return
+
+ parsed = await parse_document_file(original_path, max_chars=max_chars)
+ stored.update(
+ {
+ "text_truncated": parsed["truncated"],
+ "parser": parsed["parser"],
+ "char_count": parsed["char_count"],
+ "documents_count": parsed["documents_count"],
+ }
+ )
+
+
+def _write_office_text_sidecar(original_path: Path, text: str) -> Path:
+ """Write parsed office content next to the original as ``stem.txt``."""
+ candidate = original_path.with_suffix(".txt")
+ txt_path = _unique_path(candidate)
+ txt_path.write_text(text if isinstance(text, str) else str(text or ""), encoding="utf-8")
+ logger.info(
+ "[document.persist] wrote office text sidecar original=%s text=%s chars=%s",
+ original_path.name,
+ txt_path.name,
+ len(text or ""),
+ )
+ return txt_path
+
+
+_SUFFIX_TO_MIME: dict[str, str] = {
+ ".pdf": "application/pdf",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ".csv": "text/csv",
+ ".tsv": "text/tab-separated-values",
+ ".txt": "text/plain",
+ ".md": "text/markdown",
+ ".markdown": "text/markdown",
+ ".html": "text/html",
+ ".htm": "text/html",
+ ".json": "application/json",
+ ".ipynb": "application/x-ipynb+json",
+}
+
+
+def _mime_from_suffix(suffix: str) -> str:
+ return _SUFFIX_TO_MIME.get(suffix.lower(), "application/octet-stream")
+
+
+def _safe_session_id(session_id: str | None) -> str:
+ text = str(session_id or "default").strip() or "default"
+ return _SESSION_ID_RE.sub("_", text)[:120]
+
+
+def _safe_filename(filename: str, *, fallback: str) -> str:
+ name = Path(filename).name.strip()
+ if not name or name in {".", ".."}:
+ name = fallback
+ return _SAFE_FILENAME_RE.sub("_", name)[:180]
+
+
+def _unique_path(path: Path) -> Path:
+ if not path.exists():
+ return path
+ stem = path.stem
+ suffix = path.suffix
+ for idx in range(1, 1000):
+ candidate = path.with_name(f"{stem}-{idx}{suffix}")
+ if not candidate.exists():
+ return candidate
+ return path.with_name(f"{stem}-overflow{suffix}")
diff --git a/tests/unit_tests/gateway/test_document_attachments.py b/tests/unit_tests/gateway/test_document_attachments.py
new file mode 100644
index 0000000000..3cc2626214
--- /dev/null
+++ b/tests/unit_tests/gateway/test_document_attachments.py
@@ -0,0 +1,285 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import base64
+import json
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.common.document_parser import (
+ is_supported_document,
+ parse_document_file,
+ resolve_document_suffix,
+ supported_formats,
+)
+from jiuwenswarm.gateway.document_attachments import (
+ coerce_document_parse_flag,
+ parse_existing_document,
+ persist_and_parse_documents,
+ resolve_session_upload_path,
+)
+
+
+async def test_persist_and_parse_documents_reports_count_limit(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments._MAX_DOCUMENT_COUNT",
+ 2,
+ )
+ documents = []
+ for idx in range(4):
+ content = f"# doc {idx}"
+ documents.append(
+ {
+ "filename": f"doc-{idx}.md",
+ "mime_type": "text/markdown",
+ "base64_data": base64.b64encode(content.encode("utf-8")).decode("ascii"),
+ }
+ )
+ result = await persist_and_parse_documents(
+ {"documents": documents},
+ "sess_limit",
+ parse=True,
+ max_chars=1000,
+ )
+ items = result.get("media_items") or []
+ assert len(items) == 2
+ errors = result.get("document_errors") or []
+ assert len(errors) == 2
+ assert errors[0]["index"] == 2
+ assert errors[0]["code"] == "DOCUMENT_COUNT_LIMIT"
+ assert "limit" in errors[0]["error"].lower()
+ assert errors[1]["filename"] == "doc-3.md"
+
+
+def test_coerce_document_parse_flag():
+ assert coerce_document_parse_flag(True) is True
+ assert coerce_document_parse_flag(False) is False
+ assert coerce_document_parse_flag("false") is False
+ assert coerce_document_parse_flag("FALSE") is False
+ assert coerce_document_parse_flag("0") is False
+ assert coerce_document_parse_flag("true") is True
+ assert coerce_document_parse_flag("yes") is True
+ # 非空但无法识别的字符串 / 其它类型:回退默认 True
+ assert coerce_document_parse_flag("maybe") is True
+ assert coerce_document_parse_flag(1) is True
+ assert coerce_document_parse_flag(0, default=True) is True
+ assert coerce_document_parse_flag(None, default=True) is True
+ assert coerce_document_parse_flag("", default=False) is False
+
+
+def test_supported_formats_include_ipynb_and_office():
+ formats = set(supported_formats())
+ assert ".ipynb" in formats
+ assert ".pdf" in formats
+ assert ".docx" in formats
+ assert ".xlsx" in formats
+ assert ".md" in formats
+
+
+def test_resolve_document_suffix_from_mime_and_filename():
+ assert resolve_document_suffix(filename="a.PDF", mime_type="") == ".pdf"
+ assert (
+ resolve_document_suffix(
+ filename="x.bin",
+ mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ )
+ == ".docx"
+ )
+ assert is_supported_document(filename="note.ipynb")
+ assert not is_supported_document(filename="a.exe")
+
+
+async def test_parse_ipynb_and_markdown(tmp_path: Path):
+ nb = {
+ "cells": [
+ {"cell_type": "markdown", "source": ["# Title\n"]},
+ {
+ "cell_type": "code",
+ "source": ["print(1)\n"],
+ "outputs": [{"text": ["1\n"]}],
+ },
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5,
+ }
+ ipynb_path = tmp_path / "demo.ipynb"
+ ipynb_path.write_text(json.dumps(nb), encoding="utf-8")
+ parsed_nb = await parse_document_file(ipynb_path, max_chars=5000)
+ assert "Cell 1" in parsed_nb["text"]
+ assert "print(1)" in parsed_nb["text"]
+ assert parsed_nb["parser"] == "IpynbParser"
+
+ md_path = tmp_path / "note.md"
+ md_path.write_text("# Hello\n\nworld", encoding="utf-8")
+ parsed_md = await parse_document_file(md_path, max_chars=5000)
+ assert "Hello" in parsed_md["text"]
+ assert parsed_md["file_ext"] == ".md"
+
+
+async def test_persist_and_parse_documents(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
+ content = "# uploaded doc\n\ncontent"
+ payload = {
+ "documents": [
+ {
+ "filename": "readme.md",
+ "mime_type": "text/markdown",
+ "base64_data": base64.b64encode(content.encode("utf-8")).decode("ascii"),
+ }
+ ]
+ }
+ result = await persist_and_parse_documents(payload, "sess_test", parse=True, max_chars=1000)
+ items = result.get("media_items") or []
+ assert len(items) == 1
+ assert items[0]["type"] == "document"
+ assert Path(items[0]["path"]).is_file()
+ assert items[0]["text_truncated"] is False
+ assert "text" not in items[0]
+ assert result["files"]["uploaded_documents"][0]["path"] == items[0]["path"]
+
+
+async def test_persist_docx_writes_txt_sidecar(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
+
+ async def fake_parse(file_path, *, max_chars=None, doc_id=""):
+ return {
+ "text": "parsed office body",
+ "truncated": False,
+ "parser": "FakeDocxParser",
+ "file_ext": Path(file_path).suffix.lower(),
+ "char_count": len("parsed office body"),
+ "documents_count": 1,
+ }
+
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.parse_document_file",
+ fake_parse,
+ )
+
+ # Minimal non-empty payload; content is not really a docx — parser is mocked.
+ payload = {
+ "documents": [
+ {
+ "filename": "report.docx",
+ "mime_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "base64_data": base64.b64encode(b"fake-docx-bytes").decode("ascii"),
+ }
+ ]
+ }
+ result = await persist_and_parse_documents(payload, "sess_office", parse=True, max_chars=1000)
+ items = result.get("media_items") or []
+ assert len(items) == 1
+ item = items[0]
+ assert item["filename"] == "report.docx"
+ assert Path(item["original_path"]).suffix == ".docx"
+ assert Path(item["original_path"]).is_file()
+ assert Path(item["text_path"]).suffix == ".txt"
+ assert Path(item["text_path"]).is_file()
+ assert item["path"] == item["text_path"]
+ assert Path(item["path"]).read_text(encoding="utf-8") == "parsed office body"
+ assert result["files"]["uploaded_documents"][0]["path"] == item["text_path"]
+ assert result["files"]["uploaded_documents"][0]["original_path"] == item["original_path"]
+
+
+async def test_persist_xlsx_writes_txt_sidecar_even_when_parse_false(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
+
+ async def fake_parse(file_path, *, max_chars=None, doc_id=""):
+ return {
+ "text": "sheet A1 value",
+ "truncated": False,
+ "parser": "FakeXlsxParser",
+ "file_ext": ".xlsx",
+ "char_count": 14,
+ "documents_count": 1,
+ }
+
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.parse_document_file",
+ fake_parse,
+ )
+
+ payload = {
+ "documents": [
+ {
+ "filename": "data.xlsx",
+ "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "base64_data": base64.b64encode(b"fake-xlsx-bytes").decode("ascii"),
+ }
+ ]
+ }
+ result = await persist_and_parse_documents(payload, "sess_xlsx", parse=False, max_chars=1000)
+ item = (result.get("media_items") or [])[0]
+ assert Path(item["original_path"]).suffix == ".xlsx"
+ assert Path(item["path"]).suffix == ".txt"
+ assert Path(item["path"]).read_text(encoding="utf-8") == "sheet A1 value"
+
+
+def test_resolve_session_upload_path_blocks_traversal(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
+ upload_dir = tmp_path / "sess_test" / "uploads"
+ upload_dir.mkdir(parents=True)
+ safe_file = upload_dir / "note.md"
+ safe_file.write_text("hello", encoding="utf-8")
+
+ outside = tmp_path / "secret.json"
+ outside.write_text('{"token":"x"}', encoding="utf-8")
+
+ resolved = resolve_session_upload_path(str(safe_file), session_id="sess_test")
+ assert resolved == safe_file.resolve()
+
+ with pytest.raises(PermissionError):
+ resolve_session_upload_path(str(outside), session_id="sess_test")
+
+ with pytest.raises(PermissionError):
+ resolve_session_upload_path(
+ str(upload_dir / ".." / ".." / "secret.json"),
+ session_id="sess_test",
+ )
+
+ with pytest.raises(PermissionError):
+ resolve_session_upload_path("../../../secret.json", session_id="sess_test")
+
+
+async def test_parse_existing_document_rejects_outside_uploads(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.document_attachments.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
+ outside = tmp_path / "leak.md"
+ outside.write_text("# secret", encoding="utf-8")
+ with pytest.raises(PermissionError):
+ await parse_existing_document(str(outside), session_id="sess_test", max_chars=1000)