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(cron): 企业版定时任务立即执行跳转空白会话与蓝点残留

caozhenhua00002b9484195826
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 5d824fbf4c..1be41d41d7 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -1557,6 +1557,20 @@ function AppContent() {
startBackgroundHistoryPrefetch,
]);
+ // 轮询兜底刷新:企业版 HTTP 无 cron 结果 push,立即执行跳转后 skipHistoryLoad,
+ // syncJobRuns 检测到「当前正打开会话 == 新 last_session_id」时投递刷新请求,
+ // 这里消费并触发一次完整的历史恢复(与首次点击激活会话的时机一逻辑一致)。
+ const pendingActiveHistoryRefresh = useCronStore((s) => s.pendingActiveHistoryRefresh);
+ useEffect(() => {
+ if (!pendingActiveHistoryRefresh) return;
+ // consume 物先置空再判断,保证 effect 幂等、不会因同一值重复触发
+ const sid = useCronStore.getState().consumeActiveHistoryRefresh();
+ if (!sid) return;
+ // 仅当该会话仍是当前激活会话时刷新,避免竞态下刷新到已切走的会话
+ if (useChatStore.getState().activeSessionId !== sid) return;
+ startHistoryRestore(sid);
+ }, [pendingActiveHistoryRefresh, startHistoryRestore]);
+
// 当会话 ID 变化或页面加载时,自动加载历史会话
useEffect(() => {
if (!isConnected || !sessionId || sessionId === NEW_CONVERSATION_ID) return;
diff --git a/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts
index e97e712968..cdd32ba175 100644
--- a/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts
@@ -7,6 +7,7 @@ import {
import { projectRegistryClient } from '../features/workspace/projectRegistryClient';
import { webRequest } from '../services/webClient';
import type { Session } from '../types';
+import { useChatStore } from './chatStore';
export interface SidebarCronJob {
id: string;
@@ -44,6 +45,12 @@ interface CronState {
// job_id → 最近"立即执行"返回的 session_id,用于广播消息路由
lastRunSessionId: Record<string, string>;
setLastRunSessionId: (jobId: string, sessionId: string) => void;
+ // 轮询检测到「当前正打开会话 == 某 job 新 last_session_id」时,投递一次历史刷新请求。
+ // 企业版 HTTP 无 cron 结果 push,立即执行跳转后 skipHistoryLoad,消息两头落空;
+ // 这里用 30s 轮询作为兜底:命中就把 session_id 交给 App.tsx 触发 startHistoryRestore。
+ pendingActiveHistoryRefresh: string | null;
+ requestActiveHistoryRefresh: (sessionId: string) => void;
+ consumeActiveHistoryRefresh: () => string | null;
// 定时任务未读状态(is_placeholder=false 的广播到达时标记,点击后清除)
unreadCronJobs: Record<string, boolean>;
markCronJobUnread: (jobId: string) => void;
@@ -82,6 +89,13 @@ export const useCronStore = create<CronState>((set, get) => ({
lastRunSessionId: {},
setLastRunSessionId: (jobId, sessionId) =>
set((s) => ({ lastRunSessionId: { ...s.lastRunSessionId, [jobId]: sessionId } })),
+ pendingActiveHistoryRefresh: null,
+ requestActiveHistoryRefresh: (sessionId) => set({ pendingActiveHistoryRefresh: sessionId }),
+ consumeActiveHistoryRefresh: () => {
+ const pending = get().pendingActiveHistoryRefresh;
+ if (pending) set({ pendingActiveHistoryRefresh: null });
+ return pending;
+ },
unreadCronJobs: (() => {
try {
const value = JSON.parse(localStorage.getItem('jiuwenswarm_cron_unread') || '{}');
@@ -133,9 +147,23 @@ export const useCronStore = create<CronState>((set, get) => ({
runSyncFingerprints: nextFingerprints,
});
+ const activeSessionId = useChatStore.getState().activeSessionId;
+
for (const jobId of updatedJobIds) {
- get().markCronJobUnread(jobId);
const job = webJobs.find((item) => item.id === jobId);
+ const lastSid = (job?.last_session_id ?? '').trim();
+ // 当前正打开的会话恰好是这次新产生的 cron 会话:企业版 HTTP 无 push,
+ // 立即执行跳转后 skipHistoryLoad,消息两头落空。这里用轮询兜底——
+ // 投递一次历史刷新请求,并直接清掉蓝点(消息即将实打实显示出来)。
+ if (lastSid && activeSessionId && lastSid === activeSessionId) {
+ get().clearCronJobUnread(jobId);
+ get().requestActiveHistoryRefresh(lastSid);
+ if (job) {
+ void get().loadCronSessions(job.project_id || 'default', jobId);
+ }
+ continue;
+ }
+ get().markCronJobUnread(jobId);
if (job) {
void get().loadCronSessions(job.project_id || 'default', jobId);
}
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 37be12912b..9d18ee09ae 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -7160,8 +7160,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
if job is None:
await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")
return
- run_info = await cc.run_now_info(job_id)
- await cc.run_now(job_id, group_id=g, bot_id=b, user_id=u)
+ run_info = await cc.run_now_with_session(
+ job_id, group_id=g, bot_id=b, user_id=u
+ )
await channel.send_response(
ws, req_id, ok=True,
payload={
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py b/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py
index 23058df1fb..0bd733bd8b 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py
@@ -35,7 +35,7 @@ CRON_JOB_TABLE_DEF = TableDefinition(
ColumnDefinition("description", "string", length=4096, nullable=True),
ColumnDefinition("cron_expr", "string", length=128, nullable=False),
ColumnDefinition("timezone", "string", length=64, nullable=False),
- ColumnDefinition("wake_offset_seconds", "integer", nullable=False, default=300),
+ ColumnDefinition("wake_offset_seconds", "integer", nullable=False, default=0),
ColumnDefinition("enabled", "boolean", nullable=False, default=True),
ColumnDefinition("expired", "boolean", nullable=False, default=False),
ColumnDefinition("delete_after_run", "boolean", nullable=False, default=False),
diff --git a/jiuwenswarm/gateway/cron/controller.py b/jiuwenswarm/gateway/cron/controller.py
index 95c93ba056..917ffb90fd 100644
--- a/jiuwenswarm/gateway/cron/controller.py
+++ b/jiuwenswarm/gateway/cron/controller.py
@@ -115,7 +115,12 @@ class CronController:
cron_expr: str,
timezone: str,
) -> Any:
- """企业创建兜底:wake_offset 不得超过距下次 push 的剩余秒数。"""
+ """创建兜底:wake_offset 不得超过距下次 push 的剩余秒数。
+
+ 这是纯业务约束,与存储介质无关,个人版/企业版统一应用:
+ 若提前量大于距下次触发的剩余时间,wake 时刻会落在过去,
+ 调度器会立即误触发(或在停摆后链式补跑)。
+ """
try:
tz = ZoneInfo(timezone)
now = datetime.now(tz=tz)
@@ -305,12 +310,11 @@ class CronController:
self._validate_schedule(cron_expr=cron_expr, timezone=timezone)
description = self._normalize_description(description, name)
- if is_enterprise():
- wake_offset_seconds = self._clamp_wake_offset_for_upcoming_run(
- wake_offset_seconds,
- cron_expr=cron_expr,
- timezone=timezone,
- )
+ wake_offset_seconds = self._clamp_wake_offset_for_upcoming_run(
+ wake_offset_seconds,
+ cron_expr=cron_expr,
+ timezone=timezone,
+ )
routing_sid = self._routing_session_id(targets, params.get("session_id"))
chat_type = params.get("chat_type")
@@ -533,6 +537,26 @@ class CronController:
async def run_now_info(self, job_id: str) -> dict[str, str]:
return await self._scheduler.trigger_run_now_info(job_id)
+ async def run_now_with_session(
+ self,
+ job_id: str,
+ *,
+ group_id: str | None = None,
+ bot_id: str | None = None,
+ user_id: str | None = None,
+ ) -> dict[str, str]:
+ """web「立即执行」:校验归属并提前创建真实执行会话,返回给前端跳转。
+
+ 与 ``run_now`` 的差异仅在返回真实 session_id(非 team 模式预分配会话),
+ 避免前端跳到占位 ``cron_<ts>_<job.id>`` 空会话。预分配失败降级为占位,
+ 执行阶段仍会兜底创建。
+ """
+ job = await self._store.get_job(job_id)
+ if job is None:
+ raise KeyError("job not found")
+ self._assert_job_owned(job, group_id=group_id, bot_id=bot_id, user_id=user_id)
+ return await self._scheduler.trigger_run_now_info(job_id, preallocate=True)
+
async def _create_job_tool(
self,
name: str,
diff --git a/jiuwenswarm/gateway/cron/cron_expr.py b/jiuwenswarm/gateway/cron/cron_expr.py
index f1d2b6affe..2ffb779ce2 100644
--- a/jiuwenswarm/gateway/cron/cron_expr.py
+++ b/jiuwenswarm/gateway/cron/cron_expr.py
@@ -7,8 +7,10 @@ from typing import Any
from zoneinfo import ZoneInfo
-# Harness / CronJob 常见默认提前量;相对 one-shot 时不可超过 delay。
-_DEFAULT_WAKE_OFFSET_SECONDS = 300
+# 提前唤醒默认量:0 = 到点执行。
+# 与个人版 CronJob.wake_offset_seconds 字段默认值保持一致,企业版 DB 路径
+# 仅 NULL/缺失时回落到此值,二者语义统一(差异只在存储介质,不在默认值)。
+_DEFAULT_WAKE_OFFSET_SECONDS = 0
def cron_field_count(expr: str) -> int:
diff --git a/jiuwenswarm/gateway/cron/db_store.py b/jiuwenswarm/gateway/cron/db_store.py
index fbc8c19868..741577859b 100644
--- a/jiuwenswarm/gateway/cron/db_store.py
+++ b/jiuwenswarm/gateway/cron/db_store.py
@@ -162,7 +162,11 @@ def _row_to_job(row: Any) -> CronJob | None:
"expired": bool(data.get("expired", False)),
"cron_expr": str(data.get("cron_expr") or "").strip(),
"timezone": str(data.get("timezone") or "").strip(),
- "wake_offset_seconds": int(data.get("wake_offset_seconds") or 60),
+ "wake_offset_seconds": int(
+ data.get("wake_offset_seconds")
+ if data.get("wake_offset_seconds") is not None
+ else _DEFAULT_WAKE_OFFSET_SECONDS
+ ),
"description": str(data.get("description") or ""),
"targets": str(data.get("targets") or "").strip(),
"session_id": data.get("session_id"),
diff --git a/jiuwenswarm/gateway/cron/models.py b/jiuwenswarm/gateway/cron/models.py
index 2044bbeded..311cad8411 100644
--- a/jiuwenswarm/gateway/cron/models.py
+++ b/jiuwenswarm/gateway/cron/models.py
@@ -515,3 +515,5 @@ class CronRunState:
# ``cron.job.run_now`` 预分配 run 时使用当前时刻,与库表 ``next_run_at`` 不一致,
# 不能走条件 UPDATE 认领(否则会静默跳过 wake)。
manual_trigger: bool = False
+ # run_now 提前创建了真实执行会话(非 team 模式),_on_wake 复用而不再重复创建。
+ session_preallocated: bool = False
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.py
index 1158e2b091..0a176b3fa9 100644
--- a/jiuwenswarm/gateway/cron/scheduler.py
+++ b/jiuwenswarm/gateway/cron/scheduler.py
@@ -744,7 +744,9 @@ class CronSchedulerService:
info = await self.trigger_run_now_info(job_id)
return str(info["run_id"])
- async def trigger_run_now_info(self, job_id: str) -> dict[str, str]:
+ async def trigger_run_now_info(
+ self, job_id: str, *, preallocate: bool = False
+ ) -> dict[str, str]:
job_id = str(job_id or "").strip()
job = self._jobs.get(job_id) or await self._store.get_job(job_id)
if job is None:
@@ -755,6 +757,30 @@ class CronSchedulerService:
wake_dt = now
run_id = f"{job.id}:{int(push_dt.timestamp())}"
channel_id, exec_session_id = self._make_execution_context(job)
+ # 非 team 模式:web「立即执行」需要返回真实执行会话给前端跳转。
+ # 否则前端跳到占位 ``cron_<ts>_<job.id>``,该会话从未真正 session.create,
+ # 打开显示"没有可恢复的消息",且不在 cron 轮询列表里,不会自动刷新。
+ # 仅 web 路径(preallocate=True)提前创建真实会话,_on_wake 检测到
+ # session_preallocated 后复用,避免重复创建。创建失败降级为占位 id,
+ # run_now 仍会调度,执行时再兜底创建。
+ session_preallocated = False
+ if preallocate:
+ mode = str(job.mode or CRON_JOB_DEFAULT_MODE).strip() or CRON_JOB_DEFAULT_MODE
+ if not is_team_cron_mode(mode):
+ try:
+ exec_project_dir = self._resolve_cron_project_dir(job)
+ exec_session_id = await self._allocate_single_agent_session(
+ job,
+ mode=mode,
+ project_dir=exec_project_dir,
+ run_id=run_id,
+ )
+ session_preallocated = True
+ except Exception as prealloc_exc: # noqa: BLE001
+ logger.warning(
+ "[Cron] run_now preallocate session failed job=%s run_id=%s: %s",
+ job.id, run_id, prealloc_exc,
+ )
state = CronRunState(
run_id=run_id,
job_id=job.id,
@@ -768,6 +794,7 @@ class CronSchedulerService:
exec_channel_id=channel_id,
exec_session_id=exec_session_id,
manual_trigger=True,
+ session_preallocated=session_preallocated,
)
await self._assign_run(run_id, state)
self._schedule_event(wake_dt, "wake", job.id, run_id)
@@ -786,6 +813,23 @@ class CronSchedulerService:
)
return "__cron__", f"cron_{ts}_{job.id}"
+ @staticmethod
+ def _resolve_cron_project_dir(job: CronJob) -> str:
+ """解析 job.project_id 对应的项目目录,供 session.create 归属。
+
+ 与 ``_on_wake`` 共享同一解析逻辑,避免 run_now 预分配会话与正常触发
+ 两处各写一份。解析失败返回空串(AgentServer 侧按默认目录兜底)。
+ """
+ try:
+ from jiuwenswarm.server.runtime.session import project_store as _ps
+
+ return _ps.get_project_dir_by_id(job.project_id) or ""
+ except Exception as pdir_exc: # noqa: BLE001
+ logger.warning(
+ "[Cron] resolve project_dir failed job=%s: %s", job.id, pdir_exc,
+ )
+ return ""
+
async def _allocate_single_agent_session(
self,
job: CronJob,
@@ -1325,35 +1369,38 @@ class CronSchedulerService:
state.exec_channel_id = channel_id
state.exec_session_id = exec_session_id
# 解析 project_dir 供 AgentServer 写入会话归属(与 project_id 联动)
- try:
- from jiuwenswarm.server.runtime.session import project_store as _ps
- exec_project_dir = _ps.get_project_dir_by_id(job.project_id)
- except Exception as pdir_exc: # noqa: BLE001
- logger.warning(
- "[Cron] resolve project_dir failed job=%s: %s", job.id, pdir_exc,
- )
- exec_project_dir = ""
+ exec_project_dir = self._resolve_cron_project_dir(job)
if not is_team_cron_mode(mode):
- _log_cron_run_phase(
- "run_agent_before_session_create",
- run_id=run_id,
- job_id=job.id,
- mode=mode,
- )
- exec_session_id = await self._allocate_single_agent_session(
- job,
- mode=mode,
- project_dir=exec_project_dir,
- run_id=run_id,
- )
- state.exec_channel_id = "__cron__"
- state.exec_session_id = exec_session_id
- _log_cron_run_phase(
- "run_agent_after_session_create",
- run_id=run_id,
- job_id=job.id,
- exec_session_id=exec_session_id,
- )
+ if state.session_preallocated and state.exec_session_id:
+ # run_now 已提前创建真实会话,直接复用,避免重复 session.create。
+ exec_session_id = state.exec_session_id
+ _log_cron_run_phase(
+ "run_agent_reuse_preallocated_session",
+ run_id=run_id,
+ job_id=job.id,
+ exec_session_id=exec_session_id,
+ )
+ else:
+ _log_cron_run_phase(
+ "run_agent_before_session_create",
+ run_id=run_id,
+ job_id=job.id,
+ mode=mode,
+ )
+ exec_session_id = await self._allocate_single_agent_session(
+ job,
+ mode=mode,
+ project_dir=exec_project_dir,
+ run_id=run_id,
+ )
+ state.exec_channel_id = "__cron__"
+ state.exec_session_id = exec_session_id
+ _log_cron_run_phase(
+ "run_agent_after_session_create",
+ run_id=run_id,
+ job_id=job.id,
+ exec_session_id=exec_session_id,
+ )
cron_meta = {
"job_id": job.id,
"job_name": job.name,
diff --git a/tests/unit_tests/gateway/test_cron_expr_wake_offset.py b/tests/unit_tests/gateway/test_cron_expr_wake_offset.py
index 0410a612cd..9cfc82dbcd 100644
--- a/tests/unit_tests/gateway/test_cron_expr_wake_offset.py
+++ b/tests/unit_tests/gateway/test_cron_expr_wake_offset.py
@@ -15,8 +15,8 @@ from jiuwenswarm.gateway.cron.cron_expr import clamp_wake_offset_for_delay_secon
(300, 600, 300),
(10, 60, 10),
(0, 60, 0),
- (None, 60, 60), # missing → default 300, then clamp to 60
- (None, 600, 300),
+ (None, 60, 0), # missing → default 0(到点执行),clamp 仍为 0
+ (None, 600, 0),
(-5, 60, 0),
(300, 1, 1),
(300, 0.5, 0),
@@ -27,7 +27,7 @@ def test_clamp_wake_offset_for_delay_seconds(wake, delay, expected) -> None:
def test_clamp_wake_offset_invalid_wake_falls_back_to_default() -> None:
- assert clamp_wake_offset_for_delay_seconds("bad", 60) == 60
+ assert clamp_wake_offset_for_delay_seconds("bad", 60) == 0
def test_clamp_wake_offset_non_positive_delay() -> None:
diff --git a/tests/unit_tests/gateway/test_cron_scheduler.py b/tests/unit_tests/gateway/test_cron_scheduler.py
index 8b0c1e7a0e..7330046231 100644
--- a/tests/unit_tests/gateway/test_cron_scheduler.py
+++ b/tests/unit_tests/gateway/test_cron_scheduler.py
@@ -307,10 +307,29 @@ class TestCronLastSessionId:
info = await svc.trigger_run_now_info(job.id)
assert info["run_id"].startswith(f"{job.id}:")
+ # 默认(非 web 路径)不预分配:返回占位 cron_<ts>_<job.id>,保持 trigger_run_now
+ # 非阻塞语义不变。
assert info["session_id"].startswith("cron_")
assert info["session_id"].endswith(f"_{job.id}")
state = svc.runs[info["run_id"]]
assert state.exec_session_id == info["session_id"]
+ assert state.session_preallocated is False
+
+ @pytest.mark.asyncio
+ async def test_run_now_info_preallocate_returns_real_session_id(self, tmp_path):
+ store = CronJobStore(path=tmp_path / "cron_jobs.json")
+ job = await _create_one_job(store)
+ svc = _make_scheduler(store)
+
+ info = await svc.trigger_run_now_info(job.id, preallocate=True)
+
+ assert info["run_id"].startswith(f"{job.id}:")
+ # 非 team 模式 + preallocate:提前创建真实会话(FakeAgentClient 固定返回
+ # cron_agentserver_allocated),返回真实 session_id 供前端跳转。
+ assert info["session_id"] == "cron_agentserver_allocated"
+ state = svc.runs[info["run_id"]]
+ assert state.exec_session_id == info["session_id"]
+ assert state.session_preallocated is True
class TestCheckStoreChanged:
diff --git a/tests/unit_tests/test_web_http_settings_handlers.py b/tests/unit_tests/test_web_http_settings_handlers.py
index e6ded1a2cd..769fad717b 100644
--- a/tests/unit_tests/test_web_http_settings_handlers.py
+++ b/tests/unit_tests/test_web_http_settings_handlers.py
@@ -65,6 +65,12 @@ class _FakeCron:
raise KeyError(job_id)
return {"run_id": f"run-{job_id}", "session_id": f"sess-{job_id}"}
+ async def run_now_with_session(self, job_id, **kwargs):
+ if job_id not in self.jobs:
+ raise KeyError(job_id)
+ self.run_calls.append(job_id)
+ return {"run_id": f"run-{job_id}", "session_id": f"sess-{job_id}"}
+
async def run_now(self, job_id, **kwargs):
if job_id not in self.jobs:
raise KeyError(job_id)