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(web): 主对话展示优化:对话时间线交错展示调整&增加思考过程打印&调整工具调用展示逻辑
zhengshangyiaff134bad32b
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex 7ea5d59423..31f2add1b1 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -10,6 +10,7 @@ Migrated from JiuSwarmReActAgent:from __future__ import annotationsimport asyncio+import copyimport jsonimport refrom typing import Any, List, Optional@@ -40,6 +41,11 @@ from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (from jiuwenswarm.agents.harness.common.rails.symphony import (SymphonyToolStreamHandler,)+from jiuwenswarm.common.tool_display import (+ build_tool_display_name,+ extract_call_goal,+ inject_call_goal_schema,+)from jiuwenswarm.common.utils import logger_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify"])@@ -241,7 +247,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):# Per-session conversation contextself._conversation_ids: dict[str, str] = {}self._main_sessions: dict[str, Session] = {}- self._stream_tasks: set[asyncio.Task] = set()# Shared across sessions (same workspace → same tool instance)self._main_todo_tool: Optional[TodoListTool] = None# Track in-flight tool calls for cancellation status emission@@ -589,11 +594,107 @@ class JiuSwarmStreamEventRail(DeepAgentRail):if self._abort_requested.get(sid, False):raise asyncio.CancelledError("Agent abort requested")+ self._inject_tool_call_goal_schema(ctx)+ self._ensure_tool_call_goal_prompt()+if ctx.context is not None:if not self._read_image_multimodal_enabled():strip_image_content_from_model_context(ctx.context)await self._fix_incomplete_tool_context(ctx)+ @staticmethod+ def _inject_tool_call_goal_schema(ctx: AgentCallbackContext) -> None:+ """仅给送入 LLM 的 ToolInfo 注入 call_goal,且必须 deepcopy。++ 不可就地改 parameters / card.input_params:ToolInfo 与执行侧 schema 常共享+ 内层 properties,注入后 SchemaUtils 会补上 call_goal=None,LocalFunction+ 再 **kwargs 传给 send_file 等实现会直接 TypeError(表现为工具挂掉)。+ """+ tools = getattr(ctx.inputs, "tools", None) or []+ if not tools:+ return+ next_tools: list[Any] = []+ changed = False+ for tool in tools:+ params = getattr(tool, "parameters", None)+ if not isinstance(params, dict):+ next_tools.append(tool)+ continue+ props = params.get("properties")+ if isinstance(props, dict) and "call_goal" in props:+ next_tools.append(tool)+ continue+ cloned = copy.deepcopy(params)+ inject_call_goal_schema(cloned)+ if cloned == params:+ next_tools.append(tool)+ continue+ model_copy = getattr(tool, "model_copy", None)+ if callable(model_copy):+ try:+ next_tools.append(model_copy(update={"parameters": cloned}))+ changed = True+ continue+ except Exception as exc:+ # model_copy 可能抛 ValidationError 等与具体 ToolInfo 实现相关的异常;+ # 注入失败时跳过该工具,不阻断主链路。+ logger.warning(+ "[StreamEventRail] model_copy for call_goal failed; skip inject tool=%s err=%s",+ getattr(tool, "name", type(tool).__name__),+ exc,+ )+ # 无 model_copy / copy 失败:绝不回写原始 ToolInfo,避免 call_goal 泄漏进执行侧。+ next_tools.append(tool)+ if changed:+ try:+ ctx.inputs.tools = next_tools+ except (AttributeError, TypeError) as exc:+ logger.warning(+ "[StreamEventRail] replace tools with call_goal schema failed: %s",+ exc,+ )++ def _ensure_tool_call_goal_prompt(self) -> None:+ builder = getattr(self._deep_agent, "system_prompt_builder", None)+ if builder is None:+ return+ try:+ from openjiuwen.harness.prompts import PromptSection+ cn_text = (+ "# 工具 call_goal\n\n"+ "每次调用工具时,请填写参数 `call_goal`:用一句简短中文说明"+ "这次调用要达成的目标(如「调研 openJiuwen 官网信息」「创建三子棋对战团队」),"+ "不要只写工具名或裸 URL。"+ "该字段仅用于界面展示,不影响工具实际执行。\n"+ "团队工具也必须填 `call_goal`,且不能用其它字段代替:\n"+ "- `spawn_member` / `spawn_teammate`:`call_goal` 写「为何创建该成员」;"+ "`display_name` 仍是成员展示名,两者都要填。\n"+ "- `send_message`:`call_goal` 写「这次消息的目的」;"+ "`summary` 可继续填,但不能省略 `call_goal`。\n"+ "- `build_team`:`call_goal` 写建队目标;`display_name` 仍是团队名。"+ )+ en_text = (+ "# Tool call_goal\n\n"+ "When calling any tool, set `call_goal`: one short phrase for the goal of this call "+ "(e.g. \"Research openJiuwen official site\", \"Create tic-tac-toe team\"). "+ "Do not just repeat the tool name or raw URL. UI only; does not affect execution.\n"+ "Team tools must also set `call_goal`; do not substitute other fields:\n"+ "- `spawn_member` / `spawn_teammate`: `call_goal` = why spawn this member; "+ "`display_name` remains the member label — fill both.\n"+ "- `send_message`: `call_goal` = purpose of this message; "+ "`summary` may still be set, but `call_goal` is required too.\n"+ "- `build_team`: `call_goal` = team goal; `display_name` remains the team name."+ )+ builder.add_section(+ PromptSection(+ name="tool_call_goal",+ content={"cn": cn_text, "en": en_text},+ priority=40,+ )+ )+ except (ImportError, AttributeError, TypeError, ValueError) as exc:+ logger.warning("[StreamEventRail] inject call_goal prompt failed: %s", exc)+async def after_model_call(self, ctx: AgentCallbackContext) -> None:await self._emit_context_usage(ctx,@@ -601,10 +702,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):role=self._role or None,)- # ------------------------------------------------------------------- # before_tool_call: pause check + emit tool_call event- # -------------------------------------------------------------------async def before_tool_call(self, ctx: AgentCallbackContext) -> None:sid = self._resolve_sid(ctx, ctx.session)await self._get_pause_event(sid).wait()@@ -614,7 +711,23 @@ class JiuSwarmStreamEventRail(DeepAgentRail):session = ctx.sessionif session is not None and isinstance(ctx.inputs, ToolCallInputs):tc = ctx.inputs.tool_call- await self._emit_tool_call(session, tc)+ # 主模型随 tool_call 产出的目标文案(call_goal):取出后剥掉,避免 schema 拒收。+ # 绝不碰 display_name(team 成员名等业务字段)。+ model_display, cleaned_args = extract_call_goal(+ getattr(tc, "arguments", {}) if tc else {}+ )+ # 无论是否填了 call_goal,都写回清洗后的 arguments,避免执行侧拿到该字段。+ if tc is not None:+ try:+ tc.arguments = cleaned_args+ except (AttributeError, TypeError) as exc:+ logger.warning(+ "[StreamEventRail] rewrite tool arguments without call_goal failed; tool_id=%s err=%s",+ getattr(tc, "id", ""),+ exc,+ )+ ctx.inputs.tool_args = cleaned_args+ await self._emit_tool_call(session, tc, model_display_name=model_display)await self._emit_tool_update(session, tc, status="in_progress")self._symphony_stream_handler.bind_progress(ctx, session, tc)# Track in-flight tool call for cancellation@@ -682,19 +795,31 @@ class JiuSwarmStreamEventRail(DeepAgentRail):# ------------------------------------------------------------------@staticmethod- async def _emit_tool_call(session: Session, tool_call: Any) -> None:+ async def _emit_tool_call(+ session: Session,+ tool_call: Any,+ *,+ model_display_name: str = "",+ ) -> None:try:+ name = getattr(tool_call, "name", "")+ arguments = getattr(tool_call, "arguments", {})+ tool_call_payload: dict[str, Any] = {+ "name": name,+ "arguments": arguments,+ "tool_call_id": getattr(tool_call, "id", ""),+ }+ # 优先用主模型随 tool_call 产出的目标文案;未填时再规则兜底。+ display_name = (model_display_name or "").strip() or build_tool_display_name(+ name, arguments+ )+ if display_name:+ tool_call_payload["display_name"] = display_nameawait session.write_stream(OutputSchema(type="tool_call",index=0,- payload={- "tool_call": {- "name": getattr(tool_call, "name", ""),- "arguments": getattr(tool_call, "arguments", {}),- "tool_call_id": getattr(tool_call, "id", ""),- }- },+ payload={"tool_call": tool_call_payload},))except Exception:@@ -1085,7 +1210,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):returnmessages = context.get_messages()tools = getattr(ctx.inputs, "tools", None) or []- # fix tool parameter validationfor tool in tools:if not tool.parameters:tool.parameters = {@@ -1094,6 +1218,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):}if tool.parameters.get("type") is None:tool.parameters["type"] = "object"+ self._inject_tool_call_goal_schema(ctx)len_messages = len(messages)if len_messages == 0:returndiff --git a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.pyindex 639fe4ef3a..4e6dc6af71 100644--- a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py+++ b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py@@ -146,6 +146,7 @@ class SendFileToolkit:self,abs_file_path_list: Union[List[str], str],target_channels: Union[List[str], str, None] = None,+ **_ignored: Any,) -> str:"""Send files to user.diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 609b47ae9b..13de8c20d0 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -513,6 +513,7 @@ function AppContent() {const messages = useChatStore((s) => s.runtimes[sessionId]?.messages ?? []);const isLoadingHistory = useChatStore((s) => s.runtimes[sessionId]?.isLoadingHistory ?? false);const replaceHistoryMessages = useChatStore((s) => s.replaceHistoryMessages);+ const restoreReasoningSegments = useChatStore((s) => s.restoreReasoningSegments);const isRestoringHistorySession = isLoadingHistory && !historyPagerMeta && messages.length === 0;const isRestoringTeamHistory = mode === 'team' && isRestoringHistorySession;@@ -632,6 +633,7 @@ function AppContent() {arguments: n.arguments,description: n.description,formatted_args: n.formatted_args,+ display_name: n.display_name,memberName: n.memberName,},{ startedAt: item.at }@@ -691,6 +693,16 @@ function AppContent() {}}}++ if (result.reasoningReplay.length > 0) {+ const store = useChatStore.getState();+ const current = store.runtimes[sid]?.reasoningSegments ?? [];+ const currentItems = current.map((segment) => ({+ at: new Date(segment.startedAt + 1).toISOString(),+ text: segment.text,+ }));+ store.restoreReasoningSegments(sid, [...result.reasoningReplay, ...currentItems]);+ }}, [addToolCall, addToolResult, prependMessages]);const fetchHistoryPageResult = useCallback(async (@@ -1365,6 +1377,7 @@ function AppContent() {arguments: n.arguments,description: n.description,formatted_args: n.formatted_args,+ display_name: n.display_name,memberName: n.memberName,},{ startedAt: item.at }@@ -1427,6 +1440,9 @@ function AppContent() {}}},+ onReasoningReplay: (items) => {+ restoreReasoningSegments(sessionId, items);+ },onError: (message) => {console.warn('[history.restore]', message);setLoadingHistory(sessionId, false);@@ -1478,6 +1494,7 @@ function AppContent() {setLoadingHistory,setHistoryPagerMeta,replaceHistoryMessages,+ restoreReasoningSegments,startBackgroundHistoryPrefetch,]);diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsxindex 32f7e5f25a..3101d85e9a 100644--- a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';import ReactMarkdown from 'react-markdown';import {parseHistoryJsonFilePreviewMode,- parseHistoryJsonFileToPreviewMessages,+ parseHistoryJsonFileToTimelinePreview,} from '../../features/historyRestore';import { isHistoryPreviewFile, parseHistoryFileContent } from '../../features/historyFilePreview';import { ChatTimelineList } from '../ChatPanel/MessageList';@@ -115,19 +115,29 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr}}, [isJson, isHistoryJson, content]);- const historyMessages = useMemo(() => {+ const historyPreview = useMemo(() => {if (!isHistoryJson || !historyChatPreview || !Array.isArray(jsonParseResult.parsed)) {- return [] as ReturnType<typeof parseHistoryJsonFileToPreviewMessages>;+ return null;}- return parseHistoryJsonFileToPreviewMessages(jsonParseResult.parsed, sessionIdFromAgentPath(filePath));+ return parseHistoryJsonFileToTimelinePreview(+ jsonParseResult.parsed,+ sessionIdFromAgentPath(filePath)+ );}, [isHistoryJson, historyChatPreview, jsonParseResult.parsed, filePath]);+ const historyMessages = historyPreview?.messages ?? [];+ const historyExecutions = historyPreview?.executions ?? [];+ const historyReasoningSegments = historyPreview?.reasoningSegments ?? [];+const historyPreviewMode = useMemo(() => {+ if (historyPreview?.mode) {+ return historyPreview.mode;+ }if (!isHistoryJson || !Array.isArray(jsonParseResult.parsed)) {return null;}return parseHistoryJsonFilePreviewMode(jsonParseResult.parsed);- }, [isHistoryJson, jsonParseResult.parsed]);+ }, [historyPreview?.mode, isHistoryJson, jsonParseResult.parsed]);const todoItems = useMemo(() => {if (!isTodoJson || !Array.isArray(jsonParseResult.parsed)) {@@ -416,6 +426,9 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr<div className="w-full min-h-[280px] rounded-lg border border-border bg-card p-3 chat-content"><ChatTimelineListmessages={historyMessages}+ executions={historyExecutions}+ reasoningSegments={historyReasoningSegments}+ staticTimelinemode={historyPreviewMode ?? undefined}disableA2UIInteraction={true}/>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex 527b565e8a..e0328c186c 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -214,6 +214,8 @@ interface MessageItemProps {autoSpeak?: boolean;showAvatar?: boolean;disableA2UIInteraction?: boolean;+ hideMeta?: boolean;+ enableAssistantAvatar?: boolean;}export const MessageItem = memo(function MessageItem({@@ -221,6 +223,8 @@ export const MessageItem = memo(function MessageItem({autoSpeak = false,showAvatar = true,disableA2UIInteraction = false,+ hideMeta = false,+ enableAssistantAvatar = false,}: MessageItemProps) {const { t } = useTranslation();const {@@ -547,11 +551,19 @@ export const MessageItem = memo(function MessageItem({const hasBubbleContent =isUser || Boolean(content) || Boolean(visibleMediaItems) || Boolean(visibleFileItems);+ const withAssistantAvatar = !isUser && enableAssistantAvatar;+return (<div className={clsx(- 'flex mb-3 animate-rise',- isUser ? 'justify-end' : 'justify-start'+ 'flex animate-rise',+ isUser ? 'justify-end' : 'justify-start',+ withAssistantAvatar && 'assistant-row')}>+ {withAssistantAvatar && (+ <div className="assistant-row__avatar" aria-hidden={!showAvatar}>+ {showAvatar ? <TeamMemberAvatar member="team_leader" /> : null}+ </div>+ )}<div className="chat-bubble-wrapper max-w-[82%] min-w-0">{!isUser && (<div className="hidden" data-testid="thinking-summary" aria-hidden="true" />@@ -569,9 +581,10 @@ export const MessageItem = memo(function MessageItem({>{isStreaming ? (isUser ? (- <StreamingContent content={content} isStreaming={true} />+ <StreamingContent content={content} />) : (<A2UIMessageContent+ key={`${id}-streaming`}content={content}messageId={id}isStreaming={true}@@ -587,6 +600,7 @@ export const MessageItem = memo(function MessageItem({</div>) : (<A2UIMessageContent+ key={`${id}-final`}content={content}messageId={id}disableInteraction={disableA2UIInteraction}@@ -622,7 +636,7 @@ export const MessageItem = memo(function MessageItem({</div>)}- {!isStreaming && (+ {!isStreaming && !hideMeta && (<divclassName={clsx('flex items-center gap-3 text-sm mt-2 text-text-muted',diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsxindex 791e7f6755..fe5058cc02 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx@@ -1,31 +1,44 @@-/**- * MessageList 组件- *- * 消息列表显示:将普通消息与工具执行按时间线交错渲染。- */--import { Fragment, useMemo, type ReactNode } from 'react';+import { Fragment, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';+import { flushSync } from 'react-dom';+import clsx from 'clsx';+import { LoaderCircle } from 'lucide-react';+import { useTranslation } from 'react-i18next';import { Message, ToolExecution } from '../../types';-import { MessageItem, getMessageActor } from './MessageItem';-import { ToolGroupDisplay, collectViewedSkillIds } from './ToolGroupDisplay';+import { MessageItem } from './MessageItem';+import { ToolGroupDisplay } from './ToolGroupDisplay';+import { useNow, formatDurationPrecise } from './chatTimelineClock';+import { TeamMemberAvatar } from '../TeamMemberAvatar';import { useChatStore, useSessionStore } from '../../stores';-import { isTeamMemberCollaborationMessage } from './teamEventUtils';-import { isA2UIClientEventContent } from '../../features/a2ui/a2uiContent';--const legacyMessageKeyCache = new WeakMap<Message, string>();-let legacyMessageKeyCounter = 0;--function getMessageRenderKey(message: Message): string {- if (message.renderKey) {- return message.renderKey;- }- let key = legacyMessageKeyCache.get(message);- if (!key) {- legacyMessageKeyCounter += 1;- key = `legacy-message-${legacyMessageKeyCounter}`;- legacyMessageKeyCache.set(message, key);+import type { ReasoningSegment } from '../../stores/chatStore';+import {+ buildTimelineItems,+ buildRenderItems,+ buildTurnWorkMeta,+ buildLiveCompletedStreaks,+ buildStreakInputSignature,+ isSettlingForStreak,+ streakMapFingerprint,+ formatStreakSummaryLabel,+ messageHasDeliverable,+ filterDeliverableExecutions,+ REASONING_COLLAPSE_DELAY_MS,+ STREAK_FOLD_TRANSITION_DELAY_MS,+ type LiveWorkStreak,+} from '../../features/chatTimeline/buildTurnTimeline';++const EMPTY_REASONING: ReasoningSegment[] = [];++function runTimelineTransition(update: () => void) {+ const doc = document as Document & {+ startViewTransition?: (updateCallback: () => void) => { finished: Promise<unknown> };+ };+ if (typeof doc.startViewTransition === 'function') {+ doc.startViewTransition(() => {+ flushSync(update);+ });+ return;}- return key;+ update();}interface MessageListProps {@@ -36,345 +49,608 @@ interface MessageListProps {interface ChatTimelineListProps {messages: Message[];executions?: ToolExecution[];+ reasoningSegments?: ReasoningSegment[];+ /**+ * 历史文件/分享图等静态时间线:强制按「已完成」折叠,+ * 不依赖当前会话的 isProcessing / store 思考段。+ */+ staticTimeline?: boolean;mode?: string;disableA2UIInteraction?: boolean;renderAfterMessage?: (message: Message) => ReactNode;}-type TimelineItem =- | {- type: 'message';- key: string;- timestampMs: number;- sourceIndex: number;- message: Message;- }- | {- type: 'toolExecution';- key: string;- timestampMs: number;- sourceIndex: number;- execution: ToolExecution;- };--type RenderItem =- | {- type: 'message';- key: string;- showAvatar: boolean;- message: Message;- }- | {- type: 'toolGroup';- key: string;- showAvatar: boolean;- executions: ToolExecution[];- notices: string[];- collapseSkillTreeWhenContentStarts: boolean;- turnId: number;- viewedSkillIds: string[];- };--/**- * 将普通消息与工具执行合并为统一时间线,按时间升序渲染。- */-function toTimestampMs(value: string | undefined): number {- if (!value) {- return Number.NaN;- }- const ts = Date.parse(value);- return Number.isNaN(ts) ? Number.NaN : ts;-}--function compareTimelineItems(a: TimelineItem, b: TimelineItem): number {- const aTsValid = Number.isFinite(a.timestampMs);- const bTsValid = Number.isFinite(b.timestampMs);- 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;- }- return a.sourceIndex - b.sourceIndex;-}--function buildTimelineItems(- messages: Message[],- executions: ToolExecution[]-): TimelineItem[] {- const messageItems: TimelineItem[] = messages- .filter((msg) => {- if (msg.role === 'tool') return false;- if (msg.role === 'user' && isA2UIClientEventContent(msg.content)) return false;- return true;- })- .map((message, index) => ({- type: 'message',- key: getMessageRenderKey(message),- timestampMs: toTimestampMs(message.timestamp),- sourceIndex: index,- message,- }));-- const executionItems: TimelineItem[] = executions.map((execution, index) => ({- type: 'toolExecution',- key: `tool-execution-${execution.toolCallId}`,- timestampMs: toTimestampMs(execution.startedAt),- sourceIndex: messages.length + index,- execution,- }));-- return [...messageItems, ...executionItems].sort(compareTimelineItems);-}--function isFinalMessage(message: Message): boolean {- if (message.role === 'assistant' && !message.isStreaming) {- return true;- }- if (message.id.startsWith('team-leader-')) {- return typeof message.content === 'string' && message.content.startsWith('team.leader:');- }- return false;-}--const IMAGE_TOOL_FALLBACK_NOTICE_PREFIX = 'notice-image_tool_fallback-';--function getImageToolFallbackNoticeRequestId(message: Message): string | undefined {- if (message.role !== 'system' || !message.id.startsWith(IMAGE_TOOL_FALLBACK_NOTICE_PREFIX)) {- return undefined;+function formatElapsedCoarse(ms: number): string {+ const whole = Math.floor(Math.max(0, ms) / 1000);+ if (whole < 60) {+ return `${whole}s`;}- const requestId = message.id.slice(IMAGE_TOOL_FALLBACK_NOTICE_PREFIX.length).trim();- return requestId || undefined;+ const minutes = Math.floor(whole / 60);+ const seconds = whole % 60;+ return `${minutes}m${seconds.toString().padStart(2, '0')}s`;}-function addToolGroupNotice(notices: string[], content: string) {- const normalized = content.trim();- if (normalized && !notices.includes(normalized)) {- notices.push(normalized);+function TurnElapsed({+ startMs,+ endMs,+ isLastTurn,+ teamLayout,+}: {+ startMs: number;+ endMs: number;+ isLastTurn: boolean;+ teamLayout: boolean;+}) {+ const { t } = useTranslation();+ const isProcessing = useChatStore((s) => s.runtimes[s.activeSessionId ?? '']?.isProcessing ?? false);+ const active = isLastTurn && isProcessing;+ const now = useNow(active);+ const end = active ? now : endMs;+ const elapsed = Math.max(0, end - startMs);+ if (!active && elapsed <= 0) {+ return null;}+ return (+ <div className={clsx('turn-elapsed', teamLayout && 'turn-elapsed--team', active && 'is-active')}>+ {active && (+ <LoaderCircle className="turn-elapsed__spinner" size={12} strokeWidth={2.2} aria-hidden="true" />+ )}+ <span className="turn-elapsed__label">+ {active ? t('chatUi.turnRunning') : t('chatUi.turnElapsed')}+ </span>+ <span className="turn-elapsed__value">+ {active ? formatElapsedCoarse(elapsed) : formatDurationPrecise(elapsed)}+ </span>+ </div>+ );}-function attachToolGroupNotices(renderItems: RenderItem[]): RenderItem[] {- const nextItems = renderItems.map((item) =>- item.type === 'toolGroup'- ? { ...item, notices: [...item.notices] }- : item+function CompletedWorkChip({+ variant,+ thinkingCount = 0,+ toolCount = 0,+ durationMs = 0,+ expanded,+ onToggle,+ showAvatar,+ teamLayout,+}: {+ variant: 'turn' | 'streak';+ thinkingCount?: number;+ toolCount?: number;+ durationMs?: number;+ expanded: boolean;+ onToggle: () => void;+ showAvatar: boolean;+ teamLayout: boolean;+}) {+ const { t } = useTranslation();+ const label =+ variant === 'turn'+ ? t('chatUi.workCompleted', {+ duration: formatDurationPrecise(Math.max(0, durationMs)),+ })+ : formatStreakSummaryLabel(t, thinkingCount, toolCount);++ const chip = (+ <button+ type="button"+ className={clsx(+ 'completed-work-chip',+ variant === 'streak' && 'completed-work-chip--streak',+ expanded && 'is-expanded'+ )}+ onClick={onToggle}+ aria-expanded={expanded}+ >+ <span className="completed-work-chip__icon" aria-hidden="true">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="10" cy="10" r="6.5" />+ <path d="m7.2 10.1 1.8 1.8 3.8-3.8" />+ </svg>+ </span>+ <span className="completed-work-chip__label">{label}</span>+ <span className={clsx('tool-tree-item__disclosure', expanded && 'is-open')} aria-hidden="true">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">+ <path strokeLinecap="round" strokeLinejoin="round" d="m8 6 4 4-4 4" />+ </svg>+ </span>+ </button>);- const groupsByRequestId = new Map<string, Extract<RenderItem, { type: 'toolGroup' }>[]>();- for (const item of nextItems) {- if (item.type !== 'toolGroup') {- continue;- }- const requestIds = new Set(- item.executions- .map((execution) => execution.requestId)- .filter((requestId): requestId is string => Boolean(requestId))+ if (teamLayout) {+ return (+ <div+ className={clsx(+ 'completed-work-row',+ 'completed-work-row--team',+ variant === 'streak' && 'completed-work-row--nested',+ variant === 'streak' && 'completed-work-row--streak-enter'+ )}+ >+ <div className="pt-0.5">{showAvatar ? <TeamMemberAvatar member="team_leader" /> : null}</div>+ {chip}+ </div>);- for (const requestId of requestIds) {- const groups = groupsByRequestId.get(requestId) || [];- groups.push(item);- groupsByRequestId.set(requestId, groups);- }}- const attachedNoticeIndexes = new Set<number>();- nextItems.forEach((item, index) => {- if (item.type !== 'message') {- return;- }- const requestId = getImageToolFallbackNoticeRequestId(item.message);- if (!requestId) {- return;- }- const targetGroup = groupsByRequestId.get(requestId)?.[0];- if (!targetGroup) {- return;- }- addToolGroupNotice(targetGroup.notices, item.message.content);- attachedNoticeIndexes.add(index);- });-- return nextItems.filter((_, index) => !attachedNoticeIndexes.has(index));+ return (+ <div+ className={clsx(+ 'completed-work-row',+ variant === 'streak' && 'completed-work-row--nested',+ variant === 'streak' && 'completed-work-row--streak-enter'+ )}+ >+ <div className="completed-work-row__avatar">+ {showAvatar ? <TeamMemberAvatar member="team_leader" /> : null}+ </div>+ {chip}+ </div>+ );}-function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderItem[] {- const renderItems: RenderItem[] = [];- let currentTurnId = 0;- let currentSegment = {- toolExecutions: [] as ToolExecution[],- messages: [] as { key: string; message: Message }[],- };-- const flushCurrentSegment = (collapseSkillTreeWhenContentStarts = false) => {- if (currentSegment.toolExecutions.length > 0) {- renderItems.push({- type: 'toolGroup',- key: `tool-group-${currentSegment.toolExecutions[0].toolCallId}`,- showAvatar: true,- executions: currentSegment.toolExecutions,- notices: [],- collapseSkillTreeWhenContentStarts,- turnId: currentTurnId,- viewedSkillIds: [],- });- currentSegment.toolExecutions = [];- }- for (const { key, message } of currentSegment.messages) {- renderItems.push({- type: 'message',- key,- showAvatar: true,- message,- });- }- currentSegment.messages = [];- };-- const flushSegmentIfPresent = (collapseSkillTreeWhenContentStarts = false) => {- if (- currentSegment.toolExecutions.length > 0 ||- currentSegment.messages.length > 0- ) {- flushCurrentSegment(collapseSkillTreeWhenContentStarts);- }- };-- for (const item of items) {- if (item.type === 'toolExecution') {- currentSegment.toolExecutions.push(item.execution);- continue;- }-- if (isTeamMemberCollaborationMessage(item.message)) {- continue;- }-- if (item.message.role === 'user') {- flushSegmentIfPresent();- renderItems.push({- type: 'message',- key: item.key,- showAvatar: true,- message: item.message,- });- currentTurnId += 1;- continue;- }-- if (isFinalMessage(item.message)) {- flushSegmentIfPresent(true);- renderItems.push({- type: 'message',- key: item.key,- showAvatar: true,- message: item.message,- });- continue;+function ReasoningSegmentBlock({+ segment,+ showAvatar,+ teamLayout,+}: {+ segment: ReasoningSegment;+ showAvatar: boolean;+ teamLayout: boolean;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(!segment.closed);+ const userToggledRef = useRef(false);+ const prevClosedRef = useRef(segment.closed);+ const bodyRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!prevClosedRef.current && segment.closed && !userToggledRef.current) {+ const timer = window.setTimeout(() => {+ if (!userToggledRef.current) {+ setOpen(false);+ }+ }, REASONING_COLLAPSE_DELAY_MS);+ prevClosedRef.current = segment.closed;+ return () => window.clearTimeout(timer);}+ prevClosedRef.current = segment.closed;+ return undefined;+ }, [segment.closed]);- currentSegment.messages.push({ key: item.key, message: item.message });- }-- flushSegmentIfPresent();+ const body = segment.text.replace(/\n{3,}/g, '\n\n').trim();- const viewedSkillIdsByTurn = new Map<number, string[]>();- for (const renderItem of renderItems) {- if (renderItem.type !== 'toolGroup') {- continue;- }- const viewedSkillIds = collectViewedSkillIds(renderItem.executions);- if (viewedSkillIds.length === 0) {- continue;+ useEffect(() => {+ if (!open || segment.closed) {+ return;}- const current = viewedSkillIdsByTurn.get(renderItem.turnId) || [];- viewedSkillIdsByTurn.set(renderItem.turnId, Array.from(new Set([...current, ...viewedSkillIds])));- }- for (const renderItem of renderItems) {- if (renderItem.type === 'toolGroup') {- renderItem.viewedSkillIds = viewedSkillIdsByTurn.get(renderItem.turnId) || [];+ const el = bodyRef.current;+ if (!el) {+ return;}- }-- const renderItemsWithNotices = attachToolGroupNotices(renderItems);+ el.scrollTop = el.scrollHeight;+ }, [open, segment.closed, body]);- if (!isTeamMode) {- for (const renderItem of renderItemsWithNotices) {- if (renderItem.type === 'toolGroup') {- renderItem.showAvatar = false;- }- }- return renderItemsWithNotices;+ if (!body) {+ return null;}+ const running = !segment.closed;++ const content = (+ <div className="min-w-0 reasoning-panel">+ <button+ type="button"+ className="tool-tree__header"+ onClick={() => {+ userToggledRef.current = true;+ runTimelineTransition(() => setOpen((current) => !current));+ }}+ aria-expanded={open}+ >+ <span className="tool-tree__header-line">+ <span className="tool-tree__cat-icon" aria-hidden="true">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M10 3.2a4.4 4.4 0 0 0-2.6 7.95v1.6a.9.9 0 0 0 .9.9h3.4a.9.9 0 0 0 .9-.9v-1.6A4.4 4.4 0 0 0 10 3.2z" />+ <path d="M8.3 16.2h3.4" />+ </svg>+ </span>+ <span className={clsx('tool-tree__header-line-text', running && 'is-running')}>+ {running ? t('chatUi.reasoning.thinking') : t('chatUi.reasoning.thought')}+ </span>+ <span className={clsx('tool-tree-item__disclosure', open && 'is-open')} aria-hidden="true">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">+ <path strokeLinecap="round" strokeLinejoin="round" d="m8 6 4 4-4 4" />+ </svg>+ </span>+ </span>+ </button>+ <div className={clsx('reasoning-panel__collapse', open && 'is-open')}>+ <div className="reasoning-panel__collapse-inner">+ <div ref={bodyRef} className="reasoning-panel__body">+ {body}+ </div>+ </div>+ </div>+ </div>+ );- let clusterBlockActive = false;- for (const renderItem of renderItemsWithNotices) {- if (renderItem.type === 'toolGroup') {- renderItem.showAvatar = !clusterBlockActive;- clusterBlockActive = true;- continue;- }-- const actor = getMessageActor(renderItem.message);- if (actor === 'team_leader') {- renderItem.showAvatar = !clusterBlockActive;- clusterBlockActive = true;- continue;- }-- clusterBlockActive = false;+ if (teamLayout) {+ return (+ <div className="reasoning-row reasoning-row--team" data-testid="reasoning-block">+ <div className="pt-0.5">{showAvatar ? <TeamMemberAvatar member="team_leader" /> : null}</div>+ {content}+ </div>+ );}- return renderItemsWithNotices;+ return (+ <div className="reasoning-row" data-testid="reasoning-block">+ <div className="reasoning-row__avatar">+ {showAvatar ? <TeamMemberAvatar member="team_leader" /> : null}+ </div>+ {content}+ </div>+ );}export function ChatTimelineList({messages,executions = [],+ reasoningSegments: reasoningSegmentsProp,+ staticTimeline = false,mode = 'default',disableA2UIInteraction = false,renderAfterMessage,}: ChatTimelineListProps) {const isTeamMode = mode === 'team';+ const activeSessionId = useChatStore((s) => s.activeSessionId);+ const storeIsProcessing = useChatStore((s) => s.runtimes[s.activeSessionId ?? '']?.isProcessing ?? false);+ const isLoadingHistory = useChatStore((s) => s.runtimes[s.activeSessionId ?? '']?.isLoadingHistory ?? false);+ const storeReasoningSegments = useChatStore(+ (s) => s.runtimes[s.activeSessionId ?? '']?.reasoningSegments ?? EMPTY_REASONING+ );+ const isProcessing = staticTimeline ? false : storeIsProcessing;+ const reasoningSegments = reasoningSegmentsProp ?? (staticTimeline ? EMPTY_REASONING : storeReasoningSegments);const renderItems = useMemo(- () => buildRenderItems(buildTimelineItems(messages, executions), isTeamMode),- [messages, executions, isTeamMode]+ () => buildRenderItems(buildTimelineItems(messages, executions, reasoningSegments), isTeamMode, isProcessing),+ [messages, executions, reasoningSegments, isTeamMode, isProcessing]+ );+ const settlingForStreak = isSettlingForStreak(renderItems, Date.now());+ const settleNow = useNow(settlingForStreak);+ const streakNowMs = settlingForStreak ? settleNow : Date.now();+ const turnWorkMeta = useMemo(+ () => buildTurnWorkMeta(renderItems, isProcessing),+ [renderItems, isProcessing]+ );+ const streakInputSig = useMemo(+ () => buildStreakInputSignature(renderItems, streakNowMs),+ [renderItems, streakNowMs]+ );+ const streakCacheRef = useRef<{ sig: string; map: Map<string, LiveWorkStreak> }>({+ sig: '',+ map: new Map(),+ });+ if (streakCacheRef.current.sig !== streakInputSig) {+ streakCacheRef.current = {+ sig: streakInputSig,+ map: buildLiveCompletedStreaks(renderItems, streakNowMs),+ };+ }+ const liveStreaksByFirstKey = streakCacheRef.current.map;+ const liveStreakFp = useMemo(+ () => streakMapFingerprint(liveStreaksByFirstKey),+ [liveStreaksByFirstKey]+ );+ const [displayedStreaksByFirstKey, setDisplayedStreaksByFirstKey] = useState<Map<string, LiveWorkStreak>>(+ () => new Map());+ const displayedStreakFpRef = useRef('');+ const suppressStreakTransitionRef = useRef(true);+ const streaksForRender = staticTimeline ? liveStreaksByFirstKey : displayedStreaksByFirstKey;+ const liveStreakByItemKey = useMemo(() => {+ const map = new Map<string, LiveWorkStreak>();+ for (const streak of streaksForRender.values()) {+ for (const key of streak.keys) {+ map.set(key, streak);+ }+ }+ return map;+ }, [streaksForRender]);+ const [expandedTurns, setExpandedTurns] = useState<Record<number, boolean>>({});+ const [expandedStreaks, setExpandedStreaks] = useState<Record<string, boolean>>({});+ const chipAnchoredTurns = useRef<Set<number>>(new Set());+ chipAnchoredTurns.current = new Set();++ useEffect(() => {+ setExpandedTurns({});+ setExpandedStreaks({});+ suppressStreakTransitionRef.current = true;+ displayedStreakFpRef.current = '';+ setDisplayedStreaksByFirstKey(new Map());+ }, [activeSessionId]);++ const wasLoadingHistoryRef = useRef(false);+ useEffect(() => {+ if (staticTimeline) {+ return;+ }+ if (isLoadingHistory) {+ wasLoadingHistoryRef.current = true;+ return;+ }+ if (wasLoadingHistoryRef.current) {+ wasLoadingHistoryRef.current = false;+ setExpandedTurns({});+ setExpandedStreaks({});+ suppressStreakTransitionRef.current = true;+ displayedStreakFpRef.current = '';+ setDisplayedStreaksByFirstKey(new Map());+ }+ }, [staticTimeline, isLoadingHistory]);++ useEffect(() => {+ if (staticTimeline) {+ return;+ }+ if (liveStreakFp === displayedStreakFpRef.current) {+ return;+ }+ const nextMap = liveStreaksByFirstKey;+ if (suppressStreakTransitionRef.current) {+ displayedStreakFpRef.current = liveStreakFp;+ suppressStreakTransitionRef.current = false;+ setDisplayedStreaksByFirstKey(nextMap);+ return;+ }+ const timer = window.setTimeout(() => {+ runTimelineTransition(() => {+ displayedStreakFpRef.current = liveStreakFp;+ setDisplayedStreaksByFirstKey(nextMap);+ });+ }, STREAK_FOLD_TRANSITION_DELAY_MS);+ return () => window.clearTimeout(timer);+ }, [liveStreakFp, liveStreaksByFirstKey, staticTimeline]);if (renderItems.length === 0) {return null;}+ const toggleTurn = (turnId: number) => {+ runTimelineTransition(() => {+ setExpandedTurns((prev) => ({ ...prev, [turnId]: !prev[turnId] }));+ });+ };++ const toggleStreak = (streakId: string) => {+ runTimelineTransition(() => {+ setExpandedStreaks((prev) => ({ ...prev, [streakId]: !prev[streakId] }));+ });+ };+return (- <div className="space-y-1">+ <div className="chat-timeline">{renderItems.map((item) => {if (item.type === 'message') {+ if (item.hideMeta && item.turnId >= 0) {+ const meta = turnWorkMeta.get(item.turnId);+ if (meta?.completed && meta.hasWork && !expandedTurns[item.turnId]) {+ if (!messageHasDeliverable(item.message)) {+ return null;+ }+ return (+ <Fragment key={item.key}>+ <MessageItem+ message={{ ...item.message, content: '' }}+ showAvatar={false}+ hideMeta+ disableA2UIInteraction={disableA2UIInteraction}+ enableAssistantAvatar={!isTeamMode}+ />+ {renderAfterMessage?.(item.message)}+ </Fragment>+ );+ }+ }return (<Fragment key={item.key}><MessageItemmessage={item.message}showAvatar={item.showAvatar}+ hideMeta={item.hideMeta}disableA2UIInteraction={disableA2UIInteraction}+ enableAssistantAvatar={!isTeamMode}/>{renderAfterMessage?.(item.message)}</Fragment>);}- return (- <ToolGroupDisplay- key={item.key}- executions={item.executions}- notices={item.notices}- showAvatar={item.showAvatar}- teamLayout={isTeamMode}- collapseSkillTreeWhenContentStarts={item.collapseSkillTreeWhenContentStarts}- viewedSkillIds={item.viewedSkillIds}- />- );++ if (item.type === 'reasoning' || item.type === 'toolGroup') {+ const meta = turnWorkMeta.get(item.turnId);+ const collapsed = Boolean(meta?.completed && meta.hasWork && !expandedTurns[item.turnId]);+ if (collapsed) {+ const nodes: ReactNode[] = [];+ const shouldAnchorChip =+ Boolean(meta) &&+ (meta!.firstWorkKey === item.key ||+ (!meta!.firstWorkKey && !chipAnchoredTurns.current.has(item.turnId)));+ if (shouldAnchorChip && meta) {+ chipAnchoredTurns.current.add(item.turnId);+ nodes.push(+ <CompletedWorkChip+ key={`completed-work-${item.turnId}`}+ variant="turn"+ durationMs={+ Number.isFinite(meta.endMs) && Number.isFinite(meta.startMs)+ ? Math.max(0, meta.endMs - meta.startMs)+ : 0+ }+ expanded={false}+ onToggle={() => toggleTurn(item.turnId)}+ showAvatar={meta.showAvatar}+ teamLayout={isTeamMode}+ />+ );+ }+ if (item.type === 'toolGroup') {+ const deliverables = filterDeliverableExecutions(item.executions);+ if (deliverables.length > 0) {+ nodes.push(+ <ToolGroupDisplay+ key={`${item.key}-deliverable`}+ executions={deliverables}+ notices={[]}+ showAvatar={false}+ teamLayout={isTeamMode}+ collapseSkillTreeWhenContentStarts={false}+ viewedSkillIds={[]}+ />+ );+ }+ }+ if (nodes.length === 0) {+ return null;+ }+ return nodes.length === 1 ? nodes[0] : <Fragment key={`collapsed-work-${item.key}`}>{nodes}</Fragment>;+ }++ const turnExpanded = Boolean(meta?.completed && meta.hasWork && expandedTurns[item.turnId]);+ const streak = liveStreakByItemKey.get(item.key);+ const streakExpanded = streak ? Boolean(expandedStreaks[streak.id]) : false;+ if (streak && !streakExpanded) {+ const nodes: ReactNode[] = [];+ if (turnExpanded && meta && meta.firstWorkKey === item.key) {+ nodes.push(+ <CompletedWorkChip+ key={`completed-work-${item.turnId}`}+ variant="turn"+ durationMs={+ Number.isFinite(meta.endMs) && Number.isFinite(meta.startMs)+ ? Math.max(0, meta.endMs - meta.startMs)+ : 0+ }+ expanded+ onToggle={() => toggleTurn(item.turnId)}+ showAvatar={meta.showAvatar}+ teamLayout={isTeamMode}+ />+ );+ }+ if (streak.firstKey === item.key) {+ nodes.push(+ <CompletedWorkChip+ key={streak.id}+ variant="streak"+ thinkingCount={streak.thinkingCount}+ toolCount={streak.toolCount}+ expanded={false}+ onToggle={() => toggleStreak(streak.id)}+ showAvatar={turnExpanded ? false : streak.showAvatar}+ teamLayout={isTeamMode}+ />+ );+ }+ if (item.type === 'toolGroup') {+ const deliverables = filterDeliverableExecutions(item.executions);+ if (deliverables.length > 0) {+ nodes.push(+ <ToolGroupDisplay+ key={`${item.key}-deliverable`}+ executions={deliverables}+ notices={[]}+ showAvatar={false}+ teamLayout={isTeamMode}+ collapseSkillTreeWhenContentStarts={false}+ viewedSkillIds={[]}+ />+ );+ }+ }+ if (nodes.length === 0) {+ return null;+ }+ return nodes.length === 1 ? nodes[0] : <Fragment key={`streak-collapsed-${item.key}`}>{nodes}</Fragment>;+ }++ const nodes: ReactNode[] = [];+ if (turnExpanded && meta && meta.firstWorkKey === item.key) {+ nodes.push(+ <CompletedWorkChip+ key={`completed-work-${item.turnId}`}+ variant="turn"+ durationMs={+ Number.isFinite(meta.endMs) && Number.isFinite(meta.startMs)+ ? Math.max(0, meta.endMs - meta.startMs)+ : 0+ }+ expanded+ onToggle={() => toggleTurn(item.turnId)}+ showAvatar={meta.showAvatar}+ teamLayout={isTeamMode}+ />+ );+ }+ if (streak && streakExpanded && streak.firstKey === item.key) {+ nodes.push(+ <CompletedWorkChip+ key={streak.id}+ variant="streak"+ thinkingCount={streak.thinkingCount}+ toolCount={streak.toolCount}+ expanded+ onToggle={() => toggleStreak(streak.id)}+ showAvatar={turnExpanded ? false : streak.showAvatar}+ teamLayout={isTeamMode}+ />+ );+ }++ const hideAvatar = Boolean(turnExpanded || (streak && streakExpanded));++ if (item.type === 'reasoning') {+ nodes.push(+ <ReasoningSegmentBlock+ key={item.key}+ segment={item.segment}+ showAvatar={hideAvatar ? false : item.showAvatar}+ teamLayout={isTeamMode}+ />+ );+ } else {+ nodes.push(+ <ToolGroupDisplay+ key={item.key}+ executions={item.executions}+ notices={item.notices}+ showAvatar={hideAvatar ? false : item.showAvatar}+ teamLayout={isTeamMode}+ collapseSkillTreeWhenContentStarts={item.collapseSkillTreeWhenContentStarts}+ viewedSkillIds={item.viewedSkillIds}+ />+ );+ }++ return nodes.length === 1 ? nodes[0] : <Fragment key={`work-${item.key}`}>{nodes}</Fragment>;+ }++ if (item.type === 'turnSummary') {+ const meta = turnWorkMeta.get(item.turnId);+ if (meta?.completed && meta.hasWork) {+ return null;+ }+ return (+ <TurnElapsed+ key={item.key}+ startMs={item.startMs}+ endMs={item.endMs}+ isLastTurn={item.isLastTurn}+ teamLayout={isTeamMode}+ />+ );+ }++ return null;})}</div>);diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/StreamingContent.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/StreamingContent.tsxindex 0e47fd55d5..57b10bfc94 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/StreamingContent.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/StreamingContent.tsx@@ -1,19 +1,11 @@-/**- * StreamingContent 组件- *- * 流式内容显示- */-interface StreamingContentProps {content: string;- isStreaming: boolean;}-export function StreamingContent({ content, isStreaming }: StreamingContentProps) {+export function StreamingContent({ content }: StreamingContentProps) {return (<div className="chat-text"><span className="whitespace-pre-wrap">{content}</span>- {isStreaming && <span className="streaming-cursor" />}</div>);}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsxindex 5f7d0a6e76..c25f9de1a0 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx@@ -1,10 +1,4 @@-/**- * ToolGroupDisplay 组件- *- * 以轻量折叠列表展示工具调用状态,行内可展开查看参数和结果。- */--import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { ToolExecution } from '../../types';@@ -12,6 +6,7 @@ import { formatToolArguments, formatToolResult } from '../../utils';import { TeamMemberAvatar } from '../TeamMemberAvatar';import { SkillTreePath } from './SkillTreePath';import { BeamSearchTree } from './BeamSearchTree';+import { classifyToolCall, describeToolCall, type ToolCategory } from './toolCategory';interface ToolGroupDisplayProps {executions: ToolExecution[];@@ -22,11 +17,6 @@ interface ToolGroupDisplayProps {viewedSkillIds?: string[];}-interface ToolDetailModalProps {- execution: ToolExecution;- onClose: () => void;-}-type ToolStatusTone = 'success' | 'warning' | 'error' | 'pending';function ToolStatusIcon({@@ -50,9 +40,9 @@ function ToolStatusIcon({<circle cx="10" cy="13.65" r="0.75" fill="currentColor" stroke="none" /></svg>) : (- <svg className="tool-status-icon__spinner" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">- <circle cx="10" cy="10" r="6.8" opacity="0.22" />- <path strokeLinecap="round" d="M10 3.2A6.8 6.8 0 0 1 16.8 10" />+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">+ <circle cx="10" cy="10" r="6.8" opacity="0.4" />+ <circle cx="10" cy="10" r="2.1" fill="currentColor" stroke="none" /></svg>)}</span>@@ -63,32 +53,16 @@ function isToolResultSuccessful(result?: ToolExecution['result']) {return Boolean(result?.success && !result.result.includes('success=False'));}-function isExecutionSuccessful(execution: ToolExecution) {- return execution.status === 'completed' && isToolResultSuccessful(execution.result);-}--function getExecutionTone(execution: ToolExecution): ToolStatusTone {- if (execution.status === 'pending') {- return 'pending';- }- if (isExecutionSuccessful(execution)) {- return 'success';- }- if (execution.status === 'timeout') {- return 'warning';- }- if (execution.status === 'error' || execution.result) {- return 'error';- }- return 'pending';-}--function getExecutionLabel(execution: ToolExecution, sessionCompletedLabel: string) {+function getExecutionLabel(+ execution: ToolExecution,+ sessionCompletedLabel: string,+ t: (key: string) => string+) {if (execution.toolCall.name === 'session') {return execution.toolCall.formatted_args || sessionCompletedLabel;}- return execution.toolCall.name;+ return describeToolCall(execution.toolCall, t);}function isSkillToolName(name: string): boolean {@@ -152,236 +126,155 @@ export function collectViewedSkillIds(executions: ToolExecution[]): string[] {return Array.from(out);}-function ToolDetailModal({ execution, onClose }: ToolDetailModalProps) {+/** 行内下拉展开的工具详情:展示参数与结果(替代原弹窗)。 */+function ToolExecutionDetails({ execution }: { execution: ToolExecution }) {const { t } = useTranslation();const { toolCall, result, status } = execution;const isTimeout = status === 'timeout';- const modalTone = getExecutionTone(execution);const resultSuccess = isToolResultSuccessful(result);-- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key === 'Escape') {- onClose();- }- };-- window.addEventListener('keydown', handleKeyDown);- return () => window.removeEventListener('keydown', handleKeyDown);- }, [onClose]);+ const hasArguments = Object.keys(toolCall.arguments).length > 0;return (- <div className="fixed inset-0 z-50 flex items-center justify-center p-4">- <div className="absolute inset-0 bg-black/60" onClick={onClose} />-- <div- className="relative w-full max-w-2xl max-h-[85vh] overflow-hidden rounded-xl animate-rise"- style={{- backgroundColor: 'var(--color-surface-card)',- boxShadow: 'var(--effect-shadow-xl)',- }}- >- <div- className="px-6 py-4 flex items-center justify-between"- style={{- backgroundColor: 'var(--color-surface-panel-strong)',- borderBottom: '1px solid var(--color-border-default)',- }}- >- <div className="flex items-center gap-4">- <ToolStatusIcon tone={modalTone} className="tool-status-icon--lg" />-- <div>- <h2- className="text-lg font-semibold font-mono"- style={{ color: 'var(--color-text-strong)' }}- >- {toolCall.name}- </h2>- {toolCall.formatted_args && (- <p- className="text-sm font-mono mt-1"- style={{ color: 'var(--color-text-secondary)' }}- >- {toolCall.formatted_args}- </p>- )}- </div>+ <div className="tool-tree-item__detail">+ {hasArguments && (+ <div className="tool-tree-item__detail-block">+ <div className="tool-tree-item__detail-label">+ {t('chatUi.toolResult.arguments')}</div>-- <button- onClick={onClose}- className="p-2 rounded-lg "- style={{ color: 'var(--color-text-secondary)' }}- onMouseEnter={(event) => {- event.currentTarget.style.backgroundColor = 'var(--color-surface-hover)';- event.currentTarget.style.color = 'var(--color-text-primary)';- }}- onMouseLeave={(event) => {- event.currentTarget.style.backgroundColor = 'transparent';- event.currentTarget.style.color = 'var(--color-text-secondary)';- }}- >- <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>- <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>+ <pre className="tool-tree-item__detail-pre">+ {formatToolArguments(toolCall.arguments)}+ </pre></div>+ )}- <div- className="px-6 py-5 overflow-y-auto"- style={{ maxHeight: '60vh' }}- >- {Object.keys(toolCall.arguments).length > 0 && (- <div className="mb-6">- <div- className="flex items-center gap-2 mb-3"- style={{ color: 'var(--color-text-strong)' }}- >- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>- <path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />- </svg>- <span className="text-sm font-semibold">{t('chatUi.toolResult.arguments')}</span>- </div>- <pre- className="p-4 rounded-lg overflow-auto whitespace-pre-wrap break-all"- style={{- fontFamily: 'var(--font-mono)',- fontSize: 'var(--font-size-sm)',- lineHeight: '1.5',- backgroundColor: 'var(--color-surface-elevated)',- border: '1px solid var(--color-border-default)',- color: 'var(--color-text-primary)',- wordBreak: 'break-word',- }}- >- {formatToolArguments(toolCall.arguments)}- </pre>- </div>- )}-- {result && (- <div>- <div- className="flex items-center gap-2 mb-3"- style={{- color: resultSuccess- ? 'var(--color-feedback-success)'- : 'var(--color-feedback-danger)',- }}- >- <ToolStatusIcon tone={resultSuccess ? 'success' : 'error'} />- <span className="text-sm font-semibold">- {t('chatUi.toolResult.result')}- {!resultSuccess && (- <span- className="ml-2 px-2 py-0.5 rounded text-xs font-medium"- style={{- backgroundColor: 'var(--color-feedback-danger-subtle)',- color: 'var(--color-feedback-danger)',- }}- >- {t('chatUi.toolResult.failed')}- </span>- )}- </span>- </div>- {result.skillTree && (- <SkillTreePath tree={result.skillTree} stepIntervalMs={0} />- )}- {(!result.skillTree || result.result) && (- <pre- className={clsx(- 'p-4 rounded-lg overflow-auto whitespace-pre-wrap break-all',- result.skillTree && 'mt-4'- )}- style={{- fontFamily: 'var(--font-mono)',- fontSize: 'var(--font-size-sm)',- lineHeight: '1.5',- backgroundColor: 'var(--color-surface-elevated)',- border: '1px solid var(--color-border-default)',- color: resultSuccess- ? 'var(--color-text-primary)'- : 'var(--color-feedback-danger)',- wordBreak: 'break-word',- }}- >- {formatToolResult(result.result)}- </pre>+ {result && (+ <div className="tool-tree-item__detail-block">+ <div className="tool-tree-item__detail-label">+ {t('chatUi.toolResult.result')}+ {!resultSuccess && (+ <span className="tool-tree-item__detail-badge">+ {t('chatUi.toolResult.failed')}+ </span>+ )}+ </div>+ {result.skillTree && <SkillTreePath tree={result.skillTree} stepIntervalMs={0} />}+ {(!result.skillTree || result.result) && (+ <pre+ className={clsx(+ 'tool-tree-item__detail-pre',+ result.skillTree && 'mt-2')}- </div>- )}-- {!result && isTimeout && (- <div- className="flex items-center gap-3 p-4 rounded-lg"- style={{- backgroundColor: 'var(--color-feedback-warning-subtle)',- border: '1px solid var(--color-feedback-warning)',- color: 'var(--color-feedback-warning)',- }}>- <ToolStatusIcon tone="warning" />- <span className="font-medium">{t('chatUi.toolResult.timeout')}</span>- </div>+ {formatToolResult(result.result)}+ </pre>)}+ </div>+ )}- {!result && !isTimeout && (- <div- className="flex items-center gap-3 p-4 rounded-lg"- style={{- backgroundColor: 'var(--color-action-primary-subtle)',- border: '1px solid var(--color-action-primary)',- color: 'var(--color-action-primary)',- }}- >- <ToolStatusIcon tone="pending" />- <span className="font-medium">{t('chatUi.toolResult.running')}</span>- </div>- )}+ {!result && isTimeout && (+ <div className="tool-tree-item__detail-status is-warning">+ <ToolStatusIcon tone="warning" />+ <span>{t('chatUi.toolResult.timeout')}</span></div>- </div>+ )}++ {!result && !isTimeout && (+ <div className="tool-tree-item__detail-status is-pending">+ <ToolStatusIcon tone="pending" />+ <span>{t('chatUi.toolResult.running')}</span>+ </div>+ )}</div>);}-function ToolExecutionRow({ execution }: { execution: ToolExecution }) {- const { t } = useTranslation();- const [showModal, setShowModal] = useState(false);- const { toolCall, status } = execution;- const rowTone = getExecutionTone(execution);+/**+ * 是否按「执行中」展示。已完成/失败/超时,或已有结果,一律不当作执行中,+ * 避免 tool_update / 思考整理后重渲染把旧工具误显示成执行中。+ */+function isDisplayRunning(execution: ToolExecution): boolean {+ if (+ execution.status === 'completed' ||+ execution.status === 'error' ||+ execution.status === 'timeout'+ ) {+ return false;+ }+ if (execution.result) {+ return false;+ }+ return execution.status === 'pending';+}- return (- <>- <div- className="tool-tree-item"- data-testid={`tool-execution-${toolCall.id}`}- data-tool-name={toolCall.name}- data-tool-status={status}- >- <button- type="button"- className="tool-tree-item__button"- onClick={() => setShowModal(true)}- >- <ToolStatusIcon tone={rowTone} className="tool-tree-item__status" />+interface GroupHeaderLine {+ key: string;+ category: ToolCategory;+ text: string;+ running: boolean;+ executions: ToolExecution[];+}- <span className="tool-tree-item__main">- <span className="tool-tree-item__name">- {getExecutionLabel(execution, t('chatUi.toolGroup.sessionCompleted'))}- </span>- </span>- </button>- </div>+/**+ * 每条工具单独一行展示可读动作名(优先后端 display_name),+ * 如「抓取 workbuddy.ai」「写入 DESIGN.md」;不再按分类收成「已完成 N 次…」。+ */+function buildGroupLines(+ executions: ToolExecution[],+ t: (key: string, options?: Record<string, unknown>) => string+): GroupHeaderLine[] {+ const sessionCompletedLabel = t('chatUi.toolGroup.sessionCompleted');+ return executions.map((execution) => {+ const category = classifyToolCall(execution.toolCall.name);+ const running = isDisplayRunning(execution);+ const label = getExecutionLabel(execution, sessionCompletedLabel, t);+ return {+ key: execution.toolCallId,+ category,+ running,+ executions: [execution],+ text: running+ ? t('chatUi.toolGroup.running', { label })+ : t('chatUi.toolGroup.completed', { label }),+ };+ });+}- {showModal && (- <ToolDetailModal execution={execution} onClose={() => setShowModal(false)} />+/** 五类任务各自的图标(file/search/code/system/other)。 */+function CategoryIcon({ category }: { category: ToolCategory }) {+ return (+ <span className="tool-tree__cat-icon" aria-hidden="true">+ {category === 'file' ? (+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M5.5 3.5h5L15 8v8a.9.9 0 0 1-.9.9H5.5a.9.9 0 0 1-.9-.9V4.4a.9.9 0 0 1 .9-.9z" />+ <path d="M10.3 3.5V8H15" />+ </svg>+ ) : category === 'search' ? (+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="9" cy="9" r="4.3" />+ <path d="m12.3 12.3 3.4 3.4" />+ </svg>+ ) : category === 'code' ? (+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="m7.4 6.5-3.4 3.5 3.4 3.5" />+ <path d="m12.6 6.5 3.4 3.5-3.4 3.5" />+ </svg>+ ) : category === 'system' ? (+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <rect x="3.5" y="4.5" width="13" height="11" rx="1.6" />+ <path d="m6.5 8.6 2.3 1.9-2.3 1.9" />+ <path d="M10.8 12.7h3" />+ </svg>+ ) : (+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M13.4 4.6a2.7 2.7 0 0 0-3.3 3.4l-5 5a1.3 1.3 0 1 0 1.9 1.9l5-5a2.7 2.7 0 0 0 3.4-3.3l-2 2-1.9-.1-.1-1.9 2-2z" />+ </svg>)}- </>+ </span>);}+export { formatDurationPrecise, useNow } from './chatTimelineClock';+export function ToolGroupDisplay({executions,notices = [],@@ -391,53 +284,15 @@ export function ToolGroupDisplay({viewedSkillIds: turnViewedSkillIds = [],}: ToolGroupDisplayProps) {const { t } = useTranslation();- const scrollRef = useRef<HTMLDivElement>(null);- const [groupOpen, setGroupOpen] = useState(true);- const [userScrolled, setUserScrolled] = useState(false);+ const [openKeys, setOpenKeys] = useState<Record<string, boolean>>({});+ const toggleLine = useCallback((key: string) => {+ setOpenKeys((current) => ({ ...current, [key]: !current[key] }));+ }, []);const visibleExecutions = teamLayout? executions.filter((execution) => !execution.toolCall.memberName): executions;- const totalPairs = visibleExecutions.length;- const hasPending = visibleExecutions.some((execution) => execution.status === 'pending');- useEffect(() => {- if (hasPending) {- setGroupOpen(true);- }- }, [hasPending, visibleExecutions.length]);-- const handleScroll = useCallback(() => {- const element = scrollRef.current;- if (!element) {- return;- }- const atBottom = element.scrollHeight - element.scrollTop - element.clientHeight < 24;- setUserScrolled(!atBottom);- }, []);-- const scrollInner = useCallback((smooth = true) => {- const element = scrollRef.current;- if (!element) {- return;- }- element.scrollTo({- top: element.scrollHeight,- behavior: smooth ? 'smooth' : 'instant',- });- }, []);-- useEffect(() => {- if (groupOpen && !userScrolled) {- scrollInner(false);- }- }, [visibleExecutions.length, groupOpen, userScrolled, scrollInner]);-- const scrollToBottom = useCallback(() => {- setUserScrolled(false);- scrollInner(true);- }, [scrollInner]);-- const headerLabel = t('chatUi.toolGroup.executed', { totalPairs });+ const headerLines = buildGroupLines(visibleExecutions, t);const skillTreeExecutions = visibleExecutions.filter((execution) => execution.result?.skillTree);@@ -459,12 +314,12 @@ export function ToolGroupDisplay({return (<divclassName={clsx(- 'tool-group-frame animate-rise',+ 'tool-group-frame',teamLayout && 'tool-group-frame--team')}data-testid="tool-group">- <div className="pt-0.5">+ <div className="pt-0.5 tool-group-frame__avatar">{showAvatar ? (<TeamMemberAvatar member="team_leader" />) : null}@@ -480,39 +335,40 @@ export function ToolGroupDisplay({))}</div>)}- <button- type="button"- className="tool-tree__header"- onClick={() => setGroupOpen((current) => !current)}- aria-expanded={groupOpen}- >- <span className="tool-tree__header-text">- <span className="tool-tree__header-title-row">- <span className="tool-tree__header-title">{headerLabel}</span>- <span className={clsx('tool-tree__chevron', groupOpen && 'is-open')} aria-hidden="true">- <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">- <path strokeLinecap="round" strokeLinejoin="round" d="m6.5 8 3.5 4 3.5-4" />- </svg>- </span>- </span>- </span>- </button>+ {headerLines.map((line) => {+ const open = Boolean(openKeys[line.key]);+ return (+ <div key={line.key} className="tool-tree__section">+ <button+ type="button"+ className="tool-tree__header"+ onClick={() => toggleLine(line.key)}+ aria-expanded={open}+ >+ <span className="tool-tree__header-line">+ <CategoryIcon category={line.category} />+ <span className={clsx('tool-tree__header-line-text', line.running && 'is-running')}>+ {line.text}+ </span>+ <span+ className={clsx('tool-tree-item__disclosure', open && 'is-open')}+ aria-hidden="true"+ >+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">+ <path strokeLinecap="round" strokeLinejoin="round" d="m8 6 4 4-4 4" />+ </svg>+ </span>+ </span>+ </button>- {groupOpen && (- <>- <div ref={scrollRef} className="tool-tree__list" onScroll={handleScroll}>- {visibleExecutions.map((execution) => (- <ToolExecutionRow key={execution.toolCallId} execution={execution} />- ))}+ {open && line.executions[0] && (+ <div className="tool-tree-item__detail-wrap">+ <ToolExecutionDetails execution={line.executions[0]} />+ </div>+ )}</div>-- {userScrolled && (- <button type="button" className="tool-tree__latest" onClick={scrollToBottom}>- {t('chatUi.toolGroup.latest')}- </button>- )}- </>- )}+ );+ })}</div>{skillTrees.length > 0 && (diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/chatTimelineClock.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/chatTimelineClock.tsnew file mode 100644index 0000000000..da54221781--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/chatTimelineClock.ts@@ -0,0 +1,29 @@+import { useEffect, useState } from 'react';++export function formatDurationPrecise(ms: number): string {+ const clamped = Math.max(0, ms);+ if (clamped < 1000) {+ return `${Math.round(clamped)}ms`;+ }+ const totalSeconds = clamped / 1000;+ if (totalSeconds < 60) {+ return `${totalSeconds.toFixed(2)}s`;+ }+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = Math.floor(totalSeconds % 60);+ return `${minutes}m${seconds.toString().padStart(2, '0')}s`;+}++/** active 时 250ms 刷新;关闭时停走,避免无谓重渲染。 */+export function useNow(active: boolean): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ setNow(Date.now());+ if (!active) {+ return;+ }+ const timer = window.setInterval(() => setNow(Date.now()), 250);+ return () => window.clearInterval(timer);+ }, [active]);+ return now;+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex 9da830c9cb..920afbbde6 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -90,20 +90,6 @@ interface ChatPanelProps {onDrainTaskQueueIfIdle?: (sessionId: string) => void;}-function ThinkingIndicator() {- return (- <div className="flex justify-start animate-rise">- <div className="chat-bubble assistant chat-reading-indicator">- <div className="chat-reading-indicator__dots">- <span />- <span />- <span />- </div>- </div>- </div>- );-}-function SuggestionCard({ text, onClick }: { text: string; onClick: () => void }) {return (<button className="chat-suggestion-card" onClick={onClick}>@@ -1098,8 +1084,6 @@ export function ChatPanel({<SubtaskProgress />{/* 内联审批卡片(演进审批 & 权限审批共用) */}<InlineQuestionCard onSubmit={onUserAnswer} />- {/* 思考中指示器 */}- {isThinking && <ThinkingIndicator />}<ContextCompressionLinesruntime={contextCompressionRuntime}summary={contextCompressionSummary}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/toolCategory.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/toolCategory.tsnew file mode 100644index 0000000000..74662b8bf6--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/toolCategory.ts@@ -0,0 +1,237 @@+export type ToolCategory = 'file' | 'search' | 'code' | 'system' | 'other';++export const TOOL_CATEGORY_ORDER: ToolCategory[] = ['file', 'search', 'code', 'system', 'other'];++function normalize(name: string): string {+ return name.trim().toLowerCase().replace(/[\s-]+/g, '_');+}++const SYSTEM_TOOLS = new Set([+ 'bash',+ 'shell',+ 'sh',+ 'powershell',+ 'command',+ 'exec',+ 'run',+ 'execute_bash',+ 'run_command',+ 'mcp_exec_command',+ 'exec_command',+ 'create_terminal',+ 'terminal_create',+ 'read_terminal_output',+ 'wait_for_terminal_exit',+ 'release_terminal',+ 'sandbox_run_command',+ 'xiaoyi_gui_agent',+]);++const CODE_TOOLS = new Set([+ 'code',+ 'python',+ 'run_code',+ 'run_python',+ 'execute_code',+ 'execute_python',+ 'exec_code',+ 'exec_python',+ 'python_exec',+ 'python_execute',+ 'code_run',+ 'code_exec',+ 'code_execution',+ 'code_interpreter',+ 'run_notebook',+ 'execute_notebook',+ 'jupyter',+ 'ipython',+ 'eval',+ 'eval_code',+ 'sandbox_run_code',+ 'sandbox_execute_code',+]);++const SEARCH_TOOLS = new Set([+ 'search',+ 'grep',+ 'rg',+ 'ripgrep',+ 'glob',+ 'glob_files',+ 'glob_file_search',+ 'memory_search',+ 'ltm_search',+ 'ltm_search_summary',+ 'mem0_search',+ 'viking_search',+ 'web_search',+ 'web_free_search',+ 'free_search',+ 'mcp_free_search',+ 'web_paid_search',+ 'paid_search',+ 'mcp_paid_search',+ 'web_fetch',+ 'web_fetch_webpage',+ 'fetch',+ 'fetch_webpage',+ 'mcp_fetch_webpage',+ 'lsp',+ 'list_mcp_resources',+ 'search_tools',+ 'search_skill',+ 'search_file',+]);++const FILE_TOOLS = new Set([+ 'read',+ 'read_file',+ 'read_text_file',+ 'view',+ 'write',+ 'write_file',+ 'write_text_file',+ 'edit',+ 'edit_file',+ 'search_replace',+ 'apply_patch',+ 'list',+ 'ls',+ 'list_files',+ 'list_dir',+ 'list_directory',+ 'list_directories',+ 'delete',+ 'delete_file',+ 'remove',+ 'remove_file',+ 'rm',+ 'move',+ 'move_file',+ 'rename',+ 'rename_file',+ 'read_memory',+ 'memory_get',+ 'write_memory',+ 'edit_memory',+ 'coding_memory_read',+ 'coding_memory_write',+ 'coding_memory_edit',+ 'read_mcp_resource',+ 'send_file_to_user',+ 'upload_file',+]);++/**+ * 将工具名归类到五大类之一。+ *+ * 匹配顺序:先精确命中显式集合,再按关键字兜底,最后归为 other。+ * 注意顺序,例如 `search_replace` 属于文件编辑而非搜索、+ * `read_terminal_output` 属于系统调用而非文件读取、+ * `execute_bash` 属于系统调用(shell)而非代码执行。+ */+const FILE_ARG_KEYS = [+ 'target_file',+ 'file_path',+ 'filepath',+ 'filePath',+ 'path',+ 'file',+ 'filename',+ 'fileName',+ 'dir',+ 'directory',+ // send_file_to_user:历史回放偶发无 display_name,需从参数还原可读摘要。+ 'abs_file_path_list',+];++function firstStringArg(args: Record<string, unknown> | null | undefined, keys: string[]): string | undefined {+ if (!args) return undefined;+ for (const key of keys) {+ const value = args[key];+ if (typeof value === 'string' && value.trim()) {+ const trimmed = value.trim();+ if (trimmed.startsWith('[')) {+ try {+ const parsed = JSON.parse(trimmed);+ if (Array.isArray(parsed)) {+ const first = parsed.find((item) => typeof item === 'string' && item.trim());+ if (typeof first === 'string') {+ return first.trim();+ }+ }+ } catch {+ // 非 JSON 时按普通路径字符串用+ }+ }+ return trimmed;+ }+ if (Array.isArray(value)) {+ const first = value.find((item) => typeof item === 'string' && item.trim());+ if (typeof first === 'string') {+ return first.trim();+ }+ }+ }+ return undefined;+}++function basename(path: string): string {+ const trimmed = path.replace(/[\\/]+$/, '');+ const index = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));+ return index >= 0 ? trimmed.slice(index + 1) : trimmed;+}++/**+ * 工具行可读名:以后端 display_name(call_goal / 规则兜底)为权威来源。+ * 前端仅保留极薄兜底,避免与 Python tool_display 双实现漂移。+ */+export function describeToolCall(+ toolCall: { name: string; arguments?: Record<string, unknown>; description?: string; formatted_args?: string; display_name?: string },+ t: (key: string) => string+): string {+ const displayName = toolCall.display_name?.trim();+ if (displayName) {+ return displayName;+ }++ const n = normalize(toolCall.name);+ if (n === 'send_file_to_user') {+ const file = firstStringArg(toolCall.arguments, FILE_ARG_KEYS);+ const verb = t('chatUi.toolAction.sendFile');+ return file ? `${verb} ${basename(file)}` : verb;+ }++ const description = toolCall.description?.trim();+ if (description) return description;+ const formatted = toolCall.formatted_args?.trim();+ if (formatted) return formatted;+ return toolCall.name;+}++export function classifyToolCall(name: string): ToolCategory {+ const n = normalize(name);++ // 显式集合:system 优先,避免与文件类关键字歧义(如 read_terminal_output)+ if (SYSTEM_TOOLS.has(n)) return 'system';+ if (CODE_TOOLS.has(n)) return 'code';+ if (SEARCH_TOOLS.has(n)) return 'search';+ if (FILE_TOOLS.has(n)) return 'file';++ if (/(^|_)(search|grep|glob|fetch|retrieve|retrieval)(_|$)/.test(n)) {+ return 'search';+ }+ if (/(^|_)(python|ipython|jupyter|notebook)(_|$)/.test(n)) {+ return 'code';+ }+ // 终端/shell 必须在 read/write 文件正则之前,否则 read_terminal_* 会被误判为 file+ if (/(^|_)(terminal|bash|shell|command|exec|browser|sandbox)(_|$)/.test(n)) {+ return 'system';+ }+ if (/(^|_)(read|write|edit|delete|move|rename|list|patch)(_|$)/.test(n)) {+ return 'file';+ }++ return 'other';+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/MarkdownRenderer.css b/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/MarkdownRenderer.cssindex 67bd2e7497..b58aa8cc9e 100644--- a/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/MarkdownRenderer.css+++ b/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/MarkdownRenderer.css@@ -2,6 +2,10 @@MarkdownRenderer Component Styles=========================================== */+.chat-bubble-wrapper:has(.chat-markdown-table-wrap) {+ max-width: min(100%, 52rem);+}+/* Toolbar button */.markdown-toolbar-btn {display: inline-flex;diff --git a/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/index.tsxindex de63874124..132df64643 100644--- a/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/MarkdownRenderer/index.tsx@@ -6,6 +6,7 @@ import clsx from 'clsx';import type { MermaidConfig } from 'mermaid';import type { Element as HastElement } from 'hast';import { getSvgNaturalHeight, getSvgNaturalWidth } from '../../utils/svgDimensions';+import { unescapeLiteralNewlines } from '../../utils/finalContent';import { Check, Copy, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';import './MarkdownRenderer.css';@@ -326,13 +327,49 @@ function MarkdownPre({return <pre {...props}>{children}</pre>;}+function MarkdownTable({ children, ...props }: HTMLAttributes<HTMLTableElement>) {+ return (+ <div className='chat-markdown-table-wrap'>+ <table {...props}>{children}</table>+ </div>+ );+}++/**+ * 修复被压成一行的 GFM 表格:行与行之间只剩 ` | |`,remark-gfm 无法识别。+ * 已是多行标准表格时原样返回。+ */+export function repairCollapsedGfmTables(content: string): string {+ if (!content.includes('|') || !/\|[-: ]{3,}/.test(content)) {+ return content;+ }++ const lines = content.split(/\r?\n/);+ const tableLines = lines.filter((line) => /^\s*\|.*\|\s*$/.test(line));+ if (tableLines.length >= 3) {+ return content;+ }++ let next = content;+ // 「正文|页码」标题与表头粘连(左侧须为正文文字,避免拆开 |---| 分隔行)+ next = next.replace(/([\u4e00-\u9fffA-Za-z0-9*])\|(?=\s*[^\s|\-:])/g, '$1\n\n|');+ // 行与行之间的 `| |` / `||` → 换行(分隔行内部是 `|---`,不会命中)+ next = next.replace(/\|\s*(?=\|)/g, '|\n');+ return next;+}+export function MarkdownRenderer({ content, className, testId }: MarkdownRendererProps) {- const contentLines = useMemo(() => content.split(/\r\n|\n|\r/), [content]);+ const markdown = useMemo(+ () => repairCollapsedGfmTables(unescapeLiteralNewlines(content)),+ [content]+ );+ const contentLines = useMemo(() => markdown.split(/\r\n|\n|\r/), [markdown]);const components = useMemo(() => ({a: MarkdownLink,pre: (props: HTMLAttributes<HTMLPreElement> & { node?: HastElement }) => <MarkdownPre {...props} contentLines={contentLines} />,+ table: MarkdownTable,}),[contentLines]);@@ -340,7 +377,7 @@ export function MarkdownRenderer({ content, className, testId }: MarkdownRenderereturn (<div className={className} data-testid={testId}><ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>- {content}+ {markdown}</ReactMarkdown></div>);diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsxindex 812cb4bcef..dc94f5e91a 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx@@ -1,4 +1,4 @@-// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.import { useEffect, useMemo, memo } from 'react';import { useA2UIActions } from '@a2ui/react';@@ -207,7 +207,6 @@ export const A2UIMessageContent = memo(function A2UIMessageContent({</div>);})}- {isStreaming && <span className="streaming-cursor" />}</div>);});diff --git a/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.ts b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.tsnew file mode 100644index 0000000000..08419d1962--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.ts@@ -0,0 +1,775 @@+/**+ * 对话轮次时间线纯函数:live / history / FileViewer 共用同一套排序与折叠分组逻辑。+ */+import type { Message, ToolExecution } from '../../types';+import type { ReasoningSegment } from '../../stores/chatStore';+import { getMessageActor } from '../../components/ChatPanel/MessageItem';+import { collectViewedSkillIds } from '../../components/ChatPanel/ToolGroupDisplay';+import { isTeamMemberCollaborationMessage } from '../../components/ChatPanel/teamEventUtils';+import { isA2UIClientEventContent } from '../a2ui/a2uiContent';++const legacyMessageKeyCache = new WeakMap<Message, string>();+let legacyMessageKeyCounter = 0;++export function getMessageRenderKey(message: Message): string {+ if (message.renderKey) {+ return message.renderKey;+ }+ let key = legacyMessageKeyCache.get(message);+ if (!key) {+ legacyMessageKeyCounter += 1;+ key = `legacy-message-${legacyMessageKeyCounter}`;+ legacyMessageKeyCache.set(message, key);+ }+ return key;+}++export type TimelineItem =+ | {+ type: 'message';+ key: string;+ timestampMs: number;+ sourceIndex: number;+ message: Message;+ }+ | {+ type: 'toolExecution';+ key: string;+ timestampMs: number;+ sourceIndex: number;+ execution: ToolExecution;+ }+ | {+ type: 'reasoning';+ key: string;+ timestampMs: number;+ sourceIndex: number;+ segment: ReasoningSegment;+ };++export type RenderItem =+ | {+ type: 'message';+ key: string;+ showAvatar: boolean;+ message: Message;+ hideMeta: boolean;+ turnId: number;+ }+ | {+ type: 'toolGroup';+ key: string;+ showAvatar: boolean;+ executions: ToolExecution[];+ notices: string[];+ collapseSkillTreeWhenContentStarts: boolean;+ turnId: number;+ viewedSkillIds: string[];+ }+ | {+ type: 'reasoning';+ key: string;+ showAvatar: boolean;+ segment: ReasoningSegment;+ turnId: number;+ }+ | {+ type: 'turnSummary';+ key: string;+ turnId: number;+ startMs: number;+ endMs: number;+ isLastTurn: boolean;+ hasWork: boolean;+ };++/**+ * 将普通消息与工具执行合并为统一时间线,按时间升序渲染。+ */+export function toTimestampMs(value: string | undefined): number {+ if (!value) {+ return Number.NaN;+ }+ const ts = Date.parse(value);+ return Number.isNaN(ts) ? Number.NaN : ts;+}++function compareTimelineItems(a: TimelineItem, b: TimelineItem): number {+ const aTsValid = Number.isFinite(a.timestampMs);+ const bTsValid = Number.isFinite(b.timestampMs);+ if (aTsValid && bTsValid && a.timestampMs !== b.timestampMs) {+ return a.timestampMs - b.timestampMs;+ }+ if (aTsValid !== bTsValid) {+ return aTsValid ? -1 : 1;+ }+ return a.sourceIndex - b.sourceIndex;+}++export function buildTimelineItems(+ messages: Message[],+ executions: ToolExecution[],+ reasoningSegments: ReasoningSegment[]+): TimelineItem[] {+ const messageItems: TimelineItem[] = messages+ .filter((msg) => {+ if (msg.role === 'tool') return false;+ if (msg.role === 'user' && isA2UIClientEventContent(msg.content)) return false;+ return true;+ })+ .map((message, index) => ({+ type: 'message',+ key: getMessageRenderKey(message),+ timestampMs: toTimestampMs(message.timestamp),+ sourceIndex: index,+ message,+ }));++ const executionItems: TimelineItem[] = executions.map((execution, index) => ({+ type: 'toolExecution',+ key: `tool-execution-${execution.toolCallId}`,+ timestampMs: toTimestampMs(execution.startedAt),+ sourceIndex: messages.length + index,+ execution,+ }));++ const reasoningItems: TimelineItem[] = reasoningSegments.map((segment, index) => ({+ type: 'reasoning',+ key: `timeline/reasoning/${segment.id}`,+ timestampMs: segment.startedAt,+ sourceIndex: messages.length + executions.length + index,+ segment,+ }));++ return [...messageItems, ...executionItems, ...reasoningItems].sort(compareTimelineItems);+}++const IMAGE_TOOL_FALLBACK_NOTICE_PREFIX = 'notice-image_tool_fallback-';++function getImageToolFallbackNoticeRequestId(message: Message): string | undefined {+ if (message.role !== 'system' || !message.id.startsWith(IMAGE_TOOL_FALLBACK_NOTICE_PREFIX)) {+ return undefined;+ }+ const requestId = message.id.slice(IMAGE_TOOL_FALLBACK_NOTICE_PREFIX.length).trim();+ return requestId || undefined;+}++function addToolGroupNotice(notices: string[], content: string) {+ const normalized = content.trim();+ if (normalized && !notices.includes(normalized)) {+ notices.push(normalized);+ }+}++function attachToolGroupNotices(renderItems: RenderItem[]): RenderItem[] {+ const nextItems = renderItems.map((item) =>+ item.type === 'toolGroup'+ ? { ...item, notices: [...item.notices] }+ : item+ );+ const groupsByRequestId = new Map<string, Extract<RenderItem, { type: 'toolGroup' }>[]>();++ for (const item of nextItems) {+ if (item.type !== 'toolGroup') {+ continue;+ }+ const requestIds = new Set(+ item.executions+ .map((execution) => execution.requestId)+ .filter((requestId): requestId is string => Boolean(requestId))+ );+ for (const requestId of requestIds) {+ const groups = groupsByRequestId.get(requestId) || [];+ groups.push(item);+ groupsByRequestId.set(requestId, groups);+ }+ }++ const attachedNoticeIndexes = new Set<number>();+ nextItems.forEach((item, index) => {+ if (item.type !== 'message') {+ return;+ }+ const requestId = getImageToolFallbackNoticeRequestId(item.message);+ if (!requestId) {+ return;+ }+ const targetGroup = groupsByRequestId.get(requestId)?.[0];+ if (!targetGroup) {+ return;+ }+ addToolGroupNotice(targetGroup.notices, item.message.content);+ attachedNoticeIndexes.add(index);+ });++ return nextItems.filter((_, index) => !attachedNoticeIndexes.has(index));+}++function isToolGroupVisible(+ item: Extract<RenderItem, { type: 'toolGroup' }>,+ isTeamMode: boolean+): boolean {+ if (!isTeamMode) {+ return item.executions.length > 0;+ }+ return item.executions.some((execution) => !execution.toolCall.memberName);+}++function consolidateReasoning(items: RenderItem[], isTeamMode: boolean): RenderItem[] {+ const out: RenderItem[] = [];+ for (const item of items) {+ if (item.type === 'toolGroup' && !isToolGroupVisible(item, isTeamMode)) {+ continue;+ }+ if (item.type === 'reasoning') {+ const prev = out[out.length - 1];+ if (prev && prev.type === 'reasoning') {+ const mergedText = [prev.segment.text, item.segment.text]+ .filter((text) => text.trim())+ .join('\n\n');+ out[out.length - 1] = {+ ...prev,+ segment: { ...prev.segment, text: mergedText, closed: item.segment.closed },+ };+ continue;+ }+ }+ out.push(item);+ }+ return out;+}++export function buildRenderItems(items: TimelineItem[], isTeamMode: boolean, isProcessing: boolean): RenderItem[] {+ const renderItems: RenderItem[] = [];+ let currentTurnId = 0;+ let pendingToolExecutions: ToolExecution[] = [];++ const flushToolGroup = (collapseSkillTreeWhenContentStarts = false) => {+ if (pendingToolExecutions.length === 0) {+ return;+ }+ renderItems.push({+ type: 'toolGroup',+ key: `tool-group-${pendingToolExecutions[0].toolCallId}`,+ showAvatar: true,+ executions: pendingToolExecutions,+ notices: [],+ collapseSkillTreeWhenContentStarts,+ turnId: currentTurnId,+ viewedSkillIds: [],+ });+ pendingToolExecutions = [];+ };++ const pushMessage = (item: Extract<TimelineItem, { type: 'message' }>) => {+ renderItems.push({+ type: 'message',+ key: item.key,+ showAvatar: true,+ message: item.message,+ hideMeta: false,+ turnId: item.message.role === 'user' ? -1 : currentTurnId,+ });+ };++ for (const item of items) {+ if (item.type === 'toolExecution') {+ pendingToolExecutions.push(item.execution);+ continue;+ }++ if (item.type === 'reasoning') {+ flushToolGroup(true);+ renderItems.push({+ type: 'reasoning',+ key: item.key,+ showAvatar: true,+ segment: item.segment,+ turnId: currentTurnId,+ });+ continue;+ }++ if (isTeamMemberCollaborationMessage(item.message)) {+ continue;+ }++ flushToolGroup(true);+ pushMessage(item);++ if (item.message.role === 'user') {+ currentTurnId += 1;+ }+ }++ flushToolGroup();++ const activeTurnId = currentTurnId;+ let laterAssistantInTurn = false;+ for (let i = renderItems.length - 1; i >= 0; i -= 1) {+ const renderItem = renderItems[i];+ if (renderItem.type !== 'message') {+ continue;+ }+ if (renderItem.message.role === 'user') {+ laterAssistantInTurn = false;+ continue;+ }+ const isAssistantReply =+ renderItem.message.role === 'assistant' || getMessageActor(renderItem.message) === 'team_leader';+ if (isAssistantReply) {+ const inRunningTurn = isProcessing && renderItem.turnId === activeTurnId;+ renderItem.hideMeta = laterAssistantInTurn || inRunningTurn;+ laterAssistantInTurn = true;+ }+ }++ const viewedSkillIdsByTurn = new Map<number, string[]>();+ for (const renderItem of renderItems) {+ if (renderItem.type !== 'toolGroup') {+ continue;+ }+ const viewedSkillIds = collectViewedSkillIds(renderItem.executions);+ if (viewedSkillIds.length === 0) {+ continue;+ }+ const current = viewedSkillIdsByTurn.get(renderItem.turnId) || [];+ viewedSkillIdsByTurn.set(renderItem.turnId, Array.from(new Set([...current, ...viewedSkillIds])));+ }+ for (const renderItem of renderItems) {+ if (renderItem.type === 'toolGroup') {+ renderItem.viewedSkillIds = viewedSkillIdsByTurn.get(renderItem.turnId) || [];+ }+ }++ const renderItemsWithNotices = consolidateReasoning(+ attachToolGroupNotices(renderItems),+ isTeamMode+ );++ if (!isTeamMode) {+ let clusterActive = false;+ for (const renderItem of renderItemsWithNotices) {+ if (renderItem.type === 'reasoning' || renderItem.type === 'toolGroup') {+ renderItem.showAvatar = !clusterActive;+ clusterActive = true;+ continue;+ }+ if (renderItem.type === 'message') {+ if (renderItem.message.role === 'assistant') {+ renderItem.showAvatar = !clusterActive;+ clusterActive = true;+ } else {+ renderItem.showAvatar = false;+ clusterActive = false;+ }+ }+ }+ return insertTurnSummaries(renderItemsWithNotices, isProcessing);+ }++ let clusterBlockActive = false;+ for (const renderItem of renderItemsWithNotices) {+ if (renderItem.type === 'reasoning' || renderItem.type === 'toolGroup') {+ renderItem.showAvatar = !clusterBlockActive;+ clusterBlockActive = true;+ continue;+ }+ if (renderItem.type !== 'message') {+ continue;+ }++ const actor = getMessageActor(renderItem.message);+ if (actor === 'team_leader') {+ renderItem.showAvatar = !clusterBlockActive;+ clusterBlockActive = true;+ continue;+ }++ clusterBlockActive = false;+ }++ return insertTurnSummaries(renderItemsWithNotices, isProcessing);+}++function insertTurnSummaries(items: RenderItem[], isProcessing: boolean): RenderItem[] {+ const out: RenderItem[] = [];+ let startMs = Number.POSITIVE_INFINITY;+ let endMs = Number.NEGATIVE_INFINITY;+ let hasActivity = false;+ let hasWork = false;+ let turnId = 0;+ let seq = 0;++ const acc = (value: number) => {+ if (!Number.isFinite(value)) return;+ if (value < startMs) startMs = value;+ if (value > endMs) endMs = value;+ };+ const flush = (isLastTurn: boolean) => {+ const shouldShow = (isLastTurn && isProcessing) || hasActivity;+ if (shouldShow && Number.isFinite(startMs) && Number.isFinite(endMs)) {+ out.push({+ type: 'turnSummary',+ key: `turn-summary-${seq}`,+ turnId,+ startMs,+ endMs,+ isLastTurn,+ hasWork,+ });+ seq += 1;+ }+ startMs = Number.POSITIVE_INFINITY;+ endMs = Number.NEGATIVE_INFINITY;+ hasActivity = false;+ hasWork = false;+ };++ for (const item of items) {+ if (item.type === 'message' && item.message.role === 'user') {+ flush(false);+ turnId += 1;+ acc(toTimestampMs(item.message.timestamp));+ out.push(item);+ continue;+ }+ if (item.type === 'toolGroup') {+ hasActivity = true;+ hasWork = true;+ turnId = item.turnId;+ for (const execution of item.executions) {+ acc(toTimestampMs(execution.startedAt));+ acc(toTimestampMs(execution.updatedAt));+ }+ } else if (item.type === 'message') {+ hasActivity = true;+ acc(toTimestampMs(item.message.timestamp));+ } else if (item.type === 'reasoning') {+ hasActivity = true;+ hasWork = true;+ turnId = item.turnId;+ acc(item.segment.startedAt);+ }+ out.push(item);+ }+ flush(true);+ return out;+}++export type TurnWorkMeta = {+ turnId: number;+ completed: boolean;+ hasWork: boolean;+ firstWorkKey: string | null;+ startMs: number;+ endMs: number;+ showAvatar: boolean;+ thinkingCount: number;+ toolCount: number;+};++const DELIVERABLE_TOOL_NAMES = new Set(['send_file_to_user']);++export function isDeliverableToolName(name: string | undefined): boolean {+ return Boolean(name && DELIVERABLE_TOOL_NAMES.has(name));+}++export function messageHasDeliverable(message: Message): boolean {+ return Boolean(message.fileItems?.length || message.mediaItems?.length);+}++export function filterDeliverableExecutions(executions: ToolExecution[]): ToolExecution[] {+ return executions.filter((execution) => isDeliverableToolName(execution.toolCall.name));+}++function isExecutionRunning(execution: ToolExecution): boolean {+ if (+ execution.status === 'completed' ||+ execution.status === 'error' ||+ execution.status === 'timeout'+ ) {+ return false;+ }+ if (execution.result) {+ return false;+ }+ return execution.status === 'pending';+}++function countToolsInGroup(item: Extract<RenderItem, { type: 'toolGroup' }>): number {+ return item.executions.filter((execution) => !isDeliverableToolName(execution.toolCall.name)).length;+}++export function buildTurnWorkMeta(items: RenderItem[], isProcessing: boolean): Map<number, TurnWorkMeta> {+ const map = new Map<number, TurnWorkMeta>();+ let lastTurnId = Number.NEGATIVE_INFINITY;+ for (const item of items) {+ if (item.type === 'turnSummary') {+ lastTurnId = Math.max(lastTurnId, item.turnId);+ const prev = map.get(item.turnId);+ map.set(item.turnId, {+ turnId: item.turnId,+ completed: !(item.isLastTurn && isProcessing),+ hasWork: item.hasWork || Boolean(prev?.hasWork),+ firstWorkKey: prev?.firstWorkKey ?? null,+ startMs: item.startMs,+ endMs: item.endMs,+ showAvatar: prev?.showAvatar ?? true,+ thinkingCount: prev?.thinkingCount ?? 0,+ toolCount: prev?.toolCount ?? 0,+ });+ continue;+ }+ if (item.type !== 'reasoning' && item.type !== 'toolGroup') {+ continue;+ }+ lastTurnId = Math.max(lastTurnId, item.turnId);+ const prev = map.get(item.turnId);+ if (prev) {+ if (!prev.firstWorkKey) {+ prev.firstWorkKey = item.key;+ prev.showAvatar = item.showAvatar;+ }+ prev.hasWork = true;+ if (item.type === 'reasoning') {+ prev.thinkingCount += 1;+ } else {+ prev.toolCount += countToolsInGroup(item);+ }+ } else {+ map.set(item.turnId, {+ turnId: item.turnId,+ completed: false,+ hasWork: true,+ firstWorkKey: item.key,+ startMs: Number.NaN,+ endMs: Number.NaN,+ showAvatar: item.showAvatar,+ thinkingCount: item.type === 'reasoning' ? 1 : 0,+ toolCount: item.type === 'toolGroup' ? countToolsInGroup(item) : 0,+ });+ }+ }+ for (const meta of map.values()) {+ if (meta.thinkingCount > 0 || meta.toolCount > 0) {+ meta.hasWork = true;+ }+ const isLast = Number.isFinite(lastTurnId) && meta.turnId === lastTurnId;+ meta.completed = !(isProcessing && isLast);+ }+ return map;+}++export type LiveWorkStreak = {+ id: string;+ turnId: number;+ /** 轮次内稳定序号(不绑易变的 item.key),供展开态持久化 */+ ordinal: number;+ firstKey: string;+ keys: Set<string>;+ thinkingCount: number;+ toolCount: number;+ showAvatar: boolean;+};++export const REASONING_COLLAPSE_DELAY_MS = 2000;+const REASONING_STREAK_MERGE_EXTRA_MS = 700;+const TOOL_STREAK_SETTLE_MS = 1200;+export const STREAK_FOLD_TRANSITION_DELAY_MS = 160;++/** streak 展开态 key:绑 turnId + 轮次内 ordinal,避免 firstKey 变化导致展开态丢失 */+export function streakExpandKey(turnId: number, ordinal: number): string {+ return `streak-${turnId}-${ordinal}`;+}++function isReasoningSettledForStreak(segment: ReasoningSegment, nowMs: number): boolean {+ if (!segment.closed) {+ return false;+ }+ const closedAt = segment.closedAt ?? 0;+ return nowMs - closedAt >= REASONING_COLLAPSE_DELAY_MS + REASONING_STREAK_MERGE_EXTRA_MS;+}++function isToolGroupSettledForStreak(+ item: Extract<RenderItem, { type: 'toolGroup' }>,+ nowMs: number+): boolean {+ const workExecs = item.executions.filter(+ (execution) => !isDeliverableToolName(execution.toolCall.name)+ );+ if (workExecs.length === 0) {+ return false;+ }+ if (workExecs.some(isExecutionRunning)) {+ return false;+ }+ let latestDone = 0;+ for (const execution of workExecs) {+ const ts = toTimestampMs(execution.updatedAt);+ if (Number.isFinite(ts) && ts > latestDone) {+ latestDone = ts;+ }+ }+ if (latestDone <= 0) {+ return true;+ }+ return nowMs - latestDone >= TOOL_STREAK_SETTLE_MS;+}++export function isSettlingForStreak(items: RenderItem[], nowMs: number): boolean {+ for (const item of items) {+ if (item.type === 'reasoning') {+ if (item.segment.closed && typeof item.segment.closedAt === 'number' && !isReasoningSettledForStreak(item.segment, nowMs)) {+ return true;+ }+ continue;+ }+ if (item.type !== 'toolGroup' || countToolsInGroup(item) === 0) continue;+ if (!item.executions.some(isExecutionRunning) && !isToolGroupSettledForStreak(item, nowMs)) {+ return true;+ }+ }+ return false;+}++export function streakMapFingerprint(streaks: Map<string, LiveWorkStreak>): string {+ return [...streaks.values()]+ .map(+ (streak) =>+ `${streak.id}:${streak.thinkingCount}:${streak.toolCount}:${[...streak.keys].join(',')}`+ )+ .sort()+ .join('|');+}++/**+ * 只编码影响 streak 分组的字段。正文流式改字不触发重建;+ * settle 时钟滴答若尚未跨过阈值也不会改变签名。+ */+export function buildStreakInputSignature(items: RenderItem[], nowMs: number): string {+ const parts: string[] = [];+ for (const item of items) {+ if (item.type === 'turnSummary') {+ continue;+ }+ if (item.type === 'message') {+ parts.push(`m:${item.turnId}`);+ continue;+ }+ if (item.type === 'reasoning') {+ const settled = isReasoningSettledForStreak(item.segment, nowMs) ? 1 : 0;+ parts.push(+ `r:${item.key}:${item.turnId}:${item.segment.closed ? 1 : 0}:${settled}:${item.showAvatar ? 1 : 0}`+ );+ continue;+ }+ const workToolCount = countToolsInGroup(item);+ const running = item.executions.some(isExecutionRunning) ? 1 : 0;+ const settled = workToolCount > 0 && !running && isToolGroupSettledForStreak(item, nowMs) ? 1 : 0;+ parts.push(+ `t:${item.key}:${item.turnId}:${workToolCount}:${running}:${settled}:${item.showAvatar ? 1 : 0}`+ );+ }+ return parts.join('|');+}++export function buildLiveCompletedStreaks(+ items: RenderItem[],+ nowMs: number+): Map<string, LiveWorkStreak> {+ const sealed = new Map<string, LiveWorkStreak>();+ let streak: LiveWorkStreak | null = null;+ const ordinalByTurn = new Map<number, number>();++ const nextOrdinal = (turnId: number): number => {+ const n = ordinalByTurn.get(turnId) ?? 0;+ ordinalByTurn.set(turnId, n + 1);+ return n;+ };++ const seal = () => {+ if (streak && streak.thinkingCount + streak.toolCount >= 2) {+ sealed.set(streak.firstKey, streak);+ }+ streak = null;+ };++ for (const item of items) {+ if (item.type === 'turnSummary') {+ continue;+ }+ if (item.type === 'message') {+ seal();+ continue;+ }++ if (item.type === 'reasoning') {+ if (!isReasoningSettledForStreak(item.segment, nowMs)) {+ seal();+ continue;+ }+ if (!streak) {+ const ordinal = nextOrdinal(item.turnId);+ streak = {+ id: streakExpandKey(item.turnId, ordinal),+ turnId: item.turnId,+ ordinal,+ firstKey: item.key,+ keys: new Set(),+ thinkingCount: 0,+ toolCount: 0,+ showAvatar: item.showAvatar,+ };+ }+ streak.keys.add(item.key);+ streak.thinkingCount += 1;+ continue;+ }++ const workToolCount = countToolsInGroup(item);+ if (workToolCount === 0) {+ seal();+ continue;+ }+ const hasRunning = item.executions.some(isExecutionRunning);+ if (hasRunning || !isToolGroupSettledForStreak(item, nowMs)) {+ seal();+ continue;+ }+ if (!streak) {+ const ordinal = nextOrdinal(item.turnId);+ streak = {+ id: streakExpandKey(item.turnId, ordinal),+ turnId: item.turnId,+ ordinal,+ firstKey: item.key,+ keys: new Set(),+ thinkingCount: 0,+ toolCount: 0,+ showAvatar: item.showAvatar,+ };+ }+ streak.keys.add(item.key);+ streak.toolCount += workToolCount;+ }+ seal();+ return sealed;+}++export function formatStreakSummaryLabel(+ t: (key: string, options?: Record<string, unknown>) => string,+ thinkingCount: number,+ toolCount: number+): string {+ if (thinkingCount > 0 && toolCount > 0) {+ return t('chatUi.workCompletedBothNoDuration', { thinking: thinkingCount, tools: toolCount });+ }+ if (thinkingCount > 0) {+ return t('chatUi.workCompletedThinkingNoDuration', { thinking: thinkingCount });+ }+ if (toolCount > 0) {+ return t('chatUi.workCompletedToolsNoDuration', { tools: toolCount });+ }+ return t('chatUi.workCompletedFallback');+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.ts b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.tsnew file mode 100644index 0000000000..21c51c5834--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.ts@@ -0,0 +1,21 @@+export {+ buildTimelineItems,+ buildRenderItems,+ buildTurnWorkMeta,+ buildLiveCompletedStreaks,+ buildStreakInputSignature,+ isSettlingForStreak,+ streakMapFingerprint,+ formatStreakSummaryLabel,+ messageHasDeliverable,+ filterDeliverableExecutions,+ getMessageRenderKey,+ toTimestampMs,+ streakExpandKey,+ REASONING_COLLAPSE_DELAY_MS,+ STREAK_FOLD_TRANSITION_DELAY_MS,+ type TimelineItem,+ type RenderItem,+ type TurnWorkMeta,+ type LiveWorkStreak,+} from './buildTurnTimeline';diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex 91e9fbc7ac..ca05da48df 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -1,8 +1,9 @@-import { Message, MessageRole, UsageSummary, FileDownloadItem, MediaItem, WsEvent } from '../types';+import { Message, MessageRole, UsageSummary, FileDownloadItem, MediaItem, WsEvent, ToolExecution } from '../types';import { webClient } from '../services/webClient';import { normalizeFinalContent } from '../utils/finalContent';import { mergeFileDownloadItems } from '../utils/fileDownloadDedup';import { isA2UIClientEventContent } from './a2ui/a2uiContent';+import { normalizeToolCallPayload, normalizeToolResultPayload } from './tool-events/toolEventNormalizer';export const HISTORY_GET_METHOD = 'history.get';export const HISTORY_MESSAGE_EVENT = 'history.message';@@ -31,6 +32,12 @@ export interface HistoryToolReplayItem {payload: Record<string, unknown>;}+/** 历史中随 chat.final / chat.tool_call 落盘的模型思考(reasoning_content),用于刷新后重建思考块。 */+export interface HistoryReasoningReplayItem {+ at: string;+ text: string;+}+export interface HistoryHarnessReplayItem {kind: 'harness_message' | 'harness_stage_result';at: string;@@ -61,7 +68,8 @@ type HistoryTimelineEntry =| { kind: 'team_member'; at: string; payload: { event: Record<string, unknown> } }| { kind: 'team_task'; at: string; payload: { event: Record<string, unknown> } }| { kind: 'harness_message'; at: string; content: string; stage?: string }- | { kind: 'harness_stage_result'; at: string; stage: string; status: string; error: string; messages: string[]; metrics: Record<string, unknown> };+ | { kind: 'harness_stage_result'; at: string; stage: string; status: string; error: string; messages: string[]; metrics: Record<string, unknown> }+ | { kind: 'reasoning'; at: string; text: string };interface BeginHistoryRestoreOptions {sessionId: string;@@ -72,6 +80,8 @@ interface BeginHistoryRestoreOptions {onHarnessReplay?: (items: HistoryHarnessReplayItem[]) => void;/** 与消息同一时间线顺序,用于恢复 Team 成员/任务状态 */onTeamReplay?: (items: HistoryTeamReplayItem[]) => void;+ /** 与消息同一时间线顺序,用于恢复模型思考块(chat.reasoning) */+ onReasoningReplay?: (items: HistoryReasoningReplayItem[]) => void;/** 无消息且无工具回放时调用;`totalPages` 来自流中最后一帧(若有) */onEmpty?: (totalPages: number | null) => void;onError?: (message: string) => void;@@ -102,6 +112,22 @@ function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === 'object' && !Array.isArray(value);}+/** 从历史记录中提取随本步落盘的模型思考文本(reasoning_content 可能在顶层或 payload 内)。 */+function extractHistoryReasoningText(record: Record<string, unknown>): string {+ const direct = record.reasoning_content;+ if (typeof direct === 'string' && direct.trim()) {+ return direct.trim();+ }+ const payload = record.payload;+ if (isRecord(payload)) {+ const nested = payload.reasoning_content;+ if (typeof nested === 'string' && nested.trim()) {+ return nested.trim();+ }+ }+ return '';+}+function pickFirstString(input: Record<string, unknown>, keys: string[]): string | undefined {for (const key of keys) {const value = input[key];@@ -460,10 +486,30 @@ function parseHistoryTimelineEntry(}if (eventType === 'chat.tool_call') {+ // 与实时一致:team 成员工具不进主聊天时间线(侧栏 teamHistoryPanelRestore 另有回放)。+ if (isHiddenTeamTeammateMessageRecord(record)) {+ return null;+ }+ // 把顶层 member/role 带进 payload,供 normalize 识别(即便未隐藏也能对齐展示)。+ if (typeof record.member_name === 'string' && record.member_name.trim() && payload.member_name == null) {+ payload.member_name = record.member_name;+ }+ if (typeof record.role === 'string' && payload.role == null) {+ payload.role = record.role;+ }return { kind: 'tool_call', at, payload };}if (eventType === 'chat.tool_result') {+ if (isHiddenTeamTeammateMessageRecord(record)) {+ return null;+ }+ if (typeof record.member_name === 'string' && record.member_name.trim() && payload.member_name == null) {+ payload.member_name = record.member_name;+ }+ if (typeof record.role === 'string' && payload.role == null) {+ payload.role = record.role;+ }return { kind: 'tool_result', at, payload };}@@ -528,22 +574,160 @@ export function parseHistoryJsonFileToPreviewMessages(parsed: unknown,sessionId: string): Message[] {+ return parseHistoryJsonFileToTimelinePreview(parsed, sessionId).messages;+}++export interface HistoryTimelinePreview {+ messages: Message[];+ executions: ToolExecution[];+ reasoningSegments: { id: string; text: string; startedAt: number; closed: true; closedAt?: number }[];+ mode: 'team' | null;+}++/**+ * 历史文件完整时间线预览:消息 + 工具执行 + 思考段,供 ChatTimelineList 与会话页同一套折叠逻辑使用。+ */+export function parseHistoryJsonFileToTimelinePreview(+ parsed: unknown,+ sessionId: string+): HistoryTimelinePreview {if (!Array.isArray(parsed)) {- return [];+ return { messages: [], executions: [], reasoningSegments: [], mode: null };}const messages: Message[] = [];+ const toolReplay: HistoryToolReplayItem[] = [];+ const reasoningReplay: HistoryReasoningReplayItem[] = [];+ let isTeam = false;+for (const item of parsed) {if (!isRecord(item)) {continue;}+ if (isTeamModeRecord(item)) {+ isTeam = true;+ }const entry = parseHistoryTimelineEntry(item, sessionId);if (entry?.kind === 'message') {messages.push(entry.message);+ } else if (entry?.kind === 'tool_call' || entry?.kind === 'tool_result') {+ toolReplay.push({ kind: entry.kind, at: entry.at, payload: entry.payload });+ }+ const reasoningText = extractHistoryReasoningText(item);+ if (reasoningText) {+ reasoningReplay.push({ at: recordTimestampIso(item), text: reasoningText });}}- return messages.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));+ messages.sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));++ const executions = buildToolExecutionsFromReplay(toolReplay);+ const reasoningSegments = buildReasoningSegmentsFromReplay(sessionId, reasoningReplay);++ return {+ messages,+ executions,+ reasoningSegments,+ mode: isTeam ? 'team' : null,+ };+}++function buildReasoningSegmentsFromReplay(+ sessionId: string,+ items: HistoryReasoningReplayItem[]+): HistoryTimelinePreview['reasoningSegments'] {+ const segments: HistoryTimelinePreview['reasoningSegments'] = [];+ const seen = new Set<string>();+ items.forEach((item, index) => {+ const text = item.text?.trim();+ if (!text || seen.has(text)) {+ return;+ }+ seen.add(text);+ const parsed = Date.parse(item.at);+ const startedAt = Number.isFinite(parsed) ? parsed - 1 : index;+ segments.push({+ id: `hist-preview-rsn-${sessionId}-${index}`,+ text,+ startedAt,+ closed: true,+ closedAt: startedAt,+ });+ });+ segments.sort((a, b) => a.startedAt - b.startedAt);+ return segments;+}++function buildToolExecutionsFromReplay(toolReplay: HistoryToolReplayItem[]): ToolExecution[] {+ const byId = new Map<string, ToolExecution>();+ const order: string[] = [];++ for (const item of toolReplay) {+ if (item.kind === 'tool_call') {+ const n = normalizeToolCallPayload(item.payload);+ if (!n.id || byId.has(n.id)) {+ continue;+ }+ const startedAt = item.at;+ byId.set(n.id, {+ toolCallId: n.id,+ toolCall: {+ id: n.id,+ name: n.name,+ arguments: n.arguments,+ description: n.description,+ formatted_args: n.formatted_args,+ display_name: n.display_name,+ memberName: n.memberName,+ },+ status: 'pending',+ startedAt,+ updatedAt: startedAt,+ timeoutAt: startedAt,+ });+ order.push(n.id);+ continue;+ }++ const n = normalizeToolResultPayload(item.payload);+ if (!n.toolCallId) {+ continue;+ }+ const existing = byId.get(n.toolCallId);+ const result = {+ toolName: n.toolName,+ result: n.result,+ success: n.success,+ toolCallId: n.toolCallId,+ summary: n.summary,+ skillTree: n.skillTree,+ };+ if (!existing) {+ byId.set(n.toolCallId, {+ toolCallId: n.toolCallId,+ toolCall: {+ id: n.toolCallId,+ name: n.toolName || 'tool',+ arguments: {},+ },+ result,+ status: n.success ? 'completed' : 'error',+ startedAt: item.at,+ updatedAt: item.at,+ timeoutAt: item.at,+ });+ order.push(n.toolCallId);+ continue;+ }+ byId.set(n.toolCallId, {+ ...existing,+ result,+ status: n.success ? 'completed' : 'error',+ updatedAt: item.at,+ });+ }++ return order.map((id) => byId.get(id)).filter((item): item is ToolExecution => Boolean(item));}export function parseHistoryJsonFilePreviewMode(parsed: unknown): 'team' | null {@@ -625,6 +809,10 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historif (entry) {entries.unshift(entry);}+ const reasoningText = extractHistoryReasoningText(record);+ if (reasoningText) {+ entries.unshift({ kind: 'reasoning', at: recordTimestampIso(record), text: reasoningText });+ }}if (isHistoryBatchEnd(payload)) {@@ -648,6 +836,7 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historconst toolReplay: HistoryToolReplayItem[] = [];const harnessReplay: HistoryHarnessReplayItem[] = [];const teamReplay: HistoryTeamReplayItem[] = [];+ const reasoningReplay: HistoryReasoningReplayItem[] = [];let pendingFileItems: FileDownloadItem[] | null = null;for (const e of entries) {if (e.kind === 'message') {@@ -696,6 +885,8 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): HistorpendingFileItems = mergeFileDownloadItems(pendingFileItems, e.files);} else if (e.kind === 'team_member' || e.kind === 'team_task') {teamReplay.push({ kind: e.kind, at: e.at, payload: e.payload });+ } else if (e.kind === 'reasoning') {+ reasoningReplay.push({ at: e.at, text: e.text });} else {toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}@@ -717,6 +908,9 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historif (teamReplay.length > 0) {options.onTeamReplay?.(teamReplay);}+ if (reasoningReplay.length > 0) {+ options.onReasoningReplay?.(reasoningReplay);+ }}const handle: HistoryRestoreHandle = { generation, dispose };@@ -729,6 +923,7 @@ export interface FetchHistoryPageResult {toolReplay: HistoryToolReplayItem[];harnessReplay: HistoryHarnessReplayItem[];teamReplay: HistoryTeamReplayItem[];+ reasoningReplay: HistoryReasoningReplayItem[];totalPages: number | null;}@@ -781,6 +976,10 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestoif (entry) {entries.unshift(entry);}+ const reasoningText = extractHistoryReasoningText(record);+ if (reasoningText) {+ entries.unshift({ kind: 'reasoning', at: recordTimestampIso(record), text: reasoningText });+ }}if (isHistoryBatchEnd(payload)) {@@ -804,6 +1003,7 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestoconst toolReplay: HistoryToolReplayItem[] = [];const harnessReplay: HistoryHarnessReplayItem[] = [];const teamReplay: HistoryTeamReplayItem[] = [];+ const reasoningReplay: HistoryReasoningReplayItem[] = [];let pendingFileItems: FileDownloadItem[] | null = null;for (const e of entries) {if (e.kind === 'message') {@@ -851,6 +1051,8 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestopendingFileItems = mergeFileDownloadItems(pendingFileItems, e.files);} else if (e.kind === 'team_member' || e.kind === 'team_task') {teamReplay.push({ kind: e.kind, at: e.at, payload: e.payload });+ } else if (e.kind === 'reasoning') {+ reasoningReplay.push({ at: e.at, text: e.text });} else {toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}@@ -862,7 +1064,7 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestooptions.onEmpty?.(totalPages);return;}- options.onReady({ messages, toolReplay, harnessReplay, teamReplay, totalPages });+ options.onReady({ messages, toolReplay, harnessReplay, teamReplay, reasoningReplay, totalPages });}const handle: HistoryRestoreHandle = { generation, dispose };diff --git a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsxindex 5e75db64fd..d00cd2a971 100644--- a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx@@ -11,7 +11,7 @@ import {type ParsedTeamEvent,} from '../components/ChatPanel/teamEventUtils';import { isUserMember } from '../utils/teamMemberAvatar';-import { parseHistoryJsonFileToPreviewMessages } from './historyRestore';+import { parseHistoryJsonFileToTimelinePreview } from './historyRestore';import { parseTeamHistoryPanelRecords } from './teamHistoryPanelRestore';import { isA2UIClientEventContent } from './a2ui/a2uiContent';import { getSvgNaturalHeight, getSvgNaturalWidth } from '../utils/svgDimensions';@@ -154,12 +154,14 @@ export const ShareImageDocument = forwardRef<HTMLDivElement, ShareImageDocumentPif (!snapshot) {return null;}- const messages = parseHistoryJsonFileToPreviewMessages(snapshot.records, snapshot.session_id);+ const preview = parseHistoryJsonFileToTimelinePreview(snapshot.records, snapshot.session_id);// Filter out A2UI client event messages from exports- const filteredMessages = filterA2UIClientEvents(messages) as typeof messages;+ const filteredMessages = filterA2UIClientEvents(preview.messages) as typeof preview.messages;return {mode: normalizeMode(snapshot.records),messages: filteredMessages,+ executions: preview.executions,+ reasoningSegments: preview.reasoningSegments,groupMessages: collectGroupMessages(snapshot),};}, [snapshot]);@@ -200,7 +202,9 @@ export const ShareImageDocument = forwardRef<HTMLDivElement, ShareImageDocumentP{hasConversation ? (<ChatTimelineListmessages={data.messages}- executions={[]}+ executions={data.executions}+ reasoningSegments={data.reasoningSegments}+ staticTimelinemode={data.mode}disableA2UIInteraction={true}/>diff --git a/jiuwenswarm/channels/web/frontend/src/features/teamLeaderMessages.ts b/jiuwenswarm/channels/web/frontend/src/features/teamLeaderMessages.tsindex 0f2c1323d6..c89cf3d64a 100644--- a/jiuwenswarm/channels/web/frontend/src/features/teamLeaderMessages.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/teamLeaderMessages.ts@@ -13,6 +13,24 @@ function isTeamLeaderMessage(message: Message): boolean {return message.id.startsWith('team-leader-');}+/**+ * 取出 team-leader 消息的原始纯文字:已收尾的气泡内容形如 `team.leader:{"content":...}`,+ * 流式中的气泡内容则是原始文字本身。用于分段场景下按段拼接/去重。+ */+export function extractTeamLeaderRawContent(content: string | undefined): string {+ if (!content) return '';+ if (content.startsWith('team.leader:')) {+ const jsonStr = content.slice('team.leader:'.length);+ try {+ const data = JSON.parse(jsonStr);+ return typeof data?.content === 'string' ? data.content : '';+ } catch {+ return '';+ }+ }+ return content;+}+export function findActiveTeamLeaderMessage(messages: Message[]): Message | undefined {const latestUserIndex = findLatestUserIndex(messages);for (let index = messages.length - 1; index > latestUserIndex; index -= 1) {diff --git a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.tsindex 5c2349e92a..282cff5b56 100644--- a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts@@ -72,6 +72,8 @@ export interface NormalizedToolCall {arguments: Record<string, unknown>;description?: string;formatted_args?: string;+ /** 后端下发的可读展示名(部分工具带),前端优先直接展示,省去本地推断。 */+ display_name?: string;memberName?: string;}@@ -106,6 +108,11 @@ export function normalizeToolCallPayload(payload: UnknownPayload): NormalizedTootypeof toolCallPayload.formatted_args === 'string'? toolCallPayload.formatted_args: undefined;+ const displayNameRaw =+ (typeof toolCallPayload.display_name === 'string' && toolCallPayload.display_name) ||+ (typeof toolCallPayload.displayName === 'string' && toolCallPayload.displayName) ||+ '';+ const display_name = displayNameRaw.trim() || undefined;const memberName = resolveMemberName(toolCallPayload, payload);return {@@ -114,6 +121,7 @@ export function normalizeToolCallPayload(payload: UnknownPayload): NormalizedTooarguments: parseArguments(toolCallPayload.arguments),description,formatted_args,+ display_name,memberName,};}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 96afb6b60a..475e5961f2 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -50,7 +50,13 @@ import {playAudioBase64,sanitizeTtsText,stopAllTts,+ collapseWs,+ findAssistantSegmentIdForFinal,normalizeFinalContent,+ resolveStreamFinalContent,+ unescapeLiteralNewlines,+ interpretChatFinalAction,+ shouldCollapseTurnFinal,} from '../utils';import {findOverlappingFileExecutionEvent,@@ -61,7 +67,9 @@ import {normalizeToolResultPayload,normalizeToolUpdatePayload,} from '../features/tool-events/toolEventNormalizer';-import { findActiveTeamLeaderMessage as findActiveTeamLeaderMessageInTurn } from '../features/teamLeaderMessages';+import {+ findActiveTeamLeaderMessage as findActiveTeamLeaderMessageInTurn,+} from '../features/teamLeaderMessages';import { buildGoalCompletedContent } from '../components/GoalBar/goalCompletedMessage';const WS_RECONNECT_EVENT = 'jiuwenclaw:ws-reconnect-request';@@ -641,6 +649,7 @@ function isTeamTeammateMessagePayload(payload: Record<string, unknown>): booleanreturn typeof payload.role === 'string' && payload.role.trim().toLowerCase() === 'teammate';}+/** 仅当 final 覆盖本轮已展示全文时才允许折叠,避免步进 final 抹掉前文(如 A/B/C)。 */function isHiddenTeamTeammateMessagePayload(mode: AgentMode, payload: Record<string, unknown>): boolean {return mode === 'team' && isTeamTeammateMessagePayload(payload);}@@ -1961,7 +1970,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;- const content = typeof payload.content === 'string' ? payload.content : '';+ const content = unescapeLiteralNewlines(+ typeof payload.content === 'string' ? payload.content : ''+ );if (isHiddenTeamTeammateMessagePayload(currentMode ?? 'agent', payload)) {const memberId = getTeamPayloadMemberName(payload);@@ -1975,6 +1986,12 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}if (currentMode === 'team' && content) {clearThinkingForVisibleOutput(sessionId);+ if (content.trim()) {+ useChatStore.getState().bumpThinkingAnchor(sessionId);+ useChatStore.getState().closeReasoning(sessionId, {+ atMs: eventTimestampMs(payload),+ });+ }const existingMsg = findActiveTeamLeaderMessage(sessionId);if (existingMsg) {@@ -2007,6 +2024,12 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {let currentStreamId = useChatStore.getState().getRuntime(sessionId)?.currentStreamId;clearThinkingForVisibleOutput(sessionId);+ if (content.trim()) {+ useChatStore.getState().bumpThinkingAnchor(sessionId);+ useChatStore.getState().closeReasoning(sessionId, {+ atMs: eventTimestampMs(payload),+ });+ }if (!currentStreamId && content) {const assistantMsgId = `assistant-${Date.now()}`;useChatStore.getState().addMessage(sessionId, {@@ -2038,6 +2061,14 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (shouldRecoverProcessingFromReasoning(sessionId, payload)) {useChatStore.getState().setProcessing(sessionId, true);}++ const reasoningContent =+ typeof payload.content === 'string' ? payload.content : '';+ if (reasoningContent) {+ useChatStore.getState().appendReasoning(sessionId, reasoningContent, {+ atMs: eventTimestampMs(payload),+ });+ }}),webClient.on('chat.final', ({ payload }) => {if (shouldDropDuplicatedEvent('chat.final', payload)) return;@@ -2194,18 +2225,61 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (content) {revealPendingContextUsage(sessionId);}+ const finalAction = interpretChatFinalAction(payload);if (currentMode === 'team' && content) {clearThinkingForVisibleOutput(sessionId);const timestamp = payload.timestamp || Date.now();+ const iso = normalizeEventTimestampIso(payload.timestamp);+ const teamRuntime = useChatStore.getState().getRuntime(sessionId);+ const teamSplit = Boolean(teamRuntime?.assistantStreamSplit);+ const teamMessages = teamRuntime?.messages ?? [];++ if (teamSplit) {+ useChatStore.getState().clearStreamSplit(sessionId);+ if (shouldCollapseTurnFinal(teamMessages, content, 'team', finalAction)) {+ useChatStore.getState().collapseTurnFinal(sessionId, {+ kind: 'team',+ content,+ finalId: `team-leader-${Date.now()}`,+ timestampIso: iso,+ });+ return;+ }+ if (finalAction.type === 'append') {+ useChatStore.getState().addMessage(sessionId, {+ id: `team-leader-${Date.now()}`,+ role: 'system',+ content: `team.leader:${JSON.stringify({ content, timestamp: Date.parse(iso) || Date.now() })}`,+ timestamp: iso,+ });+ return;+ }+ if (teamLeaderMessageToFinalize) {+ useChatStore.getState().updateMessage(sessionId, teamLeaderMessageToFinalize.id, {+ content: `team.leader:${JSON.stringify({ content, timestamp: Date.parse(iso) || Date.now() })}`,+ isStreaming: false,+ timestamp: iso,+ });+ return;+ }+ useChatStore.getState().addMessage(sessionId, {+ id: `team-leader-${Date.now()}`,+ role: 'system',+ content: `team.leader:${JSON.stringify({ content, timestamp: Date.parse(iso) || Date.now() })}`,+ timestamp: iso,+ });+ return;+ }if (teamLeaderMessageToFinalize) {useChatStore.getState().updateMessage(sessionId, teamLeaderMessageToFinalize.id, {content: `team.leader:${JSON.stringify({ content, timestamp })}`,isStreaming: false,- timestamp: normalizeEventTimestampIso(payload.timestamp),+ timestamp: iso,});return;}+useChatStore.getState().addMessage(sessionId, {id: `team-leader-${Date.now()}`,role: 'system',@@ -2218,23 +2292,60 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const runtime = useChatStore.getState().getRuntime(sessionId);const currentStreamId = runtime?.currentStreamId;const messages = runtime?.messages ?? [];- const payloadSessionId =- typeof payload.session_id === 'string' ? payload.session_id.trim() : '';+ const assistantStreamSplit = Boolean(runtime?.assistantStreamSplit);+ useChatStore.getState().clearStreamSplit(sessionId);- // 检查是否为主动推荐消息const source = typeof payload.source === 'string' ? payload.source : '';const isProactiveRecommendation = source === 'proactive_recommendation';const proactiveType = typeof payload.proactive_type === 'string' ? payload.proactive_type : '';- // 仅当有明确会话绑定时才把 final 合并进当前流式气泡。- // 定时任务等广播的 session_id 为空/null,若仍走 currentStreamId 会写到错误气泡甚至”无可见更新”。const streamId = currentStreamId;- if (streamId && payloadSessionId) {- // 注意:这里不能再用 payload.timestamp 覆盖消息的 timestamp——它是"开始输出那一刻"- // 盖的章,收尾只应该改 content/isStreaming。目标模式下 chat.final 和 goal.updated- // (completed) 走的是两条独立通道、到达顺序不定,用后端 chat.final 自带的时间戳覆盖会- // 让这条回复的时间戳跟"整轮真正跑完"(含目标评估)的时刻赛跑,一旦覆盖后的新时间戳- // 晚于目标完成提示卡的时间戳,消息排序就会翻车(真机复现过,提示卡跑到回复上方)。+ const preferredSegmentId =+ finalAction.type === 'patch_segment' ? finalAction.segmentId : undefined;++ if (assistantStreamSplit && content) {+ const cronMetaEarly = payload.cron as Record<string, unknown> | undefined;+ const cronRunIdEarly =+ typeof cronMetaEarly?.run_id === 'string' ? cronMetaEarly.run_id.trim() : '';+ if (!cronRunIdEarly && !cronMetaEarly && !isProactiveRecommendation) {+ if (streamId) {+ useChatStore.getState().stopStreaming(sessionId);+ }+ if (shouldCollapseTurnFinal(messages, content, 'agent', finalAction)) {+ const finalId = `msg-final-${Date.now()}`;+ useChatStore.getState().collapseTurnFinal(sessionId, {+ kind: 'agent',+ content,+ finalId,+ timestampIso: new Date().toISOString(),+ });+ if (!content.includes('MEDIA:')) {+ handleTtsPlayback(sessionId, finalId, content);+ }+ return;+ }+ if (finalAction.type !== 'append') {+ const rewriteId = findAssistantSegmentIdForFinal(+ messages,+ content,+ preferredSegmentId || streamId+ );+ if (rewriteId) {+ useChatStore.getState().updateMessage(sessionId, rewriteId, {+ content,+ isStreaming: false,+ });+ if (!content.includes('MEDIA:')) {+ handleTtsPlayback(sessionId, rewriteId, content);+ }+ return;+ }+ }+ }+ }++ // 未分段:合并进当前流。勿用 payload.timestamp 覆盖消息时间(会与 goal 完成卡抢序)。+ if (streamId && !assistantStreamSplit) {useChatStore.getState().updateMessage(sessionId, streamId, {...(content ? { content } : {}),isStreaming: false,@@ -2246,6 +2357,25 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}return;}+ if (streamId && assistantStreamSplit && content) {+ const streamedMsg = messages.find((m) => m.id === streamId);+ const streamedContent = typeof streamedMsg?.content === 'string' ? streamedMsg.content : '';+ const nextContent = resolveStreamFinalContent(streamedContent, content, true);+ if (nextContent !== undefined) {+ useChatStore.getState().updateMessage(sessionId, streamId, {+ content: nextContent,+ isStreaming: false,+ ...(isProactiveRecommendation ? { isProactiveRecommendation, ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}) } : {}),+ });+ useChatStore.getState().stopStreaming(sessionId);+ if (!nextContent.includes('MEDIA:')) {+ handleTtsPlayback(sessionId, streamId, nextContent);+ }+ return;+ }+ useChatStore.getState().updateMessage(sessionId, streamId, { isStreaming: false });+ useChatStore.getState().stopStreaming(sessionId);+ }if (content) {const cronMeta = payload.cron as Record<string, unknown> | undefined;const cronRunId =@@ -2255,7 +2385,6 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {/正在执行中,结果稍后补发/.test(content) ||/^\[cron\].*正在执行中/.test(content);- // 正式结果:替换同 run_id 的占位气泡,或最近的定时任务「正在执行中」占位if (!isCronPlaceholderContent) {let placeholderId: string | null = null;if (cronRunId) {@@ -2303,7 +2432,81 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {return;}- // 去重:若上一条已是相同内容的助手消息(同一回复被收到两次),不再追加+ if (assistantStreamSplit && !cronRunId && !cronMeta) {+ if (streamId) {+ useChatStore.getState().stopStreaming(sessionId);+ }+ let turnStart = 0;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ if (messages[i].role === 'user') {+ turnStart = i + 1;+ break;+ }+ }+ const shownConcat = messages+ .slice(turnStart)+ .filter((m) => m.role === 'assistant' && typeof m.content === 'string')+ .map((m) => m.content as string)+ .join('');++ let remainder: string;+ if (shownConcat && content.startsWith(shownConcat)) {+ remainder = content.slice(shownConcat.length);+ } else if (shownConcat && collapseWs(content) === collapseWs(shownConcat)) {+ remainder = '';+ } else if (shownConcat && collapseWs(shownConcat).includes(collapseWs(content))) {+ remainder = '';+ } else {+ remainder = content;+ }++ if (!remainder.trim()) {+ const rewriteId = findAssistantSegmentIdForFinal(+ messages,+ content,+ preferredSegmentId || streamId+ );+ if (rewriteId) {+ useChatStore.getState().updateMessage(sessionId, rewriteId, {+ content,+ isStreaming: false,+ });+ if (!content.includes('MEDIA:')) {+ handleTtsPlayback(sessionId, rewriteId, content);+ }+ }+ return;+ }+ const finalMsgId = `msg-final-${Date.now()}`;+ useChatStore.getState().addMessage(sessionId, {+ id: finalMsgId,+ role: 'assistant',+ content: remainder,+ timestamp: new Date().toISOString(),+ isProactiveRecommendation,+ ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}),+ });+ if (!remainder.includes('MEDIA:')) {+ handleTtsPlayback(sessionId, finalMsgId, remainder);+ }+ return;+ }++ const rewriteId = findAssistantSegmentIdForFinal(+ messages,+ content,+ preferredSegmentId || streamId+ );+ if (rewriteId) {+ useChatStore.getState().updateMessage(sessionId, rewriteId, {+ content,+ isStreaming: false,+ });+ if (!content.includes('MEDIA:')) {+ handleTtsPlayback(sessionId, rewriteId, content);+ }+ return;+ }const last = messages[messages.length - 1];if (last?.role === 'assistant' && last.content === content) {return;@@ -2437,6 +2640,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;clearThinkingForVisibleOutput(sessionId);+ useChatStore.getState().closeReasoning(sessionId, {+ atMs: eventTimestampMs(payload),+ });const toolCall = normalizeToolCallPayload(payload);const shutdownMemberId = getShutdownMemberFromToolCall(toolCall);if (shutdownMemberId) {@@ -2465,21 +2671,22 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}const runtime = useChatStore.getState().getRuntime(sessionId);const currentStreamId = runtime?.currentStreamId;- const messages = runtime?.messages ?? [];const toolRequestId = getPayloadRequestId(payload) || activeRequestIdRef.current;- const currentStreamMessage =- currentMode === 'team'- ? findActiveTeamLeaderMessage(sessionId)- : currentStreamId- ? messages.find((msg) => msg.id === currentStreamId)- : undefined;- useChatStore.getState().addToolCall(- sessionId,- toolCall,- currentStreamMessage?.timestamp- ? { startedAt: currentStreamMessage.timestamp, requestId: toolRequestId }- : { requestId: toolRequestId }- );+ // 工具时间戳一律用事件自身时间,与 history 回放(item.at)对齐;勿绑气泡 timestamp。+ const toolStartedAt = normalizeEventTimestampIso(payload.timestamp);+ useChatStore.getState().addToolCall(sessionId, toolCall, {+ startedAt: toolStartedAt,+ requestId: toolRequestId,+ });+ // 工具调用会打断当前这段助手文字:收尾当前流式气泡,令后续文字另起新气泡,+ // 从而实现 codex 风格的「文字 → 工具 → 文字 → 工具」分段交错。+ // agent 模式走 currentStreamId;团队模式的 team-leader 气泡有独立生命周期,+ // 需单独收尾,否则本轮 leader 文字会全部堆进同一条气泡,与刷新后的历史(按段拆分)不一致。+ if (currentMode === 'team') {+ useChatStore.getState().finalizeTeamLeaderSegment(sessionId);+ } else if (currentStreamId) {+ useChatStore.getState().finalizeStreamSegment(sessionId);+ }if (currentMode === 'team' && !isTeamPanelClearedForPayload(payload)) {applyTeamTaskToolCall(sessionId, toolCall);}@@ -2543,7 +2750,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {activeSessionId);}- useChatStore.getState().addToolResult(sessionId, toolResult);+ useChatStore.getState().addToolResult(sessionId, toolResult, {+ updatedAt: normalizeEventTimestampIso(payload.timestamp),+ });}),webClient.on('todo.updated', ({ payload }) => {const sessionId = resolveEventSessionId(payload);diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex eebdcff051..edf3a3ec9f 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -1902,6 +1902,42 @@"waitingTasks": "Waiting Tasks","messageQueue": "Message Queue","parallelProgress": "Parallel tasks running ({{completedCount}}/{{total}} complete)",+ "turnRunning": "Running",+ "turnElapsed": "Took",+ "workCompleted": "Completed {{duration}}",+ "workCompletedFallback": "Completed",+ "workCompletedBoth": "Completed {{thinking}} thoughts, {{tools}} tool calls · {{duration}}",+ "workCompletedBothNoDuration": "Completed {{thinking}} thoughts, {{tools}} tool calls",+ "workCompletedThinking": "Completed {{thinking}} thoughts · {{duration}}",+ "workCompletedThinkingNoDuration": "Completed {{thinking}} thoughts",+ "workCompletedTools": "Completed {{tools}} tool calls · {{duration}}",+ "workCompletedToolsNoDuration": "Completed {{tools}} tool calls",+ "reasoning": {+ "thinking": "Thinking…",+ "thought": "Thought"+ },+ "toolAction": {+ "write": "Write",+ "read": "Read",+ "edit": "Edit",+ "delete": "Delete",+ "move": "Move",+ "rename": "Rename",+ "list": "List",+ "search": "Search",+ "glob": "Find",+ "webSearch": "Web search",+ "fetch": "Fetch",+ "run": "Run",+ "runCode": "Run code",+ "upload": "Upload",+ "sendFile": "Send file",+ "todoCreate": "Create todos",+ "todoModify": "Update todos",+ "todoList": "List todos",+ "todoGet": "Get todo",+ "skill": "View skill"+ },"subtask": {"starting": "Starting...","toolCall": "Calling {{tool}} (#{{count}})",@@ -1920,12 +1956,18 @@"truncated": "result truncated"},"toolGroup": {- "executed": "{{totalPairs}} tool calls executed",+ "running": "Running {{label}}",+ "completed": "Completed {{label}}",+ "category": {+ "file": "file operations",+ "search": "searches",+ "code": "code executions",+ "system": "system calls",+ "other": "tool calls"+ },"sessionExecuted": "{{count}} session tasks completed","sessionCompleted": "Session task completed","sessionFailed": "Session failed",- "pending": "{{pendingCount}} running",- "timeout": "{{timeoutCount}} timed out","latest": "↓ Latest"},"teamActivity": {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 0df191e263..d1d28e5d76 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -1903,6 +1903,42 @@"waitingTasks": "等待任务","messageQueue": "消息队列","parallelProgress": "并行任务执行中 ({{completedCount}}/{{total}} 完成)",+ "turnRunning": "任务执行",+ "turnElapsed": "任务用时",+ "workCompleted": "已完成 {{duration}}",+ "workCompletedFallback": "已完成",+ "workCompletedBoth": "已完成 {{thinking}} 次思考,{{tools}} 次工具调用 · {{duration}}",+ "workCompletedBothNoDuration": "已完成 {{thinking}} 次思考,{{tools}} 次工具调用",+ "workCompletedThinking": "已完成 {{thinking}} 次思考 · {{duration}}",+ "workCompletedThinkingNoDuration": "已完成 {{thinking}} 次思考",+ "workCompletedTools": "已完成 {{tools}} 次工具调用 · {{duration}}",+ "workCompletedToolsNoDuration": "已完成 {{tools}} 次工具调用",+ "reasoning": {+ "thinking": "思考中…",+ "thought": "已完成思考"+ },+ "toolAction": {+ "write": "写入",+ "read": "读取",+ "edit": "编辑",+ "delete": "删除",+ "move": "移动",+ "rename": "重命名",+ "list": "列出",+ "search": "搜索",+ "glob": "查找",+ "webSearch": "联网搜索",+ "fetch": "抓取",+ "run": "执行",+ "runCode": "运行代码",+ "upload": "上传",+ "sendFile": "发送文件",+ "todoCreate": "创建待办",+ "todoModify": "更新待办",+ "todoList": "查看待办",+ "todoGet": "读取待办",+ "skill": "查看技能"+ },"subtask": {"starting": "启动中...","toolCall": "调用 {{tool}} (#{{count}})",@@ -1921,12 +1957,18 @@"truncated": "结果已截断"},"toolGroup": {- "executed": "已执行 {{totalPairs}} 次工具调用",+ "running": "正在{{label}}",+ "completed": "已完成{{label}}",+ "category": {+ "file": "文件操作",+ "search": "搜索",+ "code": "代码执行",+ "system": "系统调用",+ "other": "工具调用"+ },"sessionExecuted": "{{count}} 个会话任务已完成","sessionCompleted": "会话任务已完成","sessionFailed": "会话失败",- "pending": "{{pendingCount}} 个执行中",- "timeout": "{{timeoutCount}} 个超时","latest": "↓ 最新"},"teamActivity": {diff --git a/jiuwenswarm/channels/web/frontend/src/index.css b/jiuwenswarm/channels/web/frontend/src/index.cssindex 9717ec7a0e..ac62103b9d 100644--- a/jiuwenswarm/channels/web/frontend/src/index.css+++ b/jiuwenswarm/channels/web/frontend/src/index.css@@ -559,14 +559,32 @@ select {}.chat-bubble.assistant {- border-color: var(--color-chat-bubble-assistant-border);- background: var(--color-chat-bubble-assistant);+ border-color: transparent;+ background: transparent;+ border-radius: 0;+ padding: 0;+ color: var(--color-text-primary);}.chat-bubble.streaming {animation: chatStreamPulse 1.5s ease-in-out infinite;}+ .chat-bubble.assistant.streaming {+ animation: none;+ }++ .assistant-row {+ gap: 10px;+ align-items: flex-start;+ }++ .assistant-row__avatar {+ flex: 0 0 auto;+ width: 32px;+ margin-top: 2px;+ }+/* AI disclaimer — footer note pinned below the composer */.chat-ai-disclaimer {flex: 0 0 auto;@@ -657,12 +675,53 @@ select {max-width: 100%;}- .chat-markdown :where(pre, table) {+ .chat-markdown :where(pre) {max-width: 100%;overflow-x: auto;font-size: 1em;}+ .chat-markdown-table-wrap {+ display: block;+ width: 100%;+ max-width: 100%;+ overflow-x: auto;+ margin: 0.75em 0 1em;+ border: 1px solid var(--color-border-default);+ border-radius: var(--radius-md);+ background: var(--color-surface-card, transparent);+ }++ .chat-markdown-table-wrap > table {+ width: 100%;+ min-width: 28rem;+ margin: 0;+ border-collapse: collapse;+ border-color: var(--color-border-default);+ font-size: 0.875em;+ line-height: 1.5;+ }++ .chat-markdown-table-wrap :where(th, td) {+ border: 1px solid var(--color-border-default);+ border-color: var(--color-border-default);+ padding: 0.5em 0.75em;+ vertical-align: top;+ text-align: start;+ overflow-wrap: anywhere;+ word-break: break-word;+ }++ .chat-markdown-table-wrap :where(th) {+ background: var(--color-action-secondary);+ color: var(--color-text-strong);+ font-weight: 600;+ }++ .a2ui-message-content {+ white-space: normal;+ }+.chat-markdown :where(pre code) {overflow-wrap: normal;word-break: normal;@@ -928,7 +987,7 @@ select {/* ====== Team Timeline Messages ====== */.team-member-message {width: min(100%, 920px);- margin: 12px auto;+ margin: 0 auto 12px;display: grid;grid-template-columns: 36px minmax(0, 1fr);gap: 12px;@@ -1235,14 +1294,54 @@ select {color: var(--color-feedback-warning);}+ .chat-timeline {+ display: flex;+ flex-direction: column;+ gap: 8px;+ view-transition-name: chat-timeline;+ }++ .chat-timeline > * {+ margin-top: 0;+ margin-bottom: 0;+ }++ @keyframes timeline-fold-in {+ from {+ opacity: 0;+ transform: translateY(6px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+ }+/* ====== Tool Tree ====== */.tool-group-frame {- margin: 8px 0;+ margin: 0;+ animation: timeline-fold-in 0.22s ease both;+ }++ .tool-group-frame:not(.tool-group-frame--team) {+ display: flex;+ gap: 10px;+ align-items: flex-start;+ }++ .tool-group-frame:not(.tool-group-frame--team) > .tool-group-frame__avatar {+ flex: 0 0 32px;+ width: 32px;+ }++ .tool-group-frame:not(.tool-group-frame--team) > .min-w-0 {+ flex: 1 1 auto;+ min-width: 0;}.tool-group-frame--team {width: min(100%, 920px);- margin: 12px auto;+ margin: 0 auto;display: grid;grid-template-columns: 36px minmax(0, 1fr);gap: 12px;@@ -1250,8 +1349,10 @@ select {}.tool-tree {- margin: 8px 0;- padding: 2px 0;+ margin: 0;+ padding: 0;+ --tool-muted: color-mix(in srgb, var(--color-text-secondary) 72%, var(--color-surface-elevated));+ --tool-muted-strong: var(--color-text-secondary);}.tool-tree__notices {@@ -1269,13 +1370,17 @@ select {overflow-wrap: anywhere;}+ .tool-tree__section + .tool-tree__section {+ margin-top: 4px;+ }+.tool-tree__header {width: 100%;display: flex;- align-items: center;- justify-content: space-between;+ align-items: flex-start;+ justify-content: flex-start;gap: 12px;- padding: 4px 0 6px;+ padding: 3px 0;border: 0;background: transparent;color: inherit;@@ -1283,6 +1388,46 @@ select {cursor: pointer;}+ .tool-tree__header-lines {+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .tool-tree__header-line {+ min-width: 0;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ }++ .tool-tree__cat-icon {+ width: 14px;+ height: 14px;+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--tool-muted, var(--color-text-secondary));+ }++ .tool-tree__cat-icon svg {+ width: 14px;+ height: 14px;+ }++ .tool-tree__header-line-text {+ min-width: 0;+ color: var(--tool-muted, var(--color-text-secondary));+ font-size: var(--font-size-xs);+ font-weight: 500;+ line-height: 1.3;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+.tool-tree__header-text {display: flex;flex-direction: column;@@ -1298,37 +1443,236 @@ select {width: fit-content;}- .tool-tree__header-title {- color: var(--color-text-strong);- font-size: var(--font-size-sm);- font-weight: 600;- line-height: 1.25;+ .turn-elapsed {+ display: flex;+ align-items: center;+ justify-content: flex-start;+ gap: 6px;+ margin: 0;+ padding: 0 2px 0 42px;+ font-size: var(--font-size-2xs, 11px);+ color: color-mix(in srgb, var(--color-text-secondary) 72%, var(--color-surface-elevated));}- .tool-tree__chevron {- width: 14px;- height: 14px;+ /* team:与 920px 居中栅格的内容列(36 + 12 = 48px)对齐。 */+ .turn-elapsed--team {+ width: min(100%, 920px);+ margin: 0 auto;+ padding-left: 48px;+ }++ .turn-elapsed__spinner {+ flex-shrink: 0;+ color: var(--color-text-secondary);+ animation: turn-elapsed-spin 0.8s linear infinite;+ }++ .turn-elapsed.is-active .turn-elapsed__label,+ .turn-elapsed.is-active .turn-elapsed__value {+ color: var(--color-text-secondary);+ }++ .turn-elapsed__value {+ font-variant-numeric: tabular-nums;+ color: var(--color-text-secondary);+ }++ @keyframes turn-elapsed-spin {+ to {+ transform: rotate(360deg);+ }+ }++ .completed-work-row {+ display: flex;+ gap: 10px;+ align-items: flex-start;+ margin: 2px 0;+ animation: timeline-fold-in 0.28s ease both;+ }++ .completed-work-row__avatar {+ flex: 0 0 32px;+ width: 32px;+ line-height: 0;+ }++ .completed-work-row--team {+ width: min(100%, 920px);+ margin: 2px auto;+ display: grid;+ grid-template-columns: 36px minmax(0, 1fr);+ gap: 12px;+ align-items: start;+ }++ .completed-work-row--nested {+ margin-left: 0;+ animation: timeline-fold-in 0.24s ease both;+ }++ @keyframes timeline-streak-enter {+ from {+ opacity: 0;+ transform: translateY(10px) scale(0.98);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+ }++ .completed-work-row--streak-enter {+ animation: timeline-streak-enter 0.42s cubic-bezier(0.22, 1, 0.36, 1) both;+ }++ .completed-work-row--nested .completed-work-chip--streak {+ font-size: var(--font-size-2xs, 11px);+ color: color-mix(in srgb, var(--color-text-secondary) 72%, transparent);+ }++ .completed-work-chip {display: inline-flex;align-items: center;- justify-content: center;- color: var(--color-text-secondary);- flex: 0 0 auto;+ gap: 6px;+ max-width: 100%;+ margin: 0;+ padding: 2px 4px 2px 0;+ border: 0;+ background: transparent;+ color: color-mix(in srgb, var(--color-text-secondary) 88%, transparent);+ font-size: var(--font-size-sm, 13px);+ line-height: 1.4;+ cursor: pointer;+ text-align: left;+ transition: color 0.18s ease;}- .tool-tree__chevron svg {- width: 14px;- height: 14px;+ .completed-work-chip:hover {+ color: var(--color-text-primary);}- .tool-tree__chevron.is-open {- transform: rotate(180deg);+ .completed-work-chip__icon {+ display: inline-flex;+ width: 16px;+ height: 16px;+ flex-shrink: 0;+ color: color-mix(in srgb, var(--color-success, #16a34a) 80%, var(--color-text-secondary));+ }++ .completed-work-chip__icon svg {+ width: 16px;+ height: 16px;+ }++ .completed-work-chip__label {+ font-variant-numeric: tabular-nums;+ min-width: 0;+ transition: opacity 0.28s ease, transform 0.28s ease;+ }++ .completed-work-chip .tool-tree-item__disclosure {+ opacity: 0.7;+ transition: transform 0.22s ease, opacity 0.18s ease;+ }++ .reasoning-row {+ margin: 0;+ animation: timeline-fold-in 0.22s ease both;+ }++ .reasoning-row:not(.reasoning-row--team) {+ display: flex;+ gap: 10px;+ align-items: flex-start;+ }++ .reasoning-row:not(.reasoning-row--team) > .reasoning-row__avatar {+ flex: 0 0 32px;+ width: 32px;+ line-height: 0;+ }++ .reasoning-row--team {+ width: min(100%, 920px);+ margin: 0 auto;+ display: grid;+ grid-template-columns: 36px minmax(0, 1fr);+ gap: 12px;+ align-items: start;+ }++ .reasoning-panel {+ --tool-muted: color-mix(in srgb, var(--color-text-secondary) 78%, transparent);+ display: flex;+ flex-direction: column;+ }++ .reasoning-panel .tool-tree__header {+ padding: 2px 0;+ }++ /* 思考正文:用 grid rows 做高度过渡,避免 open 切换时硬切跳变。 */+ .reasoning-panel__collapse {+ display: grid;+ grid-template-rows: 0fr;+ transition: grid-template-rows 0.3s ease;+ }++ .reasoning-panel__collapse.is-open {+ grid-template-rows: 1fr;+ }++ .reasoning-panel__collapse-inner {+ overflow: hidden;+ min-height: 0;+ }++ .reasoning-panel__body {+ margin: 2px 0 2px 20px;+ padding: 6px 10px;+ max-height: 220px;+ overflow-y: auto;+ border-left: 2px solid color-mix(in srgb, var(--color-text-secondary) 22%, transparent);+ color: color-mix(in srgb, var(--color-text-secondary) 82%, transparent);+ font-size: var(--font-size-2xs, 11px);+ line-height: 1.55;+ white-space: pre-wrap;+ word-break: break-word;+ opacity: 0;+ transform: translateY(-4px);+ transition: opacity 0.22s ease, transform 0.22s ease;+ }++ .reasoning-panel__collapse.is-open .reasoning-panel__body {+ opacity: 1;+ transform: translateY(0);+ }++ /* 执行中:不转圈,改用一条明亮窄带从左到右扫过灰字(对比更强、更明显)。 */+ .tool-tree__header-line-text.is-running {+ background: linear-gradient(+ 100deg,+ var(--tool-muted, var(--color-text-secondary)) 0%,+ var(--tool-muted, var(--color-text-secondary)) 42%,+ var(--color-text-primary) 50%,+ var(--tool-muted, var(--color-text-secondary)) 58%,+ var(--tool-muted, var(--color-text-secondary)) 100%+ );+ background-size: 220% 100%;+ -webkit-background-clip: text;+ background-clip: text;+ -webkit-text-fill-color: transparent;+ color: transparent;+ /* reverse:亮带从左向右扫过;节奏放慢,避免闪得太急。 */+ animation: shimmer 2.8s linear infinite reverse;}.tool-tree__list {display: block;width: 100%;max-width: 100%;- max-height: 220px;+ max-height: 480px;overflow-y: auto;padding-left: 0;padding-right: 6px;@@ -1349,32 +1693,156 @@ select {}.tool-tree-item + .tool-tree-item {- margin-top: 2px;+ margin-top: 4px;}.tool-tree-item__button {- width: fit-content;+ width: 100%;max-width: 100%;display: flex;align-items: center;gap: 8px;- padding: 3px 0;+ padding: 4px 8px;+ margin: 0 -8px;+ width: calc(100% + 16px);border: 0;+ border-radius: 7px;background: transparent;color: inherit;text-align: left;cursor: pointer;+ transition: background-color 0.14s ease;+ }++ .tool-tree-item__button:hover {+ background: var(--color-surface-muted);}.tool-tree-item__main {min-width: 0;- width: fit-content;+ flex: 1 1 auto;+ display: inline-flex;+ align-items: center;+ gap: 3px;+ }++ /* 紧贴工具名的展开箭头:默认隐藏,hover 才浮现为「>」,展开后转成向下「v」。 */+ .tool-tree-item__disclosure {+ width: 12px;+ height: 12px;+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--tool-muted, var(--color-text-secondary));+ opacity: 0;+ transition: transform 0.22s ease, opacity 0.16s ease;+ }++ .tool-tree-item__disclosure svg {+ width: 12px;+ height: 12px;+ }++ .tool-tree-item__button:hover .tool-tree-item__disclosure,+ .tool-tree__header:hover .tool-tree-item__disclosure,+ .tool-tree-item__disclosure.is-open {+ opacity: 1;+ }++ .tool-tree-item__disclosure.is-open {+ transform: rotate(90deg);+ }++ /* 详情内联展开:在流内占位、把后续内容顶下去(会话列表式展开),宽度铺满工具组。 */+ .tool-tree-item__detail-wrap {+ width: 100%;+ margin: 2px 0 4px;+ padding: 10px 12px;+ background: color-mix(in srgb, var(--color-surface-elevated) 60%, transparent);+ border: 1px solid color-mix(in srgb, var(--color-border-default) 70%, transparent);+ border-radius: 8px;+ animation: detailReveal 0.2s ease;+ }++ .tool-tree-item__detail {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }++ /* 展开详情里的状态图标也统一为灰色,不用彩色区分。 */+ .tool-tree-item__detail-wrap .tool-status-icon {+ color: var(--color-text-secondary);+ }++ @keyframes detailReveal {+ from {+ opacity: 0;+ transform: translateY(-2px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+ }++ .tool-tree-item__detail-block {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }++ .tool-tree-item__detail-label {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--color-text-tertiary, var(--color-text-secondary));+ font-size: var(--font-size-2xs);+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ opacity: 0.75;+ }++ .tool-tree-item__detail-badge {+ padding: 0 5px;+ border-radius: 4px;+ font-size: var(--font-size-2xs);+ font-weight: 500;+ background: var(--color-surface-muted);+ color: var(--color-text-secondary);+ }++ .tool-tree-item__detail-pre {+ margin: 0;+ max-height: 168px;+ overflow: auto;+ padding: 8px 10px;+ border-radius: 8px;+ background: var(--color-surface-muted);+ border: 1px solid var(--color-border-subtle, var(--color-border-default));+ color: var(--color-text-secondary);+ font-family: var(--font-mono);+ font-size: var(--font-size-2xs);+ line-height: 1.5;+ white-space: pre-wrap;+ word-break: break-word;+ overflow-wrap: anywhere;+ }++ .tool-tree-item__detail-status {display: inline-flex;align-items: center;+ gap: 7px;+ font-size: var(--font-size-2xs);+ font-weight: 500;+ color: var(--color-text-secondary);}.tool-tree-item__button:hover .tool-tree-item__name {- color: var(--color-text-strong);+ color: var(--color-text-secondary);}.tool-status-icon {@@ -1391,6 +1859,14 @@ select {height: 16px;}+ /* 工具行图标统一浅灰,不再用红/绿区分状态(状态含义在展开详情里体现)。 */+ .tool-tree-item__status.is-success,+ .tool-tree-item__status.is-warning,+ .tool-tree-item__status.is-error,+ .tool-tree-item__status.is-pending {+ color: var(--tool-muted, var(--color-text-secondary));+ }+.tool-status-icon.is-success {color: var(--color-feedback-success);}@@ -1407,10 +1883,6 @@ select {color: var(--color-action-primary);}- .tool-status-icon__spinner {- animation: spin 1s linear infinite;- }-.tool-status-icon--lg {width: 32px;height: 32px;@@ -1422,21 +1894,21 @@ select {}.tool-tree-item__status {- width: 15px;- height: 15px;- margin-top: 1px;+ width: 14px;+ height: 14px;}.tool-tree-item__status svg {- width: 15px;- height: 15px;+ width: 14px;+ height: 14px;}.tool-tree-item__name {min-width: 0;- color: var(--color-text-primary);- font-family: var(--font-mono);- font-size: var(--font-size-xs);+ color: var(--tool-muted, var(--color-text-secondary));+ /* 用正文字体而非等宽:等宽字形更宽、更“重”,会显得比外层标题还大。 */+ font-family: inherit;+ font-size: var(--font-size-2xs);line-height: 1.4;white-space: nowrap;overflow: hidden;@@ -1485,6 +1957,23 @@ select {.skill-action-btn:hover {background: var(--color-skill-action-hover);}++ @media (prefers-reduced-motion: reduce) {+ .chat-timeline,+ .completed-work-row,+ .completed-work-row--streak-enter,+ .reasoning-row,+ .tool-group-frame,+ .reasoning-panel__collapse,+ .reasoning-panel__body,+ .tool-tree-item__disclosure,+ .tool-tree-item__detail-wrap,+ .completed-work-chip,+ .completed-work-chip__label {+ animation: none !important;+ transition: none !important;+ }+ }}/* ===========================================@@ -1504,6 +1993,49 @@ select {animation: rise 0.35s var(--ease-out) backwards;}+::view-transition-old(chat-timeline),+::view-transition-new(chat-timeline) {+ animation-duration: 0.4s;+ animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1);+}++::view-transition-old(chat-timeline) {+ animation-name: timeline-vt-fade-out;+}++::view-transition-new(chat-timeline) {+ animation-name: timeline-vt-fade-in;+}++@keyframes timeline-vt-fade-out {+ from {+ opacity: 1;+ transform: translateY(0);+ }+ to {+ opacity: 0;+ transform: translateY(-4px);+ }+}++@keyframes timeline-vt-fade-in {+ from {+ opacity: 0;+ transform: translateY(8px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@media (prefers-reduced-motion: reduce) {+ ::view-transition-old(chat-timeline),+ ::view-transition-new(chat-timeline) {+ animation: none !important;+ }+}+/* Voice recording pulse */@keyframes voice-pulse {0%,diff --git a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.tsindex 8a4ad3854c..9441076c30 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts@@ -33,6 +33,16 @@ import { mergeFileDownloadItems } from '../utils/fileDownloadDedup';const TOOL_TIMEOUT_MS = 12_000_000;const EVOLUTION_STATUS_END_VISIBLE_MS = 3_000;+let reasoningSegmentSeq = 0;++function createReasoningSegmentId(): string {+ reasoningSegmentSeq += 1;+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {+ return `rsn-${crypto.randomUUID()}`;+ }+ return `rsn-${Date.now()}-${reasoningSegmentSeq}-${Math.random().toString(36).slice(2, 10)}`;+}+function computeTimeoutAt(baseIso: string): string {return new Date(Date.parse(baseIso) + TOOL_TIMEOUT_MS).toISOString();}@@ -71,6 +81,15 @@ export interface HistoryPagerMeta {* 单个 session 的对话运行态。* 原全局字段全部迁移到这里,按 session 隔离。*/+export interface ReasoningSegment {+ id: string;+ text: string;+ startedAt: number;+ closed: boolean;+ /** 收尾时刻;用于延迟折进 streak。历史可省略。 */+ closedAt?: number;+}+export interface ChatRuntime {messages: Message[];isProcessing: boolean;@@ -86,6 +105,11 @@ export interface ChatRuntime {isNewSession: boolean;currentStreamContent: string;currentStreamId: string | null;+ /** 本轮是否已按工具边界分段(chat.final 去重)。 */+ assistantStreamSplit: boolean;+ reasoningSegments: ReasoningSegment[];+ /** 「思考中」耗时锚点:仅在可见文字产出时前移。 */+ thinkingAnchorAt: number;messageRenderKeySeq: number;/** 最近一次 chat.error 的错误信息,用于会话列表展示异常标记 */error: string | null;@@ -126,6 +150,9 @@ function createEmptyRuntime(): ChatRuntime {isNewSession: false,currentStreamContent: '',currentStreamId: null,+ assistantStreamSplit: false,+ reasoningSegments: [],+ thinkingAnchorAt: Date.now(),messageRenderKeySeq: 0,error: null,streamBuffers: new Map(),@@ -184,8 +211,19 @@ interface ChatState {replaceHistoryMessages: (sessionId: string, messages: Message[]) => void;updateMessage: (sessionId: string, id: string, updates: Partial<Message>) => void;appendStreamContent: (sessionId: string, content: string, streamKey?: string) => void;+ appendReasoning: (sessionId: string, content: string, options?: { atMs?: number }) => void;+ closeReasoning: (sessionId: string, options?: { atMs?: number }) => void;+ restoreReasoningSegments: (sessionId: string, items: { at: string; text: string }[]) => void;startStreaming: (sessionId: string, messageId: string, streamKey?: string) => void;stopStreaming: (sessionId: string, streamKey?: string) => void;+ finalizeStreamSegment: (sessionId: string, streamKey?: string) => void;+ finalizeTeamLeaderSegment: (sessionId: string) => void;+ clearStreamSplit: (sessionId: string) => void;+ collapseTurnFinal: (+ sessionId: string,+ opts: { kind: 'agent' | 'team'; content: string; finalId: string; timestampIso: string }+ ) => void;+ bumpThinkingAnchor: (sessionId: string) => void;setExecutionError: (sessionId: string, error: string | null) => void;setProcessing: (sessionId: string, status: boolean) => void;setThinking: (sessionId: string, status: boolean) => void;@@ -278,6 +316,7 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)...runtime,messages: [...runtime.messages, ...messages],messageRenderKeySeq,+ ...(message.role === 'user' ? { assistantStreamSplit: false, reasoningSegments: [] } : {}),},},};@@ -301,6 +340,8 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)messageRenderKeySeq: assigned.messageRenderKeySeq,currentStreamContent: '',currentStreamId: null,+ assistantStreamSplit: false,+ reasoningSegments: [],streamBuffers: new Map(),evolutionStatus: null,evolutionStatusClearTimer: null,@@ -370,6 +411,97 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)});},+ appendReasoning: (sessionId, content, options) => {+ if (!content) return;+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const segments = runtime.reasoningSegments;+ const last = segments[segments.length - 1];+ const atMs =+ typeof options?.atMs === 'number' && Number.isFinite(options.atMs)+ ? options.atMs+ : Date.now();+ let next: ReasoningSegment[];+ if (last && !last.closed) {+ next = segments.slice(0, -1).concat({ ...last, text: last.text + content });+ } else {+ next = segments.concat({+ id: createReasoningSegmentId(),+ text: content,+ startedAt: atMs,+ closed: false,+ });+ }+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, reasoningSegments: next },+ },+ };+ });+ },++ closeReasoning: (sessionId, options) => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const segments = runtime.reasoningSegments;+ const last = segments[segments.length - 1];+ if (!last || last.closed) return state;+ const atMs =+ typeof options?.atMs === 'number' && Number.isFinite(options.atMs)+ ? options.atMs+ : Date.now();+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ reasoningSegments: segments.slice(0, -1).concat({+ ...last,+ closed: true,+ closedAt: atMs,+ }),+ },+ },+ };+ });+ },++ restoreReasoningSegments: (sessionId, items) => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const segments: ReasoningSegment[] = [];+ const seen = new Set<string>();+ items.forEach((item, index) => {+ const text = item.text?.trim();+ if (!text || seen.has(text)) return;+ seen.add(text);+ const parsed = Date.parse(item.at);+ // 历史里思考与同一步 final/tool_call 共用落盘时间;减 1ms 仅补齐缺失的独立时间戳,+ // 使时间线能分出「先思考、后动作」,不做跨步骤重排。+ const startedAt = Number.isFinite(parsed) ? parsed - 1 : index;+ segments.push({+ id: `hist-rsn-${sessionId}-${index}-${createReasoningSegmentId()}`,+ text,+ startedAt,+ closed: true,+ // 历史已结束:closedAt 用 startedAt,立刻 settled,且比魔法 0 更可解释。+ closedAt: startedAt,+ });+ });+ segments.sort((a, b) => a.startedAt - b.startedAt);+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, reasoningSegments: segments },+ },+ };+ });+ },+startStreaming: (sessionId, messageId, streamKey = 'default') => {set((state) => {const runtime = state.runtimes[sessionId];@@ -409,6 +541,146 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)});},+ finalizeStreamSegment: (sessionId, streamKey = 'default') => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime || !runtime.currentStreamId) return state;+ const streamingMessage = runtime.messages.find(+ (msg) => msg.id === runtime.currentStreamId+ );+ const hasVisibleText = Boolean(streamingMessage?.content?.trim());+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ messages: runtime.messages.map((msg) =>+ msg.id === runtime.currentStreamId ? { ...msg, isStreaming: false } : msg+ ),+ currentStreamId: null,+ currentStreamContent: '',+ assistantStreamSplit: runtime.assistantStreamSplit || hasVisibleText,+ streamBuffers: new Map(runtime.streamBuffers).set(streamKey, ''),+ },+ },+ };+ });+ },++ finalizeTeamLeaderSegment: (sessionId) => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ let latestUserIndex = -1;+ for (let i = runtime.messages.length - 1; i >= 0; i -= 1) {+ if (runtime.messages[i].role === 'user') {+ latestUserIndex = i;+ break;+ }+ }+ let target: Message | undefined;+ for (let i = runtime.messages.length - 1; i > latestUserIndex; i -= 1) {+ const msg = runtime.messages[i];+ if (msg.id.startsWith('team-leader-') && msg.isStreaming) {+ target = msg;+ break;+ }+ }+ if (!target || !target.content?.trim()) return state;+ const targetId = target.id;+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ messages: runtime.messages.map((msg) =>+ msg.id === targetId ? { ...msg, isStreaming: false } : msg+ ),+ assistantStreamSplit: true,+ },+ },+ };+ });+ },++ clearStreamSplit: (sessionId) => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime || !runtime.assistantStreamSplit) return state;+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, assistantStreamSplit: false },+ },+ };+ });+ },++ collapseTurnFinal: (sessionId, { kind, content, finalId, timestampIso }) => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const msgs = runtime.messages;+ let turnStart = 0;+ for (let i = msgs.length - 1; i >= 0; i -= 1) {+ if (msgs[i].role === 'user') {+ turnStart = i + 1;+ break;+ }+ }+ const isTarget = (m: Message) =>+ kind === 'team'+ ? m.role === 'system' && typeof m.id === 'string' && m.id.startsWith('team-leader-')+ : m.role === 'assistant';+ const kept: Message[] = [];+ let removed = 0;+ for (let i = 0; i < msgs.length; i += 1) {+ if (i >= turnStart && isTarget(msgs[i])) {+ removed += 1;+ continue;+ }+ kept.push(msgs[i]);+ }+ if (removed === 0) return state;+ const displayContent =+ kind === 'team'+ ? `team.leader:${JSON.stringify({ content, timestamp: Date.parse(timestampIso) || Date.now() })}`+ : content;+ kept.push({+ id: finalId,+ role: kind === 'team' ? 'system' : 'assistant',+ content: displayContent,+ timestamp: timestampIso,+ isStreaming: false,+ });+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ messages: kept,+ assistantStreamSplit: false,+ currentStreamId: null,+ currentStreamContent: '',+ },+ },+ };+ });+ },++ bumpThinkingAnchor: (sessionId) => {+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, thinkingAnchorAt: Date.now() },+ },+ };+ });+ },+setExecutionError: (sessionId, error) => {set((state) => {const runtime = state.runtimes[sessionId];@@ -426,6 +698,8 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)set((state) => {const runtime = state.runtimes[sessionId];if (!runtime) return state;+ // 新一轮开始(false→true):把「思考中」耗时锚点归到轮次起点。+ const turnStart = status && !runtime.isProcessing;return {runtimes: {...state.runtimes,@@ -434,6 +708,7 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)isProcessing: status,executionError: status ? null : runtime.executionError,...(status ? { error: null } : {}),+ ...(turnStart ? { thinkingAnchorAt: Date.now() } : {}),},},};@@ -843,6 +1118,13 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)const execution = runtime.toolExecutions.get(toolCallId);if (!execution) return state;const nextExecutions = new Map(runtime.toolExecutions);+ // 进度更新不得把已完成/失败/超时打回 pending,否则 UI 会误显示「执行中」。+ const keepStatus =+ execution.status === 'completed' ||+ execution.status === 'error' ||+ execution.status === 'timeout'+ ? execution.status+ : 'pending';nextExecutions.set(toolCallId, {...execution,result: {@@ -853,8 +1135,9 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)...execution.result,...progress,},- status: 'pending',- updatedAt: new Date().toISOString(),+ status: keepStatus,+ updatedAt:+ keepStatus === 'pending' ? new Date().toISOString() : execution.updatedAt,});return {runtimes: {diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex 762c8a97a7..1a2e5d2bde 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -97,6 +97,7 @@ export interface ToolCall {arguments: Record<string, unknown>;description?: string; // 操作描述,如 "创建 3 个任务"formatted_args?: string; // 格式化参数摘要+ display_name?: string; // 后端下发的可读展示名,前端优先直接展示memberName?: string;}diff --git a/jiuwenswarm/channels/web/frontend/src/utils/chatFinalProtocol.ts b/jiuwenswarm/channels/web/frontend/src/utils/chatFinalProtocol.tsnew file mode 100644index 0000000000..b2dde2602b--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/utils/chatFinalProtocol.ts@@ -0,0 +1,138 @@+/**+ * chat.final 落地协议。+ *+ * 后端可显式下发 final_mode:+ * - replace_turn:用 final 替换本轮全部助手气泡+ * - patch_segment:覆写当前/匹配的分段气泡(工具打断后的常见路径)+ * - append:追加新气泡+ *+ * 无 final_mode 时(旧历史)走收紧后的启发式,不再用宽松 includes 折叠整轮。+ */+import { collapseWs } from './finalContent';++export type ChatFinalMode = 'replace_turn' | 'patch_segment' | 'append';++export type ChatFinalAction =+ | { type: 'replace_turn' }+ | { type: 'patch_segment'; segmentId?: string }+ | { type: 'append' }+ | { type: 'heuristic' };++const A2UI_OPEN_TAG = '<a2ui-json>';++export function contentHasA2UIBlock(text: string): boolean {+ return text.includes(A2UI_OPEN_TAG);+}++export function parseChatFinalMode(payload: Record<string, unknown>): ChatFinalMode | null {+ const raw = payload.final_mode ?? payload.finalMode;+ if (typeof raw !== 'string') return null;+ const mode = raw.trim().toLowerCase();+ if (mode === 'replace_turn' || mode === 'replace-turn' || mode === 'covers_turn') {+ return 'replace_turn';+ }+ if (mode === 'patch_segment' || mode === 'patch-segment' || mode === 'segment') {+ return 'patch_segment';+ }+ if (mode === 'append') {+ return 'append';+ }+ return null;+}++export function parseChatFinalSegmentId(payload: Record<string, unknown>): string | undefined {+ for (const key of ['segment_id', 'segmentId', 'stream_message_id', 'streamMessageId'] as const) {+ const value = payload[key];+ if (typeof value === 'string' && value.trim()) {+ return value.trim();+ }+ }+ return undefined;+}++export function interpretChatFinalAction(payload: Record<string, unknown>): ChatFinalAction {+ const mode = parseChatFinalMode(payload);+ if (mode === 'replace_turn') {+ return { type: 'replace_turn' };+ }+ if (mode === 'patch_segment') {+ return { type: 'patch_segment', segmentId: parseChatFinalSegmentId(payload) };+ }+ if (mode === 'append') {+ return { type: 'append' };+ }+ return { type: 'heuristic' };+}++function collectTurnAssistantParts(+ messages: { role: string; id?: string; content?: string }[],+ kind: 'agent' | 'team'+): string[] {+ let turnStart = 0;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ if (messages[i].role === 'user') {+ turnStart = i + 1;+ break;+ }+ }+ const parts: string[] = [];+ for (const msg of messages.slice(turnStart)) {+ if (kind === 'agent') {+ if (msg.role === 'assistant' && typeof msg.content === 'string' && msg.content) {+ parts.push(msg.content);+ }+ continue;+ }+ if (+ msg.role === 'system' &&+ typeof msg.id === 'string' &&+ msg.id.startsWith('team-leader-') &&+ typeof msg.content === 'string' &&+ msg.content+ ) {+ const raw = msg.content;+ if (raw.startsWith('team.leader:')) {+ try {+ const parsed = JSON.parse(raw.slice('team.leader:'.length)) as { content?: unknown };+ if (typeof parsed?.content === 'string' && parsed.content) {+ parts.push(parsed.content);+ continue;+ }+ } catch {+ // fall through+ }+ }+ parts.push(raw);+ }+ }+ return parts;+}++/**+ * 是否允许折叠整轮。显式 replace_turn 优先;启发式仅允许空白折叠后的精确相等+ *(不再用 final.includes(shown) 的宽松匹配)。+ */+export function shouldCollapseTurnFinal(+ messages: { role: string; id?: string; content?: string }[],+ finalContent: string,+ kind: 'agent' | 'team',+ action: ChatFinalAction = { type: 'heuristic' }+): boolean {+ if (action.type === 'patch_segment' || action.type === 'append') {+ return false;+ }+ if (contentHasA2UIBlock(finalContent)) {+ return false;+ }+ const parts = collectTurnAssistantParts(messages, kind);+ if (parts.some(contentHasA2UIBlock)) {+ return false;+ }+ if (action.type === 'replace_turn') {+ return true;+ }+ const shownN = collapseWs(parts.join(''));+ const finalN = collapseWs(finalContent);+ if (!shownN) return true;+ return finalN === shownN;+}diff --git a/jiuwenswarm/channels/web/frontend/src/utils/finalContent.ts b/jiuwenswarm/channels/web/frontend/src/utils/finalContent.tsindex 9a01343ce9..94a074a8a5 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/finalContent.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/finalContent.ts@@ -1,7 +1,3 @@-/**- * 将 chat.final 的 payload 规范为可展示的纯文本(与实时 WS 处理一致)。- */-function decodeQuotedPythonLikeString(raw: string): string {return raw.replace(/\\r/g, '\r')@@ -12,8 +8,104 @@ function decodeQuotedPythonLikeString(raw: string): string {.replace(/\\\\/g, '\\');}+/** 字面量 `\\n` 明显多于真换行时还原,避免 GFM 表格解析失败。 */+export function unescapeLiteralNewlines(text: string): string {+ const realNl = (text.match(/\n/g) || []).length;+ const litNl = (text.match(/\\n/g) || []).length;+ if (litNl > 0 && litNl > realNl) {+ return text.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\r/g, '\r');+ }+ return text;+}+function normalizeFinalDisplayText(text: string): string {- return text.replace(/^(?:\r?\n)+/, '');+ return unescapeLiteralNewlines(text).replace(/^(?:\r?\n)+/, '');+}++export function collapseWs(value: string): string {+ return value.replace(/\s+/g, ' ').trim();+}++/** 分段收尾时优先用干净 final;整轮拼接则不覆盖本段。 */+export function resolveStreamFinalContent(+ streamed: string,+ finalContent: string,+ isSplit: boolean+): string | undefined {+ if (!finalContent) {+ return undefined;+ }+ if (!isSplit) {+ return finalContent;+ }+ const streamedN = collapseWs(streamed);+ const finalN = collapseWs(finalContent);+ if (!streamedN || streamedN === finalN || finalN.startsWith(streamedN)) {+ return finalContent;+ }+ if (streamedN.includes(finalN) && streamedN.length <= finalN.length + 40) {+ return finalContent;+ }+ if (finalN.includes(streamedN) && finalN.length > streamedN.length + 40) {+ return undefined;+ }+ return undefined;+}++/**+ * 在本轮助手气泡中定位与 final 对应的段。+ * 优先 exact;其次「一方以另一方为前缀」且长度比 ≥ 0.85(不再用宽松 includes)。+ */+export function findAssistantSegmentIdForFinal(+ messages: { role: string; id?: string; content?: string }[],+ finalContent: string,+ preferredSegmentId?: string | null+): string | null {+ const finalN = collapseWs(finalContent);+ if (!finalN) return null;++ let turnStart = 0;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ if (messages[i].role === 'user') {+ turnStart = i + 1;+ break;+ }+ }++ const turn = messages.slice(turnStart);+ if (preferredSegmentId) {+ const preferred = turn.find(+ (msg) => msg.role === 'assistant' && msg.id === preferredSegmentId+ );+ if (preferred?.id) {+ return preferred.id;+ }+ }++ for (let i = turn.length - 1; i >= 0; i -= 1) {+ const msg = turn[i];+ if (msg.role !== 'assistant' || typeof msg.id !== 'string') continue;+ if (typeof msg.content !== 'string' || !msg.content) continue;+ if (collapseWs(msg.content) === finalN) {+ return msg.id;+ }+ }++ for (let i = turn.length - 1; i >= 0; i -= 1) {+ const msg = turn[i];+ if (msg.role !== 'assistant' || typeof msg.id !== 'string') continue;+ if (typeof msg.content !== 'string' || !msg.content) continue;+ const msgN = collapseWs(msg.content);+ if (!msgN) continue;+ const longer = Math.max(msgN.length, finalN.length);+ const shorter = Math.min(msgN.length, finalN.length);+ if (shorter / longer < 0.85) continue;+ if (msgN.startsWith(finalN) || finalN.startsWith(msgN)) {+ return msg.id;+ }+ }++ return null;}export function normalizeFinalContent(payload: Record<string, unknown>): string {@@ -31,12 +123,11 @@ export function normalizeFinalContent(payload: Record<string, unknown>): stringreturn normalizeFinalDisplayText(parsed.output);}} catch {- // ignore: 继续尝试 Python dict 风格兼容解析+ // ignore}}if (!trimmed.includes('result_type') || !trimmed.includes('output')) {- // 处理嵌套在 delta 中的 chat.final 格式try {const parsed = JSON.parse(trimmed) as Record<string, unknown>;if (parsed.delta && typeof parsed.delta === 'object') {diff --git a/jiuwenswarm/channels/web/frontend/src/utils/index.ts b/jiuwenswarm/channels/web/frontend/src/utils/index.tsindex 87ab0f9b6d..c3bd47b96d 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/index.ts@@ -6,5 +6,6 @@ export * from './formatters';export * from './env';export * from './tts';export * from './finalContent';+export * from './chatFinalProtocol';export * from './harnessErrors';export * from './fileDownloadDedup';diff --git a/jiuwenswarm/common/chat_final.py b/jiuwenswarm/common/chat_final.pynew file mode 100644index 0000000000..92b35efa25--- /dev/null+++ b/jiuwenswarm/common/chat_final.py@@ -0,0 +1,47 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""chat.final 落地协议字段。++前端优先读 final_mode,避免用字符串 includes 启发式折叠整轮:+- patch_segment:覆写当前/匹配分段(工具打断后的默认路径)+- replace_turn:用 final 替换本轮全部助手气泡(需显式声明)+- append:追加新气泡+"""+from __future__ import annotations++from typing import Any, Mapping, MutableMapping++FINAL_MODE_PATCH_SEGMENT = "patch_segment"+FINAL_MODE_REPLACE_TURN = "replace_turn"+FINAL_MODE_APPEND = "append"+++def annotate_chat_final(+ payload: Mapping[str, Any] | None,+ *,+ final_mode: str = FINAL_MODE_PATCH_SEGMENT,+) -> dict[str, Any]:+ """确保 chat.final payload 带 final_mode;已有显式值时不覆盖。"""+ out: dict[str, Any] = dict(payload or {})+ if out.get("event_type") and str(out.get("event_type")).strip() != "chat.final":+ return out+ existing = out.get("final_mode")+ if isinstance(existing, str) and existing.strip():+ return out+ out["final_mode"] = final_mode+ out.setdefault("event_type", "chat.final")+ return out+++def ensure_final_mode_inplace(+ payload: MutableMapping[str, Any],+ *,+ final_mode: str = FINAL_MODE_PATCH_SEGMENT,+) -> None:+ """就地写入 final_mode(仅当缺失时)。"""+ if str(payload.get("event_type") or "").strip() not in ("", "chat.final"):+ return+ existing = payload.get("final_mode")+ if isinstance(existing, str) and existing.strip():+ return+ payload["final_mode"] = final_modediff --git a/jiuwenswarm/common/tool_display.py b/jiuwenswarm/common/tool_display.pynew file mode 100644index 0000000000..a2a0fc58be--- /dev/null+++ b/jiuwenswarm/common/tool_display.py@@ -0,0 +1,287 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""工具调用可读展示名。++优先使用主模型在 tool_call 参数里一并给出的 call_goal(一句目标说明,+如「调研 openJiuwen 官网信息」);执行前会从 arguments 剥掉该字段以免 schema 校验失败。+若模型未填,再用规则从工具名+参数兜底。++注意:绝不能用 display_name 作为 UI 字段名——team 的 spawn_teammate / build_team+等工具本身就有必填的 display_name(成员展示名),撞名会导致参数被误剥、持续报错。+"""+from __future__ import annotations++import json+from typing import Any, Mapping++_CALL_GOAL_KEYS = ("call_goal", "callGoal")++_VERB_BY_TOOL: dict[str, str] = {+ "write": "写入", "write_file": "写入", "write_text_file": "写入",+ "create": "写入", "create_file": "写入", "write_memory": "写入",+ "coding_memory_write": "写入", "upload_file": "上传", "send_file_to_user": "发送文件",+ "read": "读取", "read_file": "读取", "read_text_file": "读取", "view": "读取",+ "read_memory": "读取", "memory_get": "读取", "coding_memory_read": "读取",+ "read_mcp_resource": "读取",+ "edit": "编辑", "edit_file": "编辑", "search_replace": "编辑", "apply_patch": "编辑",+ "str_replace": "编辑", "edit_memory": "编辑", "coding_memory_edit": "编辑",+ "delete": "删除", "delete_file": "删除", "remove": "删除", "remove_file": "删除", "rm": "删除",+ "move": "移动", "move_file": "移动", "rename": "重命名", "rename_file": "重命名",+ "list": "列出", "ls": "列出", "list_files": "列出", "list_dir": "列出",+ "list_directory": "列出", "list_directories": "列出",+ "grep": "搜索", "rg": "搜索", "ripgrep": "搜索", "search": "搜索", "search_file": "搜索",+ "memory_search": "搜索", "ltm_search": "搜索", "mem0_search": "搜索", "viking_search": "搜索",+ "glob": "查找", "glob_files": "查找", "glob_file_search": "查找",+ "web_search": "联网搜索", "web_free_search": "联网搜索", "free_search": "联网搜索",+ "web_paid_search": "联网搜索", "paid_search": "联网搜索",+ "web_fetch": "抓取", "web_fetch_webpage": "抓取", "fetch": "抓取", "fetch_webpage": "抓取",+ "run_command": "执行", "run": "执行", "bash": "执行", "shell": "执行", "sh": "执行",+ "exec": "执行", "exec_command": "执行", "execute_bash": "执行", "command": "执行",+ "sandbox_run_command": "执行",+ "run_python": "运行代码", "python": "运行代码", "execute_python": "运行代码",+ "run_code": "运行代码", "execute_code": "运行代码", "code_interpreter": "运行代码", "code": "运行代码",+ "todo_create": "创建待办", "todo_modify": "更新待办", "todo_list": "查看待办", "todo_get": "读取待办",+ "skill_tool": "查看技能",+ # team tools often omit call_goal+ "spawn_member": "创建成员", "spawn_teammate": "创建成员",+ "send_message": "发送消息",+ "build_team": "创建团队",+ "shutdown_member": "关闭成员", "create_task": "创建任务", "update_task": "更新任务",+}++_FILE_VERBS = frozenset(["写入", "读取", "编辑", "删除", "移动", "重命名", "列出", "上传", "发送文件"])+_QUERY_VERBS = frozenset(["搜索", "查找", "联网搜索"])+_COMMAND_VERBS = frozenset(["执行", "运行代码"])+_SKILL_VERBS = frozenset(["查看技能"])+_TODO_VERBS = frozenset(["创建待办", "更新待办", "查看待办", "读取待办"])++_FILE_ARG_KEYS = (+ "target_file", "file_path", "filepath", "filePath", "path",+ "file", "filename", "fileName", "dir", "directory",+ "abs_file_path_list",+)+_QUERY_ARG_KEYS = ("query", "q", "search_query", "searchQuery", "pattern", "keyword", "keywords")+_COMMAND_ARG_KEYS = ("command", "cmd", "script", "code", "source")+_URL_ARG_KEYS = ("url", "uri", "link", "webpage")+_SKILL_ARG_KEYS = ("skill_name", "skillName", "name")++_CALL_GOAL_SCHEMA: dict[str, Any] = {+ "type": "string",+ "description": (+ "一句简短中文,说明这次工具调用要达成的目标(仅界面展示),"+ "例如「调研 openJiuwen 官网信息」「创建三子棋对战团队」「通知 player-x 落子」。"+ "不要只写工具名或裸 URL;不影响工具实际执行。"+ "与工具自带的 display_name(成员/团队展示名)以及 send_message.summary 都不是同一个字段,"+ "调用 spawn_member / spawn_teammate / send_message / build_team 时也必须填写。"+ ),+}+++def _normalize(name: str) -> str:+ result = name.strip().lower()+ for ch in (" ", "-"):+ result = result.replace(ch, "_")+ while "__" in result:+ result = result.replace("__", "_")+ return result+++def _as_mapping(arguments: Any) -> dict[str, Any]:+ if isinstance(arguments, Mapping):+ return dict(arguments)+ if isinstance(arguments, str) and arguments.strip():+ try:+ parsed = json.loads(arguments)+ if isinstance(parsed, Mapping):+ return dict(parsed)+ except (ValueError, TypeError):+ return {}+ return {}+++def _first_string(args: Mapping[str, Any], keys: tuple[str, ...]) -> str:+ for key in keys:+ value = args.get(key)+ if isinstance(value, str) and value.strip():+ trimmed = value.strip()+ if trimmed.startswith("["):+ try:+ parsed = json.loads(trimmed)+ if isinstance(parsed, list):+ for item in parsed:+ if isinstance(item, str) and item.strip():+ return item.strip()+ except (ValueError, TypeError):+ pass+ return trimmed+ if isinstance(value, (list, tuple)):+ for item in value:+ if isinstance(item, str) and item.strip():+ return item.strip()+ return ""+++def _basename(path: str) -> str:+ trimmed = path.rstrip("/\\")+ for sep in ("/", "\\"):+ if sep in trimmed:+ trimmed = trimmed.rsplit(sep, 1)[-1]+ return trimmed+++def _truncate(value: str, max_len: int) -> str:+ one_line = " ".join(value.split())+ return one_line[:max_len] + "…" if len(one_line) > max_len else one_line+++def inject_call_goal_schema(parameters: Any) -> None:+ """给工具 JSON Schema 注入可选 call_goal,供主模型随 tool_call 一并产出。"""+ if not isinstance(parameters, dict):+ return+ props = parameters.get("properties")+ if not isinstance(props, dict):+ props = {}+ parameters["properties"] = props+ # 若工具已有 call_goal 定义则不覆盖;永远不要碰 display_name。+ if "call_goal" not in props:+ props["call_goal"] = dict(_CALL_GOAL_SCHEMA)+ # 清理此前误注入的 UI 用 display_name(仅当描述像我们的 UI 文案时)。+ existing = props.get("display_name")+ if isinstance(existing, dict):+ desc = str(existing.get("description") or "")+ if "界面展示" in desc or "UI only" in desc or "不影响工具实际执行" in desc:+ props.pop("display_name", None)+++_CALL_GOAL_MAX_LEN = 200+++def extract_call_goal(arguments: Any) -> tuple[str, Any]:+ """从 arguments 取出 call_goal,并返回剥掉该字段后的 arguments(保持原类型风格)。++ 不会触碰 display_name(team 成员名等业务字段)。+ call_goal 截断到 _CALL_GOAL_MAX_LEN,避免异常超长撑爆展示/事件负载。+ """+ if isinstance(arguments, Mapping):+ cleaned = dict(arguments)+ name = ""+ for key in _CALL_GOAL_KEYS:+ raw = cleaned.pop(key, None)+ if isinstance(raw, str) and raw.strip() and not name:+ name = _truncate(raw.strip(), _CALL_GOAL_MAX_LEN)+ return name, cleaned++ if isinstance(arguments, str) and arguments.strip():+ try:+ parsed = json.loads(arguments)+ except (ValueError, TypeError):+ return "", arguments+ if not isinstance(parsed, Mapping):+ return "", arguments+ name, cleaned_map = extract_call_goal(parsed)+ return name, json.dumps(cleaned_map, ensure_ascii=False)++ return "", arguments+++def _format_message_to(to_value: Any) -> str:+ if isinstance(to_value, list):+ names = [str(item).strip() for item in to_value if str(item).strip()]+ if not names:+ return ""+ if len(names) == 1:+ return names[0]+ if len(names) <= 3:+ return "、".join(names)+ return f"{names[0]} 等{len(names)}人"+ if isinstance(to_value, str) and to_value.strip():+ raw = to_value.strip()+ return "全员" if raw == "*" else raw+ return ""+++def build_tool_display_name(name: str, arguments: Any) -> str:+ """规则兜底:根据工具名+参数组可读展示名;无法可靠组出时返回空串。"""+ if not name:+ return ""+ verb = _VERB_BY_TOOL.get(_normalize(name))+ if not verb:+ return ""++ args = _as_mapping(arguments)+ for key in _CALL_GOAL_KEYS:+ args.pop(key, None)++ file = _first_string(args, _FILE_ARG_KEYS)+ query = _first_string(args, _QUERY_ARG_KEYS)+ command = _first_string(args, _COMMAND_ARG_KEYS)+ url = _first_string(args, _URL_ARG_KEYS)+ skill = _first_string(args, _SKILL_ARG_KEYS)++ # team:优先复用工具自身语义字段(summary / desc),避免漏 call_goal 时 UI 空白。+ if verb == "发送消息":+ summary = _first_string(args, ("summary",))+ if summary:+ return _truncate(summary, 48)+ to_label = _format_message_to(args.get("to"))+ content = _first_string(args, ("content", "message", "text"))+ if to_label and content:+ return f"{verb}给 {to_label}:{_truncate(content, 32)}"+ if to_label:+ return f"{verb}给 {to_label}"+ if content:+ return f"{verb} {_truncate(content, 40)}"+ return verb++ if verb == "创建成员":+ desc = _first_string(args, ("desc", "description", "prompt"))+ member = _first_string(args, ("display_name", "member_name", "name"))+ if desc:+ return _truncate(desc, 48)+ if member:+ return f"{verb} {member}"+ return verb++ if verb == "创建团队":+ team = _first_string(args, ("display_name", "team_desc", "team_name"))+ return f"{verb} {team}" if team else verb++ if verb == "关闭成员":+ member = _first_string(args, ("member_name", "display_name", "name"))+ return f"{verb} {member}" if member else verb++ if verb in ("创建任务", "更新任务"):+ title = _first_string(args, ("title", "content", "task", "description", "desc"))+ return f"{verb} {_truncate(title, 40)}" if title else verb++ if verb in _FILE_VERBS and file:+ return f"{verb} {_basename(file)}"+ if verb in _QUERY_VERBS and query:+ return f'{verb} "{_truncate(query, 40)}"'+ if verb == "抓取" and url:+ return f"{verb} {_truncate(url, 48)}"+ if verb in _COMMAND_VERBS and command:+ return f"{verb} {_truncate(command, 40)}"+ if verb in _SKILL_VERBS and skill:+ return f"{verb} {skill}"+ if verb == "创建待办":+ tasks = args.get("tasks")+ count = len(tasks) if isinstance(tasks, list) else 0+ return f"{verb} {count}" if count else verb+ if verb == "更新待办":+ action = args.get("action")+ if isinstance(action, str) and action.strip():+ return f"{verb} {action.strip()}"+ return verb+ if verb in _TODO_VERBS:+ return verb++ fallback = (+ _basename(file) if file+ else f'"{_truncate(query, 40)}"' if query+ else _truncate(command, 40) if command+ else _truncate(url, 48) if url+ else skill if skill+ else ""+ )+ return f"{verb} {fallback}" if fallback else ""diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.pyindex f0fc8089e1..237ba39d03 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py@@ -56,6 +56,7 @@ _WEB_FULL_PAYLOAD_EVENT_TYPES = frozenset("connection.ack","todo.updated","chat.tool_call",+ "chat.tool_update","chat.tool_result","chat.processing_status","chat.interrupt_result",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 5f689adb59..382739eb2c 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -39,6 +39,7 @@ from jiuwenswarm.server.utils.utils import is_team_paramsfrom jiuwenswarm.common.config import get_configfrom jiuwenswarm.extensions.registry import ExtensionRegistryfrom jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+from jiuwenswarm.common.chat_final import ensure_final_mode_inplacefrom jiuwenswarm.extensions.hook_event import AgentServerHookEventsfrom jiuwenswarm.extensions.hooks_context import MemoryHookContextfrom jiuwenswarm.common.schema.message import EventType, ReqMethod@@ -2474,6 +2475,8 @@ class JiuWenSwarm:elif et == "chat.tool_call":_persist_pending_final_text()elif et == "chat.final":+ if isinstance(data.payload, dict):+ ensure_final_mode_inplace(data.payload)if suppress_a2ui_stream or a2ui_split is not None:first_a2ui_suppression = not suppress_a2ui_streamif first_a2ui_suppression:@@ -2553,6 +2556,8 @@ class JiuWenSwarm:rid,)continue+ if et == "chat.final":+ ensure_final_mode_inplace(data)if et == "chat.delta":final_answer_chunks.append(payload_content)if suppress_a2ui_stream or a2ui_split is not None: