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): align live/history chat UI for tools, files, and turn duration
zhengshangyi80310f3bbda7
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 0691cf7a56..2e5f25701f 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -670,6 +670,8 @@ function AppContent() {toolCallId: n.toolCallId,summary: n.summary,skillTree: n.skillTree,+ ...(n.timedOut ? { timedOut: true } : {}),+ ...(n.beamSearch ? { beamSearch: n.beamSearch } : {}),},{ updatedAt: item.at });@@ -1420,6 +1422,8 @@ function AppContent() {toolCallId: n.toolCallId,summary: n.summary,skillTree: n.skillTree,+ ...(n.timedOut ? { timedOut: true } : {}),+ ...(n.beamSearch ? { beamSearch: n.beamSearch } : {}),},{ updatedAt: item.at });diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsxindex 8798c8b12d..d8c58bca89 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx@@ -108,6 +108,7 @@ function CompletedWorkChip({variant,thinkingCount = 0,toolCount = 0,+ outcomeTone = 'neutral',expanded,onToggle,showAvatar,@@ -116,6 +117,7 @@ function CompletedWorkChip({variant: 'turn' | 'streak';thinkingCount?: number;toolCount?: number;+ outcomeTone?: 'success' | 'partial' | 'error' | 'neutral';expanded: boolean;onToggle: () => void;showAvatar: boolean;@@ -126,7 +128,18 @@ function CompletedWorkChip({const label =variant === 'turn'? t('chatUi.workCompletedFallback')- : formatStreakSummaryLabel(t, thinkingCount, toolCount);+ : formatStreakSummaryLabel(t, thinkingCount, toolCount, outcomeTone);+ // 最外层「已完成」始终绿勾;展开后的 streak:全成功绿勾 / 部分失败黄勾+标签 / 全失败红叉。+ const applyOutcome = variant === 'streak';+ const showErrorIcon = applyOutcome && outcomeTone === 'error';+ const showPartialBadge = applyOutcome && outcomeTone === 'partial';+ const toneClass = !applyOutcome+ ? 'is-success'+ : outcomeTone === 'error'+ ? 'is-error'+ : outcomeTone === 'partial'+ ? 'is-partial'+ : 'is-success';const chip = (<button@@ -134,18 +147,31 @@ function CompletedWorkChip({className={clsx('completed-work-chip',variant === 'streak' && 'completed-work-chip--streak',- expanded && 'is-expanded'+ expanded && 'is-expanded',+ toneClass)}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 className={clsx('completed-work-chip__icon', toneClass)} aria-hidden="true">+ {showErrorIcon ? (+ <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.6 7.6 4.8 4.8M12.4 7.6l-4.8 4.8" />+ </svg>+ ) : (+ <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>+ {showPartialBadge ? (+ <span className="completed-work-chip__badge is-partial">+ {t('chatUi.workOutcomePartial')}+ </span>+ ) : null}<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" />@@ -438,6 +464,7 @@ export function ChatTimelineList({<CompletedWorkChipkey={`completed-work-${item.turnId}`}variant="turn"+ outcomeTone={meta.outcomeTone}expanded={turnOpen}onToggle={() => toggleTurn(item.turnId)}showAvatar@@ -512,6 +539,7 @@ export function ChatTimelineList({<CompletedWorkChipkey={`completed-work-${item.turnId}`}variant="turn"+ outcomeTone={meta.outcomeTone}expanded={turnOpen}onToggle={() => toggleTurn(item.turnId)}// 折叠条就是该轮视觉顶部:头像必须挂在这里,不能跟 meta/内容区抢来抢去。@@ -531,6 +559,7 @@ export function ChatTimelineList({variant="streak"thinkingCount={streak.thinkingCount}toolCount={streak.toolCount}+ outcomeTone={streak.outcomeTone}expanded={streakOpen}onToggle={() => toggleStreak(streak.id)}// 仅当这条 streak 本身吃到了本轮顶部头像时才画;后续 streak 一律不画diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsxindex 664479054c..f2a3ff0796 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx@@ -33,7 +33,12 @@ function ToolStatusIcon({<circle cx="10" cy="10" r="6.8" /><path strokeLinecap="round" strokeLinejoin="round" d="M7.2 10.15 9.1 12.05l3.7-4.05" /></svg>- ) : tone === 'error' || tone === 'warning' ? (+ ) : tone === 'error' ? (+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">+ <circle cx="10" cy="10" r="6.8" />+ <path strokeLinecap="round" d="m7.6 7.6 4.8 4.8M12.4 7.6l-4.8 4.8" />+ </svg>+ ) : tone === 'warning' ? (<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="10" cy="10" r="6.8" /><path strokeLinecap="round" d="M10 6.4v4.5" />@@ -49,8 +54,25 @@ function ToolStatusIcon({);}-function isToolResultSuccessful(result?: ToolExecution['result']) {- return Boolean(result?.success && !result.result.includes('success=False'));+export function isToolResultSuccessful(result?: ToolExecution['result']) {+ if (!result) {+ return false;+ }+ if (result.timedOut) {+ return false;+ }+ return Boolean(result.success && !result.result.includes('success=False'));+}++/** 失败与超时统一按失败态展示(文案可区分超时)。 */+export function isToolExecutionFailed(execution: ToolExecution): boolean {+ if (execution.status === 'error' || execution.status === 'timeout') {+ return true;+ }+ if (execution.result && !isToolResultSuccessful(execution.result)) {+ return true;+ }+ return false;}function getExecutionLabel(@@ -126,16 +148,27 @@ export function collectViewedSkillIds(executions: ToolExecution[]): string[] {return Array.from(out);}-/** 行内下拉展开的工具详情:展示参数与结果(替代原弹窗)。 */+/** 行内下拉展开的工具详情:工具名 + 参数 + 结果(替代原弹窗)。 */function ToolExecutionDetails({ execution }: { execution: ToolExecution }) {const { t } = useTranslation();const { toolCall, result, status } = execution;- const isTimeout = status === 'timeout';- const resultSuccess = isToolResultSuccessful(result);+ const isTimeout = status === 'timeout' || Boolean(result?.timedOut);+ const failed = isToolExecutionFailed(execution);+ const resultSuccess = Boolean(result) && !failed;const hasArguments = Object.keys(toolCall.arguments).length > 0;+ const toolNameLabel = toolCall.name?.trim() || result?.toolName || 'tool';return (<div className="tool-tree-item__detail">+ <div className="tool-tree-item__detail-block">+ <div className="tool-tree-item__detail-label">+ {t('chatUi.toolResult.toolName')}+ </div>+ <pre className="tool-tree-item__detail-pre tool-tree-item__detail-pre--name">+ {toolNameLabel}+ </pre>+ </div>+{hasArguments && (<div className="tool-tree-item__detail-block"><div className="tool-tree-item__detail-label">@@ -151,9 +184,20 @@ function ToolExecutionDetails({ execution }: { execution: ToolExecution }) {<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')}+ {failed && (+ <span+ className={clsx(+ 'tool-tree-item__detail-badge',+ 'is-error',+ isTimeout && 'is-timeout'+ )}+ >+ {isTimeout ? t('chatUi.toolResult.timeout') : t('chatUi.toolResult.failed')}+ </span>+ )}+ {resultSuccess && (+ <span className="tool-tree-item__detail-badge is-success">+ {t('chatUi.toolResult.success')}</span>)}</div>@@ -162,6 +206,7 @@ function ToolExecutionDetails({ execution }: { execution: ToolExecution }) {<preclassName={clsx('tool-tree-item__detail-pre',+ failed && 'is-failed',result.skillTree && 'mt-2')}>@@ -172,8 +217,8 @@ function ToolExecutionDetails({ execution }: { execution: ToolExecution }) {)}{!result && isTimeout && (- <div className="tool-tree-item__detail-status is-warning">- <ToolStatusIcon tone="warning" />+ <div className="tool-tree-item__detail-status is-error">+ <ToolStatusIcon tone="error" /><span>{t('chatUi.toolResult.timeout')}</span></div>)}@@ -211,6 +256,7 @@ interface GroupHeaderLine {category: ToolCategory;text: string;running: boolean;+ failed: boolean;executions: ToolExecution[];}@@ -226,15 +272,19 @@ function buildGroupLines(return executions.map((execution) => {const category = classifyToolCall(execution.toolCall.name);const running = isDisplayRunning(execution);+ const failed = !running && isToolExecutionFailed(execution);const label = getExecutionLabel(execution, sessionCompletedLabel, t);return {key: execution.toolCallId,category,running,+ failed,executions: [execution],text: running? t('chatUi.toolGroup.running', { label })- : t('chatUi.toolGroup.completed', { label }),+ : failed+ ? t('chatUi.toolGroup.failed', { label })+ : t('chatUi.toolGroup.completed', { label }),};});}@@ -347,7 +397,13 @@ export function ToolGroupDisplay({><span className="tool-tree__header-line"><CategoryIcon category={line.category} />- <span className={clsx('tool-tree__header-line-text', line.running && 'is-running')}>+ <span+ className={clsx(+ 'tool-tree__header-line-text',+ line.running && 'is-running',+ line.failed && 'is-failed'+ )}+ >{line.text}</span><spandiff --git a/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.ts b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.tsindex 4cb7f67031..fb62c4db26 100644--- a/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/buildTurnTimeline.ts@@ -4,7 +4,10 @@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 {+ collectViewedSkillIds,+ isToolExecutionFailed,+} from '../../components/ChatPanel/ToolGroupDisplay';import { isTeamMemberCollaborationMessage } from '../../components/ChatPanel/teamEventUtils';import { isA2UIClientEventContent } from '../a2ui/a2uiContent';import { parseTimestampToMs } from '../../utils/timestamp';@@ -464,7 +467,9 @@ function insertTurnSummaries(items: RenderItem[], isProcessing: boolean): Render}} else if (item.type === 'message') {hasActivity = true;+ // timestamp:首包/落盘时间(排序用);completedAt:chat.final 收尾(live 流式合并时才有)acc(toTimestampMs(item.message.timestamp), true);+ acc(toTimestampMs(item.message.completedAt), true);} else if (item.type === 'reasoning') {hasActivity = true;hasWork = true;@@ -483,6 +488,48 @@ function insertTurnSummaries(items: RenderItem[], isProcessing: boolean): Renderreturn out;}+/** 折叠芯片图标色:全成功绿勾 / 有失败但还有成功项→部分失败 / 全失败红叉 / 无工具中性绿 */+export type WorkOutcomeTone = 'success' | 'partial' | 'error' | 'neutral';++/**+ * @param successCount 成功的工具数+ * @param failedCount 失败/超时的工具数+ * @param thinkingCount 已完成的思考段数(思考成功也算「有成功项」,避免「2 次思考 + 1 次工具失败」误标红叉)+ */+export function resolveWorkOutcomeTone(+ successCount: number,+ failedCount: number,+ thinkingCount = 0+): WorkOutcomeTone {+ const hasSuccessWork = successCount > 0 || thinkingCount > 0;+ if (failedCount <= 0) {+ return hasSuccessWork ? 'success' : 'neutral';+ }+ if (!hasSuccessWork) {+ return 'error';+ }+ return 'partial';+}++function accumulateToolOutcomes(+ executions: ToolExecution[],+ into: { toolSuccessCount: number; toolFailedCount: number }+): void {+ for (const execution of executions) {+ if (isDeliverableToolName(execution.toolCall.name)) {+ continue;+ }+ if (isExecutionRunning(execution)) {+ continue;+ }+ if (isToolExecutionFailed(execution)) {+ into.toolFailedCount += 1;+ } else {+ into.toolSuccessCount += 1;+ }+ }+}+export type TurnWorkMeta = {turnId: number;completed: boolean;@@ -495,6 +542,9 @@ export type TurnWorkMeta = {showAvatar: boolean;thinkingCount: number;toolCount: number;+ toolSuccessCount: number;+ toolFailedCount: number;+ outcomeTone: WorkOutcomeTone;};const DELIVERABLE_TOOL_NAMES = new Set(['send_file_to_user']);@@ -529,6 +579,26 @@ function countToolsInGroup(item: Extract<RenderItem, { type: 'toolGroup' }>): nureturn item.executions.filter((execution) => !isDeliverableToolName(execution.toolCall.name)).length;}+function emptyTurnMeta(turnId: number, partial?: Partial<TurnWorkMeta>): TurnWorkMeta {+ return {+ turnId,+ completed: false,+ hasWork: false,+ firstWorkKey: null,+ startMs: Number.NaN,+ endMs: Number.NaN,+ workStartMs: Number.NaN,+ workEndMs: Number.NaN,+ showAvatar: true,+ thinkingCount: 0,+ toolCount: 0,+ toolSuccessCount: 0,+ toolFailedCount: 0,+ outcomeTone: 'neutral',+ ...partial,+ };+}+export function buildTurnWorkMeta(items: RenderItem[], isProcessing: boolean): Map<number, TurnWorkMeta> {const map = new Map<number, TurnWorkMeta>();let lastTurnId = Number.NEGATIVE_INFINITY;@@ -536,19 +606,24 @@ export function buildTurnWorkMeta(items: RenderItem[], isProcessing: boolean): Mif (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,- workStartMs: item.workStartMs,- workEndMs: item.workEndMs,- showAvatar: prev?.showAvatar ?? true,- thinkingCount: prev?.thinkingCount ?? 0,- toolCount: prev?.toolCount ?? 0,- });+ map.set(+ item.turnId,+ emptyTurnMeta(item.turnId, {+ completed: !(item.isLastTurn && isProcessing),+ hasWork: item.hasWork || Boolean(prev?.hasWork),+ firstWorkKey: prev?.firstWorkKey ?? null,+ startMs: item.startMs,+ endMs: item.endMs,+ workStartMs: item.workStartMs,+ workEndMs: item.workEndMs,+ showAvatar: prev?.showAvatar ?? true,+ thinkingCount: prev?.thinkingCount ?? 0,+ toolCount: prev?.toolCount ?? 0,+ toolSuccessCount: prev?.toolSuccessCount ?? 0,+ toolFailedCount: prev?.toolFailedCount ?? 0,+ outcomeTone: prev?.outcomeTone ?? 'neutral',+ })+ );continue;}if (item.type !== 'reasoning' && item.type !== 'toolGroup') {@@ -566,21 +641,20 @@ export function buildTurnWorkMeta(items: RenderItem[], isProcessing: boolean): Mprev.thinkingCount += 1;} else {prev.toolCount += countToolsInGroup(item);+ accumulateToolOutcomes(item.executions, prev);}} else {- map.set(item.turnId, {- turnId: item.turnId,- completed: false,+ const next = emptyTurnMeta(item.turnId, {hasWork: true,firstWorkKey: item.key,- startMs: Number.NaN,- endMs: Number.NaN,- workStartMs: Number.NaN,- workEndMs: Number.NaN,showAvatar: item.showAvatar,thinkingCount: item.type === 'reasoning' ? 1 : 0,toolCount: item.type === 'toolGroup' ? countToolsInGroup(item) : 0,});+ if (item.type === 'toolGroup') {+ accumulateToolOutcomes(item.executions, next);+ }+ map.set(item.turnId, next);}}for (const meta of map.values()) {@@ -589,6 +663,11 @@ export function buildTurnWorkMeta(items: RenderItem[], isProcessing: boolean): M}const isLast = Number.isFinite(lastTurnId) && meta.turnId === lastTurnId;meta.completed = !(isProcessing && isLast);+ meta.outcomeTone = resolveWorkOutcomeTone(+ meta.toolSuccessCount,+ meta.toolFailedCount,+ meta.thinkingCount+ );// 折叠条是该轮顶部锚点:只要本轮有可折叠工作,头像就归折叠条,避免被中间气泡抢走后整轮「没头像」。if (meta.hasWork) {meta.showAvatar = true;@@ -634,6 +713,9 @@ export type LiveWorkStreak = {keys: Set<string>;thinkingCount: number;toolCount: number;+ toolSuccessCount: number;+ toolFailedCount: number;+ outcomeTone: WorkOutcomeTone;showAvatar: boolean;};@@ -751,7 +833,7 @@ export function streakMapFingerprint(streaks: Map<string, LiveWorkStreak>): strireturn [...streaks.values()].map((streak) =>- `${streak.id}:${streak.thinkingCount}:${streak.toolCount}:${[...streak.keys].join(',')}`+ `${streak.id}:${streak.thinkingCount}:${streak.toolCount}:${streak.toolSuccessCount}:${streak.toolFailedCount}:${streak.outcomeTone}:${[...streak.keys].join(',')}`).sort().join('|');@@ -804,11 +886,33 @@ export function buildLiveCompletedStreaks(const seal = () => {if (streak && streak.thinkingCount + streak.toolCount >= 2) {+ streak.outcomeTone = resolveWorkOutcomeTone(+ streak.toolSuccessCount,+ streak.toolFailedCount,+ streak.thinkingCount+ );sealed.set(streak.firstKey, streak);}streak = null;};+ const startStreak = (item: Extract<RenderItem, { type: 'reasoning' | 'toolGroup' }>): LiveWorkStreak => {+ const ordinal = nextOrdinal(item.turnId);+ return {+ id: streakExpandKey(item.turnId, ordinal),+ turnId: item.turnId,+ ordinal,+ firstKey: item.key,+ keys: new Set(),+ thinkingCount: 0,+ toolCount: 0,+ toolSuccessCount: 0,+ toolFailedCount: 0,+ outcomeTone: 'neutral',+ showAvatar: item.showAvatar,+ };+ };+for (const item of items) {if (item.type === 'turnSummary') {continue;@@ -824,17 +928,7 @@ export function buildLiveCompletedStreaks(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 = startStreak(item);}streak.keys.add(item.key);streak.thinkingCount += 1;@@ -852,20 +946,11 @@ export function buildLiveCompletedStreaks(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 = startStreak(item);}streak.keys.add(item.key);streak.toolCount += workToolCount;+ accumulateToolOutcomes(item.executions, streak);}seal();return sealed;@@ -874,8 +959,13 @@ export function buildLiveCompletedStreaks(export function formatStreakSummaryLabel(t: (key: string, options?: Record<string, unknown>) => string,thinkingCount: number,- toolCount: number+ toolCount: number,+ outcomeTone: WorkOutcomeTone = 'neutral'): string {+ // 工具全失败且无成功思考:文案用「失败」,不要「已完成」。+ if (outcomeTone === 'error' && toolCount > 0 && thinkingCount <= 0) {+ return t('chatUi.workFailedToolsNoDuration', { tools: toolCount });+ }if (thinkingCount > 0 && toolCount > 0) {return t('chatUi.workCompletedBothNoDuration', { thinking: thinkingCount, tools: toolCount });}diff --git a/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.ts b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.tsindex 582147a2d3..5c730c2fae 100644--- a/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/chatTimeline/index.ts@@ -21,4 +21,6 @@ export {type RenderItem,type TurnWorkMeta,type LiveWorkStreak,+ type WorkOutcomeTone,+ resolveWorkOutcomeTone,} from './buildTurnTimeline';diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex 5ab29a33b7..9ef8580d8f 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -600,6 +600,121 @@ function parseHistoryTimelineEntry(return null;}+function isAssistantLikeHistoryMessage(message: Message): boolean {+ return (+ message.role === 'assistant' ||+ (message.role === 'system' && Boolean(message.id?.startsWith('team-leader-')))+ );+}++/**+ * 与实时 `addFileItems` 对齐:chat.file 挂到「已经出现的」最近一条助手消息。+ * 旧逻辑挂到下一条 final,会导致刷新后文件从总结上方跑到总结气泡内部下方。+ */+function attachFilesToPreviousAssistant(messages: Message[], files: FileDownloadItem[]): boolean {+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ if (!isAssistantLikeHistoryMessage(messages[i])) {+ continue;+ }+ messages[i] = {+ ...messages[i],+ fileItems: mergeFileDownloadItems(messages[i].fileItems, files),+ };+ return true;+ }+ return false;+}++function createFileOnlyAssistantMessage(at: string, files: FileDownloadItem[]): Message {+ const timestamp = at.trim() || new Date().toISOString();+ return {+ id: `hist-file-${timestamp}`,+ role: 'assistant',+ content: '',+ timestamp,+ fileItems: files,+ };+}++interface MaterializedHistoryTimeline {+ messages: Message[];+ toolReplay: HistoryToolReplayItem[];+ harnessReplay: HistoryHarnessReplayItem[];+ teamReplay: HistoryTeamReplayItem[];+ reasoningReplay: HistoryReasoningReplayItem[];+}++/** 将已按时间升序的 history 条目折叠成消息/工具/思考,供 restore / page / 文件预览共用。 */+function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): MaterializedHistoryTimeline {+ const messages: Message[] = [];+ const toolReplay: HistoryToolReplayItem[] = [];+ const harnessReplay: HistoryHarnessReplayItem[] = [];+ const teamReplay: HistoryTeamReplayItem[] = [];+ const reasoningReplay: HistoryReasoningReplayItem[] = [];++ for (const e of entries) {+ if (e.kind === 'message') {+ messages.push(e.message);+ continue;+ }+ if (e.kind === 'usage_summary') {+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ if (messages[i].role === 'assistant') {+ messages[i] = { ...messages[i], usageSummary: e.usage };+ break;+ }+ }+ continue;+ }+ if (e.kind === 'harness_message') {+ harnessReplay.push({+ kind: 'harness_message',+ at: e.at,+ payload: { content: e.content, stage: e.stage },+ });+ messages.push({+ id: `harness-msg-${e.at}`,+ role: 'system',+ content: e.content,+ timestamp: e.at,+ isHarnessMessage: true,+ });+ continue;+ }+ if (e.kind === 'harness_stage_result') {+ harnessReplay.push({+ kind: 'harness_stage_result',+ at: e.at,+ payload: {+ stage: e.stage,+ status: e.status,+ error: e.error,+ messages: e.messages,+ metrics: e.metrics,+ },+ });+ continue;+ }+ if (e.kind === 'file_items') {+ if (!attachFilesToPreviousAssistant(messages, e.files)) {+ messages.push(createFileOnlyAssistantMessage(e.at, e.files));+ }+ continue;+ }+ if (e.kind === 'team_member' || e.kind === 'team_task') {+ teamReplay.push({ kind: e.kind, at: e.at, payload: e.payload });+ continue;+ }+ if (e.kind === 'reasoning') {+ reasoningReplay.push({ at: e.at, text: e.text });+ continue;+ }+ toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });+ }++ return { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay };+}+/*** 将磁盘上的 history.json 解析结果(通常为记录数组)转为与历史恢复相同的筛选规则下的消息列表,* 并按时间升序返回全部可展示的用户/助手消息。@@ -629,9 +744,7 @@ export function parseHistoryJsonFileToTimelinePreview(return { messages: [], executions: [], reasoningSegments: [], mode: null };}- const messages: Message[] = [];- const toolReplay: HistoryToolReplayItem[] = [];- const reasoningReplay: HistoryReasoningReplayItem[] = [];+ const entries: HistoryTimelineEntry[] = [];let isTeam = false;for (const item of parsed) {@@ -642,19 +755,23 @@ export function parseHistoryJsonFileToTimelinePreview(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 });+ if (entry) {+ entries.push(entry);}const reasoningText = extractHistoryReasoningText(item);if (reasoningText) {- reasoningReplay.push({ at: recordTimestampIso(item) ?? '', text: reasoningText });+ entries.push({ kind: 'reasoning', at: recordTimestampIso(item) ?? '', text: reasoningText });}}- messages.sort((a, b) => safeTimestampMs(a.timestamp) - safeTimestampMs(b.timestamp));+ // 文件预览按记录原始顺序;同戳时 sourceIndex 由后续 timeline 排序兜底。+ entries.sort((a, b) => {+ const aAt = a.kind === 'message' ? a.message.timestamp : a.at;+ const bAt = b.kind === 'message' ? b.message.timestamp : b.at;+ return safeTimestampMs(aAt) - safeTimestampMs(bAt);+ });+ const { messages, toolReplay, reasoningReplay } = materializeHistoryTimeline(entries);const executions = buildToolExecutionsFromReplay(toolReplay);const reasoningSegments = buildReasoningSegmentsFromReplay(sessionId, reasoningReplay);@@ -726,7 +843,8 @@ function buildToolExecutionsFromReplay(toolReplay: HistoryToolReplayItem[]): Toodisplay_name: n.display_name,memberName: n.memberName,},- status: 'completed',+ // 与实时一致:先 pending,等 tool_result 再落终态;无 result 的孤儿在循环末尾结算。+ status: 'pending',startedAt,updatedAt: startedAt,timeoutAt: startedAt,@@ -747,7 +865,14 @@ function buildToolExecutionsFromReplay(toolReplay: HistoryToolReplayItem[]): TootoolCallId: n.toolCallId,summary: n.summary,skillTree: n.skillTree,+ ...(n.timedOut ? { timedOut: true as const } : {}),+ ...(n.beamSearch ? { beamSearch: n.beamSearch } : {}),};+ const resultStatus: ToolExecution['status'] = n.timedOut+ ? 'timeout'+ : n.success+ ? 'completed'+ : 'error';const parsed = parseTimestampToMs(item.at);const atIso = Number.isFinite(parsed) ? timestampMsToIso(parsed) : undefined;if (!existing) {@@ -762,7 +887,7 @@ function buildToolExecutionsFromReplay(toolReplay: HistoryToolReplayItem[]): Tooarguments: {},},result,- status: n.success ? 'completed' : 'error',+ status: resultStatus,startedAt: atIso,updatedAt: atIso,timeoutAt: atIso,@@ -773,11 +898,30 @@ function buildToolExecutionsFromReplay(toolReplay: HistoryToolReplayItem[]): ToobyId.set(n.toolCallId, {...existing,result,- status: n.success ? 'completed' : 'error',+ status: resultStatus,...(atIso ? { updatedAt: atIso } : {}),});}+ // 与 chatStore.settleHistoricalToolExecutions 对齐:仅结算仍无结果的孤儿 call+ for (const id of order) {+ const execution = byId.get(id);+ if (!execution || execution.status !== 'pending' || execution.result) {+ continue;+ }+ byId.set(id, {+ ...execution,+ status: 'completed',+ updatedAt: execution.startedAt,+ result: {+ toolName: execution.toolCall.name,+ result: '',+ success: true,+ toolCallId: id,+ },+ });+ }+return order.map((id) => byId.get(id)).filter((item): item is ToolExecution => Boolean(item));}@@ -883,65 +1027,8 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historfunction finalize(): void {if (disposed) return;- const messages: Message[] = [];- const 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') {- if (pendingFileItems && (- e.message.role === 'assistant' ||- (e.message.role === 'system' && e.message.id?.startsWith('team-leader-'))- )) {- e.message = { ...e.message, fileItems: pendingFileItems };- pendingFileItems = null;- }- messages.push(e.message);- } else if (e.kind === 'usage_summary') {- for (let i = messages.length - 1; i >= 0; i--) {- if (messages[i].role === 'assistant') {- messages[i] = { ...messages[i], usageSummary: e.usage };- break;- }- }- } else if (e.kind === 'harness_message') {- harnessReplay.push({- kind: 'harness_message',- at: e.at,- payload: { content: e.content, stage: e.stage },- });- // Also add as system message with harness flag- messages.push({- id: `harness-msg-${e.at}`,- role: 'system',- content: e.content,- timestamp: e.at,- isHarnessMessage: true,- });- } else if (e.kind === 'harness_stage_result') {- harnessReplay.push({- kind: 'harness_stage_result',- at: e.at,- payload: {- stage: e.stage,- status: e.status,- error: e.error,- messages: e.messages,- metrics: e.metrics,- },- });- } else if (e.kind === 'file_items') {- pendingFileItems = 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 });- }- }+ const { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay } =+ materializeHistoryTimeline(entries);dispose();@@ -1050,64 +1137,8 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestofunction finalize(): void {if (disposed) return;- const messages: Message[] = [];- const 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') {- if (pendingFileItems && (- e.message.role === 'assistant' ||- (e.message.role === 'system' && e.message.id?.startsWith('team-leader-'))- )) {- e.message = { ...e.message, fileItems: pendingFileItems };- pendingFileItems = null;- }- messages.push(e.message);- } else if (e.kind === 'usage_summary') {- for (let i = messages.length - 1; i >= 0; i--) {- if (messages[i].role === 'assistant') {- messages[i] = { ...messages[i], usageSummary: e.usage };- break;- }- }- } else if (e.kind === 'harness_message') {- harnessReplay.push({- kind: 'harness_message',- at: e.at,- payload: { content: e.content, stage: e.stage },- });- messages.push({- id: `harness-msg-${e.at}`,- role: 'system',- content: e.content,- timestamp: e.at,- isHarnessMessage: true,- });- } else if (e.kind === 'harness_stage_result') {- harnessReplay.push({- kind: 'harness_stage_result',- at: e.at,- payload: {- stage: e.stage,- status: e.status,- error: e.error,- messages: e.messages,- metrics: e.metrics,- },- });- } else if (e.kind === 'file_items') {- pendingFileItems = 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 });- }- }+ const { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay } =+ materializeHistoryTimeline(entries);dispose();diff --git a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.tsindex 282cff5b56..fb9f571421 100644--- a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts@@ -82,6 +82,8 @@ export interface NormalizedToolResult {toolCallId?: string;result: string;success: boolean;+ /** status=timeout / timed_out 时为 true,供 store 落成 timeout */+ timedOut?: boolean;summary?: string;skillTree?: SkillTreePath;beamSearch?: BeamSearchProgress;@@ -144,13 +146,16 @@ export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedT: '');const status =typeof toolResultPayload.status === 'string'- ? toolResultPayload.status+ ? toolResultPayload.status.trim().toLowerCase(): '';+ const timedOut = status === 'timeout' || status === 'timed_out';+ const statusFailed =+ timedOut || status === 'error' || status === 'failed' || status === 'failure';const success =typeof toolResultPayload.success === 'boolean'- ? toolResultPayload.success+ ? toolResultPayload.success && !timedOut: status- ? status !== 'error'+ ? !statusFailed: true;const toolName =(typeof toolResultPayload.tool_name === 'string' &&@@ -174,6 +179,7 @@ export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedTtoolCallId,result,success,+ ...(timedOut ? { timedOut: true } : {}),summary,skillTree,beamSearch,diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 0d26a75a2e..56559f62e2 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -2356,6 +2356,8 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const streamId = currentStreamId;const preferredSegmentId =finalAction.type === 'patch_segment' ? finalAction.segmentId : undefined;+ // 收尾时刻单独记:勿覆盖 message.timestamp(排序/goal 卡),但任务用时必须吃到 final。+ const completedAtIso = normalizeEventTimestampIso(payload.timestamp);if (assistantStreamSplit && content) {const cronMetaEarly = payload.cron as Record<string, unknown> | undefined;@@ -2371,7 +2373,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {kind: 'agent',content,finalId,- timestampIso: new Date().toISOString(),+ timestampIso: completedAtIso,});if (!content.includes('MEDIA:')) {handleTtsPlayback(sessionId, finalId, content);@@ -2388,6 +2390,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().updateMessage(sessionId, rewriteId, {content,isStreaming: false,+ completedAt: completedAtIso,});if (!content.includes('MEDIA:')) {handleTtsPlayback(sessionId, rewriteId, content);@@ -2398,11 +2401,13 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}}- // 未分段:合并进当前流。勿用 payload.timestamp 覆盖消息时间(会与 goal 完成卡抢序)。+ // 未分段:合并进当前流。勿用 payload.timestamp 覆盖消息时间(会与 goal 完成卡抢序);+ // 另写 completedAt,供「任务用时」与历史 final 落盘时间对齐。if (streamId && !assistantStreamSplit) {useChatStore.getState().updateMessage(sessionId, streamId, {...(content ? { content } : {}),isStreaming: false,+ completedAt: completedAtIso,...(isProactiveRecommendation ? { isProactiveRecommendation, ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}) } : {}),});useChatStore.getState().stopStreaming(sessionId);@@ -2419,6 +2424,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().updateMessage(sessionId, streamId, {content: nextContent,isStreaming: false,+ completedAt: completedAtIso,...(isProactiveRecommendation ? { isProactiveRecommendation, ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}) } : {}),});useChatStore.getState().stopStreaming(sessionId);@@ -2427,7 +2433,10 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}return;}- useChatStore.getState().updateMessage(sessionId, streamId, { isStreaming: false });+ useChatStore.getState().updateMessage(sessionId, streamId, {+ isStreaming: false,+ completedAt: completedAtIso,+ });useChatStore.getState().stopStreaming(sessionId);}if (content) {@@ -2459,7 +2468,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}}if (placeholderId) {- useChatStore.getState().updateMessage(sessionId, placeholderId, { content, isStreaming: false });+ useChatStore.getState().updateMessage(sessionId, placeholderId, {+ content,+ isStreaming: false,+ completedAt: completedAtIso,+ });if (!content.includes('MEDIA:')) {handleTtsPlayback(sessionId, placeholderId, content);}@@ -2477,9 +2490,17 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const existing = messages.find((m) => m.id === messageId);if (existing) {if (existing.content === content) {+ useChatStore.getState().updateMessage(sessionId, messageId, {+ isStreaming: false,+ completedAt: completedAtIso,+ });return;}- useChatStore.getState().updateMessage(sessionId, messageId, { content, isStreaming: false });+ useChatStore.getState().updateMessage(sessionId, messageId, {+ content,+ isStreaming: false,+ completedAt: completedAtIso,+ });if (!content.includes('MEDIA:')) {handleTtsPlayback(sessionId, messageId, content);}@@ -2524,6 +2545,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().updateMessage(sessionId, rewriteId, {content,isStreaming: false,+ completedAt: completedAtIso,});if (!content.includes('MEDIA:')) {handleTtsPlayback(sessionId, rewriteId, content);@@ -2536,7 +2558,8 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {id: finalMsgId,role: 'assistant',content: remainder,- timestamp: new Date().toISOString(),+ timestamp: completedAtIso,+ completedAt: completedAtIso,isProactiveRecommendation,...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}),});@@ -2555,6 +2578,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().updateMessage(sessionId, rewriteId, {content,isStreaming: false,+ completedAt: completedAtIso,});if (!content.includes('MEDIA:')) {handleTtsPlayback(sessionId, rewriteId, content);@@ -2563,13 +2587,18 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}const last = messages[messages.length - 1];if (last?.role === 'assistant' && last.content === content) {+ useChatStore.getState().updateMessage(sessionId, last.id, {+ isStreaming: false,+ completedAt: completedAtIso,+ });return;}useChatStore.getState().addMessage(sessionId, {id: messageId,role: 'assistant',content,- timestamp: new Date().toISOString(),+ timestamp: completedAtIso,+ completedAt: completedAtIso,isProactiveRecommendation,...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}),});@@ -2682,7 +2711,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}return;}- useChatStore.getState().addFileItems(sessionId, files);+ useChatStore.getState().addFileItems(sessionId, files, {+ timestampIso: normalizeEventTimestampIso(payload.timestamp),+ });}),webClient.on('chat.tool_call', ({ payload }) => {const sessionId = resolveEventSessionId(payload);@@ -2804,9 +2835,22 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {activeSessionId);}- useChatStore.getState().addToolResult(sessionId, toolResult, {- updatedAt: normalizeEventTimestampIso(payload.timestamp),- });+ useChatStore.getState().addToolResult(+ sessionId,+ {+ toolName: toolResult.toolName,+ result: toolResult.result,+ success: toolResult.success,+ toolCallId: toolResult.toolCallId,+ summary: toolResult.summary,+ skillTree: toolResult.skillTree,+ beamSearch: toolResult.beamSearch,+ ...(toolResult.timedOut ? { timedOut: true } : {}),+ },+ {+ updatedAt: normalizeEventTimestampIso(payload.timestamp),+ }+ );}),webClient.on('todo.updated', ({ payload }) => {const sessionId = resolveEventSessionId(payload);@@ -3875,6 +3919,10 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const markAllRuntimes = () => {const runtimes = useChatStore.getState().runtimes;for (const sid of Object.keys(runtimes)) {+ // 历史回放期间不要把旧 tool_call 误标 timeout,等 settleHistorical 先按结果落终态+ if (runtimes[sid]?.isLoadingHistory) {+ continue;+ }useChatStore.getState().markTimedOutExecutions(sid);}};diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 73ee377793..0806cd3ffe 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -1947,6 +1947,8 @@"workCompletedThinkingNoDuration": "Completed {{thinking}} thoughts","workCompletedTools": "Completed {{tools}} tool calls · {{duration}}","workCompletedToolsNoDuration": "Completed {{tools}} tool calls",+ "workFailedToolsNoDuration": "{{tools}} tool calls failed",+ "workOutcomePartial": "Partial failure","reasoning": {"thinking": "Thinking…","thought": "Thought"@@ -1986,6 +1988,7 @@"failed": "failed","timeout": "Execution timed out","running": "Running...",+ "toolName": "Tool name","arguments": "Arguments","result": "Result","truncated": "result truncated"@@ -1993,6 +1996,7 @@"toolGroup": {"running": "Running {{label}}","completed": "Completed {{label}}",+ "failed": "{{label}} failed","category": {"file": "file operations","search": "searches",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 0cdc034858..21f094a13a 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -1948,6 +1948,8 @@"workCompletedThinkingNoDuration": "已完成 {{thinking}} 次思考","workCompletedTools": "已完成 {{tools}} 次工具调用 · {{duration}}","workCompletedToolsNoDuration": "已完成 {{tools}} 次工具调用",+ "workFailedToolsNoDuration": "{{tools}} 次工具调用失败",+ "workOutcomePartial": "部分失败","reasoning": {"thinking": "思考中…","thought": "已完成思考"@@ -1987,6 +1989,7 @@"failed": "失败","timeout": "执行超时","running": "执行中...",+ "toolName": "工具名称","arguments": "参数","result": "结果","truncated": "结果已截断"@@ -1994,6 +1997,7 @@"toolGroup": {"running": "正在{{label}}","completed": "已完成{{label}}",+ "failed": "{{label}}执行失败","category": {"file": "文件操作","search": "搜索",diff --git a/jiuwenswarm/channels/web/frontend/src/index.css b/jiuwenswarm/channels/web/frontend/src/index.cssindex b4787e5759..aeac2a824b 100644--- a/jiuwenswarm/channels/web/frontend/src/index.css+++ b/jiuwenswarm/channels/web/frontend/src/index.css@@ -1534,6 +1534,14 @@ select {color: var(--color-feedback-success);}+ .completed-work-chip__icon.is-partial {+ color: var(--color-feedback-warning);+ }++ .completed-work-chip__icon.is-error {+ color: var(--color-feedback-danger);+ }+.completed-work-chip__icon svg {width: 16px;height: 16px;@@ -1545,6 +1553,21 @@ select {transition: opacity 0.28s ease, transform 0.28s ease;}+ .completed-work-chip__badge {+ flex-shrink: 0;+ padding: 0;+ margin-left: 2px;+ border-radius: 0;+ font-size: var(--font-size-2xs, 11px);+ font-weight: 500;+ line-height: inherit;+ }++ .completed-work-chip__badge.is-partial {+ background: transparent;+ color: var(--color-feedback-warning);+ }+.completed-work-chip .tool-tree-item__disclosure {opacity: 0.7;transition: transform 0.22s ease, opacity 0.18s ease;@@ -1841,14 +1864,44 @@ select {}.tool-tree-item__detail-badge {- padding: 0 5px;+ padding: 1px 6px;border-radius: 4px;font-size: var(--font-size-2xs);- font-weight: 500;+ font-weight: 600;+ letter-spacing: 0.02em;background: var(--color-surface-muted);color: var(--color-text-secondary);}+ .tool-tree-item__detail-badge.is-success {+ background: var(--color-feedback-success-subtle, rgba(22, 163, 74, 0.12));+ color: var(--color-feedback-success);+ }++ .tool-tree-item__detail-badge.is-error,+ .tool-tree-item__detail-badge.is-timeout {+ background: rgba(220, 38, 38, 0.08);+ color: rgba(185, 28, 28, 0.88);+ font-weight: 500;+ }++ .tool-tree__header-line-text.is-failed {+ color: rgba(185, 28, 28, 0.78);+ }++ .tool-tree-item__detail-pre.is-failed {+ border-color: rgba(220, 38, 38, 0.14);+ }++ .tool-tree-item__detail-pre--name {+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);+ font-weight: 600;+ }++ .tool-tree-item__detail-status.is-error {+ color: rgba(185, 28, 28, 0.78);+ }+.tool-tree-item__detail-pre {margin: 0;max-height: 168px;diff --git a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.tsindex 7d66723c65..da40183a49 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts@@ -49,6 +49,9 @@ function computeTimeoutAt(baseIso: string): string {}function resolveExecutionStatus(result: ToolResult): ToolExecutionStatus {+ if (result.timedOut) {+ return 'timeout';+ }return result.success ? 'completed' : 'error';}@@ -255,7 +258,11 @@ interface ChatState {setInputValue: (sessionId: string, value: string) => void;setSessionError: (sessionId: string, error: string | null) => void;setUsageSummary: (sessionId: string, messageId: string, usage: UsageSummary) => void;- addFileItems: (sessionId: string, files: FileDownloadItem[]) => void;+ addFileItems: (+ sessionId: string,+ files: FileDownloadItem[],+ options?: { timestampIso?: string }+ ) => void;setContextCompressionStatus: (sessionId: string,runtime?: ContextCompressionRuntime,@@ -658,6 +665,7 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)role: kind === 'team' ? 'system' : 'assistant',content: displayContent,timestamp: timestampIso,+ completedAt: timestampIso,isStreaming: false,});return {@@ -1195,23 +1203,35 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)let changed = false;const nextExecutions = new Map(runtime.toolExecutions);for (const [toolCallId, execution] of nextExecutions) {- if (execution.status !== 'pending' && execution.status !== 'timeout') {+ // 只结算仍 pending 的历史孤儿 tool_call。+ // timeout/error 必须保留,否则刷新后失败/超时会被抹成「已完成」。+ if (execution.status !== 'pending') {+ continue;+ }+ if (execution.result) {+ const nextStatus = resolveExecutionStatus(execution.result);+ if (nextStatus !== execution.status) {+ changed = true;+ nextExecutions.set(toolCallId, {+ ...execution,+ status: nextStatus,+ updatedAt: execution.updatedAt || execution.startedAt,+ });+ }continue;}- // 无真实 result:按调用时刻结算,不引入 Date.now()+ // 无真实 result:按调用时刻结算为完成,不引入 Date.now()changed = true;nextExecutions.set(toolCallId, {...execution,status: 'completed',updatedAt: execution.startedAt,- result:- execution.result ??- ({- toolName: execution.toolCall.name,- result: '',- success: true,- toolCallId,- } as ToolResult),+ result: {+ toolName: execution.toolCall.name,+ result: '',+ success: true,+ toolCallId,+ } as ToolResult,});}if (!changed) return state;@@ -1530,16 +1550,24 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)});},- addFileItems: (sessionId, files) => {+ addFileItems: (sessionId, files, options) => {set((state) => {const runtime = state.runtimes[sessionId];if (!runtime) return state;const lastMessage = runtime.messages[runtime.messages.length - 1];+ // 与历史 restore 一致:优先挂当前流;否则挂最近一条助手消息(不是下一条 final)。const targetId =runtime.currentStreamId ??- (lastMessage?.role === 'assistant' ? lastMessage.id : null);+ (lastMessage?.role === 'assistant' ||+ (lastMessage?.role === 'system' && lastMessage.id?.startsWith('team-leader-'))+ ? lastMessage.id+ : null);+ const timestampIso =+ typeof options?.timestampIso === 'string' && options.timestampIso.trim()+ ? options.timestampIso.trim()+ : new Date().toISOString();if (!targetId) {- const msgId = `file-${Date.now()}`;+ const msgId = `file-${timestampIso}`;return {runtimes: {...state.runtimes,@@ -1551,7 +1579,7 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)id: msgId,role: 'assistant',content: '',- timestamp: new Date().toISOString(),+ timestamp: timestampIso,fileItems: files,},],diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex 174528d0d5..53aa34dc32 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -62,6 +62,11 @@ export interface Message {role: MessageRole;content: string;timestamp: string;+ /**+ * 流式收尾 / chat.final 完成时刻。不参与时间线排序(排序仍用 timestamp,避免与 goal 卡抢序),+ * 仅作为「任务用时」终点,避免 live 一直停在首包 delta 时间、刷新后变成 final 落盘时间。+ */+ completedAt?: string;/** 前端渲染身份,避免业务 id 重复或历史 prepend 导致 React key 抖动 */renderKey?: string;audioBase64?: string;@@ -108,6 +113,8 @@ export interface ToolResult {success: boolean;toolCallId?: string;summary?: string; // 结果摘要+ /** 历史/实时结果显式标记为超时(与 success=false 一起用于展示「执行失败」) */+ timedOut?: boolean;// agentic search(symphony 技能检索)下发的技能树路径,用于内联回放路径流转skillTree?: SkillTreePath;beamSearch?: BeamSearchProgress;diff --git a/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjs b/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjsindex eddb16632b..c769c9bab6 100644--- a/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjs@@ -92,17 +92,42 @@ test('settleHistoricalToolExecutions does not downgrade completed tools', () =>}});-test('settleHistoricalToolExecutions settles timeout tools', () => {+test('settleHistoricalToolExecutions preserves timeout tools (does not rewrite as completed)', () => {setup();try {addToolCall('call-5', 'slow_tool');+ // 把 timeoutAt 拨到过去,触发巡检超时+ const runtime = useChatStore.getState().getRuntime(SID);+ const execution = runtime.toolExecutions.get('call-5');+ runtime.toolExecutions.set('call-5', {+ ...execution,+ timeoutAt: new Date(Date.now() - 1000).toISOString(),+ });useChatStore.getState().markTimedOutExecutions(SID);- const status = getToolStatus('call-5');- assert.equal(status, 'pending');+ assert.equal(getToolStatus('call-5'), 'timeout');++ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-5'), 'timeout');+ } finally {+ teardown();+ }+});++test('settleHistoricalToolExecutions preserves error tools', () => {+ setup();+ try {+ addToolCall('call-5b', 'fail_tool');+ useChatStore.getState().addToolResult(SID, {+ toolCallId: 'call-5b',+ toolName: 'fail_tool',+ result: 'boom',+ success: false,+ });+ assert.equal(getToolStatus('call-5b'), 'error');useChatStore.getState().settleHistoricalToolExecutions(SID);- assert.equal(getToolStatus('call-5'), 'completed');+ assert.equal(getToolStatus('call-5b'), 'error');} finally {teardown();}