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(cron): persist execution history for remote session restore
Haoqiang Wang1ac6411b5363
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex 44c7d1a242..d991df6b8a 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -169,6 +169,45 @@ def _touch_remote_cron_session_catalog(session_id: str, *, now_ts: float) -> Non)+async def _persist_remote_cron_history(job: CronJob, state: CronRunState) -> None:+ """Save the execution body independently of Pod-local files and push delivery."""+ if not is_remote_storage() or not state.exec_session_id or not state.result_text:+ return+ try:+ from jiuwenswarm.channels.web.history_store.api import get_default_store++ store = get_default_store()+ request_id = f"cron-{state.run_id}"+ query = str(job.description or job.name or "").strip()+ if query:+ await store.record_user(+ request_id=request_id,+ session_id=state.exec_session_id,+ query=query,+ ts=state.started_at or state.finished_at,+ user=str(job.user_id or "").strip() or "guest",+ group_id=job.group_id,+ bot_id=job.bot_id,+ project_id=job.project_id,+ cron_id=job.id,+ work_mode=job.work_mode or DEFAULT_WEB_WORK_MODE,+ )+ await store.record_assistant(+ request_id=request_id,+ session_id=state.exec_session_id,+ content=state.result_text,+ event_type="chat.final" if state.status == "succeeded" else "chat.error",+ ts=state.finished_at,+ )+ except Exception: # noqa: BLE001+ logger.warning(+ "[Cron] persist exec history failed job=%s session_id=%s",+ job.id,+ state.exec_session_id,+ exc_info=True,+ )++def _extract_workflow_result_text(payload: dict | None) -> str | None:if not isinstance(payload, dict):return None@@ -1732,9 +1771,9 @@ class CronSchedulerService:# a job the user has removed.if not state.result_text and state.error and not is_cancelled_ghost:state.result_text = f"[cron] 任务执行失败: {state.error}"- # 仅在 local 模式写 gateway 本地磁盘兜底历史;remote 模式下会话- # 数据由 AgentServer 持久化,本地写入会污染 gateway 磁盘并被- # project.get_sessions 误读为普通会话(cron_id 丢失)。+ if not is_cancelled_ghost:+ await _persist_remote_cron_history(job, state)+ # local 模式保留磁盘兜底;remote 正文写历史库,避免依赖原 Pod。local_fallback_ok = not is_cancelled_ghost and not is_remote_storage()if state.result_text and not ok and local_fallback_ok:query = ""diff --git a/tests/unit_tests/gateway/test_cron_remote_history.py b/tests/unit_tests/gateway/test_cron_remote_history.pynew file mode 100644index 0000000000..d899d915c3--- /dev/null+++ b/tests/unit_tests/gateway/test_cron_remote_history.py@@ -0,0 +1,116 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Cron execution history must survive without its AgentServer Pod or a Web tab."""+from __future__ import annotations++import asyncio+import time+from unittest.mock import AsyncMock++import pytest++from jiuwenswarm.channels.web.history_store import api as history_api+from jiuwenswarm.channels.web.history_store.store import ChatHistoryStore+from jiuwenswarm.common.schema.agent import AgentResponse+from jiuwenswarm.gateway.cron import scheduler as scheduler_module+from jiuwenswarm.gateway.cron.models import CronJob+from jiuwenswarm.gateway.cron.scheduler import CronSchedulerService+from jiuwenswarm.gateway.cron.store import CronJobStore+++class HistoryScheduler(CronSchedulerService):+ async def execute(self, job: CronJob, run_id: str):+ await self._on_wake(job, run_id)+ await self._run_tasks[run_id]+ return self._runs[run_id]+++class AgentClient:+ def __init__(self, outcome: str):+ self.outcome = outcome+ self.requests = []++ async def send_request(self, envelope):+ self.requests.append(envelope)+ if envelope.method == "session.create":+ return AgentResponse(envelope.request_id, envelope.channel, True,+ {"session_id": "cron-history-test"})+ if self.outcome == "exception":+ raise RuntimeError("Agent connection closed")+ if self.outcome == "cancelled":+ raise asyncio.CancelledError+ ok = self.outcome == "success"+ payload = {"content": "晴,25℃"} if ok else {"error": "weather request failed"}+ return AgentResponse(envelope.request_id, envelope.channel, ok, payload)+++def history_store(monkeypatch):+ store = ChatHistoryStore.memory()+ monkeypatch.setattr(history_api, "_default_store", store)+ monkeypatch.setattr(scheduler_module, "is_remote_storage", lambda: True)+ return store+++def make_scheduler(tmp_path, outcome="success", targets="web"):+ job = CronJob(id="weather", name="查询天气", description="查询北京天气", enabled=True,+ cron_expr="* * * * *", timezone="Asia/Shanghai", targets=targets,+ user_id="owner", group_id="group", bot_id="bot", project_id="project",+ work_mode="work")+ scheduler = HistoryScheduler(store=CronJobStore(path=tmp_path / "jobs.json"),+ agent_client=AgentClient(outcome), message_handler=object())+ return scheduler, job++[email protected]("outcome", ["success", "failure", "exception"])[email protected]("targets", ["web", "tui"])+async def test_completed_execution_saves_owned_body_without_push(+ tmp_path, history_store, outcome, targets,+):+ scheduler, job = make_scheduler(tmp_path, outcome, targets)+ run_id = f"weather:{int(time.time())}"+ state = await scheduler.execute(job, run_id)+ detail = history_store.get_session_detail_blocking(+ state.exec_session_id, user="owner", group_id="group", bot_id="bot",+ )+ assert detail is not None+ assert detail["cron_id"] == "weather"+ assert detail["project_id"] == "project"+ assert detail["message_count"] == 2+ messages = detail["messages"]+ assert [message["role"] for message in messages] == ["user", "assistant"]+ assert messages[0]["content"] == "查询北京天气"+ assert messages[1]["content"] == state.result_text+ assert messages[1]["event_type"] == ("chat.final" if outcome == "success" else "chat.error")+ assert all(message["request_id"] == f"cron-{run_id}" for message in messages)+ assert history_store.get_session_detail_blocking(state.exec_session_id, user="other") is None+ # A duplicate wake must not add duplicate messages or rerun the task.+ await scheduler.execute(job, run_id)+ assert history_store.get_session_detail_blocking(state.exec_session_id, user="owner")["message_count"] == 2+++async def test_cancelled_execution_does_not_save_or_deliver_body(tmp_path, history_store):+ scheduler, job = make_scheduler(tmp_path, "cancelled")+ with pytest.raises(asyncio.CancelledError):+ await scheduler.execute(job, f"weather:{int(time.time())}")+ detail = history_store.get_session_detail_blocking("cron-history-test", user="owner")+ assert detail is not None+ assert detail["messages"] == []+++async def test_history_db_failure_does_not_change_execution_result(tmp_path, history_store, monkeypatch):+ monkeypatch.setattr(history_store, "record_assistant", AsyncMock(side_effect=RuntimeError("DB unavailable")))+ scheduler, job = make_scheduler(tmp_path)+ state = await scheduler.execute(job, f"weather:{int(time.time())}")+ assert state.status == "succeeded"+ assert state.result_text == "晴,25℃"+++async def test_local_mode_does_not_write_remote_history(tmp_path, history_store, monkeypatch):+ monkeypatch.setattr(scheduler_module, "is_remote_storage", lambda: False)+ scheduler, job = make_scheduler(tmp_path)+ await scheduler.execute(job, f"weather:{int(time.time())}")+ assert history_store.list_sessions_blocking(user="owner", limit=20, offset=0) == []