Skip to content

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

Python

fix(session): make history jsonl durable, compatible, and reversible

yangzequ0648b1fa4a58
diff --git a/jiuwenswarm/agents/harness/common/memory/dreaming/sweeper.py b/jiuwenswarm/agents/harness/common/memory/dreaming/sweeper.py
index 981257faad..351aa57167 100644
--- a/jiuwenswarm/agents/harness/common/memory/dreaming/sweeper.py
+++ b/jiuwenswarm/agents/harness/common/memory/dreaming/sweeper.py
@@ -14,6 +14,11 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any
+from jiuwenswarm.server.runtime.session.session_history import (
+ _read_history,
+ _read_history_jsonl,
+)
+
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
@@ -160,10 +165,7 @@ class Sweeper:
if succeeded_ids:
sessions_root = Path(self._sessions_dir)
for sid in succeeded_ids:
- try:
- history_mtime = (sessions_root / sid / "history.json").stat().st_mtime
- except OSError:
- history_mtime = 0.0
+ history_mtime = self._get_session_history_mtime(sid) or 0.0
events = self._parse_history(sessions_root / sid)
rounds = self._detect_rounds(events)
self.scanned_sessions[sid] = {
@@ -209,10 +211,8 @@ class Sweeper:
new_ids = brand_new.copy()
for sid in all_ids & scanned_ids:
- history_path = sessions_root / sid / "history.json"
- try:
- current_mtime = history_path.stat().st_mtime
- except OSError:
+ current_mtime = self._get_session_history_mtime(sid)
+ if current_mtime is None:
continue
snapshot = self.scanned_sessions.get(sid, {})
if current_mtime <= snapshot.get("history_mtime", 0):
@@ -297,16 +297,30 @@ class Sweeper:
return False
return session_mode.startswith(self._mode)
+ def _get_session_history_mtime(self, session_id: str) -> float | None:
+ session_dir = Path(self._sessions_dir) / session_id
+ history_jsonl = session_dir / "history.jsonl"
+ history_json = session_dir / "history.json"
+ history_path = history_jsonl if history_jsonl.exists() else history_json
+ if not history_path.exists():
+ return None
+ try:
+ return history_path.stat().st_mtime
+ except OSError:
+ return None
+
@staticmethod
def _parse_history(session_dir: Path) -> list[dict]:
- path = session_dir / "history.json"
- if not path.exists():
- return []
+ history_jsonl = session_dir / "history.jsonl"
+ history_json = session_dir / "history.json"
try:
- data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
+ if history_jsonl.exists():
+ data = _read_history_jsonl(history_jsonl)
+ else:
+ data = _read_history(history_json)
if not isinstance(data, list):
return []
- except (OSError, json.JSONDecodeError):
+ except Exception:
return []
def _should_keep(entry: dict) -> bool:
@@ -780,4 +794,4 @@ Output a JSON array, each element is an independent memory entry. Output [] if n
```
Requirements: Each memory entry is self-contained. Better to have nothing than to force entries.
-"""
\ No newline at end of file
+"""
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.py
index 80482b40fa..268a36377c 100644
--- a/jiuwenswarm/agents/harness/common/session_ops_service.py
+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py
@@ -10,6 +10,13 @@ from pathlib import Path
from typing import Any, TYPE_CHECKING
from jiuwenswarm.common.utils import get_agent_sessions_dir, get_agent_workspace_dir
+from jiuwenswarm.server.runtime.session.session_history import (
+ get_read_history_path,
+ history_exists,
+ load_history_records,
+ write_history_records,
+ _write_records_to_path,
+)
if TYPE_CHECKING:
from openjiuwen.harness import DeepAgent
@@ -73,23 +80,24 @@ def fork_session(
target_dir.mkdir(parents=True, exist_ok=True)
- source_history = source_dir / "history.json"
- target_history = target_dir / "history.json"
history_data: list[dict[str, Any]] = []
- if source_history.exists():
- shutil.copy2(source_history, target_history)
+ if history_exists(source_session_id):
try:
- data = json.loads(target_history.read_text(encoding="utf-8"))
+ data = load_history_records(source_session_id)
if isinstance(data, list):
history_data = data
+ forked_records: list[dict[str, Any]] = []
for record in data:
- record["forked_from"] = {
+ forked_record = dict(record)
+ forked_record["forked_from"] = {
"session_id": source_session_id,
"original_id": record.get("id", ""),
}
- target_history.write_text(
- json.dumps(data, ensure_ascii=False, indent=2),
- encoding="utf-8",
+ forked_records.append(forked_record)
+ write_history_records(
+ target_session_id,
+ forked_records,
+ preserve_existing_format=False,
)
except Exception as exc:
logger.warning("fork: failed to add forked_from to history: %s", exc)
@@ -154,14 +162,13 @@ def rewind_session(
if turn_index < 1:
raise ValueError("turn_index must be >= 1")
- sessions_dir = get_agent_sessions_dir()
- history_path = sessions_dir / session_id / "history.json"
+ history_path = get_read_history_path(session_id)
if not history_path.exists():
raise ValueError("session history not found")
from jiuwenswarm.server.runtime.session.session_history import truncate_history_records
- history = json.loads(history_path.read_text(encoding="utf-8"))
+ history = load_history_records(session_id)
if not isinstance(history, list):
raise ValueError("invalid history format")
@@ -230,12 +237,11 @@ def compact_partial_session(
if turn_index < 1:
raise ValueError("turn_index must be >= 1")
- sessions_dir = get_agent_sessions_dir()
- history_path = sessions_dir / session_id / "history.json"
+ history_path = get_read_history_path(session_id)
if not history_path.exists():
raise ValueError("session history not found")
- history = json.loads(history_path.read_text(encoding="utf-8"))
+ history = load_history_records(session_id)
if not isinstance(history, list):
raise ValueError("invalid history format")
@@ -291,10 +297,7 @@ def compact_partial_session(
_WRITE_QUEUE.join()
with _FILE_LOCK:
- history_path.write_text(
- json.dumps(kept, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
+ _write_records_to_path(history_path, kept)
else:
raise ValueError(f"unknown direction: {direction}")
@@ -347,7 +350,7 @@ def compact_partial_session(
_WRITE_QUEUE.join()
with _FILE_LOCK:
- existing = json.loads(history_path.read_text(encoding="utf-8")) if history_path.exists() else []
+ existing = load_history_records(session_id) if history_path.exists() else []
if not isinstance(existing, list):
existing = []
existing.append(boundary_record)
@@ -373,10 +376,7 @@ def compact_partial_session(
}
existing.append(compact_summary_record)
- history_path.write_text(
- json.dumps(existing, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
+ _write_records_to_path(history_path, existing)
return {
"session_id": session_id,
@@ -413,14 +413,11 @@ def list_session_turns(
session_id: str,
project_dir: str | None = None,
) -> dict[str, Any]:
- sessions_dir = get_agent_sessions_dir()
- history_path = sessions_dir / session_id / "history.json"
-
- if not history_path.exists():
+ if not history_exists(session_id):
return {"turns": [], "total": 0}
try:
- history = json.loads(history_path.read_text(encoding="utf-8"))
+ history = load_history_records(session_id)
except Exception as exc:
logger.warning("list_session_turns: failed to read history: %s", exc)
return {"turns": [], "total": 0}
@@ -580,18 +577,15 @@ async def rewind_session_context(
return False
# --- 1. Load truncated history.json (already cut by caller) ---
- sessions_dir = get_agent_sessions_dir()
- history_path = sessions_dir / session_id / "history.json"
+ history_path = get_read_history_path(session_id)
if not history_path.exists():
- logger.warning("rewind_session_context: history.json not found for %s", session_id)
+ logger.warning("rewind_session_context: history not found for %s", session_id)
return False
try:
- history_records: list[dict[str, Any]] = json.loads(
- history_path.read_text(encoding="utf-8"),
- )
- except (json.JSONDecodeError, OSError) as exc:
- logger.warning("rewind_session_context: failed to read history.json for %s: %s", session_id, exc)
+ history_records = load_history_records(session_id)
+ except OSError as exc:
+ logger.warning("rewind_session_context: failed to read history for %s: %s", session_id, exc)
return False
if not isinstance(history_records, list) or not history_records:
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.py
index beffabc9f6..07b00b145b 100644
--- a/jiuwenswarm/channels/web/app_web.py
+++ b/jiuwenswarm/channels/web/app_web.py
@@ -33,6 +33,7 @@ from jiuwenswarm.agents.harness.common.tools.ssl_config import get_insecure_ssl_
from jiuwenswarm.agents.harness.team.bootstrap import configure_agent_teams_home
from jiuwenswarm.common.utils import get_agent_root_dir, get_logs_dir, \
get_agent_sessions_dir, get_root_dir, get_user_workspace_dir, is_package_installation, wait_for_tcp_port
+from jiuwenswarm.server.runtime.session.session_history import history_exists, load_history_records
configure_agent_teams_home()
@@ -583,12 +584,11 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
except ValueError as exc:
raise FileNotFoundError("history_not_found") from exc
- history_path = session_dir / "history.json"
- if not session_dir.exists() or not history_path.exists():
+ if not session_dir.exists() or not history_exists(session_id):
raise FileNotFoundError("history_not_found")
try:
- history_raw = json.loads(history_path.read_text(encoding="utf-8"))
- except json.JSONDecodeError as exc:
+ history_raw = load_history_records(session_id)
+ except Exception as exc:
raise ValueError("invalid_history_json") from exc
if not isinstance(history_raw, list):
raise ValueError("invalid_history_shape")
diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx
index 297b09f106..f0a72984cd 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx
@@ -5,6 +5,7 @@ import {
parseHistoryJsonFilePreviewMode,
parseHistoryJsonFileToPreviewMessages,
} from '../../features/historyRestore';
+import { isHistoryPreviewFile, parseHistoryFileContent } from '../../features/historyFilePreview';
import { ChatTimelineList } from '../ChatPanel/MessageList';
import '../ChatPanel/ChatPanel.css';
@@ -92,8 +93,8 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr
const [fileEncoding, setFileEncoding] = useState<string>('auto');
const lowerFileName = fileName.toLowerCase();
const isMarkdown = lowerFileName.endsWith('.md') || lowerFileName.endsWith('.mdx');
- const isJson = lowerFileName.endsWith('.json');
- const isHistoryJson = lowerFileName === 'history.json';
+ const isHistoryJson = isHistoryPreviewFile(fileName);
+ const isJson = lowerFileName.endsWith('.json') || lowerFileName.endsWith('.jsonl');
const isTodoJson = lowerFileName === 'todo.json';
const isPreviewable = isMarkdown || isJson;
const fileNotFound = Boolean(error && error.includes('HTTP 404'));
@@ -107,12 +108,12 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr
};
}
try {
- const parsed: unknown = JSON.parse(content);
+ const parsed: unknown = isHistoryJson ? parseHistoryFileContent(content) : JSON.parse(content);
return { parsed, invalid: false };
} catch {
return { parsed: null as unknown, invalid: true };
}
- }, [isJson, content]);
+ }, [isJson, isHistoryJson, content]);
const historyMessages = useMemo(() => {
if (!isHistoryJson || !historyChatPreview || !Array.isArray(jsonParseResult.parsed)) {
diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx
index 6a28d0381a..8cedd4dd8b 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FileViewer } from './FileViewer';
import { containsIgnoredDirectory } from '../../features/fileTreeFilters';
+import { isHistoryPreviewFile } from '../../features/historyFilePreview';
interface AgentPanelProps {
sessionId: string;
@@ -55,7 +56,7 @@ const normalizeFolderKey = (folderKey: string) => (folderKey ? folderKey : ROOT_
const isPreviewableFile = (fileName: string) => {
const lowerName = fileName.toLowerCase();
- return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json');
+ return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json') || isHistoryPreviewFile(fileName);
};
const getParentFolderKey = (folderKey: string) => {
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx
index 7de6943d6e..88c534f547 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FileViewer } from '../AgentPanel/FileViewer';
import { containsIgnoredDirectory } from '../../features/fileTreeFilters';
+import { isHistoryPreviewFile } from '../../features/historyFilePreview';
import { webRequest } from '../../services/webClient';
interface SessionsPanelProps {
@@ -228,7 +229,7 @@ function toSessionFiles(raw: unknown[]): SessionFileItem[] {
function isPreviewableSessionFile(fileName: string): boolean {
const lowerName = fileName.toLowerCase();
- return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json');
+ return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json') || isHistoryPreviewFile(fileName);
}
export function SessionsPanel({
diff --git a/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx
index 4cf946350a..578ada341c 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/TeamPanel/index.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { FileViewer } from '../AgentPanel/FileViewer';
import { webRequest } from '../../services/webClient';
import { containsIgnoredDirectory } from '../../features/fileTreeFilters';
+import { isHistoryPreviewFile } from '../../features/historyFilePreview';
interface SessionListResponse {
sessions?: unknown[];
@@ -30,7 +31,7 @@ function normalizePath(path: string): string {
function isPreviewableFile(fileName: string): boolean {
const lowerName = fileName.toLowerCase();
- return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json');
+ return lowerName.endsWith('.md') || lowerName.endsWith('.mdx') || lowerName.endsWith('.json') || isHistoryPreviewFile(fileName);
}
function getParentPath(filePath: string): string {
diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyFilePreview.ts b/jiuwenswarm/channels/web/frontend/src/features/historyFilePreview.ts
new file mode 100644
index 0000000000..dbb715f46f
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/historyFilePreview.ts
@@ -0,0 +1,20 @@
+export function isHistoryPreviewFile(fileName: string): boolean {
+ const lowerName = fileName.toLowerCase();
+ return lowerName === 'history.json' || lowerName === 'history.jsonl';
+}
+
+export function parseHistoryFileContent(content: string): unknown[] {
+ const trimmed = content.trim();
+ if (!trimmed) {
+ return [];
+ }
+ if (trimmed.startsWith('[')) {
+ const parsed = JSON.parse(trimmed);
+ return Array.isArray(parsed) ? parsed : [];
+ }
+ return trimmed
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => JSON.parse(line));
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index ae3379fb0b..dbd5095715 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -58,6 +58,16 @@ function isCompletedResumeResult(interruptResult: unknown): boolean {
return result.intent === 'resume' && result.success === true && result.has_active_task === false;
}
+function getConnectSignature(options: WebConnectOptions): string {
+ return JSON.stringify({
+ provider: options.provider || '',
+ apiKey: options.apiKey || '',
+ apiBase: options.apiBase || '',
+ model: options.model || '',
+ projectPath: options.projectPath || '',
+ });
+}
+
const TEAM_TASK_STATUS_SET = new Set<TeamTaskStatus>([
'pending',
'blocked',
@@ -438,6 +448,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const [isConnected, setIsConnected] = useState(false);
const [connectionState, setConnectionState] =
useState<WebConnectionState>('idle');
+ const lastConnectSignatureRef = useRef<string>('');
const onConnectRef = useRef(onConnect);
const onDisconnectRef = useRef(onDisconnect);
const onErrorRef = useRef(onError);
@@ -2439,13 +2450,42 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
model,
projectPath,
};
- void webClient.connect(connectOptions).catch((error) => {
- const webError = error as WebError;
- setConnectionStats({ lastError: webError.message });
- onErrorRef.current?.(webError.message || 'WebSocket connection error');
- });
+ const nextSignature = getConnectSignature(connectOptions);
+ const previousSignature = lastConnectSignatureRef.current;
+ const state = webClient.getState();
+
+ if (nextSignature === previousSignature && state !== 'closed') {
+ return;
+ }
+
+ lastConnectSignatureRef.current = nextSignature;
+
+ const runConnect = async () => {
+ try {
+ if (previousSignature && previousSignature !== nextSignature && state !== 'closed') {
+ await webClient.disconnect('connect options changed');
+ }
+ await webClient.connect(connectOptions);
+ } catch (error) {
+ const webError = error as WebError;
+ setConnectionStats({ lastError: webError.message });
+ onErrorRef.current?.(webError.message || 'WebSocket connection error');
+ }
+ };
+ void runConnect();
+ }, [
+ apiBase,
+ apiKey,
+ model,
+ projectPath,
+ provider,
+ setConnectionStats,
+ ]);
+
+ useEffect(() => {
return () => {
+ lastConnectSignatureRef.current = '';
webClient.disconnect();
clearMessages();
clearTodos();
@@ -2457,14 +2497,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
setConnectionStats({ state: 'closed', inflight: 0 });
};
}, [
- apiBase,
- apiKey,
clearMessages,
clearSubtasks,
clearTodos,
- model,
- projectPath,
- provider,
setContextCompressionStats,
setConnectionStats,
setConnected,
diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.ts
index 536b2662c6..c16f0f7457 100644
--- a/jiuwenswarm/channels/web/frontend/vite.config.ts
+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts
@@ -255,14 +255,23 @@ function devFileContentApi(): Plugin {
return
}
- const historyPath = path.resolve(sessionDir, 'history.json')
+ const jsonlHistoryPath = path.resolve(sessionDir, 'history.jsonl')
+ const legacyHistoryPath = path.resolve(sessionDir, 'history.json')
+ const historyPath = fs.existsSync(jsonlHistoryPath) ? jsonlHistoryPath : legacyHistoryPath
if (!fs.existsSync(sessionDir) || !fs.existsSync(historyPath)) {
writeJson(404, { error: 'history_not_found' })
return
}
try {
- const historyRaw = JSON.parse(fs.readFileSync(historyPath, 'utf-8')) as unknown
+ const historyText = fs.readFileSync(historyPath, 'utf-8')
+ const historyRaw = historyPath.endsWith('.jsonl')
+ ? historyText
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => JSON.parse(line) as unknown)
+ : (JSON.parse(historyText) as unknown)
if (!Array.isArray(historyRaw)) {
writeJson(400, { error: 'invalid_history_shape' })
return
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 646fadb809..a4c9a8da21 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -39,7 +39,12 @@ from jiuwenswarm.agents.harness.common.rails.permissions.permissions_persist imp
from jiuwenswarm.extensions.hooks_context import AgentServerChatHookContext
from jiuwenswarm.server.runtime.agent_manager import AgentManager, ACP_DEFAULT_CAPABILITIES
from jiuwenswarm.server.runtime.session.session_metadata import get_all_sessions_metadata, remove_session_metadata_cache
-from jiuwenswarm.server.runtime.session.session_history import append_compact_history_records, read_team_history_records
+from jiuwenswarm.server.runtime.session.session_history import (
+ append_compact_history_records,
+ history_exists,
+ load_history_records,
+ read_team_history_records,
+)
from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (
build_filesystem_policy,
find_auto_managed_match,
@@ -2597,6 +2602,7 @@ class AgentWebSocketServer:
payload={
"event_type": "history.message",
"message": item,
+ "session_id": str(session_id or ""),
"total_pages": total_pages,
"page_idx": page,
},
@@ -2616,6 +2622,7 @@ class AgentWebSocketServer:
payload={
"event_type": "history.message",
"status": "done",
+ "session_id": str(session_id or ""),
"total_pages": total_pages,
"page_idx": page,
},
@@ -5244,11 +5251,11 @@ class AgentWebSocketServer:
if not isinstance(page_idx, int) or page_idx <= 0:
return None
- history_path: Path = get_agent_sessions_dir() / session_id.strip() / "history.json"
- if not history_path.exists():
+ normalized_session_id = session_id.strip()
+ if not history_exists(normalized_session_id):
return None
try:
- raw = json.loads(history_path.read_text(encoding="utf-8"))
+ raw = load_history_records(normalized_session_id)
except Exception:
return None
if not isinstance(raw, list):
@@ -5270,7 +5277,7 @@ class AgentWebSocketServer:
page_messages = ordered[start:end]
logger.debug(
"[history.get] session_id=%s page_idx=%s raw_total=%s restorable_total=%s total_pages=%s returned=%s",
- session_id.strip(),
+ normalized_session_id,
page_idx,
len(raw),
total,
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 0b87bfd105..a24caf892c 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1581,6 +1581,42 @@ class JiuWenSwarm:
stream_done = asyncio.Event()
final_answer_content = ""
final_answer_chunks: list[str] = []
+ durable_pending_final_chunks: list[str] = []
+ durable_pending_reasoning_chunks: list[str] = []
+ durable_final_content = ""
+
+ def _consume_durable_reasoning_content() -> str:
+ nonlocal durable_pending_reasoning_chunks
+ reasoning_text = "".join(durable_pending_reasoning_chunks)
+ durable_pending_reasoning_chunks = []
+ return reasoning_text if reasoning_text.strip() else ""
+
+ def _attach_reasoning_content(extra_fields: dict[str, Any] | None = None) -> dict[str, Any] | None:
+ reasoning_text = _consume_durable_reasoning_content()
+ if not reasoning_text:
+ return extra_fields
+ merged = dict(extra_fields) if isinstance(extra_fields, dict) else {}
+ merged["reasoning_content"] = reasoning_text
+ return merged
+
+ def _persist_pending_final_text() -> None:
+ nonlocal durable_pending_final_chunks, durable_final_content
+ pending_text = "".join(durable_pending_final_chunks)
+ durable_pending_final_chunks = []
+ if not pending_text or pending_text == durable_final_content:
+ return
+ append_history_record(
+ session_id=session_id,
+ request_id=rid,
+ channel_id=cid,
+ role="assistant",
+ event_type="chat.final",
+ content=pending_text,
+ timestamp=time.time(),
+ extra=_attach_reasoning_content(),
+ mode=request.params.get("mode", "unknown"),
+ )
+ durable_final_content = pending_text
async def run_stream_task():
try:
@@ -1672,14 +1708,25 @@ class JiuWenSwarm:
)
payload_content = str(data.payload.get("content", ""))
- if et == "chat.delta" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):
- suppress_a2ui_stream = True
+ if et == "chat.delta":
final_answer_chunks.append(payload_content)
- continue
- if et == "chat.final" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):
- suppress_a2ui_stream = True
- final_answer_content = payload_content
- continue
+ if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):
+ suppress_a2ui_stream = True
+ continue
+ durable_pending_final_chunks.append(payload_content)
+ should_record = False
+ elif et == "chat.reasoning":
+ durable_pending_reasoning_chunks.append(payload_content)
+ should_record = False
+ elif et == "chat.tool_call":
+ _persist_pending_final_text()
+ elif et == "chat.final":
+ if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):
+ suppress_a2ui_stream = True
+ final_answer_content = payload_content
+ durable_pending_final_chunks = []
+ continue
+ durable_pending_final_chunks = []
if should_record:
payload_dict = dict(data.payload)
@@ -1691,6 +1738,8 @@ class JiuWenSwarm:
for k, v in event_data.items():
if k not in ("type", "timestamp", "content"):
extra_fields[k] = v
+ if et in {"chat.final", "chat.tool_call"}:
+ extra_fields = _attach_reasoning_content(extra_fields)
append_history_record(
session_id=session_id,
request_id=rid,
@@ -1702,10 +1751,10 @@ class JiuWenSwarm:
extra=extra_fields if extra_fields else None,
mode=request.params.get("mode", "unknown"),
)
+ if et == "chat.final":
+ durable_final_content = str(data.payload.get("content", ""))
if et == "chat.final":
final_answer_content = str(data.payload.get("content", ""))
- elif et == "chat.delta":
- final_answer_chunks.append(str(data.payload.get("content", "")))
yield data
elif isinstance(data, dict) and isinstance(data.get("event_type"), str):
et = str(data.get("event_type"))
@@ -1722,14 +1771,25 @@ class JiuWenSwarm:
)
payload_content = str(data.get("content", ""))
- if et == "chat.delta" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):
- suppress_a2ui_stream = True
+ if et == "chat.delta":
final_answer_chunks.append(payload_content)
- continue
- if et == "chat.final" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):
- suppress_a2ui_stream = True
- final_answer_content = payload_content
- continue
+ if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):
+ suppress_a2ui_stream = True
+ continue
+ durable_pending_final_chunks.append(payload_content)
+ should_record = False
+ elif et == "chat.reasoning":
+ durable_pending_reasoning_chunks.append(payload_content)
+ should_record = False
+ elif et == "chat.tool_call":
+ _persist_pending_final_text()
+ elif et == "chat.final":
+ if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):
+ suppress_a2ui_stream = True
+ final_answer_content = payload_content
+ durable_pending_final_chunks = []
+ continue
+ durable_pending_final_chunks = []
if should_record:
extra_fields = {k: v for k, v in data.items() if k not in ("event_type", "content")}
@@ -1739,6 +1799,8 @@ class JiuWenSwarm:
for k, v in event_data.items():
if k not in ("type", "timestamp", "content"):
extra_fields[k] = v
+ if et in {"chat.final", "chat.tool_call"}:
+ extra_fields = _attach_reasoning_content(extra_fields)
append_history_record(
session_id=session_id,
request_id=rid,
@@ -1750,10 +1812,10 @@ class JiuWenSwarm:
extra=extra_fields if extra_fields else None,
mode=request.params.get("mode", "unknown"),
)
+ if et == "chat.final":
+ durable_final_content = str(data.get("content", ""))
if et == "chat.final":
final_answer_content = str(data.get("content", ""))
- elif et == "chat.delta":
- final_answer_chunks.append(str(data.get("content", "")))
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
@@ -1790,6 +1852,7 @@ class JiuWenSwarm:
event_type="chat.final",
content=finalized_assistant_message,
timestamp=time.time(),
+ extra=_attach_reasoning_content(),
mode=request.params.get("mode", "unknown"),
)
final_answer_content = finalized_assistant_message
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index acc2f577df..d5f1bfd805 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -143,7 +143,7 @@ from jiuwenswarm.agents.harness.common.memory.config import (
from jiuwenswarm.agents.harness.common.memory.external_memory_config import is_builtin_memory_allowed
from jiuwenswarm.agents.harness.common.rails.permissions.tool_permission_context import TOOL_PERMISSION_CHANNEL_ID
from jiuwenswarm.server.runtime.session.session_metadata import build_server_push_message
-from jiuwenswarm.server.runtime.session.session_history import append_history_record
+from jiuwenswarm.server.runtime.session.session_history import append_history_record, load_history_records
from jiuwenswarm.server.runtime.skill import filter_visible_skill_names
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from jiuwenswarm.server.runtime.prompt_attachment_loader import PromptAttachmentLoader
@@ -6721,7 +6721,7 @@ class JiuWenSwarmDeepAdapter:
"""从当前 agent 对话上下文中提取最近N条消息。
当 context_engine 中没有该 session 的上下文时(例如 /resume 之后),
- 回退到从磁盘读取 history.json。
+ 回退到从磁盘读取兼容格式的 history 文件。
"""
# --- 快速路径:context_engine 已加载 ---
if self._instance is not None and self._instance.react_agent is not None:
@@ -6735,17 +6735,13 @@ class JiuWenSwarmDeepAdapter:
except Exception as exc:
logger.debug("[JiuWenSwarmDeepAdapter] _get_recent_messages from context_engine failed: %s", exc)
- # --- 回退路径:从磁盘读取 history.json ---
+ # --- 回退路径:从磁盘读取兼容格式 history ---
# 典型场景:/resume 之后,context_engine 还未加载新 session 的上下文,
# 但磁盘上已有该 session 的历史消息。
try:
from types import SimpleNamespace
- from jiuwenswarm.common.utils import get_agent_sessions_dir
- from jiuwenswarm.server.runtime.session.session_history import _read_history
-
- history_path = get_agent_sessions_dir() / session_id / "history.json"
- records = _read_history(history_path)
+ records = load_history_records(session_id)
if not records:
logger.debug(
"[JiuWenSwarmDeepAdapter] _get_recent_messages: no history records on disk for session %s",
diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.py
index a6fc65f863..1c920ca62b 100644
--- a/jiuwenswarm/server/runtime/session/session_history.py
+++ b/jiuwenswarm/server/runtime/session/session_history.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import datetime
import logging
import json
+import os
import queue
import threading
import time
@@ -17,25 +18,108 @@ _FILE_LOCK = threading.Lock()
_WRITE_QUEUE: queue.Queue[tuple[str, dict[str, Any]]] = queue.Queue(maxsize=20000)
_WORKER_STARTED = False
_WORKER_LOCK = threading.Lock()
+_LEGACY_HISTORY_FILENAME = "history.json"
+_JSONL_HISTORY_FILENAME = "history.jsonl"
+_LEGACY_HISTORY_ENV = "JIUWENSWARM_USE_LEGACY_HISTORY_JSON"
-def _serialize_value(obj: Any) -> Any:
- """将对象转换为 JSON 可序列化的格式."""
+def _serialize_value_with_flag(obj: Any) -> tuple[Any, bool]:
+ """将对象转换为 JSON 可序列化的格式,并返回是否发生降级处理."""
+ if obj is None or isinstance(obj, (str, int, float, bool)):
+ return obj, False
if isinstance(obj, datetime.datetime):
- return obj.isoformat()
+ return obj.isoformat(), True
if isinstance(obj, datetime.date):
- return obj.isoformat()
+ return obj.isoformat(), True
+ if callable(obj):
+ name = getattr(obj, "__qualname__", None) or getattr(obj, "__name__", None) or type(obj).__name__
+ return f"<callable:{name}>", True
if isinstance(obj, dict):
- return {k: _serialize_value(v) for k, v in obj.items()}
- if isinstance(obj, (list, tuple)):
- return [_serialize_value(item) for item in obj]
- return obj
+ changed = False
+ serialized: dict[Any, Any] = {}
+ for k, v in obj.items():
+ serialized_value, value_changed = _serialize_value_with_flag(v)
+ serialized[k] = serialized_value
+ changed = changed or value_changed
+ return serialized, changed
+ if isinstance(obj, (list, tuple, set, frozenset)):
+ changed = not isinstance(obj, list)
+ serialized_items = []
+ for item in obj:
+ serialized_item, item_changed = _serialize_value_with_flag(item)
+ serialized_items.append(serialized_item)
+ changed = changed or item_changed
+ return serialized_items, changed
+ try:
+ json.dumps(obj, ensure_ascii=False)
+ except TypeError:
+ return repr(obj), True
+ return obj, False
-def _history_file(session_id: str) -> Path:
+def _serialize_value(obj: Any) -> Any:
+ return _serialize_value_with_flag(obj)[0]
+
+
+def _session_dir(session_id: str, *, create: bool = True) -> Path:
session_dir = get_agent_sessions_dir() / session_id
- session_dir.mkdir(parents=True, exist_ok=True)
- return session_dir / "history.json"
+ if create:
+ session_dir.mkdir(parents=True, exist_ok=True)
+ return session_dir
+
+
+def _history_file(session_id: str) -> Path:
+ return _session_dir(session_id) / _LEGACY_HISTORY_FILENAME
+
+
+def _history_jsonl_file(session_id: str) -> Path:
+ return _session_dir(session_id) / _JSONL_HISTORY_FILENAME
+
+
+def use_legacy_history_json() -> bool:
+ raw = str(os.environ.get(_LEGACY_HISTORY_ENV, "") or "").strip().lower()
+ return raw in {"1", "true", "yes", "on"}
+
+
+def get_write_history_path(session_id: str) -> Path:
+ """Return the preferred durable history write target for a session."""
+ if use_legacy_history_json():
+ return _history_file(session_id)
+ return _history_jsonl_file(session_id)
+
+
+def get_read_history_path(session_id: str) -> Path:
+ """Return the preferred history source, falling back to legacy json."""
+ if use_legacy_history_json():
+ legacy_path = _history_file(session_id)
+ if legacy_path.exists():
+ return legacy_path
+ jsonl_path = _history_jsonl_file(session_id)
+ if jsonl_path.exists():
+ return jsonl_path
+ return legacy_path
+
+ jsonl_path = _history_jsonl_file(session_id)
+ if jsonl_path.exists():
+ return jsonl_path
+ legacy_path = _history_file(session_id)
+ if legacy_path.exists():
+ return legacy_path
+ return jsonl_path
+
+
+def history_exists(session_id: str) -> bool:
+ return get_read_history_path(session_id).exists()
+
+
+def get_history_mtime(session_id: str) -> float | None:
+ path = get_read_history_path(session_id)
+ if not path.exists():
+ return None
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return None
def _read_history(path: Path) -> list[dict[str, Any]]:
@@ -51,6 +135,111 @@ def _read_history(path: Path) -> list[dict[str, Any]]:
return []
+def _read_history_jsonl(path: Path) -> list[dict[str, Any]]:
+ if not path.exists():
+ return []
+
+ records: list[dict[str, Any]] = []
+ try:
+ for lineno, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
+ line = raw_line.strip()
+ if not line:
+ continue
+ try:
+ item = json.loads(line)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("读取 history.jsonl 第 %d 行失败,已跳过: %s", lineno, exc)
+ continue
+ if isinstance(item, dict):
+ records.append(item)
+ else:
+ logger.warning(
+ "读取 history.jsonl 第 %d 行不是对象记录,已跳过: %s",
+ lineno,
+ type(item).__name__,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("读取 history.jsonl 失败,已忽略: %s", exc)
+ return []
+ return records
+
+
+def load_history_records(session_id: str) -> list[dict[str, Any]]:
+ path = get_read_history_path(session_id)
+ if path.suffix.lower() == ".jsonl":
+ return _read_history_jsonl(path)
+ return _read_history(path)
+
+
+def _write_records_to_path(path: Path, records: list[dict[str, Any]]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if path.suffix.lower() == ".jsonl":
+ payload = "\n".join(
+ json.dumps(record, ensure_ascii=False) for record in records
+ )
+ if payload:
+ payload += "\n"
+ path.write_text(payload, encoding="utf-8")
+ return
+
+ path.write_text(
+ json.dumps(records, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+
+def _append_record_jsonl(path: Path, record: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8") as fh:
+ fh.write(json.dumps(record, ensure_ascii=False))
+ fh.write("\n")
+
+
+def _ensure_jsonl_bootstrap(session_id: str) -> Path:
+ jsonl_path = _history_jsonl_file(session_id)
+ if jsonl_path.exists():
+ return jsonl_path
+
+ legacy_path = _history_file(session_id)
+ if legacy_path.exists():
+ legacy_records = _read_history(legacy_path)
+ _write_records_to_path(jsonl_path, legacy_records)
+ else:
+ jsonl_path.parent.mkdir(parents=True, exist_ok=True)
+ return jsonl_path
+
+
+def _ensure_legacy_json_bootstrap(session_id: str) -> Path:
+ legacy_path = _history_file(session_id)
+ if legacy_path.exists():
+ return legacy_path
+
+ jsonl_path = _history_jsonl_file(session_id)
+ if jsonl_path.exists():
+ jsonl_records = _read_history_jsonl(jsonl_path)
+ _write_records_to_path(legacy_path, jsonl_records)
+ else:
+ legacy_path.parent.mkdir(parents=True, exist_ok=True)
+ return legacy_path
+
+
+def write_history_records(
+ session_id: str,
+ records: list[dict[str, Any]],
+ *,
+ preserve_existing_format: bool = True,
+) -> Path:
+ """Rewrite a session's history in its current format, defaulting new sessions to jsonl."""
+ path = (
+ get_read_history_path(session_id)
+ if preserve_existing_format
+ else get_write_history_path(session_id)
+ )
+ with _FILE_LOCK:
+ _write_records_to_path(path, records)
+ return path
+
+
_TEAM_RELEVANT_EVENT_TYPES = frozenset({
"team.message",
"team.member",
@@ -78,14 +267,14 @@ def _is_team_relevant(item: dict[str, Any]) -> bool:
def read_team_history_records(session_id: str) -> list[dict[str, Any]]:
"""读取指定会话的历史记录,仅返回 team 模式相关的记录。"""
- fpath = _history_file(session_id)
- all_records = _read_history(fpath)
+ fpath = get_read_history_path(session_id)
+ all_records = load_history_records(session_id)
# write_text 非原子写入(先截断再写入),读取可能命中截断窗口,
# 用递增间隔重试最多 5 次等待写入完成
if not all_records and fpath.exists():
for attempt in range(1, 6):
time.sleep(0.2 * attempt)
- all_records = _read_history(fpath)
+ all_records = load_history_records(session_id)
if all_records:
logger.info("read_team_history_records: recovered on retry %d", attempt)
break
@@ -99,14 +288,16 @@ def read_team_history_records(session_id: str) -> list[dict[str, Any]]:
def _write_item(session_id: str, item: dict[str, Any]) -> None:
- fpath = _history_file(session_id)
with _FILE_LOCK:
- history = _read_history(fpath)
- history.append(item)
- fpath.write_text(
- json.dumps(history, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
+ if use_legacy_history_json():
+ target_path = _ensure_legacy_json_bootstrap(session_id)
+ records = _read_history(target_path)
+ records.append(item)
+ _write_records_to_path(target_path, records)
+ return
+
+ target_path = _ensure_jsonl_bootstrap(session_id)
+ _append_record_jsonl(target_path, item)
def _ensure_worker_started() -> None:
@@ -145,7 +336,7 @@ def append_history_record(
channel_metadata: dict[str, Any] | None = None,
mode: str | None = None,
) -> None:
- """向指定 session 的 history.json 异步追加一条记录."""
+ """向指定 session 的当前激活历史文件异步追加一条记录."""
sid = (session_id or "default").strip() or "default"
rid = str(request_id or "").strip()
cid = str(channel_id or "").strip()
@@ -163,9 +354,17 @@ def append_history_record(
if role_norm == "assistant" and event_type:
item["event_type"] = event_type
if isinstance(extra, dict) and extra:
- serialized_extra = _serialize_value(extra)
+ serialized_extra, extra_changed = _serialize_value_with_flag(extra)
if isinstance(serialized_extra, dict):
item.update(serialized_extra)
+ if extra_changed:
+ logger.debug(
+ "history payload sanitized: session_id=%s request_id=%s event_type=%s extra_keys=%s",
+ sid,
+ rid,
+ event_type or "",
+ list(serialized_extra.keys()),
+ )
if mode:
item["mode"] = str(mode)
@@ -258,17 +457,17 @@ def append_compact_history_records(
def truncate_history_records(*, session_id: str, cut_index: int) -> dict[str, Any]:
"""截断会话历史到指定位置(线程安全)。
- 先等待异步写入队列刷盘,再持锁截断 history.json。
+ 先等待异步写入队列刷盘,再持锁截断当前激活的历史文件。
返回截断结果 dict,包含 remaining / removed 计数。
"""
sid = (session_id or "default").strip() or "default"
_WRITE_QUEUE.join()
- fpath = _history_file(sid)
+ fpath = get_read_history_path(sid)
with _FILE_LOCK:
if not fpath.exists():
return {"remaining_records": 0, "removed_records": 0}
- history = _read_history(fpath)
+ history = load_history_records(sid)
if not isinstance(history, list):
return {"remaining_records": 0, "removed_records": 0}
total = len(history)
@@ -277,10 +476,7 @@ def truncate_history_records(*, session_id: str, cut_index: int) -> dict[str, An
if cut_index > total:
cut_index = total
truncated = history[:cut_index]
- fpath.write_text(
- json.dumps(truncated, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
+ _write_records_to_path(fpath, truncated)
return {
"remaining_records": len(truncated),
"removed_records": total - len(truncated),
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index ce6c85cb8f..1eb2528a34 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -12,6 +12,7 @@ from pathlib import Path
from typing import Any
from jiuwenswarm.common.utils import get_agent_sessions_dir, get_agent_workspace_dir, get_user_workspace_dir
+from jiuwenswarm.server.runtime.session.session_history import load_history_records
logger = logging.getLogger(__name__)
@@ -147,11 +148,8 @@ class DiffService:
@staticmethod
def _read_history(session_id: str) -> list[dict[str, Any]]:
"""读取 session history."""
- history_file = get_agent_sessions_dir() / session_id / "history.json"
- if not history_file.exists():
- return []
try:
- return json.loads(history_file.read_text(encoding="utf-8"))
+ return load_history_records(session_id)
except Exception:
return []
diff --git a/tests/system_tests/test_dreaming_e2e.py b/tests/system_tests/test_dreaming_e2e.py
index 1442c28b18..c333a02caf 100644
--- a/tests/system_tests/test_dreaming_e2e.py
+++ b/tests/system_tests/test_dreaming_e2e.py
@@ -48,8 +48,10 @@ def _create_valid_session(sessions_root: Path, sid: str, num_rounds: int = 5,
for i in range(num_rounds):
entries.append(_make_history_entry("user", f"请问第{i+1}个问题"))
entries.append(_make_history_entry("assistant", f"这是第{i+1}个回答", event_type="chat.final"))
- (session_dir / "history.json").write_text(
- json.dumps(entries, ensure_ascii=False), encoding="utf-8")
+ history_payload = "\n".join(json.dumps(item, ensure_ascii=False) for item in entries)
+ if history_payload:
+ history_payload += "\n"
+ (session_dir / "history.jsonl").write_text(history_payload, encoding="utf-8")
metadata = {"mode": mode, "session_id": sid, "created_at": time.time()}
(session_dir / "metadata.json").write_text(
json.dumps(metadata, ensure_ascii=False), encoding="utf-8")
@@ -157,7 +159,7 @@ class TestDreamingE2EAgent:
for sid in ["sess_001", "sess_a", "sess_b"]:
_create_valid_session(sessions_root, sid, num_rounds=5)
session_dir = sessions_root / "sess_001"
- orig_mtime = (session_dir / "history.json").stat().st_mtime
+ orig_mtime = (session_dir / "history.jsonl").stat().st_mtime
sweeper1 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
sweeper1.init()
@@ -171,11 +173,11 @@ class TestDreamingE2EAgent:
# mark sess_a and sess_b as scanned, then update them too
sweeper1.scanned_sessions["sess_a"] = {
- "history_mtime": (sessions_root / "sess_a" / "history.json").stat().st_mtime,
+ "history_mtime": (sessions_root / "sess_a" / "history.jsonl").stat().st_mtime,
"round_count": 5,
}
sweeper1.scanned_sessions["sess_b"] = {
- "history_mtime": (sessions_root / "sess_b" / "history.json").stat().st_mtime,
+ "history_mtime": (sessions_root / "sess_b" / "history.jsonl").stat().st_mtime,
"round_count": 5,
}
@@ -183,7 +185,10 @@ class TestDreamingE2EAgent:
# add 4 more rounds to sess_001, sess_a and sess_b
for sid in ["sess_001", "sess_a", "sess_b"]:
sdir = sessions_root / sid
- existing = json.loads((sdir / "history.json").read_text(encoding="utf-8"))
+ existing = [
+ json.loads(line)
+ for line in (sdir / "history.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()
+ ]
existing.extend([
_make_history_entry("user", "新问题6"),
_make_history_entry("assistant", "新回答6", event_type="chat.final"),
@@ -194,7 +199,9 @@ class TestDreamingE2EAgent:
_make_history_entry("user", "新问题9"),
_make_history_entry("assistant", "新回答9", event_type="chat.final"),
])
- (sdir / "history.json").write_text(json.dumps(existing), encoding="utf-8")
+ (sdir / "history.jsonl").write_text(
+ "\n".join(json.dumps(item, ensure_ascii=False) for item in existing) + "\n", encoding="utf-8"
+ )
sweeper2 = Sweeper(str(sessions_root), str(output_dir), mode="agent")
sweeper2.init()
diff --git a/tests/unit/agentserver/test_interface_chat_error.py b/tests/unit/agentserver/test_interface_chat_error.py
index 4ac88a9af2..bdc06f4ec1 100644
--- a/tests/unit/agentserver/test_interface_chat_error.py
+++ b/tests/unit/agentserver/test_interface_chat_error.py
@@ -173,24 +173,17 @@ async def test_chat_error_history_record_persists_error_type_at_top_level(
async for _chunk in facade.process_message_stream(request):
pass
- history_file = sessions_root / sid / "history.json"
+ history_file = session_history.get_write_history_path(sid)
chat_errors: list[dict[str, Any]] = []
for _ in range(100):
if history_file.exists():
- raw = history_file.read_text(encoding="utf-8")
- if raw.strip():
- try:
- persisted = json.loads(raw)
- except json.JSONDecodeError:
- # 文件正在写入中,下一轮重试
- pass
- else:
- chat_errors = [r for r in persisted if r.get("event_type") == "chat.error"]
- if chat_errors:
- break
+ persisted = session_history.load_history_records(sid)
+ chat_errors = [r for r in persisted if r.get("event_type") == "chat.error"]
+ if chat_errors:
+ break
await asyncio.sleep(0.05)
- assert history_file.exists(), f"history.json not written at {history_file}"
+ assert history_file.exists(), f"history file not written at {history_file}"
assert len(chat_errors) == 1, f"expected 1 chat.error record, got {len(chat_errors)}"
# The doc claims this field is at the top level (not nested under
# event_payload or extra). Pin it.
diff --git a/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py b/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py
index 2152adeae9..f4ee127fe6 100644
--- a/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py
+++ b/tests/unit_tests/agentserver/memory/test_dreaming_sweeper.py
@@ -50,15 +50,26 @@ _MIN_SESSION_AGE_BYPASS_DAYS = 7
# ── parse_history ──
def _parse_history(session_dir: Path) -> list[dict]:
- path = session_dir / "history.json"
- if not path.exists():
- return []
- try:
- data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
- if not isinstance(data, list):
+ path_jsonl = session_dir / "history.jsonl"
+ path_json = session_dir / "history.json"
+ if path_jsonl.exists():
+ try:
+ data = [
+ json.loads(line)
+ for line in path_jsonl.read_text(encoding="utf-8", errors="replace").splitlines()
+ if line.strip()
+ ]
+ except (OSError, json.JSONDecodeError):
+ return []
+ else:
+ if not path_json.exists():
+ return []
+ try:
+ data = json.loads(path_json.read_text(encoding="utf-8", errors="replace"))
+ if not isinstance(data, list):
+ return []
+ except (OSError, json.JSONDecodeError):
return []
- except (OSError, json.JSONDecodeError):
- return []
def _should_keep(entry: dict) -> bool:
if entry.get("role") == "user":
@@ -147,15 +158,20 @@ def _make_history_entry(role: str, content: str, event_type: str | None = None)
return entry
-def _write_history_json(path: Path, entries: list[dict]) -> None:
+def _write_history_json(path: Path, entries) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
+ if path.suffix == ".jsonl":
+ payload = "\n".join(json.dumps(item, ensure_ascii=False) for item in entries)
+ if payload:
+ payload += "\n"
+ path.write_text(payload, encoding="utf-8")
+ return
path.write_text(json.dumps(entries, ensure_ascii=False), encoding="utf-8")
# ===========================================================================
# DreamingConfig.load()
# ===========================================================================
-
class TestDreamingConfigLoad:
"""Test DreamingConfig.load() with mock config."""
@@ -538,12 +554,12 @@ class TestScanNewSessions:
def _make_session(sessions_root: Path, sid: str, entries: list[dict], age_delta: float = 0):
session_dir = sessions_root / sid
session_dir.mkdir(parents=True)
- _write_history_json(session_dir / "history.json", entries)
+ _write_history_json(session_dir / "history.jsonl", entries)
metadata = {"mode": "code.normal", "session_id": sid, "created_at": time.time()}
_write_history_json(session_dir / "metadata.json", metadata)
mtime = time.time() - age_delta
os.utime(session_dir, (mtime, mtime))
- os.utime(session_dir / "history.json", (mtime, mtime))
+ os.utime(session_dir / "history.jsonl", (mtime, mtime))
@staticmethod
def test_no_sessions_dir(tmp_path):
@@ -621,7 +637,7 @@ class TestScanNewSessions:
for i in range(3):
sid = f"sess_00{i+1}"
sweeper.scanned_sessions[sid] = {
- "history_mtime": (sessions_root / sid / "history.json").stat().st_mtime,
+ "history_mtime": (sessions_root / sid / "history.jsonl").stat().st_mtime,
"round_count": 4,
}
result2 = sweeper.scan_new_sessions()
@@ -641,7 +657,7 @@ class TestScanNewSessions:
sweeper.init()
# mark sess_001 as already scanned (with 4 rounds), sess_002 and sess_003 as new
sweeper.scanned_sessions["sess_001"] = {
- "history_mtime": (sessions_root / "sess_001" / "history.json").stat().st_mtime - 1,
+ "history_mtime": (sessions_root / "sess_001" / "history.jsonl").stat().st_mtime - 1,
"round_count": 4,
}
@@ -653,9 +669,12 @@ class TestScanNewSessions:
_make_history_entry("user", "q7"), _make_history_entry("assistant", "a7", "chat.final"),
_make_history_entry("user", "q8"), _make_history_entry("assistant", "a8", "chat.final"),
]
- existing = json.loads((sessions_root / "sess_001" / "history.json").read_text(encoding="utf-8"))
+ existing = []
+ for line in (sessions_root / "sess_001" / "history.jsonl").read_text(encoding="utf-8").splitlines():
+ if line.strip():
+ existing.append(json.loads(line))
existing.extend(more_entries)
- (sessions_root / "sess_001" / "history.json").write_text(json.dumps(existing), encoding="utf-8")
+ _write_history_json(sessions_root / "sess_001" / "history.jsonl", existing)
result = sweeper.scan_new_sessions()
assert len(result) == 3 # sess_001 updated + sess_002 & sess_003 new
diff --git a/tests/unit_tests/test_compact_history_records.py b/tests/unit_tests/test_compact_history_records.py
index 9b83025566..862e7e4f75 100644
--- a/tests/unit_tests/test_compact_history_records.py
+++ b/tests/unit_tests/test_compact_history_records.py
@@ -4,15 +4,16 @@ import time
from jiuwenswarm.server.runtime.session import session_history
-def _read_history_file(path):
+def _read_history_file(session_id):
deadline = time.time() + 5
while time.time() < deadline:
+ path = session_history.get_write_history_path(session_id)
if path.exists():
- data = json.loads(path.read_text(encoding="utf-8"))
+ data = session_history.load_history_records(session_id)
if len(data) >= 2:
return data
time.sleep(0.05)
- raise AssertionError(f"history file was not written: {path}")
+ raise AssertionError(f"history file was not written for session: {session_id}")
def test_append_compact_history_records_writes_boundary_and_transcript_summary(tmp_path, monkeypatch):
@@ -29,7 +30,7 @@ def test_append_compact_history_records_writes_boundary_and_transcript_summary(t
mode="agent.plan",
)
- data = _read_history_file(tmp_path / "s1" / "history.json")
+ data = _read_history_file("s1")
assert [item["event_type"] for item in data] == [
"context.compact_boundary",
diff --git a/tests/unit_tests/test_compact_partial.py b/tests/unit_tests/test_compact_partial.py
index 8ea176235f..ec501f90d9 100644
--- a/tests/unit_tests/test_compact_partial.py
+++ b/tests/unit_tests/test_compact_partial.py
@@ -13,6 +13,12 @@ import pytest
# ---------------------------------------------------------------------------
def _write_history(path: Path, records: list[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
+ if path.suffix == ".jsonl":
+ payload = "\n".join(json.dumps(record, ensure_ascii=False) for record in records)
+ if payload:
+ payload += "\n"
+ path.write_text(payload, encoding="utf-8")
+ return
path.write_text(json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8")
@@ -20,11 +26,26 @@ def _read_history(path: Path) -> list[dict]:
deadline = time.time() + 5
while time.time() < deadline:
if path.exists():
- data = json.loads(path.read_text(encoding="utf-8"))
+ if path.suffix == ".jsonl":
+ data = [
+ json.loads(line)
+ for line in path.read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+ else:
+ data = json.loads(path.read_text(encoding="utf-8"))
if data:
return data
time.sleep(0.05)
- return json.loads(path.read_text(encoding="utf-8")) if path.exists() else []
+ if not path.exists():
+ return []
+ if path.suffix == ".jsonl":
+ return [
+ json.loads(line)
+ for line in path.read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+ return json.loads(path.read_text(encoding="utf-8"))
def _make_user_record(index: int, content: str | None = None, ts: float | None = None) -> dict:
@@ -93,7 +114,7 @@ class TestCompactPartialSessionFrom:
_make_user_record(3, "third question"),
_make_assistant_record(3, "third answer"),
]
- _write_history(tmp_path / "s1" / "history.json", records)
+ _write_history((tmp_path / "s1" / "history.jsonl"), records)
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
@@ -105,7 +126,7 @@ class TestCompactPartialSessionFrom:
assert result["removed_records"] == 4
assert "second question" in result["content"]
- final_history = _read_history(tmp_path / "s1" / "history.json")
+ final_history = _read_history(tmp_path / "s1" / "history.jsonl")
event_types = [r.get("event_type") for r in final_history]
assert "context.compact_boundary" in event_types
assert "context.rewind_summary" in event_types
@@ -118,7 +139,7 @@ class TestCompactPartialSessionFrom:
_make_user_record(1, "hello"),
_make_assistant_record(1, "hi there"),
]
- _write_history(tmp_path / "s2" / "history.json", records)
+ _write_history((tmp_path / "s2" / "history.jsonl"), records)
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
@@ -129,7 +150,7 @@ class TestCompactPartialSessionFrom:
llm_summary="LLM generated summary text",
)
- final_history = _read_history(tmp_path / "s2" / "history.json")
+ final_history = _read_history(tmp_path / "s2" / "history.jsonl")
event_types = [r.get("event_type") for r in final_history]
assert event_types == [
"context.compact_boundary",
@@ -155,7 +176,7 @@ class TestCompactPartialSessionUpTo:
_make_user_record(3, "third question"),
_make_assistant_record(3, "third answer"),
]
- _write_history(tmp_path / "s3" / "history.json", records)
+ _write_history((tmp_path / "s3" / "history.jsonl"), records)
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
@@ -166,7 +187,7 @@ class TestCompactPartialSessionUpTo:
assert result["summarized_messages"] == 4
assert "third question" in result["content"]
- final_history = _read_history(tmp_path / "s3" / "history.json")
+ final_history = _read_history(tmp_path / "s3" / "history.jsonl")
event_types = [r.get("event_type") for r in final_history]
assert "context.compact_boundary" in event_types
assert "context.rewind_summary" in event_types
@@ -179,11 +200,15 @@ class TestCompactPartialSessionErrors:
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: tmp_path,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
records = [
_make_user_record(1, "hello"),
_make_assistant_record(1, "hi"),
]
- _write_history(tmp_path / "s4" / "history.json", records)
+ _write_history((tmp_path / "s4" / "history.jsonl"), records)
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
@@ -199,6 +224,10 @@ class TestCompactPartialSessionErrors:
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: tmp_path,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
with pytest.raises(ValueError, match="session history not found"):
@@ -210,6 +239,10 @@ class TestCompactPartialSessionErrors:
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: tmp_path,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
records = [
{
"id": "a1",
@@ -219,7 +252,7 @@ class TestCompactPartialSessionErrors:
"timestamp": 1.0,
},
]
- _write_history(tmp_path / "s5" / "history.json", records)
+ _write_history((tmp_path / "s5" / "history.jsonl"), records)
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
@@ -232,11 +265,15 @@ class TestCompactPartialSessionErrors:
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: tmp_path,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: tmp_path,
+ )
records = [
_make_user_record(1, "hello"),
_make_assistant_record(1, "hi"),
]
- _write_history(tmp_path / "s6" / "history.json", records)
+ _write_history((tmp_path / "s6" / "history.jsonl"), records)
from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session
@@ -452,12 +489,16 @@ class TestRewindSessionContextInjectsSummaries:
"event_type": "context.compact_summary", "timestamp": 2.002,
},
]
- _write_history(sessions_dir / "s1" / "history.json", history)
+ _write_history((sessions_dir / "s1" / "history.jsonl"), history)
monkeypatch.setattr(
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: sessions_dir,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: sessions_dir,
+ )
from unittest.mock import AsyncMock, MagicMock
@@ -521,12 +562,16 @@ class TestRewindSessionContextInjectsSummaries:
"event_type": "context.rewind_summary", "timestamp": 2.0,
},
]
- _write_history(sessions_dir / "s2" / "history.json", history)
+ _write_history((sessions_dir / "s2" / "history.jsonl"), history)
monkeypatch.setattr(
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: sessions_dir,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: sessions_dir,
+ )
from unittest.mock import AsyncMock, MagicMock
diff --git a/tests/unit_tests/test_session_ops_rewind_turns.py b/tests/unit_tests/test_session_ops_rewind_turns.py
index 6b13b4bcb6..25b4101355 100644
--- a/tests/unit_tests/test_session_ops_rewind_turns.py
+++ b/tests/unit_tests/test_session_ops_rewind_turns.py
@@ -10,23 +10,27 @@ def test_list_session_turns_includes_project_file_change_stats(tmp_path, monkeyp
session_dir = sessions_dir / session_id
session_dir.mkdir(parents=True)
- (session_dir / "history.json").write_text(
- json.dumps(
+ (session_dir / "history.jsonl").write_text(
+ "\n".join(
[
- {
- "role": "user",
- "content": "change the file",
- "timestamp": 1000.0,
- "id": "u1",
- "request_id": "r1",
- },
- {
- "role": "assistant",
- "content": "done",
- "timestamp": 1002.0,
- },
+ json.dumps(
+ {
+ "role": "user",
+ "content": "change the file",
+ "timestamp": 1000.0,
+ "id": "u1",
+ "request_id": "r1",
+ }
+ ),
+ json.dumps(
+ {
+ "role": "assistant",
+ "content": "done",
+ "timestamp": 1002.0,
+ }
+ ),
]
- ),
+ ) + "\n",
encoding="utf-8",
)
@@ -53,6 +57,10 @@ def test_list_session_turns_includes_project_file_change_stats(tmp_path, monkeyp
"jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",
lambda: sessions_dir,
)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: sessions_dir,
+ )
monkeypatch.setattr(
"jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",
lambda: tmp_path / "agent-workspace",