JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: 前端支持会话恢复,端到端联调完成
NickFuryXXXaa2da9188a3f
diff --git a/jiuwenclaw/start_services.py b/jiuwenclaw/start_services.pyindex 6a67f215fe..722c99a4e4 100644--- a/jiuwenclaw/start_services.py+++ b/jiuwenclaw/start_services.py@@ -51,6 +51,11 @@ def _build_commands(mode: str) -> list[tuple[str, list[str], Path]]:def _start_process(name: str, cmd: list[str], cwd: Path) -> subprocess.Popen[bytes]:print(f"[start_services] starting {name}: {' '.join(cmd)} (cwd={cwd})")+ # Windows: npm/npx resolve to .cmd shims; CreateProcess cannot spawn .cmd without a shell.+ if sys.platform == "win32" and cmd:+ first = cmd[0].lower()+ if first in ("npm", "npx"):+ cmd = ["cmd", "/c", *cmd]return subprocess.Popen(cmd, cwd=str(cwd))diff --git a/jiuwenclaw/web/src/App.tsx b/jiuwenclaw/web/src/App.tsxindex 4958370150..cf3cb2dbcc 100644--- a/jiuwenclaw/web/src/App.tsx+++ b/jiuwenclaw/web/src/App.tsx@@ -19,6 +19,16 @@ import { ChannelsPanel } from './components/ChannelsPanel';import { BrowserPanel } from './components/BrowserPanel';import { StatusBar } from './components/StatusBar';import { HeartbeatMessageModal } from './features/HeartbeatMessageModal';+import {+ beginHistoryRestore,+ fetchHistoryPage,+ HISTORY_GET_METHOD,+ type HistoryRestoreHandle,+} from './features/historyRestore';+import {+ normalizeToolCallPayload,+ normalizeToolResultPayload,+} from './features/tool-events/toolEventNormalizer';import { useWebSocket } from './hooks';import { webRequest } from './services/webClient';import { AgentMode } from './types';@@ -241,8 +251,42 @@ function AppContent() {const newSessionToastTimerRef = useRef<number | null>(null);const heartbeatToastTimerRef = useRef<number | null>(null);const lastHeartbeatToastKeyRef = useRef<string | null>(null);+ /** 自「恢复会话」加载 history 后的分页元数据;用于聊天区顶部加载更早消息 */+ const [historyPagerMeta, setHistoryPagerMeta] = useState<{+ loadedPages: number;+ totalPages: number;+ } | null>(null);+ const [historyLoadingMore, setHistoryLoadingMore] = useState(false);+ const sessionIdRef = useRef(sessionId);+ const historyRestoreHandleRef = useRef<HistoryRestoreHandle | null>(null);+ const historyPageHandleRef = useRef<HistoryRestoreHandle | null>(null);++ const disposeInFlightHistoryHandles = useCallback(() => {+ historyRestoreHandleRef.current?.dispose();+ historyRestoreHandleRef.current = null;+ historyPageHandleRef.current?.dispose();+ historyPageHandleRef.current = null;+ }, []);++ useEffect(() => {+ sessionIdRef.current = sessionId;+ }, [sessionId]);++ useEffect(() => () => disposeInFlightHistoryHandles(), [disposeInFlightHistoryHandles]);+const { setCurrentSession, setSessions, heartbeatMessage, heartbeatUpdatedAt } = useSessionStore();- const { clearMessages, isProcessing } = useChatStore();+ const {+ clearMessages,+ clearSubtasks,+ addMessage,+ addToolCall,+ addToolResult,+ prependMessages,+ isProcessing,+ setProcessing,+ setThinking,+ setPaused,+ } = useChatStore();const { clearTodos } = useTodoStore();// WebSocket 连接 - provider 由后端配置决定 - provider 由后端配置决定,前端默认不在 URL query 传递@@ -442,6 +486,12 @@ function AppContent() {// 新建会话:立即生成可用的 session_id,避免停留在 'new' 导致无法发送消息const handleNewSession = useCallback(async () => {+ disposeInFlightHistoryHandles();+ setHistoryPagerMeta(null);+ setHistoryLoadingMore(false);+ setProcessing(false);+ setThinking(false);+ setPaused(false);clearMessages();clearTodos();const newSid = generateSessionId();@@ -471,9 +521,13 @@ function AppContent() {clearMessages,clearNewSessionToastTimer,clearTodos,+ disposeInFlightHistoryHandles,fetchSessions,request,setCurrentSession,+ setPaused,+ setProcessing,+ setThinking,]);// 切换模式@@ -514,6 +568,226 @@ function AppContent() {void sendUserAnswer(sessionId, requestId, answers);}, [sendUserAnswer, sessionId]);+ const handleLoadMoreHistory = useCallback(async () => {+ if (!sessionId.startsWith('sess_') || !historyPagerMeta) return;+ if (historyLoadingMore || historyPagerMeta.loadedPages >= historyPagerMeta.totalPages) return;++ const sid = sessionId;+ const nextPage = historyPagerMeta.loadedPages + 1;+ const fallbackTotal = historyPagerMeta.totalPages;++ setHistoryLoadingMore(true);+ const pageHandle = fetchHistoryPage({+ sessionId: sid,+ onReady: ({ messages, toolReplay, totalPages }) => {+ if (sessionIdRef.current !== sid) {+ setHistoryLoadingMore(false);+ historyPageHandleRef.current = null;+ return;+ }+ prependMessages(messages);+ for (const item of toolReplay) {+ if (item.kind === 'tool_call') {+ const n = normalizeToolCallPayload(item.payload);+ addToolCall(+ {+ id: n.id,+ name: n.name,+ arguments: n.arguments,+ description: n.description,+ formatted_args: n.formatted_args,+ },+ { startedAt: item.at }+ );+ } else {+ const n = normalizeToolResultPayload(item.payload);+ addToolResult(+ {+ toolName: n.toolName,+ result: n.result,+ success: n.success,+ toolCallId: n.toolCallId,+ summary: n.summary,+ },+ { updatedAt: item.at }+ );+ }+ }+ setHistoryPagerMeta({+ loadedPages: nextPage,+ totalPages: totalPages ?? fallbackTotal,+ });+ setHistoryLoadingMore(false);+ historyPageHandleRef.current = null;+ },+ onEmpty: (emptyTotalPages) => {+ if (sessionIdRef.current !== sid) {+ setHistoryLoadingMore(false);+ historyPageHandleRef.current = null;+ return;+ }+ setHistoryPagerMeta({+ loadedPages: nextPage,+ totalPages: emptyTotalPages ?? fallbackTotal,+ });+ setHistoryLoadingMore(false);+ historyPageHandleRef.current = null;+ },+ onError: (message) => {+ console.warn('[history.page]', message);+ },+ });+ historyPageHandleRef.current = pageHandle;++ try {+ await request(HISTORY_GET_METHOD, {+ session_id: sid,+ page_idx: nextPage,+ });+ } catch (error) {+ pageHandle.dispose();+ historyPageHandleRef.current = null;+ console.error('Failed to load older history:', error);+ setHistoryLoadingMore(false);+ }+ }, [+ addToolCall,+ addToolResult,+ historyLoadingMore,+ historyPagerMeta,+ prependMessages,+ request,+ sessionId,+ ]);++ const handleRestoreSession = useCallback(+ async (targetSessionId: string) => {+ if (!targetSessionId.startsWith('sess_')) return;++ disposeInFlightHistoryHandles();+ setHistoryPagerMeta(null);+ setHistoryLoadingMore(false);+ setProcessing(false);+ setThinking(false);+ setPaused(false);+ clearMessages();+ clearTodos();+ clearSubtasks();+ setSessionId(targetSessionId);+ setCurrentSession(null);+ storeSessionId(targetSessionId);+ setActiveNav('chat');++ const restoreHandle = beginHistoryRestore({+ sessionId: targetSessionId,+ onReady: (messages, totalPages) => {+ if (sessionIdRef.current !== targetSessionId) {+ return;+ }+ messages.forEach((message) => addMessage(message));+ setHistoryPagerMeta({+ loadedPages: 1,+ totalPages: totalPages ?? 1,+ });+ queueMicrotask(() => {+ historyRestoreHandleRef.current = null;+ });+ },+ onEmpty: (emptyTotalPages) => {+ if (sessionIdRef.current !== targetSessionId) {+ return;+ }+ setHistoryPagerMeta({+ loadedPages: 1,+ totalPages: emptyTotalPages ?? 1,+ });+ addMessage({+ id: `history-restore-empty-${Date.now()}`,+ role: 'system',+ content: t('sessions.restoreEmpty'),+ timestamp: new Date().toISOString(),+ });+ historyRestoreHandleRef.current = null;+ },+ onToolReplay: (items) => {+ if (sessionIdRef.current !== targetSessionId) {+ return;+ }+ for (const item of items) {+ if (item.kind === 'tool_call') {+ const n = normalizeToolCallPayload(item.payload);+ addToolCall(+ {+ id: n.id,+ name: n.name,+ arguments: n.arguments,+ description: n.description,+ formatted_args: n.formatted_args,+ },+ { startedAt: item.at }+ );+ } else {+ const n = normalizeToolResultPayload(item.payload);+ addToolResult(+ {+ toolName: n.toolName,+ result: n.result,+ success: n.success,+ toolCallId: n.toolCallId,+ summary: n.summary,+ },+ { updatedAt: item.at }+ );+ }+ }+ },+ onError: (message) => {+ console.warn('[history.restore]', message);+ },+ });+ historyRestoreHandleRef.current = restoreHandle;++ try {+ await request(HISTORY_GET_METHOD, {+ session_id: targetSessionId,+ page_idx: 1,+ });+ } catch (error) {+ restoreHandle.dispose();+ historyRestoreHandleRef.current = null;+ setHistoryPagerMeta(null);+ console.error('Failed to restore history:', error);+ if (sessionIdRef.current === targetSessionId) {+ addMessage({+ id: `history-restore-failed-${Date.now()}`,+ role: 'system',+ content: t('sessions.errors.restoreFailed', { sessionId: targetSessionId }),+ timestamp: new Date().toISOString(),+ });+ }+ }+ },+ [+ addMessage,+ addToolCall,+ addToolResult,+ clearMessages,+ clearSubtasks,+ clearTodos,+ disposeInFlightHistoryHandles,+ request,+ setActiveNav,+ setCurrentSession,+ setHistoryPagerMeta,+ setHistoryLoadingMore,+ setPaused,+ setProcessing,+ setSessionId,+ setThinking,+ t,+ ]+ );+const handleNavigate = useCallback((nav: MainNavKey) => {setActiveNav(nav);if (nav === 'skills') setHasVisitedSkills(true);@@ -590,6 +864,16 @@ function AppContent() {isProcessing={isProcessing}onNewSession={handleNewSession}onUserAnswer={handleUserAnswer}+ historyPager={+ historyPagerMeta+ ? {+ loadedPages: historyPagerMeta.loadedPages,+ totalPages: historyPagerMeta.totalPages,+ loadingMore: historyLoadingMore,+ onLoadMore: handleLoadMoreHistory,+ }+ : null+ }/></div>@@ -613,7 +897,12 @@ function AppContent() {)}{activeNav === 'sessions' && (<div className="app-section">- <SessionsPanel currentSessionId={sessionId} />+ <SessionsPanel+ currentSessionId={sessionId}+ isConnected={isConnected}+ isProcessing={isProcessing}+ onRestoreSession={handleRestoreSession}+ /></div>)}{activeNav === 'heartbeat' && (diff --git a/jiuwenclaw/web/src/components/AgentPanel/FileViewer.tsx b/jiuwenclaw/web/src/components/AgentPanel/FileViewer.tsxindex d2673a14f7..f7e6cb5dec 100644--- a/jiuwenclaw/web/src/components/AgentPanel/FileViewer.tsx+++ b/jiuwenclaw/web/src/components/AgentPanel/FileViewer.tsx@@ -1,12 +1,20 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useMemo } from 'react';import { useTranslation } from 'react-i18next';import ReactMarkdown from 'react-markdown';+import { parseHistoryJsonFileToPreviewMessages } from '../../features/historyRestore';+import { MessageItem } from '../ChatPanel/MessageItem';+import '../ChatPanel/ChatPanel.css';interface FileViewerProps {filePath: string;fileName: string;}+function sessionIdFromAgentPath(filePath: string): string {+ const m = filePath.match(/sess_[a-zA-Z0-9_]+/);+ return m ? m[0] : 'file';+}+export function FileViewer({ filePath, fileName }: FileViewerProps) {const { t } = useTranslation();const [content, setContent] = useState<string>('');@@ -16,12 +24,45 @@ export function FileViewer({ filePath, fileName }: FileViewerProps) {const [isEditing, setIsEditing] = useState(false);const [error, setError] = useState<string | null>(null);const [saveError, setSaveError] = useState<string | null>(null);- const isMarkdown = fileName.toLowerCase().endsWith('.md') || fileName.toLowerCase().endsWith('.mdx');+ const lowerFileName = fileName.toLowerCase();+ const isMarkdown = lowerFileName.endsWith('.md') || lowerFileName.endsWith('.mdx');+ const isJson = lowerFileName.endsWith('.json');+ const isHistoryJson = lowerFileName === 'history.json';+ const isPreviewable = isMarkdown || isJson;const fileNotFound = Boolean(error && error.includes('HTTP 404'));+ const [historyChatPreview, setHistoryChatPreview] = useState(true);++ /** 任意 .json 单次 parse,避免预览/格式化重复 JSON.parse */+ const jsonDerived = useMemo(() => {+ if (!isJson || !content.trim()) {+ return {+ historyMessages: [] as ReturnType<typeof parseHistoryJsonFileToPreviewMessages>,+ historyInvalid: false,+ formatted: content,+ };+ }+ try {+ const parsed: unknown = JSON.parse(content);+ const formatted = JSON.stringify(parsed, null, 2);+ if (!isHistoryJson) {+ return { historyMessages: [], historyInvalid: false, formatted };+ }+ if (!Array.isArray(parsed)) {+ return { historyMessages: [], historyInvalid: true, formatted };+ }+ return {+ historyMessages: parseHistoryJsonFileToPreviewMessages(parsed, sessionIdFromAgentPath(filePath)),+ historyInvalid: false,+ formatted,+ };+ } catch {+ return { historyMessages: [], historyInvalid: true, formatted: content };+ }+ }, [isJson, isHistoryJson, content, filePath]);useEffect(() => {if (!filePath) return;- if (!isMarkdown) {+ if (!isPreviewable) {setLoading(false);setError(null);setSaveError(null);@@ -61,7 +102,13 @@ export function FileViewer({ filePath, fileName }: FileViewerProps) {};loadFile();- }, [filePath, fileName, isMarkdown]);+ }, [filePath, fileName, isPreviewable]);++ useEffect(() => {+ if (isHistoryJson) {+ setHistoryChatPreview(true);+ }+ }, [filePath, isHistoryJson]);const handleStartEdit = () => {setDraftContent(content);@@ -108,7 +155,7 @@ export function FileViewer({ filePath, fileName }: FileViewerProps) {return (<div className="h-full min-h-0 flex flex-col overflow-hidden"><div className="flex-shrink-0 px-4 py-3 bg-secondary/30 border-b border-border">- <div className="flex items-start justify-between gap-4">+ <div className="flex items-stretch justify-between gap-4"><div className="flex items-center gap-3 min-w-0 flex-1"><span className="h-9 w-9 rounded-lg border border-border bg-card flex items-center justify-center text-text-muted flex-shrink-0"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.6} className="h-7 w-7">@@ -123,7 +170,7 @@ export function FileViewer({ filePath, fileName }: FileViewerProps) {</div></div>{isMarkdown && !loading ? (- <div className="flex items-center gap-2 flex-shrink-0">+ <div className="flex flex-shrink-0 items-center gap-2 self-stretch">{isEditing ? (<><button@@ -154,6 +201,23 @@ export function FileViewer({ filePath, fileName }: FileViewerProps) {)}</div>) : null}+ {isHistoryJson && isJson && !loading ? (+ <div className="flex flex-shrink-0 items-center gap-2 self-stretch">+ <span className="text-xs leading-snug text-text-muted whitespace-nowrap">{t('fileViewer.chatPreview')}</span>+ <button+ type="button"+ role="switch"+ aria-checked={historyChatPreview}+ onClick={() => setHistoryChatPreview((v) => !v)}+ className={`inline-flex h-8 w-12 shrink-0 items-center rounded-full border border-border p-1 transition-colors ${+ historyChatPreview ? 'justify-end bg-accent' : 'justify-start bg-secondary'+ }`}+ title={t('fileViewer.chatPreview')}+ >+ <span className="pointer-events-none h-5 w-5 rounded-full bg-card shadow-sm ring-1 ring-black/5 dark:ring-white/10" />+ </button>+ </div>+ ) : null}</div>{error ? (<div className="mt-2 rounded-md border border-danger/30 bg-danger/10 px-2.5 py-1.5 text-xs text-danger">@@ -190,6 +254,28 @@ export function FileViewer({ filePath, fileName }: FileViewerProps) {<ReactMarkdown>{content || ' '}</ReactMarkdown></article>)+ ) : isJson ? (+ isHistoryJson && historyChatPreview ? (+ jsonDerived.historyInvalid ? (+ <pre className="w-full h-full min-h-[280px] overflow-auto rounded-lg border border-border bg-card p-3 text-sm text-text mono whitespace-pre-wrap break-all">+ {jsonDerived.formatted || ' '}+ </pre>+ ) : jsonDerived.historyMessages.length === 0 ? (+ <div className="h-full min-h-[280px] flex items-center justify-center rounded-lg border border-border bg-card px-4 text-sm text-text-muted text-center">+ {t('fileViewer.historyPreviewEmpty')}+ </div>+ ) : (+ <div className="w-full min-h-[280px] rounded-lg border border-border bg-card p-3">+ {jsonDerived.historyMessages.map((message) => (+ <MessageItem key={message.id} message={message} />+ ))}+ </div>+ )+ ) : (+ <pre className="w-full h-full min-h-[280px] overflow-auto rounded-lg border border-border bg-card p-3 text-sm text-text mono whitespace-pre-wrap break-all">+ {jsonDerived.formatted || ' '}+ </pre>+ )) : (<div className="h-full flex items-center justify-center text-text-muted text-sm">{t('fileViewer.notPreviewable')}diff --git a/jiuwenclaw/web/src/components/AgentPanel/index.tsx b/jiuwenclaw/web/src/components/AgentPanel/index.tsxindex 45652324f2..d86573aff4 100644--- a/jiuwenclaw/web/src/components/AgentPanel/index.tsx+++ b/jiuwenclaw/web/src/components/AgentPanel/index.tsx@@ -34,7 +34,7 @@ interface TreeData {>;directoryCount: number;totalFileCount: number;- markdownFileCount: number;+ previewableFileCount: number;}const compareByName = (a: string, b: string) => a.localeCompare(b, 'zh-Hans-CN');@@ -50,6 +50,11 @@ const isSkillFolder = (folderKey: string) =>const normalizeFolderKey = (folderKey: string) => (folderKey ? folderKey : ROOT_FOLDER_KEY);+const isPreviewableFile = (fileName: string) => {+ const lowerName = fileName.toLowerCase();+ return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json');+};+const getParentFolderKey = (folderKey: string) => {if (folderKey === ROOT_FOLDER_KEY) return null;const separatorIndex = folderKey.lastIndexOf('/');@@ -159,7 +164,7 @@ const buildTreeData = (data: Record<string, FileInfo[]>, t: (key: string) => strrootEntries,directoryCount: Math.max(directoryMap.size - 1, 0),totalFileCount: allFiles.length,- markdownFileCount: allFiles.filter((file) => file.isMarkdown).length,+ previewableFileCount: allFiles.filter((file) => isPreviewableFile(file.name)).length,};};@@ -266,7 +271,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {};const handleFileClick = (file: FileInfo) => {- if (!file.isMarkdown) {+ if (!isPreviewableFile(file.name)) {return;}const folderKey = getFolderKeyByFilePath(file.path);@@ -329,7 +334,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {<div>{node.childDirectoryKeys.map((childKey) => renderTree(childKey, depth + 1))}{node.files.map((file) => {- const selectable = file.isMarkdown;+ const selectable = isPreviewableFile(file.name);const selected = selectedFile?.path === file.path;return (<button@@ -356,7 +361,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {)}</svg><span className="flex-1 min-w-0 truncate">{file.name}</span>- {!file.isMarkdown ? (+ {!selectable ? (<span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/40">{t('agent.notPreviewable')}</span>@@ -387,7 +392,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {{t('agent.fileCount', { count: treeData.totalFileCount })}</span><span className="mono px-2.5 py-1 rounded-full border border-border bg-secondary/60">- {t('agent.previewableCount', { count: treeData.markdownFileCount })}+ {t('agent.previewableCount', { count: treeData.previewableFileCount })}</span></div></div>@@ -430,7 +435,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {return renderTree(entry.key, 0);}const file = entry.file;- const selectable = file.isMarkdown;+ const selectable = isPreviewableFile(file.name);const selected = selectedFile?.path === file.path;return (<button@@ -455,7 +460,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {)}</svg><span className="flex-1 min-w-0 truncate">{file.name}</span>- {!file.isMarkdown ? (+ {!selectable ? (<span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/40">{t('agent.notPreviewable')}</span>diff --git a/jiuwenclaw/web/src/components/ChatPanel/HistoryPagerBar.tsx b/jiuwenclaw/web/src/components/ChatPanel/HistoryPagerBar.tsxnew file mode 100644index 0000000000..88fd5f9b73--- /dev/null+++ b/jiuwenclaw/web/src/components/ChatPanel/HistoryPagerBar.tsx@@ -0,0 +1,40 @@+import { useTranslation } from 'react-i18next';++export interface HistoryPagerBarProps {+ loadedPages: number;+ totalPages: number;+ loadingMore: boolean;+ onLoadMore: () => void;+}++export function HistoryPagerBar({+ loadedPages,+ totalPages,+ loadingMore,+ onLoadMore,+}: HistoryPagerBarProps) {+ const { t } = useTranslation();+ const hasMore = loadedPages < totalPages;++ return (+ <div className="history-pager-bar mb-3 rounded-lg border border-white/10 bg-secondary/50 px-3 py-2.5 flex flex-wrap items-center justify-between gap-2 text-sm">+ <span className="text-text-muted tabular-nums">+ {t('chat.historyPager.loadedOfTotal', { loaded: loadedPages, total: totalPages })}+ </span>+ {hasMore ? (+ <button+ type="button"+ className="btn !py-1.5 !px-3 text-xs shrink-0"+ disabled={loadingMore}+ onClick={() => {+ void onLoadMore();+ }}+ >+ {loadingMore ? t('chat.historyPager.loadingMore') : t('chat.historyPager.loadMore')}+ </button>+ ) : (+ <span className="text-xs text-text-muted shrink-0">{t('chat.historyPager.allLoaded')}</span>+ )}+ </div>+ );+}diff --git a/jiuwenclaw/web/src/components/ChatPanel/index.tsx b/jiuwenclaw/web/src/components/ChatPanel/index.tsxindex f45c641487..09f2e44d5c 100644--- a/jiuwenclaw/web/src/components/ChatPanel/index.tsx+++ b/jiuwenclaw/web/src/components/ChatPanel/index.tsx@@ -4,7 +4,7 @@* 聊天面板,包含消息列表和输入区域*/-import { useRef, useEffect, useCallback } from 'react';+import { useRef, useEffect, useLayoutEffect, useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '../../stores';import { AgentMode, UserAnswer } from '../../types';@@ -12,8 +12,16 @@ import { MessageList } from './MessageList';import { InputArea } from './InputArea';import { SubtaskProgress } from './SubtaskProgress';import { InlineQuestionCard } from './InlineQuestionCard';+import { HistoryPagerBar } from './HistoryPagerBar';import './ChatPanel.css';+export interface ChatHistoryPagerProps {+ loadedPages: number;+ totalPages: number;+ loadingMore: boolean;+ onLoadMore: () => void | Promise<void>;+}+interface ChatPanelProps {onSendMessage: (content: string) => void;onInterrupt: (newInput?: string) => void;@@ -21,6 +29,8 @@ interface ChatPanelProps {isProcessing: boolean;onNewSession: () => void;onUserAnswer: (requestId: string, answers: UserAnswer[]) => void;+ /** 自会话管理恢复历史后出现;支持分页加载更早消息 */+ historyPager?: ChatHistoryPagerProps | null;}function ThinkingIndicator() {@@ -60,19 +70,57 @@ export function ChatPanel({isProcessing,onNewSession,onUserAnswer,+ historyPager = null,}: ChatPanelProps) {const { t } = useTranslation();const { messages, isThinking } = useChatStore();const messagesEndRef = useRef<HTMLDivElement>(null);+ const scrollContainerRef = useRef<HTMLDivElement>(null);+ const prependScrollSnapRef = useRef<{ sh: number; st: number } | null>(null);+ const wasHistoryLoadingRef = useRef(false);+ const suppressNextScrollToEndRef = useRef(false);const suggestions = [t('chat.welcomeSuggestions.journey'),t('chat.welcomeSuggestions.skills'),];useEffect(() => {+ if (suppressNextScrollToEndRef.current) {+ suppressNextScrollToEndRef.current = false;+ return;+ }messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });}, [messages, isThinking]);+ useLayoutEffect(() => {+ if (!historyPager) {+ wasHistoryLoadingRef.current = false;+ prependScrollSnapRef.current = null;+ return;+ }+ const el = scrollContainerRef.current;+ if (!el) return;++ if (historyPager.loadingMore) {+ if (!wasHistoryLoadingRef.current) {+ prependScrollSnapRef.current = { sh: el.scrollHeight, st: el.scrollTop };+ }+ wasHistoryLoadingRef.current = true;+ return;+ }++ if (wasHistoryLoadingRef.current && prependScrollSnapRef.current) {+ const snap = prependScrollSnapRef.current;+ const delta = el.scrollHeight - snap.sh;+ if (delta > 0) {+ el.scrollTop = snap.st + delta;+ suppressNextScrollToEndRef.current = true;+ }+ prependScrollSnapRef.current = null;+ }+ wasHistoryLoadingRef.current = false;+ }, [historyPager, messages.length]);+const handleSuggestion = useCallback((text: string) => onSendMessage(text),[onSendMessage],@@ -80,7 +128,15 @@ export function ChatPanel({return (<div className="flex flex-col h-full">- <div className="flex-1 overflow-y-auto px-3 py-4">+ <div ref={scrollContainerRef} className="flex-1 overflow-y-auto px-3 py-4">+ {historyPager && messages.length > 0 ? (+ <HistoryPagerBar+ loadedPages={historyPager.loadedPages}+ totalPages={historyPager.totalPages}+ loadingMore={historyPager.loadingMore}+ onLoadMore={historyPager.onLoadMore}+ />+ ) : null}{messages.length === 0 ? (<div className="chat-welcome"><img src="/logo.png" alt={t('chat.welcomeLogoAlt')} className="chat-welcome__logo" />diff --git a/jiuwenclaw/web/src/components/SessionsPanel/index.tsx b/jiuwenclaw/web/src/components/SessionsPanel/index.tsxindex 7b63cc2441..cde1168993 100644--- a/jiuwenclaw/web/src/components/SessionsPanel/index.tsx+++ b/jiuwenclaw/web/src/components/SessionsPanel/index.tsx@@ -6,6 +6,9 @@ import { webRequest } from '../../services/webClient';interface SessionsPanelProps {currentSessionId: string;+ isConnected: boolean;+ isProcessing: boolean;+ onRestoreSession: (sessionId: string) => void | Promise<void>;}interface SessionListResponse {@@ -117,7 +120,17 @@ function toSessionFiles(raw: unknown[]): SessionFileItem[] {return rows;}-export function SessionsPanel({ currentSessionId }: SessionsPanelProps) {+function isPreviewableSessionFile(fileName: string): boolean {+ const lowerName = fileName.toLowerCase();+ return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json');+}++export function SessionsPanel({+ currentSessionId,+ isConnected,+ isProcessing,+ onRestoreSession,+}: SessionsPanelProps) {const { t } = useTranslation();const [sessions, setSessions] = useState<string[]>([]);const [loadingSessions, setLoadingSessions] = useState(true);@@ -229,6 +242,15 @@ export function SessionsPanel({ currentSessionId }: SessionsPanelProps) {() => (selectedSessionId ? parseSessionDisplayLabel(selectedSessionId, t) : t('sessions.noneSelected')),[selectedSessionId, t]);+ const canRestoreSelectedSession =+ Boolean(selectedSessionId?.startsWith('sess_')) && isConnected && !isProcessing;+ const restoreButtonTitle = !isConnected+ ? t('sessions.restoreDisabledNotConnected')+ : isProcessing+ ? t('sessions.restoreDisabledProcessing')+ : !selectedSessionId?.startsWith('sess_')+ ? t('sessions.restoreDisabledUnsupported')+ : t('sessions.restore');return (<div className="flex-1 min-h-0">@@ -257,11 +279,25 @@ export function SessionsPanel({ currentSessionId }: SessionsPanelProps) {<div className="flex-1 min-h-0 grid grid-cols-[minmax(0,1fr)_minmax(0,4fr)] gap-4"><div className="rounded-xl border border-border bg-card/70 backdrop-blur-sm overflow-hidden shadow-sm flex flex-col min-h-0"><div className="px-4 py-3 bg-secondary/30 border-b border-border">- <div>- <h3 className="text-sm font-medium text-text">{t('sessions.history')}</h3>- <p className="text-xs text-text-muted mt-1 mono">- {t('sessions.count', { count: sessions.length })}- </p>+ <div className="flex items-stretch justify-between gap-4">+ <div>+ <h3 className="text-sm font-medium text-text">{t('sessions.history')}</h3>+ <p className="text-xs text-text-muted mt-1 mono">+ {t('sessions.count', { count: sessions.length })}+ </p>+ </div>+ <button+ type="button"+ title={restoreButtonTitle}+ disabled={!canRestoreSelectedSession}+ onClick={() => {+ if (!selectedSessionId || !canRestoreSelectedSession) return;+ void onRestoreSession(selectedSessionId);+ }}+ className="btn !px-3 !py-1.5 shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {t('sessions.restore')}+ </button></div></div><div className="flex-1 overflow-auto p-2 space-y-1">@@ -321,7 +357,7 @@ export function SessionsPanel({ currentSessionId }: SessionsPanelProps) {) : (<div className="space-y-1">{files.map((file) => {- const canPreview = !file.isDirectory;+ const canPreview = !file.isDirectory && isPreviewableSessionFile(file.name);return (<buttonkey={file.path}@@ -347,7 +383,7 @@ export function SessionsPanel({ currentSessionId }: SessionsPanelProps) {<span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/50 text-text-muted">{t('sessions.folder')}</span>- ) : !file.isMarkdown ? (+ ) : !canPreview ? (<span className="text-[10px] px-1.5 py-0.5 rounded border border-border bg-secondary/50 text-text-muted">{t('sessions.notPreviewable')}</span>diff --git a/jiuwenclaw/web/src/features/historyRestore.ts b/jiuwenclaw/web/src/features/historyRestore.tsnew file mode 100644index 0000000000..d8232c921f--- /dev/null+++ b/jiuwenclaw/web/src/features/historyRestore.ts@@ -0,0 +1,496 @@+import { Message, MessageRole, WsEvent } from '../types';+import { webClient } from '../services/webClient';+import { normalizeFinalContent } from '../utils/finalContent';++export const HISTORY_GET_METHOD = 'history.get';+export const HISTORY_MESSAGE_EVENT = 'history.message';++/** 助手侧仅恢复这些事件;用户消息无 event_type,单独保留 */+const ALLOWED_ASSISTANT_EVENT_TYPES = new Set([+ 'chat.final',+ 'chat.tool_call',+ 'chat.tool_result',+]);++/** 后端约定:最后一帧 `history.message` 使用 `payload.status: done`(兼容旧版 `payload.content: done`) */+const HISTORY_RESTORE_DONE_CONTENT = 'done';+/** 流式 chunk 之间的兜底:正常情况由 `done` / `page_complete` 等结束帧关闭;仅当缺少明确结束标记时使用 */+const HISTORY_RESTORE_IDLE_MS = 500;++export interface HistoryToolReplayItem {+ kind: 'tool_call' | 'tool_result';+ at: string;+ payload: Record<string, unknown>;+}++type HistoryTimelineEntry =+ | { kind: 'message'; message: Message }+ | { kind: 'tool_call'; at: string; payload: Record<string, unknown> }+ | { kind: 'tool_result'; at: string; payload: Record<string, unknown> };++interface BeginHistoryRestoreOptions {+ sessionId: string;+ onReady: (messages: Message[], totalPages: number | null) => void;+ /** 与消息同一时间线顺序,用于恢复 ToolGroupDisplay */+ onToolReplay?: (items: HistoryToolReplayItem[]) => void;+ /** 无消息且无工具回放时调用;`totalPages` 来自流中最后一帧(若有) */+ onEmpty?: (totalPages: number | null) => void;+ onError?: (message: string) => void;+}++export interface HistoryRestoreHandle {+ generation: number;+ dispose: () => void;+}++let restoreGeneration = 0;+let activeRestore: HistoryRestoreHandle | null = null;++/** 分页拉取与全量恢复互斥,避免 chunk 串台 */+let activePageFetchDispose: (() => void) | null = null;++function disposeActivePageFetch(): void {+ activePageFetchDispose?.();+ activePageFetchDispose = null;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++function pickFirstString(input: Record<string, unknown>, keys: string[]): string | undefined {+ for (const key of keys) {+ const value = input[key];+ if (typeof value === 'string') {+ const trimmed = value.trim();+ if (trimmed) {+ return trimmed;+ }+ }+ }+ return undefined;+}++function normalizeHistoryRole(rawRole: unknown): MessageRole {+ if (typeof rawRole !== 'string') return 'assistant';+ const role = rawRole.trim().toLowerCase();+ if (role === 'user' || role === 'human') return 'user';+ if (role === 'assistant' || role === 'ai' || role === 'bot') return 'assistant';+ if (role === 'system') return 'system';+ if (role === 'tool' || role === 'tool_call' || role === 'tool_result') return 'tool';+ return 'assistant';+}++function isHistoryRestoreDoneContent(rawContent: unknown): boolean {+ if (typeof rawContent !== 'string') {+ return false;+ }+ return rawContent.trim().toLowerCase() === HISTORY_RESTORE_DONE_CONTENT;+}++function isHistoryRestoreDonePayload(payload: Record<string, unknown>): boolean {+ const rawStatus = payload.status;+ if (typeof rawStatus === 'string' && rawStatus.trim().toLowerCase() === HISTORY_RESTORE_DONE_CONTENT) {+ return true;+ }+ return isHistoryRestoreDoneContent(payload.content);+}++function extractHistoryMessagePayload(payload: Record<string, unknown>): unknown {+ if ('message' in payload) {+ return payload.message;+ }+ return payload.content;+}++function normalizeHistoryContent(+ rawContent: unknown,+ onError?: (message: string) => void+): Record<string, unknown> | null {+ if (isHistoryRestoreDoneContent(rawContent)) {+ return null;+ }+ if (isRecord(rawContent)) {+ return rawContent;+ }+ if (typeof rawContent !== 'string') {+ return null;+ }+ try {+ const parsed = JSON.parse(rawContent);+ if (isRecord(parsed)) {+ return parsed;+ }+ return null;+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ onError?.(`history.message.content parse failed: ${detail}`);+ return null;+ }+}++function recordTimestampIso(record: Record<string, unknown>): string {+ const ts = record.timestamp;+ if (typeof ts === 'number' && Number.isFinite(ts)) {+ const millis = ts > 1_000_000_000_000 ? ts : ts * 1000;+ const d = new Date(millis);+ if (!Number.isNaN(d.getTime())) {+ return d.toISOString();+ }+ }+ if (typeof ts === 'string') {+ const parsed = Date.parse(ts);+ if (!Number.isNaN(parsed)) {+ return new Date(parsed).toISOString();+ }+ }+ return new Date().toISOString();+}++/** 合并 event_payload 与顶层 content,供 final / tool 解析 */+function buildEventPayloadForRecord(record: Record<string, unknown>): Record<string, unknown> {+ const ep = record.event_payload;+ const base = isRecord(ep) ? { ...ep } : {};+ if (typeof record.content === 'string' && typeof base.content !== 'string') {+ base.content = record.content;+ }+ return base;+}++function parseHistoryTimelineEntry(+ record: Record<string, unknown>,+ sessionId: string+): HistoryTimelineEntry | null {+ const role = normalizeHistoryRole(record.role);+ const at = recordTimestampIso(record);++ if (role === 'user') {+ const content = pickFirstString(record, ['content', 'text', 'body']) ?? '';+ if (!content.trim()) {+ return null;+ }+ const id =+ pickFirstString(record, ['id', 'message_id', 'msg_id']) ?? `hist-user-${sessionId}-${at}`;+ return {+ kind: 'message',+ message: { id, role: 'user', content, timestamp: at },+ };+ }++ if (role !== 'assistant') {+ return null;+ }++ let eventType = typeof record.event_type === 'string' ? record.event_type.trim() : '';++ if (!eventType) {+ const raw = String(record.content ?? '').trim();+ if (!raw) {+ return null;+ }+ eventType = 'chat.final';+ }++ if (!ALLOWED_ASSISTANT_EVENT_TYPES.has(eventType)) {+ return null;+ }++ const payload = buildEventPayloadForRecord(record);++ if (eventType === 'chat.final') {+ const content = normalizeFinalContent(payload);+ if (!content.trim()) {+ return null;+ }+ const id =+ pickFirstString(record, ['id', 'message_id', 'msg_id']) ?? `hist-final-${sessionId}-${at}`;+ return {+ kind: 'message',+ message: { id, role: 'assistant', content, timestamp: at },+ };+ }++ if (eventType === 'chat.tool_call') {+ return { kind: 'tool_call', at, payload };+ }++ if (eventType === 'chat.tool_result') {+ return { kind: 'tool_result', at, payload };+ }++ return null;+}++/** 工作区 history.json 预览:最多展示条数(按消息时间取最近) */+export const HISTORY_FILE_PREVIEW_MAX_MESSAGES = 20;++/**+ * 将磁盘上的 history.json 解析结果(通常为记录数组)转为与历史恢复相同的筛选规则下的消息列表,+ * 并按时间升序仅保留时间上最近的 {@link HISTORY_FILE_PREVIEW_MAX_MESSAGES} 条用户/助手消息。+ */+export function parseHistoryJsonFileToPreviewMessages(+ parsed: unknown,+ sessionId: string+): Message[] {+ if (!Array.isArray(parsed)) {+ return [];+ }++ const messages: Message[] = [];+ for (const item of parsed) {+ if (!isRecord(item)) {+ continue;+ }+ const entry = parseHistoryTimelineEntry(item, sessionId);+ if (entry?.kind === 'message') {+ messages.push(entry.message);+ }+ }++ const sorted = [...messages].sort(+ (a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp)+ );+ return sorted.slice(-HISTORY_FILE_PREVIEW_MAX_MESSAGES);+}++function isHistoryBatchEnd(payload: Record<string, unknown>): boolean {+ const markers = [+ payload.done,+ payload.last,+ payload.is_last,+ payload.page_complete,+ payload.end,+ ];+ return markers.some((marker) => marker === true);+}++/**+ * 仅处理属于当前 `history.get` 会话的帧,避免多标签/乱序下的串台。+ * 无 `session_id` 时:丢弃数据行;仍接受明确的结束帧(兼容未注入 id 的旧链路)。+ */+function shouldProcessHistoryPayload(payload: Record<string, unknown>, expectedSessionId: string): boolean {+ const sid = typeof payload.session_id === 'string' ? payload.session_id.trim() : '';+ if (sid && sid !== expectedSessionId) {+ return false;+ }+ if (!sid) {+ return isHistoryRestoreDonePayload(payload) || isHistoryBatchEnd(payload);+ }+ return true;+}++export function beginHistoryRestore(options: BeginHistoryRestoreOptions): HistoryRestoreHandle {+ disposeActivePageFetch();+ activeRestore?.dispose();++ const generation = restoreGeneration + 1;+ restoreGeneration = generation;++ const entries: HistoryTimelineEntry[] = [];+ let totalPages: number | null = null;+ let idleTimer: number | null = null;+ let disposed = false;++ const clearIdleTimer = () => {+ if (idleTimer !== null) {+ window.clearTimeout(idleTimer);+ idleTimer = null;+ }+ };++ const unsubscribe = webClient.on(HISTORY_MESSAGE_EVENT, (event: WsEvent) => {+ if (disposed || generation !== restoreGeneration) {+ return;+ }++ const payload = event.payload;+ if (!shouldProcessHistoryPayload(payload, options.sessionId)) {+ return;+ }++ if (typeof payload.total_pages === 'number' && Number.isFinite(payload.total_pages)) {+ totalPages = payload.total_pages;+ }++ if (isHistoryRestoreDonePayload(payload)) {+ clearIdleTimer();+ finalize();+ return;+ }++ const raw = extractHistoryMessagePayload(payload);+ const record = normalizeHistoryContent(raw, options.onError);+ if (record) {+ const entry = parseHistoryTimelineEntry(record, options.sessionId);+ if (entry) {+ entries.unshift(entry);+ }+ }++ if (isHistoryBatchEnd(payload)) {+ clearIdleTimer();+ finalize();+ return;+ }++ clearIdleTimer();+ idleTimer = window.setTimeout(() => {+ finalize();+ }, HISTORY_RESTORE_IDLE_MS);+ });++ function dispose(): void {+ if (disposed) return;+ disposed = true;+ clearIdleTimer();+ unsubscribe();+ if (activeRestore?.generation === generation) {+ activeRestore = null;+ }+ }++ function finalize(): void {+ if (disposed) return;++ const messages: Message[] = [];+ const toolReplay: HistoryToolReplayItem[] = [];+ for (const e of entries) {+ if (e.kind === 'message') {+ messages.push(e.message);+ } else {+ toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });+ }+ }++ dispose();++ if (messages.length === 0 && toolReplay.length === 0) {+ options.onEmpty?.(totalPages);+ return;+ }+ options.onReady(messages, totalPages);+ if (toolReplay.length > 0) {+ options.onToolReplay?.(toolReplay);+ }+ }++ const handle: HistoryRestoreHandle = { generation, dispose };+ activeRestore = handle;+ return handle;+}++export interface FetchHistoryPageResult {+ messages: Message[];+ toolReplay: HistoryToolReplayItem[];+ totalPages: number | null;+}++export interface FetchHistoryPageOptions {+ sessionId: string;+ onReady: (result: FetchHistoryPageResult) => void;+ onEmpty?: (totalPages: number | null) => void;+ onError?: (message: string) => void;+}++/**+ * 拉取单页历史(用于「加载更早」),与 beginHistoryRestore 互斥。+ * 调用方需在订阅建立后再发 `history.get`(含对应 `page_idx`)。+ */+export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestoreHandle {+ disposeActivePageFetch();+ activeRestore?.dispose();++ const generation = restoreGeneration + 1;+ restoreGeneration = generation;++ const entries: HistoryTimelineEntry[] = [];+ let totalPages: number | null = null;+ let idleTimer: number | null = null;+ let disposed = false;++ const clearIdleTimer = () => {+ if (idleTimer !== null) {+ window.clearTimeout(idleTimer);+ idleTimer = null;+ }+ };++ const unsubscribe = webClient.on(HISTORY_MESSAGE_EVENT, (event: WsEvent) => {+ if (disposed || generation !== restoreGeneration) {+ return;+ }++ const payload = event.payload;+ if (!shouldProcessHistoryPayload(payload, options.sessionId)) {+ return;+ }++ if (typeof payload.total_pages === 'number' && Number.isFinite(payload.total_pages)) {+ totalPages = payload.total_pages;+ }++ if (isHistoryRestoreDonePayload(payload)) {+ clearIdleTimer();+ finalize();+ return;+ }++ const raw = extractHistoryMessagePayload(payload);+ const record = normalizeHistoryContent(raw, options.onError);+ if (record) {+ const entry = parseHistoryTimelineEntry(record, options.sessionId);+ if (entry) {+ entries.unshift(entry);+ }+ }++ if (isHistoryBatchEnd(payload)) {+ clearIdleTimer();+ finalize();+ return;+ }++ clearIdleTimer();+ idleTimer = window.setTimeout(() => {+ finalize();+ }, HISTORY_RESTORE_IDLE_MS);+ });++ function dispose(): void {+ if (disposed) return;+ disposed = true;+ clearIdleTimer();+ unsubscribe();+ activePageFetchDispose = null;+ if (activeRestore?.generation === generation) {+ activeRestore = null;+ }+ }++ function finalize(): void {+ if (disposed) return;++ const messages: Message[] = [];+ const toolReplay: HistoryToolReplayItem[] = [];+ for (const e of entries) {+ if (e.kind === 'message') {+ messages.push(e.message);+ } else {+ toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });+ }+ }++ dispose();++ if (messages.length === 0 && toolReplay.length === 0) {+ options.onEmpty?.(totalPages);+ return;+ }+ options.onReady({ messages, toolReplay, totalPages });+ }++ const handle: HistoryRestoreHandle = { generation, dispose };+ activeRestore = handle;+ activePageFetchDispose = dispose;+ return handle;+}diff --git a/jiuwenclaw/web/src/hooks/useWebSocket.ts b/jiuwenclaw/web/src/hooks/useWebSocket.tsindex d13409b045..5b8e760da0 100644--- a/jiuwenclaw/web/src/hooks/useWebSocket.ts+++ b/jiuwenclaw/web/src/hooks/useWebSocket.ts@@ -30,6 +30,7 @@ import {playAudioBase64,sanitizeTtsText,stopAllTts,+ normalizeFinalContent,} from '../utils';import {normalizeToolCallPayload,@@ -78,59 +79,6 @@ interface UseWebSocketReturn {getInflightCount: () => number;}-function decodeQuotedPythonLikeString(raw: string): string {- return raw- .replace(/\\r/g, '\r')- .replace(/\\n/g, '\n')- .replace(/\\t/g, '\t')- .replace(/\\'/g, "'")- .replace(/\\"/g, '"')- .replace(/\\\\/g, '\\');-}--function normalizeFinalDisplayText(text: string): string {- return text.replace(/^(?:\r?\n)+/, '');-}--function normalizeFinalContent(payload: Record<string, unknown>): string {- const rawContent = payload.content;- if (typeof rawContent !== 'string') {- return '';- }-- const trimmed = rawContent.trim();-- // 优先按标准 JSON 解析(例如 {"output":"...","result_type":"answer"})- if (trimmed.startsWith('{') && trimmed.endsWith('}')) {- try {- const parsed = JSON.parse(trimmed) as Record<string, unknown>;- if (typeof parsed.output === 'string') {- return normalizeFinalDisplayText(parsed.output);- }- } catch {- // ignore: 继续尝试 Python dict 风格兼容解析- }- }-- // 常规场景:后端直接返回纯文本- if (!trimmed.includes('result_type') || !trimmed.includes('output')) {- return normalizeFinalDisplayText(rawContent);- }-- // 兼容后端返回的 Python dict 字符串(例如 "{'output': '...'}")- const singleQuoted = rawContent.match(/['"]output['"]\s*:\s*'((?:\\'|[^'])*)'/s);- if (singleQuoted?.[1] != null) {- return normalizeFinalDisplayText(decodeQuotedPythonLikeString(singleQuoted[1]));- }-- const doubleQuoted = rawContent.match(/['"]output['"]\s*:\s*"((?:\\"|[^"])*)"/s);- if (doubleQuoted?.[1] != null) {- return normalizeFinalDisplayText(decodeQuotedPythonLikeString(doubleQuoted[1]));- }-- return normalizeFinalDisplayText(rawContent);-}-function normalizeAgentMode(rawMode: unknown): AgentMode {if (typeof rawMode !== 'string') return 'plan';const normalized = rawMode.trim().toLowerCase();diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.jsonindex e37d9f0bd7..b108c85c10 100644--- a/jiuwenclaw/web/src/i18n/locales/en.json+++ b/jiuwenclaw/web/src/i18n/locales/en.json@@ -55,7 +55,13 @@"removeTask": "Remove task","holdToSpeak": "Hold to speak","send": "Send (Enter)",- "newSessionDisabled": "Cannot create session while processing or recording"+ "newSessionDisabled": "Cannot create session while processing or recording",+ "historyPager": {+ "loadedOfTotal": "History loaded {{loaded}} / {{total}} pages",+ "loadMore": "Load older messages",+ "loadingMore": "Loading…",+ "allLoaded": "All history loaded"+ }},"connection": {"connected": "Connected",@@ -85,6 +91,11 @@"history": "Session History","count": "Up to 20 items, currently {{count}}","empty": "No sessions",+ "restore": "Restore session",+ "restoreDisabledNotConnected": "Disconnected: cannot restore session",+ "restoreDisabledProcessing": "Assistant is busy: wait until idle to restore a session",+ "restoreDisabledUnsupported": "Only web frontend sessions (sess_) can be restored",+ "restoreEmpty": "This session has no restorable messages (empty or filtered). You can still chat from here.","delete": "Delete session","files": "Session Files","selectFirst": "Select a session first",@@ -110,7 +121,8 @@"errors": {"loadSessions": "Failed to load sessions","loadFiles": "Failed to load session files",- "deleteSession": "Failed to delete session: {{sessionId}}"+ "deleteSession": "Failed to delete session: {{sessionId}}",+ "restoreFailed": "Failed to restore session: {{sessionId}}"}},"sessionSidebar": {@@ -565,20 +577,22 @@"empty": "No files","notPreviewable": "Not previewable","contentPreview": "Content Preview",- "selectMarkdown": "Select a Markdown file on the left to view",- "selectMarkdownContent": "Select a Markdown file on the left to view its content",- "markdownOnly": "Only Markdown (.md/.mdx) preview is supported",+ "selectMarkdown": "Select a previewable file on the left to view",+ "selectMarkdownContent": "Select a previewable file on the left to view its content",+ "markdownOnly": "Only Markdown/JSON (.md/.mdx/.json) preview is supported","errors": {"refreshFailed": "Refresh failed: unable to rebuild the agent file index. Check the generator script logs.","loadFailed": "Unable to read the agent file list. Check whether agent/workspace/agent-data.json has been generated."}},"fileViewer": {+ "chatPreview": "Chat preview",+ "historyPreviewEmpty": "No messages to show after the same filtering as history restore (or the file is empty). Turn off preview to see raw JSON.","edit": "Edit","unknownError": "Unknown error",- "fileMissingPrefix": "This file does not exist. Create the Markdown file at",+ "fileMissingPrefix": "This file does not exist. Create the file at","fileMissingSuffix": "before editing.",- "notPreviewable": "This file cannot be previewed. Only Markdown (.md/.mdx) files are supported."+ "notPreviewable": "This file cannot be previewed. Only Markdown/JSON (.md/.mdx/.json) files are supported."},"chatUi": {"copyMessage": "Copy message",diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.jsonindex 075dbcb370..741643c769 100644--- a/jiuwenclaw/web/src/i18n/locales/zh.json+++ b/jiuwenclaw/web/src/i18n/locales/zh.json@@ -55,7 +55,13 @@"removeTask": "移除任务","holdToSpeak": "按住说话","send": "发送 (Enter)",- "newSessionDisabled": "处理中或录音中不可新建"+ "newSessionDisabled": "处理中或录音中不可新建",+ "historyPager": {+ "loadedOfTotal": "历史已加载 {{loaded}} / {{total}} 页",+ "loadMore": "加载更早的消息",+ "loadingMore": "加载中…",+ "allLoaded": "已显示全部历史"+ }},"connection": {"connected": "已连接",@@ -85,6 +91,11 @@"history": "历史会话","count": "最多 20 条,当前 {{count}} 条","empty": "暂无会话",+ "restore": "恢复会话",+ "restoreDisabledNotConnected": "连接断开,无法恢复会话",+ "restoreDisabledProcessing": "助手处理中,请结束当前任务后再恢复会话",+ "restoreDisabledUnsupported": "仅支持恢复 web 前端会话(sess_)",+ "restoreEmpty": "该会话没有可恢复的消息(为空或均被过滤)。仍可在此继续对话。","delete": "删除会话","files": "会话文件","selectFirst": "请先选择会话",@@ -110,7 +121,8 @@"errors": {"loadSessions": "会话列表加载失败","loadFiles": "会话文件列表加载失败",- "deleteSession": "删除会话失败:{{sessionId}}"+ "deleteSession": "删除会话失败:{{sessionId}}",+ "restoreFailed": "恢复会话失败:{{sessionId}}"}},"sessionSidebar": {@@ -565,20 +577,22 @@"empty": "暂无文件","notPreviewable": "不可预览","contentPreview": "内容预览",- "selectMarkdown": "选择左侧 Markdown 文件查看",- "selectMarkdownContent": "请选择左侧 Markdown 文件查看内容",- "markdownOnly": "仅支持 Markdown(.md/.mdx)预览",+ "selectMarkdown": "选择左侧可预览文件查看",+ "selectMarkdownContent": "请选择左侧可预览文件查看内容",+ "markdownOnly": "仅支持 Markdown/JSON(.md/.mdx/.json)预览","errors": {"refreshFailed": "刷新失败:无法重建 agent 文件索引,请检查生成脚本日志。","loadFailed": "无法读取 agent 文件列表,请检查 agent/workspace/agent-data.json 是否已生成。"}},"fileViewer": {+ "chatPreview": "对话预览",+ "historyPreviewEmpty": "按与历史恢复相同的规则过滤后,没有可展示的消息(或文件为空)。可关闭预览查看原始 JSON。","edit": "编辑","unknownError": "未知错误","fileMissingPrefix": "文件不存在。请先在",- "fileMissingSuffix": "创建该 Markdown 文件后再编辑。",- "notPreviewable": "该文件无法预览,仅支持 Markdown(.md/.mdx)文件"+ "fileMissingSuffix": "创建该文件后再编辑。",+ "notPreviewable": "该文件无法预览,仅支持 Markdown/JSON(.md/.mdx/.json)文件"},"chatUi": {"copyMessage": "复制消息",diff --git a/jiuwenclaw/web/src/stores/chatStore.ts b/jiuwenclaw/web/src/stores/chatStore.tsindex 950b4a0fdd..c5d6b4bdbc 100644--- a/jiuwenclaw/web/src/stores/chatStore.ts+++ b/jiuwenclaw/web/src/stores/chatStore.ts@@ -79,12 +79,14 @@ interface ChatState {setThinking: (status: boolean) => void;setPaused: (paused: boolean, task?: string | null) => void;setInterruptResult: (result: InterruptResultPayload | null) => void;- addToolCall: (toolCall: ToolCall) => void;- addToolResult: (toolResult: ToolResult) => void;+ addToolCall: (toolCall: ToolCall, options?: { startedAt?: string }) => void;+ addToolResult: (toolResult: ToolResult, options?: { updatedAt?: string }) => void;markTimedOutExecutions: () => void;updateSubtask: (payload: SubtaskUpdatePayload) => void;clearSubtasks: () => void;clearMessages: () => void;+ /** 在列表头部插入更早的历史消息(数组内建议时间升序) */+ prependMessages: (olderFirst: Message[]) => void;// 任务队列相关addToTaskQueue: (content: string) => void;clearTaskQueue: () => void;@@ -196,7 +198,7 @@ export const useChatStore = create<ChatState>((set, get) => ({}},- addToolCall: (toolCall) => {+ addToolCall: (toolCall, options) => {set((state) => {if (!toolCall.id) {const nextDropped = state.toolMetrics.toolCallDedupDropped + 1;@@ -231,21 +233,25 @@ export const useChatStore = create<ChatState>((set, get) => ({};}const nowIso = new Date().toISOString();+ const startedAt =+ typeof options?.startedAt === 'string' && options.startedAt.trim()+ ? options.startedAt.trim()+ : nowIso;const orphanResult = state.orphanResults.get(toolCall.id);const nextExecutions = new Map(state.toolExecutions);const nextOrphanResults = new Map(state.orphanResults);if (orphanResult) {nextOrphanResults.delete(toolCall.id);}- const timeoutAt = computeTimeoutAt(nowIso);+ const timeoutAt = computeTimeoutAt(startedAt);const resultStatus = orphanResult ? resolveExecutionStatus(orphanResult) : 'pending';nextExecutions.set(toolCall.id, {toolCallId: toolCall.id,toolCall,result: orphanResult,status: resultStatus,- startedAt: nowIso,- updatedAt: nowIso,+ startedAt,+ updatedAt: startedAt,timeoutAt,});@@ -258,7 +264,7 @@ export const useChatStore = create<ChatState>((set, get) => ({});},- addToolResult: (toolResult) => {+ addToolResult: (toolResult, options) => {set((state) => {const incomingToolCallId = toolResult.toolCallId;if (!incomingToolCallId) {@@ -278,6 +284,10 @@ export const useChatStore = create<ChatState>((set, get) => ({};}const nowIso = new Date().toISOString();+ const updatedAt =+ typeof options?.updatedAt === 'string' && options.updatedAt.trim()+ ? options.updatedAt.trim()+ : nowIso;const existingExecution = state.toolExecutions.get(incomingToolCallId);if (!existingExecution) {@@ -339,7 +349,7 @@ export const useChatStore = create<ChatState>((set, get) => ({...existingExecution,result: toolResult,status: nextStatus,- updatedAt: nowIso,+ updatedAt,resultArrivedAfterTimeout:existingExecution.status === 'timeout' ? true : existingExecution.resultArrivedAfterTimeout,});@@ -442,6 +452,15 @@ export const useChatStore = create<ChatState>((set, get) => ({set({ activeSubtasks: new Map() });},+ prependMessages: (olderFirst) => {+ if (!olderFirst.length) {+ return;+ }+ set((state) => ({+ messages: [...olderFirst, ...state.messages],+ }));+ },+clearMessages: () => {set({messages: [],diff --git a/jiuwenclaw/web/src/utils/finalContent.ts b/jiuwenclaw/web/src/utils/finalContent.tsnew file mode 100644index 0000000000..8ad2ab53ed--- /dev/null+++ b/jiuwenclaw/web/src/utils/finalContent.ts@@ -0,0 +1,53 @@+/**+ * 将 chat.final 的 payload 规范为可展示的纯文本(与实时 WS 处理一致)。+ */++function decodeQuotedPythonLikeString(raw: string): string {+ return raw+ .replace(/\\r/g, '\r')+ .replace(/\\n/g, '\n')+ .replace(/\\t/g, '\t')+ .replace(/\\'/g, "'")+ .replace(/\\"/g, '"')+ .replace(/\\\\/g, '\\');+}++function normalizeFinalDisplayText(text: string): string {+ return text.replace(/^(?:\r?\n)+/, '');+}++export function normalizeFinalContent(payload: Record<string, unknown>): string {+ const rawContent = payload.content;+ if (typeof rawContent !== 'string') {+ return '';+ }++ const trimmed = rawContent.trim();++ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {+ try {+ const parsed = JSON.parse(trimmed) as Record<string, unknown>;+ if (typeof parsed.output === 'string') {+ return normalizeFinalDisplayText(parsed.output);+ }+ } catch {+ // ignore: 继续尝试 Python dict 风格兼容解析+ }+ }++ if (!trimmed.includes('result_type') || !trimmed.includes('output')) {+ return normalizeFinalDisplayText(rawContent);+ }++ const singleQuoted = rawContent.match(/['"]output['"]\s*:\s*'((?:\\'|[^'])*)'/s);+ if (singleQuoted?.[1] != null) {+ return normalizeFinalDisplayText(decodeQuotedPythonLikeString(singleQuoted[1]));+ }++ const doubleQuoted = rawContent.match(/['"]output['"]\s*:\s*"((?:\\"|[^"])*)"/s);+ if (doubleQuoted?.[1] != null) {+ return normalizeFinalDisplayText(decodeQuotedPythonLikeString(doubleQuoted[1]));+ }++ return normalizeFinalDisplayText(rawContent);+}diff --git a/jiuwenclaw/web/src/utils/index.ts b/jiuwenclaw/web/src/utils/index.tsindex 9dc72aa5b9..069a78fb35 100644--- a/jiuwenclaw/web/src/utils/index.ts+++ b/jiuwenclaw/web/src/utils/index.ts@@ -5,3 +5,4 @@export * from './formatters';export * from './env';export * from './tts';+export * from './finalContent';diff --git a/uv.lock b/uv.lockindex a45d64a9f3..d5ad82feb4 100644--- a/uv.lock+++ b/uv.lock@@ -1384,7 +1384,7 @@ wheels = [[[package]]name = "jiuwenclaw"-version = "0.1.5"+version = "0.1.7.post1"source = { editable = "." }dependencies = [{ name = "aiosqlite" },