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:json文件查看用虚拟视图,避免页面因为数据太多在切换时卡死;放开历史数据预览所有数据,并优化样式;优化集群模式下文件输出的样式
xiaoyao42e49df2cf6e72
diff --git a/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx b/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsxindex 8c1b79e416..8d8b28ebb6 100644--- a/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx+++ b/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx@@ -1,8 +1,11 @@-import { useState, useEffect, useMemo } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import ReactMarkdown from 'react-markdown';-import { parseHistoryJsonFileToPreviewMessages } from '../../features/historyRestore';-import { MessageItem } from '../ChatPanel/MessageItem';+import {+ parseHistoryJsonFilePreviewMode,+ parseHistoryJsonFileToPreviewMessages,+} from '../../features/historyRestore';+import { ChatTimelineList } from '../ChatPanel/MessageList';import '../ChatPanel/ChatPanel.css';interface FileViewerProps {@@ -35,6 +38,48 @@ function sessionIdFromAgentPath(filePath: string): string {return m ? m[0] : 'file';}+function VirtualizedTextViewer({ text }: { text: string }) {+ const lineHeight = 20;+ const overscan = 8;+ const [scrollTop, setScrollTop] = useState(0);+ const [viewportHeight, setViewportHeight] = useState(0);++ const lines = useMemo(() => (text || ' ').split(/\r\n|\n|\r/), [text]);+ const totalHeight = Math.max(lines.length * lineHeight, lineHeight);+ const visibleCount = Math.max(1, Math.ceil(viewportHeight / lineHeight) + overscan * 2);+ const startIndex = Math.max(0, Math.floor(scrollTop / lineHeight) - overscan);+ const endIndex = Math.min(lines.length, startIndex + visibleCount);+ const visibleLines = lines.slice(startIndex, endIndex);++ const measure = useCallback((node: HTMLDivElement | null) => {+ if (!node) {+ return;+ }+ setViewportHeight(node.clientHeight);+ }, []);++ return (+ <div+ ref={measure}+ className="w-full h-full min-h-[280px] overflow-auto rounded-lg border border-border bg-card p-3 text-sm text-text mono"+ onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}+ >+ <div style={{ height: totalHeight, position: 'relative' }}>+ <pre+ className="absolute left-0 m-0 min-w-full whitespace-pre"+ style={{+ top: startIndex * lineHeight,+ lineHeight: `${lineHeight}px`,+ width: 'max-content',+ }}+ >+ {visibleLines.join('\n')}+ </pre>+ </div>+ </div>+ );+}+export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerProps) {const { t } = useTranslation();const [content, setContent] = useState<string>('');@@ -54,49 +99,50 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPrconst fileNotFound = Boolean(error && error.includes('HTTP 404'));const [historyChatPreview, setHistoryChatPreview] = useState(true);- /** 任意 .json 单次 parse,避免预览/格式化重复 JSON.parse */- const jsonDerived = useMemo(() => {+ const jsonParseResult = useMemo(() => {if (!isJson || !content.trim()) {return {- historyMessages: [] as ReturnType<typeof parseHistoryJsonFileToPreviewMessages>,- historyInvalid: false,- todoItems: [] as TodoPreviewItem[],- todoInvalid: false,- formatted: content,+ parsed: null as unknown,+ invalid: false,};}try {const parsed: unknown = JSON.parse(content);- const formatted = JSON.stringify(parsed, null, 2);- if (!isHistoryJson && !isTodoJson) {- return { historyMessages: [], historyInvalid: false, todoItems: [], todoInvalid: false, formatted };- }- if (isTodoJson) {- if (!Array.isArray(parsed)) {- return { historyMessages: [], historyInvalid: false, todoItems: [], todoInvalid: true, formatted };- }- return {- historyMessages: [],- historyInvalid: false,- todoItems: parseTodoJsonFileToPreview(parsed),- todoInvalid: false,- formatted,- };- }- if (!Array.isArray(parsed)) {- return { historyMessages: [], historyInvalid: true, todoItems: [], todoInvalid: false, formatted };- }- return {- historyMessages: parseHistoryJsonFileToPreviewMessages(parsed, sessionIdFromAgentPath(filePath)),- historyInvalid: false,- todoItems: [],- todoInvalid: false,- formatted,- };+ return { parsed, invalid: false };} catch {- return { historyMessages: [], historyInvalid: true, todoItems: [], todoInvalid: true, formatted: content };+ return { parsed: null as unknown, invalid: true };}- }, [isJson, isHistoryJson, isTodoJson, content, filePath]);+ }, [isJson, content]);++ const historyMessages = useMemo(() => {+ if (!isHistoryJson || !historyChatPreview || !Array.isArray(jsonParseResult.parsed)) {+ return [] as ReturnType<typeof parseHistoryJsonFileToPreviewMessages>;+ }+ return parseHistoryJsonFileToPreviewMessages(jsonParseResult.parsed, sessionIdFromAgentPath(filePath));+ }, [isHistoryJson, historyChatPreview, jsonParseResult.parsed, filePath]);++ const historyPreviewMode = useMemo(() => {+ if (!isHistoryJson || !Array.isArray(jsonParseResult.parsed)) {+ return null;+ }+ return parseHistoryJsonFilePreviewMode(jsonParseResult.parsed);+ }, [isHistoryJson, jsonParseResult.parsed]);++ const todoItems = useMemo(() => {+ if (!isTodoJson || !Array.isArray(jsonParseResult.parsed)) {+ return [] as TodoPreviewItem[];+ }+ return parseTodoJsonFileToPreview(jsonParseResult.parsed);+ }, [isTodoJson, jsonParseResult.parsed]);++ const formattedJson = useMemo(() => {+ if (!isJson || isHistoryJson || jsonParseResult.invalid || jsonParseResult.parsed === null) {+ return content;+ }+ return JSON.stringify(jsonParseResult.parsed, null, 2);+ }, [isJson, isHistoryJson, jsonParseResult.invalid, jsonParseResult.parsed, content]);++ const historyInvalid = isHistoryJson && jsonParseResult.invalid;useEffect(() => {if (!filePath) return;@@ -328,13 +374,13 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr</article>)) : isJson ? (- isTodoJson && jsonDerived.todoItems.length > 0 ? (+ isTodoJson && todoItems.length > 0 ? (<div className="w-full min-h-[280px] rounded-lg border border-border bg-card p-4 space-y-4">{(() => {- const inProgress = jsonDerived.todoItems.filter((i) => i.status === 'in_progress');- const pending = jsonDerived.todoItems.filter((i) => i.status === 'pending');- const completed = jsonDerived.todoItems.filter((i) => i.status === 'completed');- const cancelled = jsonDerived.todoItems.filter((i) => i.status === 'cancelled');+ const inProgress = todoItems.filter((i) => i.status === 'in_progress');+ const pending = todoItems.filter((i) => i.status === 'pending');+ const completed = todoItems.filter((i) => i.status === 'completed');+ const cancelled = todoItems.filter((i) => i.status === 'cancelled');const renderGroup = (title: string, items: TodoPreviewItem[], colorClass: string, icon: string) => (items.length > 0 ? (@@ -367,25 +413,22 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr})()}</div>) : isHistoryJson && historyChatPreview ? (- jsonDerived.historyInvalid ? (- <pre className="w-full h-full min-h-[280px] overflow-auto rounded-lg border border-border bg-card p-3 text-sm text-text mono whitespace-pre-wrap break-all">- {jsonDerived.formatted || ' '}- </pre>- ) : jsonDerived.historyMessages.length === 0 ? (+ historyInvalid ? (+ <VirtualizedTextViewer text={content} />+ ) : historyMessages.length === 0 ? (<div className="h-full min-h-[280px] flex items-center justify-center rounded-lg border border-border bg-card px-4 text-sm text-text-muted text-center">{t('fileViewer.historyPreviewEmpty')}</div>) : (- <div className="w-full min-h-[280px] rounded-lg border border-border bg-card p-3">- {jsonDerived.historyMessages.map((message) => (- <MessageItem key={message.id} message={message} />- ))}+ <div className="w-full min-h-[280px] rounded-lg border border-border bg-card p-3 chat-content">+ <ChatTimelineList+ messages={historyMessages}+ mode={historyPreviewMode ?? undefined}+ /></div>)) : (- <pre className="w-full h-full min-h-[280px] overflow-auto rounded-lg border border-border bg-card p-3 text-sm text-text mono whitespace-pre-wrap break-all">- {jsonDerived.formatted || ' '}- </pre>+ <VirtualizedTextViewer text={isHistoryJson ? content : formattedJson} />)) : (<div className="h-full flex items-center justify-center text-text-muted text-sm">diff --git a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex 423818ac28..3d4b2be7d0 100644--- a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -112,15 +112,17 @@ export function formatMemberName(member?: string) {return member || 'Unknown';}-function MarkdownMessageBody({+export function MarkdownMessageBody({content,+ className,testId,}: {content: string;+ className?: string;testId?: string;}) {return (- <div className="chat-text" data-testid={testId}>+ <div className={clsx('chat-text chat-markdown', className)} data-testid={testId}><ReactMarkdownremarkPlugins={[remarkGfm]}components={{@@ -171,19 +173,25 @@ function TeamLeaderPlainTextMessage({member = 'team_leader',content,showAvatar = true,+ fileItems,}: {member?: string;content: string;showAvatar?: boolean;+ fileItems?: FileDownloadItem[];}) {return (<TeamMemberMessageFramemember={member}showAvatar={showAvatar}>- <div className="team-member-message__plain">- {content}- </div>+ {fileItems && fileItems.length > 0 && (+ <FileDownloadList files={fileItems} className="w-full md:w-1/2" />+ )}+ <MarkdownMessageBody+ content={content}+ className="team-member-message__plain"+ /></TeamMemberMessageFrame>);}@@ -452,7 +460,10 @@ export function MessageItem({@所有人</span>)}- <span>{event.content}</span>+ <MarkdownMessageBody+ content={event.content}+ className="team-message-markdown team-message-markdown--inline"+ /></div></div></TeamMemberMessageFrame>@@ -487,6 +498,7 @@ export function MessageItem({member="team_leader"content={messageContent || (isStreaming ? '正在接收中...' : '')}showAvatar={showAvatar}+ fileItems={fileItems}/>);}@@ -669,7 +681,13 @@ function getFileTypeConfig(mimeType: string | undefined, name: string) {return { label: 'FILE', bg: 'bg-[#6b7280]', icon: '��' };}-function FileDownloadList({ files }: { files: FileDownloadItem[] }) {+function FileDownloadList({+ files,+ className,+}: {+ files: FileDownloadItem[];+ className?: string;+}) {const handleDownload = (file: FileDownloadItem) => {const link = document.createElement('a');link.href = file.download_url;@@ -680,7 +698,7 @@ function FileDownloadList({ files }: { files: FileDownloadItem[] }) {};return (- <div className="mt-2 space-y-2">+ <div className={clsx('mt-2 space-y-2', className)}>{files.map((file, index) => {const typeConfig = getFileTypeConfig(file.mime_type, file.name);const ext = getFileExtension(file.name);diff --git a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageList.tsxindex d6ec5eb789..f3c70d4b61 100644--- a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageList.tsx+++ b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/MessageList.tsx@@ -16,6 +16,12 @@ interface MessageListProps {messages: Message[];}+interface ChatTimelineListProps {+ messages: Message[];+ executions?: ToolExecution[];+ mode?: string;+}+type TimelineItem =| {type: 'message';@@ -48,6 +54,7 @@ type RenderItem =| {type: 'teamEventGroup';key: string;+ showAvatar: boolean;messages: Message[];};@@ -68,6 +75,10 @@ function compareTimelineItems(a: TimelineItem, b: TimelineItem): number {if (aTsValid && bTsValid && a.timestampMs !== b.timestampMs) {return a.timestampMs - b.timestampMs;}+ if (a.type !== b.type) {+ if (a.type === 'toolExecution') return -1;+ if (b.type === 'toolExecution') return 1;+ }if (aTsValid !== bTsValid) {return aTsValid ? -1 : 1;}@@ -131,6 +142,7 @@ function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderIterenderItems.push({type: 'teamEventGroup',key: `team-event-group-${currentSegment.teamMessages[0].key}`,+ showAvatar: true,messages: currentSegment.teamMessages.map((item) => item.message),});currentSegment.teamMessages = [];@@ -212,6 +224,7 @@ function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderIte}if (renderItem.type === 'teamEventGroup') {+ renderItem.showAvatar = !clusterBlockActive;clusterBlockActive = true;continue;}@@ -229,17 +242,12 @@ function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderItereturn renderItems;}-export function MessageList({ messages }: MessageListProps) {- const { toolExecutions, toolExecutionOrder } = useChatStore();- const { mode } = useSessionStore();+export function ChatTimelineList({+ messages,+ executions = [],+ mode = 'default',+}: ChatTimelineListProps) {const isTeamMode = mode === 'team';- const executions = useMemo(- () => toolExecutionOrder- .map((toolCallId) => toolExecutions.get(toolCallId))- .filter((item): item is NonNullable<typeof item> => !!item),- [toolExecutions, toolExecutionOrder]- );-const renderItems = useMemo(() => buildRenderItems(buildTimelineItems(messages, executions), isTeamMode),[messages, executions, isTeamMode]@@ -275,9 +283,23 @@ export function MessageList({ messages }: MessageListProps) {<TeamEventGroupDisplaykey={item.key}messages={item.messages}+ showAvatar={item.showAvatar}/>);})}</div>);}++export function MessageList({ messages }: MessageListProps) {+ const { toolExecutions, toolExecutionOrder } = useChatStore();+ const { mode } = useSessionStore();+ const executions = useMemo(+ () => toolExecutionOrder+ .map((toolCallId) => toolExecutions.get(toolCallId))+ .filter((item): item is NonNullable<typeof item> => !!item),+ [toolExecutions, toolExecutionOrder]+ );++ return <ChatTimelineList messages={messages} executions={executions} mode={mode} />;+}diff --git a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/TeamEventGroupDisplay.tsx b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/TeamEventGroupDisplay.tsxindex 007bfb7ee5..26218dbf68 100644--- a/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/TeamEventGroupDisplay.tsx+++ b/jiuwenclaw/channels/web/frontend/src/components/ChatPanel/TeamEventGroupDisplay.tsx@@ -4,11 +4,12 @@ import {parseTeamEventMessage,ParsedTeamEvent,} from './teamEventUtils';-import { formatMemberName, TeamMemberAvatar } from './MessageItem';+import { formatMemberName, MarkdownMessageBody, TeamMemberAvatar } from './MessageItem';import teamIcon from '../../assets/team.svg';interface TeamEventGroupDisplayProps {messages: Message[];+ showAvatar?: boolean;}function isTeamLeaderDisplayName(member: string) {@@ -57,14 +58,20 @@ function TeamEventRow({@所有人</span>)}- <span>{event.content}</span>+ <MarkdownMessageBody+ content={event.content}+ className="team-message-markdown team-message-markdown--inline"+ /></div></div></div>);}-export function TeamEventGroupDisplay({ messages }: TeamEventGroupDisplayProps) {+export function TeamEventGroupDisplay({+ messages,+ showAvatar = true,+}: TeamEventGroupDisplayProps) {const events = useMemo(() => messages.map(parseTeamEventMessage)@@ -83,7 +90,9 @@ export function TeamEventGroupDisplay({ messages }: TeamEventGroupDisplayProps)return (<div className="team-event-group-shell animate-rise" data-testid="team-event-group">- <div className="team-event-group-shell__spacer" aria-hidden="true" />+ <div className="team-event-group-shell__spacer">+ {showAvatar ? <TeamMemberAvatar member="team_leader" /> : null}+ </div><div className="team-event-group"><div className="team-event-group-summary"><div className="team-event-group-summary__main">diff --git a/jiuwenclaw/channels/web/frontend/src/features/historyRestore.ts b/jiuwenclaw/channels/web/frontend/src/features/historyRestore.tsindex 16e78dca20..846ce4d576 100644--- a/jiuwenclaw/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenclaw/channels/web/frontend/src/features/historyRestore.ts@@ -330,12 +330,9 @@ function parseHistoryTimelineEntry(return null;}-/** 工作区 history.json 预览:最多展示条数(按消息时间取最近) */-export const HISTORY_FILE_PREVIEW_MAX_MESSAGES = 20;-/*** 将磁盘上的 history.json 解析结果(通常为记录数组)转为与历史恢复相同的筛选规则下的消息列表,- * 并按时间升序仅保留时间上最近的 {@link HISTORY_FILE_PREVIEW_MAX_MESSAGES} 条用户/助手消息。+ * 并按时间升序返回全部可展示的用户/助手消息。*/export function parseHistoryJsonFileToPreviewMessages(parsed: unknown,@@ -356,10 +353,15 @@ export function parseHistoryJsonFileToPreviewMessages(}}- const sorted = [...messages].sort(- (a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp)- );- return sorted.slice(-HISTORY_FILE_PREVIEW_MAX_MESSAGES);+ return messages.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));+}++export function parseHistoryJsonFilePreviewMode(parsed: unknown): 'team' | null {+ if (!Array.isArray(parsed)) {+ return null;+ }++ return parsed.some((item) => isRecord(item) && isTeamModeRecord(item)) ? 'team' : null;}function isHistoryBatchEnd(payload: Record<string, unknown>): boolean {diff --git a/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.tsindex e90e68c6da..9594f64837 100644--- a/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenclaw/channels/web/frontend/src/hooks/useWebSocket.ts@@ -100,6 +100,23 @@ function normalizeAgentMode(rawMode: unknown): AgentMode {const EVENT_DEDUP_WINDOW_MS = 1500;+function normalizeEventTimestampIso(value: unknown): string {+ if (typeof value === 'number' && Number.isFinite(value)) {+ const millis = value > 1_000_000_000_000 ? value : value * 1000;+ const date = new Date(millis);+ if (!Number.isNaN(date.getTime())) {+ return date.toISOString();+ }+ }+ if (typeof value === 'string') {+ const parsed = Date.parse(value);+ if (!Number.isNaN(parsed)) {+ return new Date(parsed).toISOString();+ }+ }+ return new Date().toISOString();+}+function stringifyPayloadForDedup(payload: Record<string, unknown>): string {try {const serialized = JSON.stringify(payload);@@ -304,6 +321,33 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {[]);+ const findActiveTeamLeaderMessage = useCallback(() => {+ const { messages } = useChatStore.getState();+ let latestUserIndex = -1;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ if (messages[i].role === 'user') {+ latestUserIndex = i;+ break;+ }+ }+ for (let i = messages.length - 1; i > latestUserIndex; i -= 1) {+ const msg = messages[i];+ if (msg.id.startsWith('team-leader-') && msg.isStreaming) {+ return msg;+ }+ }+ return undefined;+ }, []);++ const closeActiveTeamLeaderMessages = useCallback(() => {+ const { messages } = useChatStore.getState();+ for (const msg of messages) {+ if (msg.id.startsWith('team-leader-') && msg.isStreaming) {+ updateMessage(msg.id, { isStreaming: false });+ }+ }+ }, [updateMessage]);+// 发送聊天消息const sendMessage = useCallback(async (content: string, sessionId: string) => {@@ -376,6 +420,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (intent === 'supplement' && newInput) {userInputVersionRef.current += 1;stopAllTts();+ if (useSessionStore.getState().mode === 'team') {+ closeActiveTeamLeaderMessages();+ }addMessage({id: `user-${Date.now()}`,role: 'user',@@ -404,7 +451,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {onErrorRef.current?.(webError.message || i18n.t('network.interruptFailed'));}},- [addMessage, request, setConnectionStats]+ [addMessage, closeActiveTeamLeaderMessages, request, setConnectionStats]);// 暂停 - 显式暂停当前任务@@ -643,11 +690,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {// team 模式下,累积 chat.delta 内容if (currentMode === 'team' && content) {clearThinkingForVisibleOutput();- const { messages } = useChatStore.getState();- const existingMsg = messages.find(m =>- m.id.startsWith('team-leader-') &&- (m as { isStreaming?: boolean }).isStreaming === true- );+ const existingMsg = findActiveTeamLeaderMessage();if (existingMsg) {const existingContent = existingMsg.content || '';@@ -694,18 +737,14 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {// team 模式下,将 chat.final 作为 team_leader 消息处理if (currentMode === 'team' && content) {clearThinkingForVisibleOutput();- const { messages } = useChatStore.getState();- const existingMsg = messages.find(m =>- m.id.startsWith('team-leader-') &&- (m as { isStreaming?: boolean }).isStreaming === true- );+ const existingMsg = findActiveTeamLeaderMessage();const timestamp = payload.timestamp || Date.now();if (existingMsg) {updateMessage(existingMsg.id, {content: `team.leader:${JSON.stringify({ content, timestamp })}`,isStreaming: false,- timestamp: new Date().toISOString(),+ timestamp: normalizeEventTimestampIso(payload.timestamp),});return;}@@ -728,7 +767,6 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {updateMessage(streamId, {...(content ? { content } : {}),isStreaming: false,- timestamp: new Date().toISOString(),});stopStreaming();if (content && !content.includes('MEDIA:')) {@@ -834,17 +872,44 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (!shouldHandleSessionEvent(payload)) return;const files = (payload.files ?? []) as FileDownloadItem[];if (!files.length) return;+ if (useSessionStore.getState().mode === 'team') {+ const target = findActiveTeamLeaderMessage();+ if (target) {+ updateMessage(target.id, {+ fileItems: [...(target.fileItems || []), ...files],+ });+ } else {+ addMessage({+ id: `team-leader-${Date.now()}`,+ role: 'system',+ content: '',+ timestamp: new Date().toISOString(),+ isStreaming: true,+ fileItems: files,+ });+ }+ return;+ }addFileItems(files);}),webClient.on('chat.tool_call', ({ payload }) => {if (!shouldHandleSessionEvent(payload)) return;if (shouldDropDuplicatedEvent('chat.tool_call', payload)) return;clearThinkingForVisibleOutput();- addToolCall(normalizeToolCallPayload(payload));- const { currentStreamId } = useChatStore.getState();- if (currentStreamId) {- updateMessage(currentStreamId, { timestamp: new Date().toISOString() });- }+ const toolCall = normalizeToolCallPayload(payload);+ const { currentStreamId, messages } = useChatStore.getState();+ const currentStreamMessage =+ useSessionStore.getState().mode === 'team'+ ? findActiveTeamLeaderMessage()+ : currentStreamId+ ? messages.find((msg) => msg.id === currentStreamId)+ : undefined;+ addToolCall(+ toolCall,+ currentStreamMessage?.timestamp+ ? { startedAt: currentStreamMessage.timestamp }+ : undefined+ );}),webClient.on('chat.tool_result', ({ payload }) => {if (!shouldHandleSessionEvent(payload)) return;@@ -1348,6 +1413,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {setContextCompressionStats,setHeartbeatStatus,clearThinkingForVisibleOutput,+ findActiveTeamLeaderMessage,updateSession,shouldHandleSessionEvent,shouldDropDuplicatedEvent,diff --git a/jiuwenclaw/channels/web/frontend/src/index.css b/jiuwenclaw/channels/web/frontend/src/index.cssindex 09e161d575..3f290c4534 100644--- a/jiuwenclaw/channels/web/frontend/src/index.css+++ b/jiuwenclaw/channels/web/frontend/src/index.css@@ -833,7 +833,7 @@ select {white-space: pre-wrap;}- .chat-bubble.assistant.markdown .chat-text {+ .chat-markdown {@apply prose prose-sm max-w-none;--tw-prose-body: var(--chat-text);--tw-prose-headings: var(--text-strong);@@ -988,7 +988,7 @@ select {/* ====== Team Timeline Messages ====== */.team-member-message {- width: min(95%, 820px);+ width: min(95%, 920px);margin: 12px auto;display: grid;grid-template-columns: 36px minmax(0, 1fr);@@ -1039,6 +1039,37 @@ select {word-break: break-word;}+ .team-member-message__plain.chat-markdown {+ white-space: normal;+ }++ .team-message-markdown {+ color: var(--text);+ font-size: inherit;+ line-height: inherit;+ --tw-prose-body: var(--text);+ --tw-prose-bold: var(--text-strong);+ --tw-prose-code: var(--text);+ --tw-prose-links: var(--accent);+ }++ .team-message-markdown > :first-child {+ margin-top: 0;+ }++ .team-message-markdown > :last-child {+ margin-bottom: 0;+ }++ .team-message-markdown--inline {+ display: inline;+ }++ .team-message-markdown--inline > p:first-child {+ display: inline;+ margin: 0;+ }+/* ====== Team Event Group Cards ====== */.team-event-group {margin: 8px auto;@@ -1050,7 +1081,7 @@ select {}.team-event-group-shell {- width: min(95%, 820px);+ width: min(95%, 920px);margin: 8px auto;display: grid;grid-template-columns: 36px minmax(0, 1fr);@@ -1240,7 +1271,7 @@ select {}.tool-group-frame--team {- width: min(95%, 820px);+ width: min(95%, 920px);margin: 12px auto;display: grid;grid-template-columns: 36px minmax(0, 1fr);diff --git a/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts b/jiuwenclaw/channels/web/frontend/src/stores/chatStore.tsindex 8aedc68772..20b02b9c15 100644--- a/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts+++ b/jiuwenclaw/channels/web/frontend/src/stores/chatStore.ts@@ -584,9 +584,10 @@ export const useChatStore = create<ChatState>((set, get) => ({addFileItems: (files) => {const { currentStreamId, messages } = get();- let targetId =+ const lastMessage = messages[messages.length - 1];+ const targetId =currentStreamId ??- [...messages].reverse().find((msg) => msg.role === 'assistant')?.id;+ (lastMessage?.role === 'assistant' ? lastMessage.id : null);if (!targetId) {const msgId = `file-${Date.now()}`;set((state) => ({