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(history): preserve error messages when restoring conversations
whqxbs5a55fd772ab1
diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex 9055f20bc4..eff0a746b5 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -1,6 +1,7 @@import { Message, MessageRole, UsageSummary, FileDownloadItem, MediaItem, WsEvent, ToolExecution, AskUserQuestionPayload } from '../types';import { webClient } from '../services/webClient';import { normalizeFinalContent } from '../utils/finalContent';+import i18n from '../i18n';import { mergeFileDownloadItems } from '../utils/fileDownloadDedup';import { parseTimestampToMs, timestampMsToIso } from '../utils/timestamp';import { isA2UIClientEventContent } from './a2ui/a2uiContent';@@ -17,6 +18,7 @@ export const HISTORY_MESSAGE_EVENT = 'history.message';/** 助手侧仅恢复这些事件;用户消息无 event_type,单独保留 */const ALLOWED_ASSISTANT_EVENT_TYPES = new Set(['chat.final',+ 'chat.error','chat.tool_call','chat.tool_result','chat.usage_summary',@@ -498,6 +500,20 @@ function parseHistoryTimelineEntry(const payload = buildEventPayloadForRecord(record);+ if (eventType === 'chat.error') {+ const error = pickFirstString(payload, ['error', 'content']);+ if (!error) return null;+ return {+ kind: 'message',+ message: {+ id: pickFirstString(record, ['id', 'message_id', 'msg_id']) ?? `hist-error-${sessionId}-${at}`,+ role: 'system',+ content: i18n.t('network.errorPrefix', { message: error }),+ timestamp: at,+ },+ };+ }+if (eventType === 'chat.final') {let content = normalizeFinalContent(payload);const isGoalCompletedMessage =diff --git a/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs b/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjsindex 09b66929a4..109481b601 100644--- a/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/historyRestoreSourceSkill.test.mjs@@ -3,6 +3,26 @@ import test from 'node:test';import { parseHistoryJsonFileToTimelinePreview } from '../node_modules/.cache/history-restore/historyRestore.mjs';+test('history replay restores failed turns as system error messages', () => {+ const { messages } = parseHistoryJsonFileToTimelinePreview([+ { role: 'user', content: 'create a task', timestamp: 1757800000 },+ { role: 'assistant', event_type: 'chat.error', content: 'cron failed', timestamp: 1757800001 },+ { role: 'assistant', event_type: 'chat.error', content: '', error: 'route failed', timestamp: 1757800002 },+ { role: 'assistant', event_type: 'chat.error', event_payload: { error: 'agent failed' }, timestamp: 1757800003 },+ { role: 'assistant', event_type: 'chat.error', content: ' ', timestamp: 1757800004 },+ { role: 'assistant', event_type: 'chat.final', content: 'retry succeeded', timestamp: 1757800005 },+ ], 'error-session');+ assert.equal(messages.length, 5);+ assert.equal(messages[1].role, 'system');+ assert.match(messages[1].content, /cron failed/);+ assert.equal(messages[2].role, 'system');+ assert.match(messages[2].content, /route failed/);+ assert.equal(messages[3].role, 'system');+ assert.match(messages[3].content, /agent failed/);+ assert.equal(messages[4].role, 'assistant');+ assert.equal(messages[4].content, 'retry succeeded');+});+// 历史记录字段对齐 pod 本地 history.json 的落盘结构:chat.tool_call 事件把// tool_call(含 source_skill)展平在 extra 里(interface.py _append_history_record)。const TOOL_CALL_WITH_SOURCE_SKILL = {diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.pyindex 9ceac8b49c..5e08c3e120 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py@@ -176,6 +176,7 @@ async def _history_page_from_pg("timestamp": m.get("timestamp"),"session_id": sid,"request_id": m.get("request_id"),+ **({"event_type": "chat.error"} if m.get("event_type") == "chat.error" else {}),}for m in ordered[start:start + _HISTORY_PG_PAGE_SIZE]]diff --git "a/jiuwenswarm/gateway/docs/Gateway Web HTTP\346\216\245\345\217\243\346\226\207\346\241\243.md" "b/jiuwenswarm/gateway/docs/Gateway Web HTTP\346\216\245\345\217\243\346\226\207\346\241\243.md"index e8bf66db42..49cd4b62fe 100644--- "a/jiuwenswarm/gateway/docs/Gateway Web HTTP\346\216\245\345\217\243\346\226\207\346\241\243.md"+++ "b/jiuwenswarm/gateway/docs/Gateway Web HTTP\346\216\245\345\217\243\346\226\207\346\241\243.md"@@ -699,6 +699,8 @@ X-Bot-Id: b1JSON 路径若收到 `chat.error` 且文案含本地历史缺失,remote 模式可能回退 PG 合成同形 `data`;回退失败则 **404** `NOT_FOUND`。+历史分页保留已持久化的 `chat.error`,Web 恢复时显示为系统错误消息;remote 数据库回退也保留该事件类型,避免刷新后把失败提示丢弃或显示成普通助手回复。+**SSE 示例:**```httpdiff --git a/jiuwenswarm/server/wire_truncate.py b/jiuwenswarm/server/wire_truncate.pyindex 3382f9a27f..b1e42cccf4 100644--- a/jiuwenswarm/server/wire_truncate.py+++ b/jiuwenswarm/server/wire_truncate.py@@ -51,6 +51,7 @@ _TRUNCATE_SUFFIX = " [truncated]"_HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset({"chat.final",+ "chat.error","chat.tool_call","chat.tool_result","chat.usage_summary",diff --git a/tests/transport/test_handlers_session.py b/tests/transport/test_handlers_session.pyindex 36167261a7..22db5f6524 100644--- a/tests/transport/test_handlers_session.py+++ b/tests/transport/test_handlers_session.py@@ -2,13 +2,18 @@from __future__ import annotationsimport asyncio+import jsonimport pytestfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethodfrom jiuwenswarm.server.context import RequestContext-from jiuwenswarm.server.handlers.session import _coerce_int, handle_session_list+from jiuwenswarm.server.handlers.session import (+ _coerce_int,+ get_conversation_history,+ handle_session_list,+)from jiuwenswarm.server.transports.sink import UnaryHTTPSink@@ -27,6 +32,46 @@ def _run(ctx: RequestContext) -> None:asyncio.run(handle_session_list(ctx))+ "error_fields",+ [+ {"content": "cron failed"},+ {"content": "", "error": "route failed"},+ {"content": "", "event_payload": {"error": "agent failed"}},+ ],+)+def test_history_page_keeps_persisted_error(tmp_path, error_fields) -> None:+ session_id = "failed-conversation"+ directory = tmp_path / session_id+ directory.mkdir()+ error_record = {+ "role": "assistant",+ "event_type": "chat.error",+ "timestamp": 2,+ **error_fields,+ }+ records = [+ {"role": "user", "content": "create a task", "timestamp": 1},+ error_record,+ {"role": "assistant", "event_type": "chat.processing_status", "content": "working", "timestamp": 3},+ {"role": "assistant", "event_type": "chat.final", "content": "retry succeeded", "timestamp": 4},+ ]+ (directory / "history.json").write_text(+ "\n".join(json.dumps(record) for record in records) + "\n",+ encoding="utf-8",+ )++ page = get_conversation_history(session_id, 1, str(tmp_path))++ assert page is not None+ messages = page["messages"]+ assert [message.get("event_type") for message in messages] == ["chat.final", "chat.error", None]+ assert messages[1]["timestamp"] == 2+ for key, value in error_fields.items():+ assert messages[1][key] == value+ assert all(message["session_id"] == session_id for message in messages)++@pytest.mark.parametrize(("raw", "expected"),[diff --git a/tests/unit_tests/test_web_http.py b/tests/unit_tests/test_web_http.pyindex 90149ebbaf..4ec194ee0b 100644--- a/tests/unit_tests/test_web_http.py+++ b/tests/unit_tests/test_web_http.py@@ -105,6 +105,13 @@ def app_with_mock(monkeypatch: pytest.MonkeyPatch) -> tuple[FastAPI, AsyncMock]:"jiuwenswarm.gateway.channel_manager.web.trajectory_http",trajectory,)+ diagnosis = ModuleType("jiuwenswarm.gateway.channel_manager.web.diagnose_http")+ diagnosis.attach_diagnose_routes = lambda app, channel, **kwargs: None+ monkeypatch.setitem(+ sys.modules,+ "jiuwenswarm.gateway.channel_manager.web.diagnose_http",+ diagnosis,+ )# web_http_app imports timeout helpers from web_http_server (stdlib-only)._load_module(@@ -516,6 +523,25 @@ def test_history_json_collects_messages(app_with_mock):assert dispatch.await_args.kwargs["params"]["page_idx"] == 1+def test_history_database_fallback_preserves_error_event_type(app_with_mock, monkeypatch):+ from starlette.requests import Request++ index = ModuleType("jiuwenswarm.gateway.routing.session_index")+ index.is_remote_storage = lambda: True+ monkeypatch.setitem(sys.modules, index.__name__, index)+ history = ModuleType("jiuwenswarm.channels.web.history_store.api")+ history.get_session_detail_strict_sync = lambda *args, **kwargs: {+ "messages": [{"role": "assistant", "event_type": "chat.error",+ "content": "cron failed", "timestamp": 1}],+ }+ monkeypatch.setitem(sys.modules, history.__name__, history)+ request = Request({"type": "http", "headers": [(b'x-user-id', b'user')]})+ module = sys.modules["jw_web_http_app_under_test"]+ page = asyncio.run(module._history_page_from_pg(request, {"session_id": "s1", "page_idx": 1}))+ assert page["messages"][0]["event_type"] == "chat.error"+ assert page["messages"][0]["content"] == "cron failed"++def test_doc_ui_and_openapi(app_with_mock):app, _dispatch = app_with_mockclient = TestClient(app, follow_redirects=False)