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
[mirror] openJiuwen-ai/jiuwenswarm#1857: fix: persist chat.tool_result to history so tool status restores corr…
d30029696ff92c6a8c7aa
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex c634fd80ef..ceeb00960d 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -18,6 +18,7 @@"test:stream-delta-batcher": "tsc src/services/streamDeltaBatcher.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/stream-delta-batcher --skipLibCheck --noEmitOnError && node --test tests/streamDeltaBatcher.test.mjs","test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs","test:chat-store-streaming": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/chatStoreStreaming.test.mjs",+ "test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs","lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0","preview": "vite preview"},diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 8a48c54bcc..b271e5ae39 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -2862,6 +2862,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().setThinking(sessionId, false);useChatStore.getState().clearSubtasks(sessionId);useChatStore.getState().stopStreaming(sessionId);+ useChatStore.getState().settleHistoricalToolExecutions(sessionId);// 检查是否有等待的任务队列const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;diff --git a/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjs b/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjsnew file mode 100644index 0000000000..eddb16632b--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/settleHistoricalToolExecutions.test.mjs@@ -0,0 +1,126 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { useChatStore } from '../node_modules/.cache/chat-store-streaming/chatStore.mjs';++const SID = 'settle-historical-test';++function setup() {+ useChatStore.getState().ensureRuntime(SID);+}++function teardown() {+ useChatStore.getState().removeRuntime(SID);+}++function addToolCall(toolCallId, toolName) {+ useChatStore.getState().addToolCall(SID, {+ id: toolCallId,+ name: toolName,+ arguments: {},+ }, { startedAt: new Date().toISOString() });+}++function getToolStatus(toolCallId) {+ const runtime = useChatStore.getState().getRuntime(SID);+ if (!runtime) return undefined;+ const execution = runtime.toolExecutions.get(toolCallId);+ return execution?.status;+}++test('settleHistoricalToolExecutions settles pending tools when isProcessing is false', () => {+ setup();+ try {+ addToolCall('call-1', 'list_files');+ assert.equal(getToolStatus('call-1'), 'pending');++ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-1'), 'completed');+ } finally {+ teardown();+ }+});++test('settleHistoricalToolExecutions skips settling when isProcessing is true', () => {+ setup();+ try {+ useChatStore.getState().setProcessing(SID, true);+ addToolCall('call-2', 'code');++ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-2'), 'pending');+ } finally {+ useChatStore.getState().setProcessing(SID, false);+ teardown();+ }+});++test('settleHistoricalToolExecutions settles after setProcessing false', () => {+ setup();+ try {+ useChatStore.getState().setProcessing(SID, true);+ addToolCall('call-3', 'cron');++ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-3'), 'pending');++ useChatStore.getState().setProcessing(SID, false);+ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-3'), 'completed');+ } finally {+ teardown();+ }+});++test('settleHistoricalToolExecutions does not downgrade completed tools', () => {+ setup();+ try {+ addToolCall('call-4', 'search');++ useChatStore.getState().addToolResult(SID, {+ toolCallId: 'call-4',+ toolName: 'search',+ result: 'found',+ success: true,+ });+ assert.equal(getToolStatus('call-4'), 'completed');++ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-4'), 'completed');+ } finally {+ teardown();+ }+});++test('settleHistoricalToolExecutions settles timeout tools', () => {+ setup();+ try {+ addToolCall('call-5', 'slow_tool');++ useChatStore.getState().markTimedOutExecutions(SID);+ const status = getToolStatus('call-5');+ assert.equal(status, 'pending');++ useChatStore.getState().settleHistoricalToolExecutions(SID);+ assert.equal(getToolStatus('call-5'), 'completed');+ } finally {+ teardown();+ }+});++test('addToolCall then addToolResult yields completed status', () => {+ setup();+ try {+ addToolCall('call-6', 'read_file');++ useChatStore.getState().addToolResult(SID, {+ toolCallId: 'call-6',+ toolName: 'read_file',+ result: 'content',+ success: true,+ });+ assert.equal(getToolStatus('call-6'), 'completed');+ } finally {+ teardown();+ }+});diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex 4f7cc6eaa2..66fa4632b6 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -50,6 +50,8 @@ def _has_persistable_assistant_payload(return Trueif et == "chat.tool_call" and (payload.get("tool_call") or payload.get("tool_calls")):return True+ if et == "chat.tool_result" and (payload.get("tool_result") or payload.get("tool_call_id")):+ return Trueif payload.get("error") or payload.get("files"):return Trueif payload.get("tool_call") or payload.get("tool_calls"):diff --git a/tests/unit_tests/test_session_history_empty_filter.py b/tests/unit_tests/test_session_history_empty_filter.pyindex 68075ad159..7c06651732 100644--- a/tests/unit_tests/test_session_history_empty_filter.py+++ b/tests/unit_tests/test_session_history_empty_filter.py@@ -66,3 +66,140 @@ def test_append_history_skips_empty_chat_final_and_heartbeat(tmp_path, monkeypatassert [item.get("event_type") for item in data] == ["chat.file", "chat.final"]assert data[1]["content"] == "hello"assert session_history.load_history_records("heartbeat_abc") == []+++def test_has_persistable_assistant_payload_tool_result_with_tool_call_id():+ assert session_history._has_persistable_assistant_payload(+ content_text="",+ event_type="chat.tool_result",+ extra={"tool_call_id": "call_abc", "tool_name": "list_files", "result": "ok"},+ ) is True+++def test_has_persistable_assistant_payload_tool_result_with_nested_tool_result():+ assert session_history._has_persistable_assistant_payload(+ content_text="",+ event_type="chat.tool_result",+ extra={"tool_result": {"tool_name": "test", "tool_call_id": "call_abc", "result": "ok"}},+ ) is True+++def test_has_persistable_assistant_payload_tool_result_empty_rejected():+ assert session_history._has_persistable_assistant_payload(+ content_text="",+ event_type="chat.tool_result",+ extra={},+ ) is False+++def test_has_persistable_assistant_payload_tool_result_falsy_values_rejected():+ assert session_history._has_persistable_assistant_payload(+ content_text="",+ event_type="chat.tool_result",+ extra={"tool_call_id": "", "tool_result": None},+ ) is False+++def test_has_persistable_assistant_payload_processing_status_still_rejected():+ assert session_history._has_persistable_assistant_payload(+ content_text="",+ event_type="chat.processing_status",+ extra={"is_processing": True},+ ) is False+++def test_has_persistable_assistant_payload_tool_update_still_rejected():+ assert session_history._has_persistable_assistant_payload(+ content_text="",+ event_type="chat.tool_update",+ extra={"tool_call_id": "call_abc", "beam_search": {}},+ ) is False+++def test_append_history_persists_tool_result(tmp_path, monkeypatch):+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)++ session_history.append_history_record(+ session_id="s-tool-result",+ request_id="r1",+ channel_id="web",+ role="assistant",+ event_type="chat.tool_call",+ content="",+ timestamp=1.0,+ extra={"tool_call": {"name": "list_files", "id": "call_abc", "arguments": "{}"}},+ )+ session_history.append_history_record(+ session_id="s-tool-result",+ request_id="r1",+ channel_id="web",+ role="assistant",+ event_type="chat.tool_result",+ content="",+ timestamp=2.0,+ extra={"tool_call_id": "call_abc", "tool_name": "list_files", "result": "file1.txt", "success": True},+ )+ session_history.append_history_record(+ session_id="s-tool-result",+ request_id="r1",+ channel_id="web",+ role="assistant",+ event_type="chat.final",+ content="Done",+ timestamp=3.0,+ )++ data = _wait_history("s-tool-result", min_count=3)+ event_types = [item.get("event_type") for item in data]+ assert event_types == ["chat.tool_call", "chat.tool_result", "chat.final"]++ tool_result_record = data[1]+ assert tool_result_record["event_type"] == "chat.tool_result"+ assert tool_result_record["tool_call_id"] == "call_abc"+ assert tool_result_record["tool_name"] == "list_files"+++def test_append_history_persists_tool_result_with_nested_payload(tmp_path, monkeypatch):+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)++ session_history.append_history_record(+ session_id="s-nested",+ request_id="r1",+ channel_id="web",+ role="assistant",+ event_type="chat.tool_result",+ content="cancelled",+ timestamp=1.0,+ extra={+ "tool_result": {+ "tool_name": "code",+ "tool_call_id": "call_xyz",+ "result": "cancelled",+ "status": "error",+ },+ },+ )++ data = _wait_history("s-nested", min_count=1)+ assert len(data) == 1+ assert data[0]["event_type"] == "chat.tool_result"+++def test_append_history_tool_result_empty_payload_skipped(tmp_path, monkeypatch):+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)++ session_history.append_history_record(+ session_id="s-empty-tr",+ request_id="r1",+ channel_id="web",+ role="assistant",+ event_type="chat.tool_result",+ content="",+ timestamp=1.0,+ extra={},+ )++ import time as _t+ _t.sleep(0.3)+ data = session_history.load_history_records("s-empty-tr")+ assert data == []